From 78b833c4958465b5e345b0e337018011b00dab72 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Thu, 15 Oct 2026 22:44:17 -0700 Subject: [PATCH] Dispatch routine and monitor work at saved deadlines (#16514) ## Thinking Path > - Paperclip manages work that agents run for a company. > - Routines and issue monitors store their next run time in the database. > - The app currently waits for the heartbeat interval to find that work. > - This can delay work after a workspace wakes before its saved deadline. > - This pull request uses the existing work coordinator to schedule each known deadline. > - It also parses each cron expression once, so sparse schedules do less work on the event loop. > - Agents can start due work sooner while the existing execution checks stay in place. ## Linked Issues or Issue Description **What happened?** Routine and issue-monitor dispatch depends on the heartbeat scan interval. A workspace can wake early and still wait for the next scan. A sparse cron search also parses the same expression for every minute it checks. In a local annual-schedule test, the deadline callback ran on time but schedule calculation delayed the routine record by 13.6 seconds. **Expected behavior** Use a saved future deadline to request the existing dispatch scan. Restore deadlines at startup and update them after a producer transaction settles. Do not let future timers keep an idle workspace active. Parse a cron expression once for each search. **Steps to reproduce** 1. Set an active routine and an assigned issue monitor to the same future deadline. 2. Choose a deadline between heartbeat scans. Use an annual routine expression to exercise a sparse search. 3. Compare the saved deadline with the routine firing and agent start times. **Paperclip version or commit** Source checkout based on c7ea5c0216b86c4ece4abebd3fe9aa66c65e7a2f. Related public changes: #16215 reports routine deadlines for external wake. #8034 caches time-zone formatters in the cron search. This change reuses those contracts. ## What Changed - Register separate routine and issue-monitor workers with the existing delivery coordinator after startup housekeeping. - Restore the earliest eligible future deadline from the database after each scan. - Notify the matching worker when routine or monitor writes settle, including the native `set_task_monitor` tool. Keep the heartbeat interval as a recovery scan for blocked or externally written work. - Retain the scan-start cutoff so a deadline crossed during a slow scan receives an immediate follow-up scan. - Retain the coordinator gates for standby, idle drain, and shutdown. Future timers do not count as active work. Bound expired deadline retries during idle reconciliation so a paused worker cannot spin. - Parse a cron expression once during a next-run search. Skip impossible UTC dates before time-zone formatting. Preserve the existing calendar and time-zone matching. - Add clock, transaction, failure, SQL eligibility, and producer notification tests. Document the scheduler behavior. ## Verification - `pnpm -r typecheck`: passed. - `pnpm build`: passed. - Full CI, browser tests, and security scan: passed on final head 9fc857dcecf4e9eb4f0e9223712c8c44edf02dcf. Greptile Apex is 5/5 with no unresolved comments. - Final focused startup, deadline, routine, SQL eligibility, native monitor, cron, and coordinator tests: 159 passed across seven suites. The crossed-deadline and native-notification regressions failed before their fixes. - CI caught the existing startup suppression assertion. It failed locally before restoring the outer timer-dispatch guard; all 38 startup tests now pass. - A canceled-drain regression also failed before the fix. Future timers keep their saved time; only expired deadlines use the bounded idle retry. Server typecheck and build passed again. - The idle-drain regression reproduced 22 checks in 20 ms before its fix. After the fix, 43 coordinator and related worker tests passed. Server typecheck and build passed again after the review fixes. - The broad local `pnpm test:run` attempt reported existing host-sensitive failures. Two Git fixture tests fail identically on unchanged c7ea5c0 because the host default `main` leaves an extra branch in an intended master-only remote. Both pass with a command-scoped `init.defaultBranch=master` setting. No Git settings were changed on disk. - A diagnostics test also fails on both unchanged master and this branch because its broad `private` substring assertion matches the canonical macOS temporary source path in an error stack. A local Anthropic hire assertion failed only in the broad run; all 70 tests in that file pass on both source revisions when run separately. Its broad-run cause is not determined. These failures remain recorded. The full exact-head CI matrix passed; the broad local development attempt was then stopped. - An earlier full run was interrupted after PostgreSQL reported host shared-memory exhaustion. One retry was stopped when timing required the UTC optimization. Acceptance then used an owned database on the existing local PostgreSQL service. No shared services were stopped or reset. - Local dispatch: routine record at +0.102 s, routine agent start at +0.171 s, monitor agent start at +0.159 s. Both scripted agents succeeded using real run-scoped API authentication. No model provider was called. No duplicate runs occurred during the 70-second follow-up. Platform: macOS, Node 25.6.1, isolated database on local PostgreSQL 16, source checkout. The final run used a fresh database and a clean checkout of 9fc857dcecf4e9eb4f0e9223712c8c44edf02dcf. - The first timing run exposed the repeated cron parsing described above. A diagnostic run showed the timer fired 1 ms after the deadline while the annual search blocked the event loop. Parsing once reduced local dispatch to 5.9 seconds, which still missed the five-second test target. The next change skips impossible UTC dates before formatting. A second regression failed before that fix. The final timing result and duplicate check passed. - A separate acceptance setup failed because the direct local server had no agent signing key. That owned fixture was removed. The retry uses an ephemeral key in its isolated process environment. - Owned fixtures were deleted, the local runtime exited normally, and the disposable databases were dropped. Shared services remain running. - No production deployment or npm publication is part of this PR. ## Risks - Known deadlines now trigger a scan between heartbeat ticks. Existing atomic claims, suppression checks, budgets, and execution rules still decide whether work runs. - Direct database writers rely on the heartbeat recovery scan. Overdue blocked work also retains that recovery interval to avoid a tight retry loop. - This is not a hard real-time guarantee. Provider startup, queue load, and other synchronous work can still delay agent execution. - No database migration or API schema change. Revert this commit to restore interval-only dispatch. ## Model Used OpenAI GPT-6 (Codex), with reasoning, repository tools, terminal execution, and automated tests. The session does not expose a more specific model version or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass for the changed areas; full-suite CI and local exceptions are documented above - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/DEVELOPING.md | 17 ++ .../delivery-work-coordinator.test.ts | 38 ++++ server/src/__tests__/routines-service.test.ts | 36 ++++ .../__tests__/scheduled-work-postgres.test.ts | 65 +++++++ server/src/__tests__/scheduled-work.test.ts | 164 ++++++++++++++++++ server/src/index.ts | 44 +++-- .../src/services/delivery-work-coordinator.ts | 5 +- .../services/delivery-work-notifications.ts | 2 + server/src/services/issues.ts | 6 + .../paperclip-runner-tool-authority.ts | 2 + .../task-monitor.integration.test.ts | 28 +++ .../services/routines-formatter-cache.test.ts | 32 ++++ server/src/services/routines.ts | 26 ++- server/src/services/scheduled-work.ts | 46 +++++ 14 files changed, 480 insertions(+), 31 deletions(-) create mode 100644 server/src/__tests__/scheduled-work-postgres.test.ts create mode 100644 server/src/__tests__/scheduled-work.test.ts create mode 100644 server/src/services/scheduled-work.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 8a9bfe8d0b5..6ab0d3e9e37 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1448,6 +1448,23 @@ When a workspace service runs Paperclip for browser OAuth QA, configure its `exp ## Heartbeat Service Extractions +Routine and issue-monitor dispatch uses saved future deadlines through +`server/src/services/scheduled-work.ts` and the existing delivery coordinator. +Startup restores the next deadline. Routine edits and monitor changes notify +their worker after the enclosing database transaction settles, including native +`set_task_monitor` writes. Deadlines crossed during a scan receive an immediate +follow-up scan. Work already overdue at scan start retains heartbeat recovery. +Each worker runs +independently and retains the existing atomic claims and execution checks. +The heartbeat interval still requests a recovery scan; it does not determine +the dispatch time of a known future deadline. Failed scans retry at that same +interval. Future timers do not hold idle work open, and standby, idle drain and +shutdown retain the coordinator's admission gates. During idle drain, expired +deadlines retry at the recovery interval while dispatch is paused; future +deadlines keep their original timer so a canceled drain does not delay them. External database writers +rely on the periodic recovery scan. Sparse cron searches reuse one parsed +expression and skip impossible UTC dates before localized formatting. + Keep relevant heartbeat extractions and their focused tests in `server/src/services/heartbeat/`. Follow [Heartbeat execution boundaries](../rules/heartbeat-execution-boundaries.mdc) for state lifetime, admission, recovery ownership, cleanup ordering, and verification. diff --git a/server/src/__tests__/delivery-work-coordinator.test.ts b/server/src/__tests__/delivery-work-coordinator.test.ts index c964714698c..b4406a7cd5d 100644 --- a/server/src/__tests__/delivery-work-coordinator.test.ts +++ b/server/src/__tests__/delivery-work-coordinator.test.ts @@ -163,6 +163,44 @@ describe("delivery work coordinator", () => { expect(t.run).toHaveBeenCalledTimes(2); expect(idleWorkSnapshot().active).toBe(0); }); + it("bounds an expired deadline retry during idle reconciliation and resumes after drain", async () => { + const s = setup(), t = task(); + const due = Date.now() + 10_000; + let next: number | null = due; + const scheduled = { ...t, nextRunAt: () => next }; + await s.coordinator.register(DELIVERY_QUEUES.routineSchedules, scheduled).ready; + s.canRun.mockReturnValue(false); + s.canReconcile.mockReturnValue(true); + await vi.advanceTimersByTimeAsync(10_020); + expect(t.run).toHaveBeenCalledTimes(1); + expect(t.hasPending).toHaveBeenCalledTimes(2); + expect(s.coordinator.nextWakeAt()).toBe(due + t.retryMs); + expect(idleWorkSnapshot().active).toBe(0); + next = null; + s.canRun.mockReturnValue(true); + await vi.advanceTimersByTimeAsync(t.retryMs - 20); + expect(t.run).toHaveBeenCalledTimes(2); + expect(s.coordinator.nextWakeAt()).toBeNull(); + }); + + it("preserves a future deadline while reconciling a write during idle drain", async () => { + const s = setup(), t = task(); + const due = Date.now() + 1000; + let next: number | null = due; + await s.coordinator.register(DELIVERY_QUEUES.routineSchedules, { ...t, nextRunAt: () => next }).ready; + s.canRun.mockReturnValue(false); + s.canReconcile.mockReturnValue(true); + await s.enqueue(DELIVERY_QUEUES.routineSchedules); + await vi.advanceTimersByTimeAsync(1); + expect(s.coordinator.nextWakeAt()).toBe(due); + expect(t.run).toHaveBeenCalledTimes(1); + next = null; + s.canRun.mockReturnValue(true); + await vi.advanceTimersByTimeAsync(999); + expect(t.run).toHaveBeenCalledTimes(2); + expect(idleWorkSnapshot().active).toBe(0); + }); + it("does not query during standby and resumes when admission opens", async () => { const s = setup(), t = task(); s.canRun.mockReturnValue(false); await s.coordinator.register(DELIVERY_QUEUES.toolAction, t).ready; diff --git a/server/src/__tests__/routines-service.test.ts b/server/src/__tests__/routines-service.test.ts index 9d4949e30ab..1f01bc32801 100644 --- a/server/src/__tests__/routines-service.test.ts +++ b/server/src/__tests__/routines-service.test.ts @@ -1,3 +1,5 @@ +import { subscribeDatabaseWork } from "@paperclipai/db"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; import { createHmac, randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; @@ -214,6 +216,40 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => { return { companyId, agentId, issueSvc, projectId, routine, svc, wakeups }; } + it("notifies scheduled routine work after trigger transactions settle", async () => { + const f = await seedFixture(); + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.routineSchedules, event => { events.push(event); }); + try { + const created = await f.svc.createTrigger(f.routine.id, + { kind: "schedule", cronExpression: "0 * * * *", timezone: "UTC" }, {}); + expect(events).toEqual(["intent", "settled"]); + events.length = 0; + await f.svc.updateTrigger(created.trigger.id, { cronExpression: "30 * * * *" }, {}); + expect(events).toEqual(["intent", "settled"]); + events.length = 0; + await f.svc.deleteTrigger(created.trigger.id, {}); + expect(events).toEqual(["intent", "settled"]); + } finally { unsubscribe(); } + }); + + it("notifies monitor work when an issue deadline is created and changed", async () => { + const f = await seedFixture(); + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.issueMonitors, event => { events.push(event); }); + const next = new Date(Date.now() + 600_000); + try { + const issue = await f.issueSvc.create(f.companyId, { + title: "Scheduled check", status: "in_progress", assigneeAgentId: f.agentId, + executionPolicy: { mode: "normal", commentRequired: true, stages: [], monitor: { nextCheckAt: next.toISOString() } }, + }); + expect(events).toEqual(["intent", "settled"]); + events.length = 0; + await f.issueSvc.update(issue.id, { monitorNextCheckAt: new Date(next.getTime() + 60_000) }); + expect(events).toEqual(["intent", "settled"]); + } finally { unsubscribe(); } + }); + async function armWorktreeExecution(cutoff: Date, instanceId = "worktree-routines-test") { await db.insert(instanceSettings).values({ singletonKey: "default", diff --git a/server/src/__tests__/scheduled-work-postgres.test.ts b/server/src/__tests__/scheduled-work-postgres.test.ts new file mode 100644 index 00000000000..fb4d9a8d180 --- /dev/null +++ b/server/src/__tests__/scheduled-work-postgres.test.ts @@ -0,0 +1,65 @@ +import { agents, companies, createDb, issues, routines, routineTriggers } from "@paperclipai/db"; +import { sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import type { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, type DeliveryQueue } from "../services/delivery-work-notifications.js"; +import { registerScheduledWork } from "../services/scheduled-work.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("scheduled deadline database queries", () => { + let database: Awaited>; + let db: Db; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-scheduled-deadlines"); + db = createDb(database.connectionString); + }, 30_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + it("selects future eligible deadlines and excludes inactive, mismatched and past work", async () => { + const now = Date.now(); + const at = (minutes: number) => new Date(now + minutes * 60_000); + const [company, pausedCompany] = await db.insert(companies).values([ + { name: "Active schedules", issuePrefix: "SCH" }, + { name: "Paused schedules", issuePrefix: "PAU", status: "paused" }, + ]).returning(); + const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Scheduled agent" }).returning(); + const [active, paused, otherCompany] = await db.insert(routines).values([ + { companyId: company!.id, title: "Active routine" }, + { companyId: company!.id, title: "Paused routine", status: "paused" }, + { companyId: pausedCompany!.id, title: "Paused company routine" }, + ]).returning(); + const trigger = { companyId: company!.id, routineId: active!.id, kind: "schedule" }; + await db.insert(routineTriggers).values([ + { ...trigger, nextRunAt: at(10) }, + { ...trigger, enabled: false, nextRunAt: at(1) }, + { ...trigger, archived: true, nextRunAt: at(2) }, + { ...trigger, routineId: paused!.id, nextRunAt: at(3) }, + { ...trigger, companyId: pausedCompany!.id, nextRunAt: at(4) }, + { ...trigger, companyId: pausedCompany!.id, routineId: otherCompany!.id, nextRunAt: at(5) }, + { ...trigger, nextRunAt: at(-1) }, + ]); + const monitor = { companyId: company!.id, title: "Monitor", status: "in_progress", assigneeAgentId: agent!.id }; + await db.insert(issues).values([ + { ...monitor, monitorNextCheckAt: at(15) }, + { ...monitor, status: "done", monitorNextCheckAt: at(1) }, + { ...monitor, assigneeUserId: "fixture-user", monitorNextCheckAt: at(2) }, + { ...monitor, assigneeAgentId: null, monitorNextCheckAt: at(3) }, + { ...monitor, companyId: pausedCompany!.id, monitorNextCheckAt: at(4) }, + { ...monitor, monitorNextCheckAt: at(-1) }, + ]); + type Task = Parameters["register"]>[1]; + const tasks = new Map(); + registerScheduledWork({ register: (queue, task) => { + tasks.set(queue, task); + return { ready: Promise.resolve(), wake: () => {} }; + } }, db, { retryMs: 60_000, tickTimers: async () => {}, tickRoutines: async () => {} }); + for (const task of tasks.values()) await task.run(new AbortController().signal); + expect(tasks.get(DELIVERY_QUEUES.routineSchedules)!.nextRunAt!()).toBe(at(10).getTime()); + expect(tasks.get(DELIVERY_QUEUES.issueMonitors)!.nextRunAt!()).toBe(at(15).getTime()); + await db.execute(sql`truncate table companies restart identity cascade`); + for (const task of tasks.values()) await task.run(new AbortController().signal); + for (const task of tasks.values()) expect(task.nextRunAt!()).toBeNull(); + }); +}); diff --git a/server/src/__tests__/scheduled-work.test.ts b/server/src/__tests__/scheduled-work.test.ts new file mode 100644 index 00000000000..a2e3acb6161 --- /dev/null +++ b/server/src/__tests__/scheduled-work.test.ts @@ -0,0 +1,164 @@ +import { PgDialect } from "drizzle-orm/pg-core"; +import type { Db } from "@paperclipai/db"; +import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../services/delivery-work-notifications.js"; +import { registerScheduledWork } from "../services/scheduled-work.js"; +import { idleWorkSnapshot } from "../services/task-admission.js"; + +const coordinators: ReturnType[] = []; +afterEach(async () => { + for (const coordinator of coordinators.splice(0)) await coordinator.stop(); + vi.useRealTimers(); +}); + +function fixture(input: { routine?: number | null; monitor?: number | null; tickTimers?: () => Promise; tickRoutines?: () => Promise } = {}) { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2020-01-01T00:00:00.000Z")); + const dialect = new PgDialect(); + const deadlines = { routine: input.routine ?? null, monitor: input.monitor ?? null }; + let canRun = true; + let canReconcile = true; + let failRead = false; + const execute = vi.fn(async (query: any) => { + const compiled = dialect.sqlToQuery(query); + const text = compiled.sql; + if (text.includes("pg_current_xact_id")) return [{ xid: "42" }]; + if (failRead) throw new Error("database unavailable"); + const at = deadlines[text.includes("routine_triggers") ? "routine" : "monitor"]; + return [{ next_at: at !== null && at > Date.parse(String(compiled.params[0])) ? new Date(at) : null }]; + }); + const owner = installDatabaseWorkSignals({ execute, async transaction(callback: (tx: any) => Promise) { + return callback({ execute, transaction: owner.transaction }); + } }); + const errors = vi.fn(); + const coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => canRun, canReconcile: () => canReconcile, onError: errors }); + coordinators.push(coordinator); + const tickTimers = vi.fn(input.tickTimers ?? (async () => {})); + const tickRoutines = vi.fn(input.tickRoutines ?? (async () => {})); + const workers = registerScheduledWork(coordinator, owner as unknown as Db, + { retryMs: 60_000, tickTimers, tickRoutines }); + return { coordinator, workers, owner, deadlines, execute, tickTimers, tickRoutines, errors, + ready: () => Promise.all([workers.routines.ready, workers.timers.ready]), + canRun: (value: boolean) => { canRun = value; }, canReconcile: (value: boolean) => { canReconcile = value; }, failRead: (value: boolean) => { failRead = value; } }; +} + +describe("scheduled routine and monitor deadlines", () => { + it("dispatches at each saved deadline without waiting for a periodic tick", async () => { + const now = Date.UTC(2020, 0, 1); + const f = fixture({ routine: now + 10_000, monitor: now + 20_000 }); + await f.ready(); + expect(f.coordinator.nextWakeAt()).toBe(now + 10_000); + expect(idleWorkSnapshot().active).toBe(0); + await vi.advanceTimersByTimeAsync(9999); + expect(f.tickRoutines).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + expect(f.tickRoutines).toHaveBeenCalledTimes(2); + expect(f.tickTimers).toHaveBeenCalledTimes(1); + expect(f.coordinator.nextWakeAt()).toBe(now + 20_000); + await vi.advanceTimersByTimeAsync(10_000); + expect(f.tickTimers).toHaveBeenCalledTimes(2); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(f.execute).toHaveBeenCalledTimes(4); + expect(idleWorkSnapshot().active).toBe(0); + await vi.advanceTimersByTimeAsync(3_600_000); + expect(f.execute).toHaveBeenCalledTimes(4); + }); + + it.each(["routine", "monitor"] as const)("rescans a %s deadline crossed during an earlier scan", async kind => { + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + const tick = vi.fn().mockImplementationOnce(() => held).mockResolvedValue(undefined); + const now = Date.UTC(2020, 0, 1); + const f = fixture({ [kind]: now + 10_000, + ...(kind === "routine" ? { tickRoutines: tick } : { tickTimers: tick }) }); + try { + await (kind === "routine" ? f.workers.timers.ready : f.workers.routines.ready); + await vi.advanceTimersByTimeAsync(12_000); + } finally { release(); await f.ready(); } + expect(f.coordinator.nextWakeAt()).toBe(Date.now()); + await vi.advanceTimersByTimeAsync(1); + expect(tick).toHaveBeenCalledTimes(2); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(idleWorkSnapshot().active).toBe(0); + }); + + it("leaves work already overdue at scan start for bounded heartbeat recovery", async () => { + const f = fixture({ routine: Date.UTC(2020, 0, 1) - 10_000 }); + await f.ready(); + expect(f.coordinator.nextWakeAt()).toBeNull(); + await vi.advanceTimersByTimeAsync(3_600_000); + expect(f.tickRoutines).toHaveBeenCalledTimes(1); + expect(idleWorkSnapshot().active).toBe(0); + }); + + it("rearms an earlier deadline only after the producer transaction settles", async () => { + const now = Date.UTC(2020, 0, 1); + const f = fixture({ routine: now + 600_000 }); + await f.ready(); + let commit!: () => void; + const held = new Promise(resolve => { commit = resolve; }); + const writing = f.owner.transaction(async tx => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.routineSchedules); + f.deadlines.routine = now + 10_000; + await held; + }); + try { + await vi.advanceTimersByTimeAsync(1000); + expect(f.tickRoutines).toHaveBeenCalledTimes(1); + expect(idleWorkSnapshot().active).toBe(1); + } finally { commit(); await writing; } + await vi.advanceTimersByTimeAsync(1); + expect(f.coordinator.nextWakeAt()).toBe(now + 10_000); + expect(idleWorkSnapshot().active).toBe(0); + await vi.advanceTimersByTimeAsync(8999); + expect(f.tickRoutines).toHaveBeenCalledTimes(3); + expect(f.tickTimers).toHaveBeenCalledTimes(1); + }); + + it("keeps monitor dispatch responsive while routine work is slow", async () => { + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + const f = fixture({ monitor: Date.UTC(2020, 0, 1) + 10_000, tickRoutines: () => held }); + try { + await f.workers.timers.ready; + await vi.advanceTimersByTimeAsync(10_000); + expect(f.tickTimers).toHaveBeenCalledTimes(2); + expect(f.tickRoutines).toHaveBeenCalledTimes(1); + } finally { release(); await f.workers.routines.ready; } + }); + + it("does not dispatch during idle drain or standby and cancels deadlines on stop", async () => { + const f = fixture({ routine: Date.UTC(2020, 0, 1) + 10_000 }); + await f.ready(); + f.canRun(false); + await vi.advanceTimersByTimeAsync(10_000); + expect(f.tickRoutines).toHaveBeenCalledTimes(1); + expect(idleWorkSnapshot().active).toBe(0); + f.canReconcile(false); + await vi.advanceTimersByTimeAsync(60_000); + expect(f.execute).toHaveBeenCalledTimes(2); + await f.coordinator.stop(); + f.canRun(true); + await vi.advanceTimersByTimeAsync(3_600_000); + expect(f.tickRoutines).toHaveBeenCalledTimes(1); + expect(vi.getTimerCount()).toBe(0); + }); + + it("retries failed deadline reads at the fallback interval without a tight loop", async () => { + const f = fixture(); + await f.ready(); + f.failRead(true); + f.workers.routines.wake(); + await vi.advanceTimersByTimeAsync(1); + expect(f.errors).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(59_000); + expect(f.tickRoutines).toHaveBeenCalledTimes(2); + f.failRead(false); + await vi.advanceTimersByTimeAsync(1000); + expect(f.tickRoutines).toHaveBeenCalledTimes(3); + expect(f.coordinator.nextWakeAt()).toBeNull(); + expect(idleWorkSnapshot().active).toBe(0); + }); +}); diff --git a/server/src/index.ts b/server/src/index.ts index b76a63fb107..264adcd5589 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -7,6 +7,7 @@ import { } from "./services/skill-version-retention.js"; import { subscribeAllCompanyLiveEvents } from "./services/live-events.js"; import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js"; +import { registerScheduledWork } from "./services/scheduled-work.js"; import type { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js"; import { registerTerminalWorkspaceWork, TERMINAL_WORKSPACE_RETRY_MS } from "./services/terminal-workspace-work.js"; import { isIdleTaskDrainActive, beginIdleTrackedWork, trackIdleWork } from "./services/task-admission.js"; @@ -1718,7 +1719,7 @@ async function startServerWithDatabaseTeardown( await step("retention_sweep", runRetentionSweep); }; - const startHeartbeatScheduler = () => startHeartbeatSchedulerInterval(() => { + const createHeartbeatSchedulerTick = (scheduled: ReturnType) => () => { // Track the outer async callback as well as the work it starts. Shutdown // can then wait through an already-running suppression check before it // captures the authoritative set of running heartbeat rows. @@ -1738,18 +1739,7 @@ async function startServerWithDatabaseTeardown( ); } - if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) { - trackHeartbeatSchedulerWork(heartbeat - .tickTimers(new Date()) - .then((result) => { - if (result.enqueued > 0) { - logger.info({ ...result }, "heartbeat timer tick enqueued runs"); - } - }) - .catch((err) => { - logger.error({ err }, "heartbeat timer tick failed"); - })); - } + scheduled.timers.wake(); if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; scheduleExternalObjectRefreshSweep(new Date()); @@ -1763,16 +1753,7 @@ async function startServerWithDatabaseTeardown( scheduleEnvironmentLeaseCleanupSweep(); if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; - trackHeartbeatSchedulerWork(routines - .tickScheduledTriggers(new Date()) - .then((result) => { - if (result.triggered > 0) { - logger.info({ ...result }, "routine scheduler tick enqueued runs"); - } - }) - .catch((err) => { - logger.error({ err }, "routine scheduler tick failed"); - })); + scheduled.routines.wake(); if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; trackHeartbeatSchedulerWork((async () => { @@ -1896,7 +1877,22 @@ async function startServerWithDatabaseTeardown( })().catch((err) => { logger.error({ err }, "heartbeat scheduler tick failed"); })); - }); + }; + const startHeartbeatScheduler = () => { + const scheduled = registerScheduledWork(deliveryWork, db, { + retryMs: config.heartbeatSchedulerIntervalMs, + tickTimers: async () => { + if ((await heartbeat.resolveSchedulingSuppression()).suppressed) return; + const result = await heartbeat.tickTimers(new Date()); + if (result.enqueued > 0) logger.info({ ...result }, "heartbeat timer tick enqueued runs"); + }, + tickRoutines: () => routines.tickScheduledTriggers(new Date()).then(result => { + if (result.triggered > 0) logger.info({ ...result }, "routine scheduler tick enqueued runs"); + }), + }); + trackHeartbeatSchedulerWork(Promise.all([scheduled.timers.ready, scheduled.routines.ready])); + startHeartbeatSchedulerInterval(createHeartbeatSchedulerTick(scheduled)); + }; trackHeartbeatSchedulerWork(runStartupHousekeeping().then(() => { if (!heartbeatSchedulerStopped) startHeartbeatScheduler(); })); diff --git a/server/src/services/delivery-work-coordinator.ts b/server/src/services/delivery-work-coordinator.ts index b0b580a2289..c8c9a468bf3 100644 --- a/server/src/services/delivery-work-coordinator.ts +++ b/server/src/services/delivery-work-coordinator.ts @@ -56,7 +56,10 @@ export function createDeliveryWorkCoordinator(input: { if (pending || databaseWorkPending(input.owner, queue)) schedule(task.retryMs); else { finishIntent?.(); finishIntent = undefined; } const next = task.nextRunAt?.(); - if (next != null) schedule(Math.max(0, next - Date.now())); + if (next != null) { + const delay = Math.max(0, next - Date.now()); + schedule(delay === 0 && !input.canRun() ? task.retryMs : delay); + } }).catch(error => { schedule(task.retryMs); // Logging must never turn a recoverable sweep failure into an diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index 88387c21709..e03b811e275 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -27,6 +27,8 @@ export const DELIVERY_QUEUES = { pluginLifecycle: "plugin-resource-lifecycle", toolAction: "tool-action-receipts", terminalWorkspaces: "terminal-workspaces", + routineSchedules: "routine-schedules", + issueMonitors: "issue-monitors", } as const; export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES]; diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 584c483612f..aaae404ac66 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -9,6 +9,7 @@ import { type TaskWorkspaceSelection, type TaskWorkspaceIntent } from "@papercli import { executionWorkspaceService } from "./execution-workspaces.js"; import { notifyChatPublicationWork } from "./chat-work-notifications.js"; import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { recordChatHandoff, recordChatCompletion, existingChatCompletionReply, acknowledgeChatCompletionReply } from "./chat-completion-delivery.js"; import { mirrorSlackBoardComment, slackBoardReplyBindings } from "./slack-board-messages.js"; import { assertAgentRunWriteAllowed } from "../agent-run-cancellation.js"; @@ -10383,6 +10384,7 @@ export function issueService(db: Db) { await notifyTerminalWorkspaceWork(tx, values.executionWorkspaceId ? `workspace:${values.executionWorkspaceId}` : values.parentId ? `issue:${values.parentId}` : undefined); } + if (values.monitorNextCheckAt) await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); const [issue] = await tx.insert(issues).values(values).returning(); await attachOwnedDraftImages(tx, issue, issue.description, { userId: issueData.createdByUserId, agentId: issueData.createdByAgentId }); if (issue.visibility === "private" && !inheritedPrivateSubtree && issueData.createdByAgentId) { @@ -11205,6 +11207,10 @@ export function issueService(db: Db) { || issueData.parentId !== undefined || issueData.executionWorkspaceId !== undefined) { await notifyTerminalWorkspaceWork(tx, `issue:${id}`); } + if (patch.monitorNextCheckAt !== undefined || (receiptExisting.monitorNextCheckAt && + (patch.status !== undefined || patch.assigneeAgentId !== undefined || patch.assigneeUserId !== undefined))) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + } const updated = await tx .update(issues) .set(patch) diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index cbe300ec2da..3728aa51173 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -1,3 +1,4 @@ +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; import { skillAccessService } from "../skill-access.js"; import { callTaskWorkspaceTool } from "../task-workspace-tools.js"; import { TaskAttachmentReadCache, TASK_ATTACHMENT_DEFINITIONS, TASK_ATTACHMENT_SCHEMAS, listTaskAttachments, readTaskAttachment } from "./runner-task-attachments.js"; @@ -1647,6 +1648,7 @@ export class PaperclipRunnerToolAuthority { return { taskId: target.id, status: target.status, monitor: replayMonitor }; } const patch = prepareIssueMonitorUpdate(target, input.monitor, actor); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); const [updated] = await tx.update(issues).set({ ...patch, updatedAt: new Date() }) .where(and(eq(issues.id, target.id), eq(issues.companyId, this.binding.companyId))).returning(); if (!updated) throw notFound("Task not found"); diff --git a/server/src/services/native-runtime/task-monitor.integration.test.ts b/server/src/services/native-runtime/task-monitor.integration.test.ts index 2c7f5930ac2..ecef6fc9b82 100644 --- a/server/src/services/native-runtime/task-monitor.integration.test.ts +++ b/server/src/services/native-runtime/task-monitor.integration.test.ts @@ -1,3 +1,5 @@ +import { subscribeDatabaseWork } from "@paperclipai/db"; +import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; import { randomUUID } from "node:crypto"; import { and, eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; @@ -39,6 +41,32 @@ describeEmbeddedPostgres("native task monitors", () => { return { ...binding, binding, authority, monitor, call, read }; } + it("notifies committed monitor changes for another owned task without replay or authorization wakeups", async () => { + const value = await fixture(), targetId = randomUUID(); + await db.insert(issues).values({ id: targetId, companyId: value.companyId, + title: "Another owned monitor", status: "in_review", assigneeAgentId: value.agentId }); + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.issueMonitors, event => { events.push(event); }); + const original = { taskId: targetId, idempotencyKey: "notify-first", monitor: value.monitor }; + try { + await value.call(original); + expect(events).toEqual(["intent", "settled"]); + events.length = 0; + await value.call({ ...original, idempotencyKey: "notify-earlier", + monitor: { ...value.monitor, nextCheckAt: new Date(Date.now() + 30_000).toISOString() } }); + expect(events).toEqual(["intent", "settled"]); + events.length = 0; + await value.call(original); + expect(events).toEqual([]); + await value.call({ taskId: targetId, idempotencyKey: "notify-clear", monitor: null }); + expect(events).toEqual(["intent", "settled"]); + events.length = 0; + await db.update(issues).set({ assigneeAgentId: null }).where(eq(issues.id, targetId)); + await expect(value.call({ ...original, idempotencyKey: "notify-forbidden" })).rejects.toThrow(); + expect(events).toEqual([]); + } finally { unsubscribe(); } + }); + it("advertises a real binding only in standard execution", async () => { const value = await fixture(); expect(value.authority.definitions().some(tool => tool.name === "set_task_monitor")).toBe(true); diff --git a/server/src/services/routines-formatter-cache.test.ts b/server/src/services/routines-formatter-cache.test.ts index daf9064a3f7..8ff9d4b9ac0 100644 --- a/server/src/services/routines-formatter-cache.test.ts +++ b/server/src/services/routines-formatter-cache.test.ts @@ -1,11 +1,43 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { nextCronTickInTimeZone } from "./routines.js"; +import * as cron from "./cron.js"; describe("nextCronTickInTimeZone formatter caching", () => { afterEach(() => { vi.restoreAllMocks(); }); + it("parses a sparse schedule once instead of once per searched minute", () => { + const parse = cron.parseCron; + let parses = 0; + vi.spyOn(cron, "parseCron").mockImplementation(expression => { + parses++; + if (parses > 1) throw new Error("Repeated cron parsing blocks unrelated scheduled work"); + return parse(expression); + }); + const next = nextCronTickInTimeZone("0 12 1 1 *", "UTC", new Date("2020-01-01T12:00:00Z")); + expect(next?.toISOString()).toBe("2021-01-01T12:00:00.000Z"); + expect(parses).toBe(1); + }); + + it("skips impossible UTC dates before localized formatting", () => { + const format = Intl.DateTimeFormat.prototype.formatToParts; + let formats = 0; + vi.spyOn(Intl.DateTimeFormat.prototype, "formatToParts").mockImplementation(function(this: Intl.DateTimeFormat, date) { + formats++; + if (formats > 48) throw new Error("Sparse UTC schedules must skip impossible dates"); + return format.call(this, date); + }); + const next = nextCronTickInTimeZone("0 12 1 1 *", "UTC", new Date("2020-01-01T12:00:00Z")); + expect(next?.toISOString()).toBe("2021-01-01T12:00:00.000Z"); + expect(formats).toBeLessThanOrEqual(48); + }); + + it.each(["UTC", "America/New_York"])("rejects invalid search dates in %s", timeZone => { + expect(() => nextCronTickInTimeZone("0 12 1 1 *", timeZone, new Date(Number.NaN))) + .toThrow(RangeError); + }); + it("computes the next occurrence of a sparse monthly cron correctly", () => { const next = nextCronTickInTimeZone( "30 6 1 * *", diff --git a/server/src/services/routines.ts b/server/src/services/routines.ts index 98bffd4f184..d92bae9560a 100644 --- a/server/src/services/routines.ts +++ b/server/src/services/routines.ts @@ -1,3 +1,4 @@ +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { verifyAppWebhook } from "./app-webhook.js"; import crypto from "node:crypto"; import { verifyFirefliesWebhook } from "./fireflies-webhook.js"; @@ -253,8 +254,13 @@ function getZonedMinuteParts(date: Date, timeZone: string) { }; } -function matchesCronMinute(expression: string, timeZone: string, date: Date) { - const cron = parseCron(expression); +function matchesCronMinute(cron: ReturnType, timeZone: string, date: Date) { + if (timeZone === "UTC" && Number.isFinite(date.getTime()) && ( + !cron.minutes.includes(date.getUTCMinutes()) + || !cron.daysOfMonth.includes(date.getUTCDate()) + || !cron.months.includes(date.getUTCMonth() + 1) + || !cron.daysOfWeek.includes(date.getUTCDay()) + )) return false; const parts = getZonedMinuteParts(date, timeZone); return ( cron.minutes.includes(parts.minute) && @@ -268,16 +274,18 @@ function matchesCronMinute(expression: string, timeZone: string, date: Date) { export function nextCronTickInTimeZone(expression: string, timeZone: string, after: Date) { const trimmed = expression.trim(); assertTimeZone(timeZone); - const error = validateCron(trimmed); - if (error) { - throw unprocessable(error); + let cron: ReturnType; + try { + cron = parseCron(trimmed); + } catch (error) { + throw unprocessable(error instanceof Error ? error.message : String(error)); } const cursor = floorToMinute(after); cursor.setUTCMinutes(cursor.getUTCMinutes() + 1); const limit = 366 * 24 * 60 * 5; for (let i = 0; i < limit; i += 1) { - if (matchesCronMinute(trimmed, timeZone, cursor)) { + if (matchesCronMinute(cron, timeZone, cursor)) { return new Date(cursor.getTime()); } cursor.setUTCMinutes(cursor.getUTCMinutes() + 1); @@ -2230,6 +2238,7 @@ export function routineService( } const createdRoutine = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); const [created] = await txDb .insert(routines) .values({ @@ -2334,6 +2343,7 @@ export function routineService( } const updatedRoutine = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); await tx.execute(sql`select id from ${routines} where ${routines.id} = ${id} for update`); const locked = await txDb .select() @@ -2488,6 +2498,7 @@ export function routineService( const { trigger, revision } = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); await tx.execute(sql`select id from ${routines} where ${routines.id} = ${routine.id} for update`); const [createdTrigger] = await txDb .insert(routineTriggers) @@ -2562,6 +2573,7 @@ export function routineService( const result = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); await tx.execute(sql`select id from ${routines} where ${routines.id} = ${existing.routineId} for update`); const [updated] = await txDb .update(routineTriggers) @@ -2601,6 +2613,7 @@ export function routineService( if (!existing) return { deleted: false, revision: null }; const result = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); await tx.execute(sql`select id from ${routines} where ${routines.id} = ${existing.routineId} for update`); await txDb.delete(routineTriggers).where(eq(routineTriggers.id, id)); const routine = await txDb @@ -2719,6 +2732,7 @@ export function routineService( const result = await db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.routineSchedules); await tx.execute(sql`select id from ${routines} where ${routines.id} = ${existingRoutine.id} for update`); const locked = await txDb .select() diff --git a/server/src/services/scheduled-work.ts b/server/src/services/scheduled-work.ts new file mode 100644 index 00000000000..6f31e2e420a --- /dev/null +++ b/server/src/services/scheduled-work.ts @@ -0,0 +1,46 @@ +import type { Db } from "@paperclipai/db"; +import { sql, type SQL } from "drizzle-orm"; +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, type DeliveryQueue } from "./delivery-work-notifications.js"; + +export function registerScheduledWork( + coordinator: Pick, "register">, + db: Pick, + options: { + retryMs: number; + tickTimers: () => Promise; + tickRoutines: () => Promise; + }, +) { + function register(queue: DeliveryQueue, work: () => Promise, query: (now: Date) => SQL) { + let next: number | null = null; + return coordinator.register(queue, { + retryMs: options.retryMs, + run: async () => { + const cutoff = new Date(); + await work(); + const [row] = await db.execute<{ next_at: Date | string | null }>(query(cutoff)); + if (!row || row.next_at === undefined) throw new Error("Scheduled deadline query returned no result"); + next = row.next_at === null ? null + : row.next_at instanceof Date ? row.next_at.getTime() : Date.parse(row.next_at); + if (next !== null && !Number.isFinite(next)) throw new Error("Scheduled deadline is invalid"); + }, + hasPending: async () => false, + nextRunAt: () => next, + }); + } + + const routines = register(DELIVERY_QUEUES.routineSchedules, options.tickRoutines, now => sql` + SELECT min(t.next_run_at) AS next_at + FROM routine_triggers t JOIN routines r ON r.id = t.routine_id AND r.company_id = t.company_id + JOIN companies c ON c.id = r.company_id + WHERE t.kind = 'schedule' AND t.enabled AND NOT t.archived + AND r.status = 'active' AND c.status = 'active' AND t.next_run_at > ${now.toISOString()}::timestamptz`); + const timers = register(DELIVERY_QUEUES.issueMonitors, options.tickTimers, now => sql` + SELECT min(i.monitor_next_check_at) AS next_at + FROM issues i JOIN companies c ON c.id = i.company_id + WHERE c.status = 'active' AND i.status IN ('in_progress', 'in_review') + AND i.assignee_agent_id IS NOT NULL AND i.assignee_user_id IS NULL + AND i.monitor_next_check_at > ${now.toISOString()}::timestamptz`); + return { routines, timers }; +}