From 2a38d73ca81523bd16b520326dfb96871035448b Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 19:10:59 +0000 Subject: [PATCH] GEN-2003 add durable cron scheduling --- package-lock.json | 22 ++++++++++ packages/app/package.json | 1 + packages/app/src/flow-schemas.ts | 5 ++- packages/app/src/job-domain.ts | 6 +++ packages/app/src/schedule.ts | 28 +++++++++++++ packages/app/src/tenant.ts | 56 ++++++++++++++++++++++++-- packages/app/test/flow-service.test.ts | 2 +- packages/app/test/job-domain.test.ts | 1 + packages/app/test/schedule.test.ts | 28 +++++++++++++ 9 files changed, 144 insertions(+), 5 deletions(-) create mode 100644 packages/app/src/schedule.ts create mode 100644 packages/app/test/schedule.test.ts diff --git a/package-lock.json b/package-lock.json index 74eaa336..733128a6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3887,6 +3887,18 @@ "url": "https://opencollective.com/express" } }, + "node_modules/cron-parser": { + "version": "5.10.1", + "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-5.10.1.tgz", + "integrity": "sha512-pKRrRagItwk9rGIStcUyMxFX34x56zoX3KDf9HJ4ttwkXIK1qxK63EvXvEDmlxI9AdPJ+Y7TEKRftRlW5eSS7A==", + "license": "MIT", + "dependencies": { + "luxon": "^3.7.2" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -4462,6 +4474,15 @@ "dev": true, "license": "MIT" }, + "node_modules/luxon": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz", + "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -5778,6 +5799,7 @@ "@cloudflare/workers-oauth-provider": "^0.10.3", "@modelcontextprotocol/hono": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", + "cron-parser": "^5.10.1", "hono": "^4.11.4", "mustache": "^4.2.0", "zod": "^4.6.2" diff --git a/packages/app/package.json b/packages/app/package.json index a55fcfb6..eb3ba05e 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -15,6 +15,7 @@ "@cloudflare/workers-oauth-provider": "^0.10.3", "@modelcontextprotocol/hono": "^2.0.0", "@modelcontextprotocol/server": "^2.0.0", + "cron-parser": "^5.10.1", "hono": "^4.11.4", "mustache": "^4.2.0", "zod": "^4.6.2" diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 165173c8..5129a1e0 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -33,7 +33,10 @@ export const listEventsSchema = z.object({ const stringRecordSchema = z.record(z.string(), z.string()); export const triggerSchema = z.discriminatedUnion("kind", [ z.object({ kind: z.literal("manual"), config: z.object({}).strict().default({}) }).strict(), - z.object({ kind: z.literal("schedule"), config: z.record(z.string(), z.unknown()) }).strict(), + z.object({ kind: z.literal("schedule"), config: z.object({ + cron: z.string().trim().min(1), timezone: z.string().trim().min(1), + context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}), + }).strict() }).strict(), z.object({ kind: z.literal("webhook"), config: z.record(z.string(), z.unknown()) }).strict(), ]); export const jobInputSchema = z.object({ diff --git a/packages/app/src/job-domain.ts b/packages/app/src/job-domain.ts index fe9bfebc..0130bfd6 100644 --- a/packages/app/src/job-domain.ts +++ b/packages/app/src/job-domain.ts @@ -167,4 +167,10 @@ export const JOB_SCHEMA = ` ); CREATE INDEX IF NOT EXISTS job_runs_queue ON job_runs(state, created_at); CREATE INDEX IF NOT EXISTS job_runs_active ON job_runs(job_id, state); + CREATE TABLE IF NOT EXISTS schedule_state ( + trigger_id TEXT PRIMARY KEY REFERENCES triggers(id) ON DELETE CASCADE, + job_id TEXT NOT NULL UNIQUE REFERENCES jobs(id) ON DELETE CASCADE, + next_run_at INTEGER, last_triggered_at TEXT + ); + CREATE INDEX IF NOT EXISTS schedules_due ON schedule_state(next_run_at); `; diff --git a/packages/app/src/schedule.ts b/packages/app/src/schedule.ts new file mode 100644 index 00000000..260b9435 --- /dev/null +++ b/packages/app/src/schedule.ts @@ -0,0 +1,28 @@ +import { CronExpressionParser } from "cron-parser"; + +export interface ScheduleConfig { + cron: string; + timezone: string; + context?: string; + parameters?: Record; +} + +export function validateScheduleConfig(value: unknown): ScheduleConfig { + const config = value as ScheduleConfig; + if (!config || typeof config.cron !== "string" || typeof config.timezone !== "string") throw new Error("Schedule cron and timezone are required"); + try { new Intl.DateTimeFormat("en-US", { timeZone: config.timezone }).format(); } + catch { throw new Error("Schedule timezone must be a valid IANA timezone"); } + try { CronExpressionParser.parse(config.cron, { tz: config.timezone }); } + catch { throw new Error("Schedule cron expression is invalid"); } + return config; +} + +/** cron-parser resolves skipped and repeated wall-clock times deterministically in the supplied IANA zone. */ +export function nextOccurrence(config: ScheduleConfig, after: Date): Date { + return CronExpressionParser.parse(config.cron, { currentDate: after, tz: config.timezone }).next().toDate(); +} + +export function catchUpOccurrence(config: ScheduleConfig, nextDue: Date, wakeAt: Date): { occurredAt: Date; nextRunAt: Date } | null { + if (nextDue.getTime() > wakeAt.getTime()) return null; + return { occurredAt: nextDue, nextRunAt: nextOccurrence(config, wakeAt) }; +} diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index c0da7f92..38249526 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -16,6 +16,7 @@ import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, rend import { renderSourcePrompt } from "./source-lifecycle"; import { JOB_SCHEMA, renderJobPrompt } from "./job-domain"; import { normalizeExecutionState, type RunHandle } from "./execution"; +import { catchUpOccurrence, nextOccurrence, validateScheduleConfig, type ScheduleConfig } from "./schedule"; export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -152,6 +153,7 @@ export class Tenant extends DurableObject { async alarm(): Promise { await this.processGitHubVerifications(); + await this.processDueSchedules(); // Release completed slots before looking at the queue, so capacity is used // immediately rather than waiting for the next polling alarm. const running = this.rows("SELECT * FROM runs WHERE state IN ('running','blocked','recovering') ORDER BY updated_at LIMIT 40"); @@ -171,7 +173,9 @@ export class Tenant extends DurableObject { const pending = this.one("SELECT count(*) AS count FROM runs WHERE state IN ('queued','starting','running','blocked','recovering')") as Row; const verification = this.one("SELECT min(next_attempt_at) AS next_attempt_at FROM pending_verifications") as Row; const nextVerification = Number(verification?.next_attempt_at || 0); - if (Number(pending.count) > 0 || nextVerification) await this.ctx.storage.setAlarm(nextVerification ? Math.min(Date.now() + 15_000, nextVerification) : Date.now() + 15_000); + const schedule = this.one("SELECT min(next_run_at) AS next_run_at FROM schedule_state") as Row; + const candidates = [Number(pending.count) > 0 ? Date.now() + 15_000 : 0, nextVerification, Number(schedule?.next_run_at || 0)].filter(Boolean); + if (candidates.length) await this.ctx.storage.setAlarm(Math.min(...candidates)); } private async saveLinear(input: unknown): Promise { @@ -296,7 +300,8 @@ export class Tenant extends DurableObject { promptTemplate: await decrypt(String(row.encrypted_prompt_template), this.env.CREDENTIAL_ENCRYPTION_KEY), parameterDefaults, concurrencyLimit: Number(row.concurrency_limit), executionTargetId: String(executionTarget.connectionId ?? ""), - trigger: { kind: String(trigger?.kind ?? "manual"), config: triggerConfig }, + trigger: { kind: String(trigger?.kind ?? "manual"), config: triggerConfig, + ...(trigger?.kind === "schedule" ? (() => { const state = this.one("SELECT next_run_at,last_triggered_at FROM schedule_state WHERE job_id=?", row.id) as Row | undefined; return { nextRunAt: state?.next_run_at == null ? null : new Date(Number(state.next_run_at)).toISOString(), lastTriggeredAt: state?.last_triggered_at ?? null }; })() : {}) }, enabled: Boolean(row.enabled), createdAt: row.created_at, updatedAt: row.updated_at, }; } @@ -313,6 +318,18 @@ export class Tenant extends DurableObject { if (!input.trigger || !["manual", "schedule", "webhook"].includes(input.trigger.kind)) throw new Error("Job trigger is invalid"); if (Object.prototype.hasOwnProperty.call(input.parameterDefaults ?? {}, "context")) throw new Error("context is reserved and cannot be a job parameter"); Mustache.parse(input.promptTemplate); + if (input.trigger.kind === "schedule") validateScheduleConfig(input.trigger.config); + } + + private async resetSchedule(jobId: string): Promise { + const job = this.one("SELECT j.enabled,t.id AS trigger_id,t.kind,t.config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.id=?", jobId) as Row | undefined; + if (!job || job.kind !== "schedule") { this.ctx.storage.sql.exec("DELETE FROM schedule_state WHERE job_id=?", jobId); return; } + const config = validateScheduleConfig(JSON.parse(String(job.config))); + const next = Boolean(job.enabled) ? nextOccurrence(config, new Date()).getTime() : null; + this.ctx.storage.sql.exec("INSERT INTO schedule_state(trigger_id,job_id,next_run_at) VALUES(?,?,?) ON CONFLICT(job_id) DO UPDATE SET trigger_id=excluded.trigger_id,next_run_at=excluded.next_run_at", job.trigger_id, jobId, next); + if (next === null) return; + const alarm = await this.ctx.storage.getAlarm(); + if (alarm === null || next < alarm) await this.ctx.storage.setAlarm(next); } private async createJob(input: any): Promise { @@ -320,6 +337,7 @@ export class Tenant extends DurableObject { const target = await this.jobTarget(input.executionTargetId), jobId = id(), triggerId = id(), timestamp = now(); this.ctx.storage.sql.exec("INSERT INTO jobs VALUES (?,?,?,?,?,?,?,?,?)", jobId, input.name, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(input.parameterDefaults ?? {}), JSON.stringify(target), input.concurrencyLimit, 1, timestamp, timestamp); this.ctx.storage.sql.exec("INSERT INTO triggers VALUES (?,?,?,?,?,?)", triggerId, jobId, input.trigger.kind, JSON.stringify(input.trigger.config ?? {}), timestamp, timestamp); + await this.resetSchedule(jobId); return json(await this.publicJob(this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row)); } @@ -334,12 +352,14 @@ export class Tenant extends DurableObject { const target = await this.jobTarget(input.executionTargetId), timestamp = now(); this.ctx.storage.sql.exec("UPDATE jobs SET name=?,encrypted_prompt_template=?,parameter_defaults=?,execution_target=?,concurrency_limit=?,updated_at=? WHERE id=?", input.name, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(input.parameterDefaults ?? {}), JSON.stringify(target), input.concurrencyLimit, timestamp, jobId); this.ctx.storage.sql.exec("UPDATE triggers SET kind=?,config=?,updated_at=? WHERE job_id=?", input.trigger.kind, JSON.stringify(input.trigger.config ?? {}), timestamp, jobId); + await this.resetSchedule(jobId); return json(await this.publicJob(this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row)); } - private setJobEnabled(jobId: string, enabled: boolean): Response { + private async setJobEnabled(jobId: string, enabled: boolean): Promise { if (!this.one("SELECT id FROM jobs WHERE id = ?", jobId)) return new Response("Not found", { status: 404 }); this.ctx.storage.sql.exec("UPDATE jobs SET enabled=?,updated_at=? WHERE id=?", enabled ? 1 : 0, now(), jobId); + await this.resetSchedule(jobId); return json({ id: jobId, enabled }); } @@ -376,6 +396,36 @@ export class Tenant extends DurableObject { return json({ invocationId, runId, state: "queued", duplicate: false }); } + private async processDueSchedules(): Promise { + const wake = Date.now(); + const due = this.rows("SELECT s.job_id,s.next_run_at,t.config FROM schedule_state s JOIN jobs j ON j.id=s.job_id JOIN triggers t ON t.id=s.trigger_id WHERE j.enabled=1 AND t.kind='schedule' AND s.next_run_at<=? ORDER BY s.next_run_at LIMIT 100", wake); + for (const row of due) { + const config = validateScheduleConfig(JSON.parse(String(row.config))) as ScheduleConfig; + const catchUp = catchUpOccurrence(config, new Date(Number(row.next_run_at)), new Date(wake)); + if (!catchUp) continue; + const occurredAt = catchUp.occurredAt.toISOString(); + await this.enqueueScheduledJob(String(row.job_id), occurredAt, config); + this.ctx.storage.sql.exec("UPDATE schedule_state SET next_run_at=?,last_triggered_at=? WHERE job_id=? AND next_run_at=?", catchUp.nextRunAt.getTime(), occurredAt, row.job_id, row.next_run_at); + } + } + + private async enqueueScheduledJob(jobId: string, occurredAt: string, config: ScheduleConfig): Promise { + const row = this.one("SELECT * FROM jobs WHERE id=? AND enabled=1", jobId) as Row | undefined; + if (!row) return; + const claimKey = `schedule:${occurredAt}`; + if (this.one("SELECT id FROM invocations WHERE job_id=? AND claim_key=?", jobId, claimKey)) return; + const job = await this.publicJob(row), parameters = config.parameters ?? {}; + const prompt = renderJobPrompt({ promptTemplate: String(job.promptTemplate), parameterDefaults: job.parameterDefaults as Record }, { context: config.context, parameters }); + const invocationId = id(), runId = id(), timestamp = now(), occurrence = JSON.stringify({ occurredAt }); + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO invocations (id,job_id,source,claim_key,context,parameters,occurrence,created_at) VALUES (?,?,?,?,?,?,?,?)", invocationId, jobId, "schedule", claimKey, config.context ?? null, JSON.stringify(parameters), occurrence, timestamp); + const winner = this.one("SELECT id FROM invocations WHERE job_id=? AND claim_key=?", jobId, claimKey) as Row; + if (winner.id !== invocationId) return; + const encryptedPrompt = await encrypt(prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); + this.ctx.storage.sql.exec("INSERT INTO job_runs (id,job_id,invocation_id,state,encrypted_prompt,created_at,updated_at) VALUES (?,?,?,?,?,?,?)", runId, jobId, invocationId, "queued", encryptedPrompt, timestamp, timestamp); + let target: Record = {}; try { target = JSON.parse(String(row.execution_target)); } catch {} + this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, jobId, invocationId, String(row.name), null, claimKey, `factorize-${runId}`, String(target.workspace ?? ""), String(target.agentKind ?? ""), "queued", encryptedPrompt, "pending", "schedule", "exe-herdr", JSON.stringify(["output", "prompt-delivery", "recovery", "stop"]), "https://exe.dev/", timestamp, timestamp); + } + private deletePipe(pipeId: string): Response { if (!pipeId || !this.one("SELECT id FROM pipes WHERE id = ?", pipeId)) return new Response("Not found", { status: 404 }); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id = ?", pipeId); diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index 4ec44c08..a38810c5 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -65,7 +65,7 @@ describe("shared API schemas", () => { }); it("validates job configuration and reserved invocation context", () => { - const job = jobInputSchema.parse({ name: "Deploy", promptTemplate: "Deploy {{environment}}: {{context}}", parameterDefaults: { environment: "staging" }, concurrencyLimit: 2, executionTargetId: "exe-1", trigger: { kind: "schedule", config: { cron: "0 * * * *" } } }); + const job = jobInputSchema.parse({ name: "Deploy", promptTemplate: "Deploy {{environment}}: {{context}}", parameterDefaults: { environment: "staging" }, concurrencyLimit: 2, executionTargetId: "exe-1", trigger: { kind: "schedule", config: { cron: "0 * * * *", timezone: "UTC" } } }); expect(job.trigger.kind).toBe("schedule"); expect(() => jobInputSchema.parse({ ...job, apiToken: "secret" })).toThrow(); expect(() => jobInputSchema.parse({ ...job, parameterDefaults: { context: "wrong" } })).toThrow(); diff --git a/packages/app/test/job-domain.test.ts b/packages/app/test/job-domain.test.ts index 9faedffb..e95c1c74 100644 --- a/packages/app/test/job-domain.test.ts +++ b/packages/app/test/job-domain.test.ts @@ -47,6 +47,7 @@ describe("job invocation domain", () => { it("defines exactly one trigger per job and durable claims in the clean schema", () => { expect(JOB_SCHEMA).toContain("job_id TEXT NOT NULL UNIQUE"); expect(JOB_SCHEMA).toContain("UNIQUE(job_id, claim_key)"); + expect(JOB_SCHEMA).toContain("CREATE TABLE IF NOT EXISTS schedule_state"); expect(JOB_SCHEMA).not.toContain("pipes"); }); }); diff --git a/packages/app/test/schedule.test.ts b/packages/app/test/schedule.test.ts new file mode 100644 index 00000000..09a649ce --- /dev/null +++ b/packages/app/test/schedule.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { catchUpOccurrence, nextOccurrence, validateScheduleConfig } from "../src/schedule"; + +describe("durable schedules", () => { + it("calculates occurrences in the configured IANA timezone", () => { + const config = validateScheduleConfig({ cron: "0 9 * * *", timezone: "America/New_York" }); + expect(nextOccurrence(config, new Date("2026-01-15T00:00:00Z")).toISOString()).toBe("2026-01-15T14:00:00.000Z"); + expect(nextOccurrence(config, new Date("2026-07-15T00:00:00Z")).toISOString()).toBe("2026-07-15T13:00:00.000Z"); + }); + + it("handles spring-forward and fall-back deterministically", () => { + const config = validateScheduleConfig({ cron: "30 2 * * *", timezone: "America/New_York" }); + expect(nextOccurrence(config, new Date("2026-03-08T00:00:00Z")).toISOString()).toBe("2026-03-08T07:30:00.000Z"); + expect(nextOccurrence(config, new Date("2026-11-01T00:00:00Z")).toISOString()).toBe("2026-11-01T07:30:00.000Z"); + }); + + it("rejects invalid cron and timezone values", () => { + expect(() => validateScheduleConfig({ cron: "nope", timezone: "UTC" })).toThrow(/cron/); + expect(() => validateScheduleConfig({ cron: "0 * * * *", timezone: "Mars/Olympus" })).toThrow(/IANA/); + }); + + it("coalesces any number of missed intervals into one catch-up", () => { + const config = validateScheduleConfig({ cron: "*/5 * * * *", timezone: "UTC" }); + const result = catchUpOccurrence(config, new Date("2026-09-16T10:00:00Z"), new Date("2026-09-16T11:02:00Z")); + expect(result?.occurredAt.toISOString()).toBe("2026-09-16T10:00:00.000Z"); + expect(result?.nextRunAt.toISOString()).toBe("2026-09-16T11:05:00.000Z"); + }); +});