fix(schedules): clean up orphaned schedule records and add schedule URL state management

This commit is contained in:
Chris Scott committed 2026-06-05 13:37:11 -04:00
1 parent 70cb62b77b
commit 9368a7f8e2
16 files changed
+1859 -118

No files matched your search

+25
View File
@@ -205,6 +205,31 @@ export function deleteScheduleJob(db: Database, repoId: number, jobId: number):
return result.changes > 0
}
export function deleteScheduleJobsByRepo(db: Database, repoId: number): number {
// Delete runs first in case FK enforcement is off (e.g. during migration)
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ?').run(repoId)
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ?')
const result = stmt.run(repoId)
return result.changes
}
export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
const runStmt = db.prepare(`
DELETE FROM schedule_runs
WHERE repo_id NOT IN (SELECT id FROM repos)
OR job_id NOT IN (SELECT id FROM schedule_jobs)
`)
const orphanedRuns = runStmt.run().changes
const jobStmt = db.prepare(`
DELETE FROM schedule_jobs
WHERE repo_id NOT IN (SELECT id FROM repos)
`)
const orphanedJobs = jobStmt.run().changes
return { orphanedJobs, orphanedRuns }
}
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
+4
View File
@@ -10,6 +10,10 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
mkdirSync(dirname(dbPath), { recursive: true })
const db = new Database(dbPath)
// Enable foreign key enforcement so ON DELETE CASCADE works.
// SQLite defaults to OFF, and bun:sqlite inherits this default.
db.exec('PRAGMA foreign_keys = ON')
migrate(db, allMigrations)
ensureOpenCodeModelStateTable(db)
+5
View File
@@ -273,6 +273,11 @@ app.get('/', async (c) => {
return c.json({ error: 'Repo not found' }, 404)
}
// Unregister and delete all schedule jobs/runs for this repo first,
// so the ScheduleRunner doesn't hold stale cron timers and the DB
// cascade (or explicit delete) cleans up schedule data cleanly.
scheduleService.deleteJobsByRepo(id)
await repoService.deleteRepoFiles(database, id)
return c.json({ success: true })
+34
View File
@@ -10,9 +10,11 @@ import {
import { getRepoById } from '../db/queries'
import type { ScheduleJobWithRepo } from '../db/schedules'
import {
cleanupOrphanedSchedules,
createScheduleJob,
createScheduleRun,
deleteScheduleJob,
deleteScheduleJobsByRepo,
getScheduleJobById,
getRunningScheduleRunByJob,
getScheduleRunById,
@@ -444,6 +446,33 @@ export class ScheduleService {
this.onJobChange?.(null, jobId)
}
/**
* Deletes all schedule jobs (and their runs) for a repo and notifies the
* ScheduleRunner so in-memory cron timers are removed. This should be called
* **before** the repo row itself is deleted.
*/
deleteJobsByRepo(repoId: number): void {
// Notify the runner for each job so in-memory timers are cleaned up.
const jobs = listScheduleJobsByRepo(this.db, repoId)
for (const job of jobs) {
this.onJobChange?.(null, job.id)
}
deleteScheduleJobsByRepo(this.db, repoId)
}
/**
* Removes any schedule_jobs and schedule_runs whose repo_id (or job_id for
* runs) no longer exists in the repos / schedule_jobs table. Safe to call
* on every startup — no-op when there are no orphans.
*/
cleanupOrphanedSchedules(): { orphanedJobs: number; orphanedRuns: number } {
const result = cleanupOrphanedSchedules(this.db)
if (result.orphanedJobs > 0 || result.orphanedRuns > 0) {
logger.info(`Cleaned up ${result.orphanedJobs} orphaned schedule job(s) and ${result.orphanedRuns} run(s)`)
}
return result
}
listRuns(repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
this.assertJob(repoId, jobId)
return listScheduleRunsByJob(this.db, repoId, jobId, limit)
@@ -1120,6 +1149,11 @@ export class ScheduleRunner {
}
})
// Clean up any schedule records whose repo no longer exists. This handles
// leftovers from before foreign-key enforcement was enabled, and guards
// against edge cases where a repo row was removed outside the normal flow.
this.scheduleService.cleanupOrphanedSchedules()
await this.scheduleService.recoverRunningRuns()
this.registerAllEnabledJobs()
}