From c1d3f90b3753f91a666ba15599a30c8e6ba5f574 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:28:55 -0600 Subject: [PATCH 1/8] fix(recovery): keep the resolved-dependency probes per task whatever the statistics (#21574) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The `resolved-dependencies` recovery queue loads the blocked tasks whose blockers are all done (#21517). It runs this load on recovery hints. > - The load has two correlated subqueries on `issue_relations`. PostgreSQL turns them into a semi join and an anti join, and lets the statistics choose how. > - After a bulk change in a company that the statistics have not seen (a large import, a restore, a big cleanup), the planner estimates one row for the company. It then picks nested loops whose inner side scans every relation of the company and filters by task id. On a local copy with 5,000 open tasks the query ran for more than 20 seconds (once 19 minutes) until the table was analyzed; after `ANALYZE` it takes 3.7 ms. > - This pull request keeps both subqueries as per-task subplans, so each one is an index probe by (company, task id) whatever the statistics say. > - The benefit is that the load stays proportional to the blocked tasks it reads, also right after bulk changes. This is prevention: the hosted instance does not show this query as slow today. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/bug_report.yml`. **What happened?** On a local database that had been analyzed with a smaller dataset and then loaded with 5,000 open tasks in a new company, the `resolved-dependencies` load query did not finish within 20 seconds; in a benchmark run it stayed active for 19 minutes after its server stopped. **Steps to reproduce** 1. Load a company with about 1,500 tasks and run `ANALYZE issues, issue_relations`. 2. With autovacuum off for these tables, load another company with 5,000 tasks, 1,900 of them blocked with `blocks` relations. 3. Run the load query of `resolved-dependencies` for the new company. Plan with stale statistics (abridged): ``` Limit -> Nested Loop Semi Join (rows=1) Join Filter: (issues.id = r.related_issue_id) -> Nested Loop Anti Join (rows=1) Join Filter: (r_1.related_issue_id = issues.id) -> Index Scan using issues_company_id_uq on issues Index Cond: (company_id = ...) -> Nested Loop -> Index Scan using issue_relations_company_related_issue_idx on issue_relations r_1 Index Cond: (company_id = ...) -> Index Scan using issues_company_id_uq on issues blocker Index Cond: (company_id = ...) -> Index Scan using issue_relations_company_related_issue_idx on issue_relations r Index Cond: (company_id = ...) ``` The index condition holds only `company_id`. The task id is a join filter, so each blocked task rescans every relation (and every task, for the blocker) of the company. **Expected behavior** Each blocked task probes its own relations through `issue_relations_company_related_issue_idx` (company_id, related_issue_id) and its blockers through `issues_company_id_uq` (company_id, id). ## What Changed - `server/src/services/recovery/work.ts`: the candidate predicate is a named export, `resolvedDependencyCandidate`, and both subqueries end with `offset 0`. PostgreSQL does not pull a subquery with `OFFSET` up into a join, so it stays a correlated subplan. Its index condition then includes the outer task id. The predicate and its results are otherwise unchanged. - `server/src/__tests__/resolved-dependency-candidates.test.ts`: two tests. Indexes that the subplans use (all existing): `issue_relations_company_related_issue_idx` (company_id, related_issue_id) for both relation probes, and `issues_company_id_uq` (company_id, id) for the blocker status. `issue_relations_company_issue_idx` (company_id, issue_id) is not needed here. ## Verification - `selects the same tasks as the earlier predicate`: 40 blocked tasks with a done blocker, an open blocker, a done and a cancelled blocker, or no blocker. The new predicate returns the same 10 tasks as the earlier one. - `probes the relations of each task, whatever the planner statistics say`: analyzes a small company, then loads 3,000 blocked tasks in a new company. The plan (`EXPLAIN (FORMAT JSON)`) has two subplans and no semi or anti join, and the load returns 100 rows within a 5-second statement timeout. I saw it fail first with the earlier predicate: the plan had a semi join and an anti join. - Local plan on the stale database: EXPLAIN ANALYZE shows `SubPlan 1` and `SubPlan 2` with `Index Cond: ((company_id = issues.company_id) AND (related_issue_id = issues.id))`, 1,933 probes each, 4.9 ms. - `issue-recovery-deadlines.test.ts` and `issue-recovery-dependencies.test.ts` pass (14 tests). `pnpm check:module-boundaries` passes. ## Risks - With fresh statistics the planner could use a merge or hash join for a large page; the subplan form gives up that choice. Each blocked task now costs two index probes, which is the same order as the fresh-statistics plan (3.7 ms before, 4.9 ms after on 1,933 blocked tasks, measured once each on a loaded machine). - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../resolved-dependency-candidates.test.ts | 62 +++++++++++++++++++ server/src/services/recovery/work.ts | 14 +++-- 2 files changed, 70 insertions(+), 6 deletions(-) create mode 100644 server/src/__tests__/resolved-dependency-candidates.test.ts diff --git a/server/src/__tests__/resolved-dependency-candidates.test.ts b/server/src/__tests__/resolved-dependency-candidates.test.ts new file mode 100644 index 00000000000..f133fab36fc --- /dev/null +++ b/server/src/__tests__/resolved-dependency-candidates.test.ts @@ -0,0 +1,62 @@ +import { and, eq, inArray, sql } from "drizzle-orm"; +import { expect, it } from "vitest"; +import { issueRelations, issues } from "@paperclipai/db"; +import { resolvedDependencyCandidate } from "../services/recovery/work.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +const earlierPredicate = sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId} + and r.related_issue_id = ${issues.id} and r.type = 'blocks') + and not exists (select 1 from ${issueRelations} r inner join ${issues} blocker + on blocker.id = r.issue_id and blocker.company_id = r.company_id + where r.company_id = ${issues.companyId} and r.related_issue_id = ${issues.id} + and r.type = 'blocks' and blocker.status <> 'done')`; + +describeIssueRecovery("resolved dependency candidates", () => { + const state = issueRecoveryFixture(); + async function blockedGraph(companyId: string, agentId: string, count: number) { + const blockers = await state.db.insert(issues).values([ + { companyId, title: "Open blocker", status: "in_progress", assigneeAgentId: agentId }, + { companyId, title: "Done blocker", status: "done" }, + { companyId, title: "Cancelled blocker", status: "cancelled" }, + ]).returning({ id: issues.id }); + const blocked = await state.db.insert(issues).values(Array.from({ length: count }, (_, index) => ({ + companyId, title: `Blocked ${index}`, status: "blocked", assigneeAgentId: agentId, + }))).returning({ id: issues.id }); + const relations = blocked.flatMap((row, index) => { + const shape = index % 4; + if (shape === 0) return [{ blocker: 1, row }]; + if (shape === 1) return [{ blocker: 0, row }]; + if (shape === 2) return [{ blocker: 1, row }, { blocker: 2, row }]; + return []; + }).map(({ blocker, row }) => ({ companyId, issueId: blockers[blocker].id, relatedIssueId: row.id, type: "blocks" as const })); + for (let index = 0; index < relations.length; index += 500) await state.db.insert(issueRelations).values(relations.slice(index, index + 500)); + } + const candidates = (companyId: string, predicate: ReturnType) => state.db.select({ id: issues.id }).from(issues) + .where(and(eq(issues.companyId, companyId), inArray(issues.status, ["blocked"]), predicate)).orderBy(issues.id); + it("selects the same tasks as the earlier predicate", async () => { + const f = await state.fixture(); + await blockedGraph(f.companyId, f.agentId, 40); + const current = await candidates(f.companyId, resolvedDependencyCandidate); + expect(current).toEqual(await candidates(f.companyId, earlierPredicate)); + expect(current).toHaveLength(10); + }); + it("probes the relations of each task, whatever the planner statistics say", async () => { + const small = await state.fixture(); + await blockedGraph(small.companyId, small.agentId, 8); + await state.db.execute(sql`analyze issues`); + await state.db.execute(sql`analyze issue_relations`); + const large = await state.fixture(); + await blockedGraph(large.companyId, large.agentId, 3000); + const query = candidates(large.companyId, resolvedDependencyCandidate).limit(100).toSQL(); + const [{ "QUERY PLAN": plan }] = await state.db.$client.unsafe(`explain (format json) ${query.sql}`, query.params as never[]) as Array<{ "QUERY PLAN": unknown }>; + const text = JSON.stringify(plan); + expect(text).not.toMatch(/"Join Type":"(Semi|Anti)"/); + expect(text.match(/"Subplan Name"/g)).toHaveLength(2); + const rows = await state.db.transaction(async tx => { + await tx.execute(sql`set local statement_timeout = '5s'`); + return tx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, large.companyId), + inArray(issues.status, ["blocked"]), resolvedDependencyCandidate)).limit(100); + }); + expect(rows).toHaveLength(100); + }); +}); diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index 5aa16dfc9f6..00f3dbd0eb4 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -11,6 +11,13 @@ type Entry = { id: string; companyId: string; dueAt: number }; type Scope = { companyId: string; issueId: string; onDeferredDeadline: (at: number) => void }; const PAGE_SIZE = 100; +export const resolvedDependencyCandidate = sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId} + and r.related_issue_id = ${issues.id} and r.type = 'blocks' offset 0) + and not exists (select 1 from ${issueRelations} r inner join ${issues} blocker + on blocker.id = r.issue_id and blocker.company_id = r.company_id + where r.company_id = ${issues.companyId} and r.related_issue_id = ${issues.id} + and r.type = 'blocks' and blocker.status <> 'done' offset 0)`; + export function registerIssueRecoveryWork( db: Db, coordinator: ReturnType, @@ -155,12 +162,7 @@ export function registerIssueRecoveryWork( const dependencies = register(DELIVERY_QUEUES.resolvedDependencies, ["blocked"], async scope => { const result = await owner.dependencies(scope); if (result.enqueueFailed > 0) throw new Error("Resolved dependency wake remains undelivered"); - }, sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId} - and r.related_issue_id = ${issues.id} and r.type = 'blocks') - and not exists (select 1 from ${issueRelations} r inner join ${issues} blocker - on blocker.id = r.issue_id and blocker.company_id = r.company_id - where r.company_id = ${issues.companyId} and r.related_issue_id = ${issues.id} - and r.type = 'blocks' and blocker.status <> 'done')`); + }, resolvedDependencyCandidate); const locks = register(DELIVERY_QUEUES.staleIssueLocks, null, owner.locks); const assignedWork = owner.assignedWork ? registerAssignedWork(owner.assignedWork) : null; const watchdogs = registerTaskWatchdogWork(db, coordinator, { From 340157d1d6ec01ad0fa55970e148c6cd332bbcb1 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:29:22 -0600 Subject: [PATCH 2/8] perf(recovery): scope run lifecycle recovery hints to the run's task graph (#21552) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server runs issue recovery queues in the background. Two of them, `stranded-assignments` and `assigned-work-invariant`, find assigned tasks that have no live run and restart them. > - Every run dispatch and every run state change sent a recovery hint for the whole company. On each hint these queues reload every eligible open task of the company and check each one again, at most every 30 seconds per queue. > - With live runs the hint comes all the time, so the queues never stop. Their cost is (run activity) x (open-task backlog). On a hosted instance with about 1,400 open tasks and 5 live runs, the server main thread stayed at 87-92% of a core. > - A run event can only change the tasks of its own task graph. This pull request makes run and task producers name that graph, and keeps one slow full pass as a backstop. > - The benefit is that a run event costs a few checks, whatever the size of the backlog, and a missed hint still delays recovery by at most five minutes. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** The issue recovery queues in `server/src/services/recovery/work.ts` (`stranded-assignments`, `assigned-work-invariant`, `resolved-dependencies`, `stale-issue-locks`) and the producers that wake them on run dispatch, run start, run state change, run finalization and accounting settlement. **Subsystem affected** Server background recovery (`server/src/services/recovery/`, `server/src/services/scoped-deadline-work.ts`, the notification helpers in `server/src/services/*-notifications.ts`). **Current behavior** `notifyRunDispatch`, `notifyNativeStatusReassessment` and `notifyExternalConversationSettlement` sent `notifyIssueRecovery(tx, { companyId })`. Most run lifecycle paths call one of them, often two or three in the same transaction (for example `notifyIssueReviewState`). Some other run paths sent the company hint directly: the wake status update, the execution-control deadline writes, legacy run terminalization, scheduled retries, accounting settlement, task checkout and task document writes. Each company hint makes each task queue reload all eligible open tasks of the company, 100 per page, and check each task again. A company hint is reconstructed at most every 30 seconds per queue, so one run event per 30 seconds is enough to keep a full pass running all the time. `issue-recovery-deadlines.test.ts` pinned this: a company hint re-checks every eligible task. **Proposed behavior** Design. For each task queue, a run event of run R on task T can change: | Queue | What the check reads | What one run event can change | | --- | --- | --- | | `stranded-assignments` | T's own runs, wakes, handoffs, questions, recovery actions, goal, assignee eligibility | T (its runs). The parent of T and the tasks T blocks when the event also writes T's status. | | `assigned-work-invariant` | the same plus open blockers and open children | T, the parent of T (open children), the tasks T blocks (open blockers) | | `resolved-dependencies` | blocked tasks whose blockers are all done | the tasks T blocks | | `stale-issue-locks` | tasks whose checkout or execution run is R | T | The assignee's agent status (`running`, `idle`, `error`) does not change whether the agent is invokable (`packages/shared/src/agent-eligibility.ts`), and a freed concurrency slot starts the agent's next queued run through the `queued-run-dispatch` queue, which keeps its company hint. So the agent's other tasks are not in the set. - `notifyIssueGraphRecovery(tx, { companyId, runId?, issueId? })` sends `{ companyId, graphRunId?, graphIssueId? }` to the four task queues. It runs no query in the producer transaction. - When a task queue loads that hint, it resolves the graph with one bounded, indexed query (`resolveIssueGraph`): the task of the run (`issue_id`, `native_issue_id`, or the saved `issueId`/`taskId`, validated and cast so the primary key is used), its parent, and the tasks it blocks. The four queues share the result for 2 seconds. With no task or more than 100 tasks, the queue turns the hint into the plain company hint, so task-less runs coalesce under its 30-second gate instead of each starting its own full pass. The lookup runs after commit, so it sees the written state. Graph hints do not wait for the 30-second reconstruction gate (they load at most 100 tasks); hints for the same run coalesce while dirty, and the lookup is shared across the four queues, so it runs about once per pass instead of once per producer call. An earlier round ran the lookup in every producer transaction: 34 lookups/s at 1,500 open tasks and 70/s at 5,000. - The three company-level queues (`orphan-blockers`, `active-recovery-actions`, `task-watchdogs`) keep the company hint. They hold one entry per company or per watchdog, not per open task. - `notifyRunDispatch`, `notifyScheduledRetryDispatch`, `notifyNativeStatusReassessment` and `notifyExternalConversationSettlement` use it when the scope names a run or a task. A scope with only a company keeps the company hint. - Run paths that knew the run or the task but sent only the company now pass it. This includes three `writeExecutionControl` deadline writes, legacy run terminalization (`notifyExecutionRunWork`) and native safe replacement. Those helpers also forward the scope to `notifyLiveRunRecovery` and `notifyLiveResourceRecovery`, so their hints to the live-run queues now carry the run id. - Recovery action changes (`issue-recovery-actions.ts`: create, supersede, update, exhaust, resolve) name their source task. A recovery action is a fact of its source task for these queues. The company-level `active-recovery-actions` queue still gets the company hint. In the fixture, failing runs create and resolve recovery actions every few seconds, and that alone kept a full pass running. - `writeExecutionControl` and `notifyExecutionRunWork` send the attention retention hint for a task through `notifyIssueAttentionRetentionWork` (the task, its parents and the tasks it blocks), a superset of the single-task hint they sent before. A recovery action of a blocker can change the blocker attention of its dependents, so the narrower recovery action scope needs this. - `promoteDeferredWorkIntents` scopes `lock_released` with a task to that task, and `accounting_settled` to the run when the company has no active hard-stop budget policy. Only a reached hard stop can refuse work because of accounting (`evaluateAdmissionInTransaction`), so without such a policy the settlement of one run cannot admit another task. The other hold releases keep the company hint. Backstop. Each scoped hint also sends `{ companyId, backstop: true }` to the same four queues. Nothing else arms it. The queue runs it as a full company pass, but not before 5 minutes after the last full pass of that queue for that company or of the startup pass. It is a scheduler deadline (`nextWakeAt` reports it), but it holds no idle intent and does not mark the queue unreconciled. So: - Startup still reconstructs every company. - A failed scoped load retries with the existing back-off (30 seconds to 5 minutes). The backstop is pending in any case. - A graph with no task or more than 100 tasks loads the whole company at once. - A task that a scoped hint missed is checked at most `ISSUE_RECOVERY_BACKSTOP_MS` (5 minutes) after the event. While runs continue, each queue runs at most one full pass per company per 5 minutes. With no activity, nothing is scheduled. Why arming on activity only cannot leave a stranded task undetected when the instance then goes quiet. A task becomes stranded only through a write or through a run that stops without a write: 1. The write names the task's graph (run and task producers). The scoped pass checks the task at once. 2. The write sends a company hint (pause, budget, agent and company configuration, tree holds, the producers listed below). The company pass checks it within the 30-second gate, as before. 3. The write is a run event whose graph does not contain the task. That same event armed the backstop. The backstop deadline stays scheduled while the instance is quiet and checks the task at most 5 minutes later. 4. A run stops without any write (process lost, controller gone). The existing deadline paths find it: `stale-issue-locks` waits for the stored controller lease, and `active-run-silence` and `orphan-active-leases` act on their own deadlines. Each of them terminalizes the run, which is a run write and falls under 1 or 3. The new test `restarts a task whose run vanished without a final event once its lease lapses` covers this with the production backstop. 5. The process restarts or a quiet instance is woken by a restart. The startup pass reconstructs every company. 6. A check that found a task waiting (grace, back-off, monitor) returns its own deadline. That entry keeps its deadline whatever hints arrive. Five minutes is the existing upper bound of recovery back-off in this area: the maximum retry delay of a failed scoped-deadline check (`scoped-deadline-work.ts`), and `DEFERRED_WAKE_PENDING_BOUND_MS`, the time `assigned-work-sweep.ts` already trusts a deferred wake before it calls a task stranded. Producers that keep the company hint, and why. They can change eligibility of tasks outside one task graph, or I could not show that their effect stays in the graph. None of them fires once per run event in the fixture. - Eligibility for many tasks: company status (`companies.ts`), budgets (`budgets.ts`), agent lifecycle and configuration (`agent-lifecycle.ts`, `agent-configuration.ts`), instance settings (`instance-settings.ts`, `*`), tree holds (`issue-tree-control.ts`), company deletion and import (`company-deletion.ts`, `company-portability.ts`), and the hold releases `pause_lifted`, `tree_hold_released`, `scheduling_resumed` and `reconciler_backstop`. `accounting_settled` also keeps it when the company has an active hard-stop budget policy. - Task writes that can move a task between graphs or change eligibility: task creation and a task update that changes the parent in `issues.ts` (other task updates and checkout releases now name the task), document delete and restore paths in `documents.ts`, task watchdogs (`task-watchdogs.ts`), system and workspace recovery (`system-recovery.ts`, `task-retry.ts`, `workspace-recovery-capture-policy.ts`, `workspace-recovery-stop-proof.ts`). - Conversation and chat paths: `agent-conversations.ts`, the daily-cap release in `heartbeat/queue.ts`, the Telegram attachment failure, `chat-attachment-reuse.ts`, `native-runner-file-handoff.ts`, `notifyChatRunMilestones` without a task or run (company authority change), and `notifyNativeStatusReassessment` from `access.ts`. - `writeExecutionControl` and `notifyExecutionRunWork` callers that pass only a company. **Reason and benefit** Background work must not grow with the backlog of open tasks. The checks a run event causes now depend on its task graph, not on the company. ## What Changed - `server/src/services/issue-recovery-notifications.ts`: `notifyIssueGraphRecovery`, `resolveIssueGraph`, the scope matcher and decoder, `ISSUE_RECOVERY_MAX_ISSUE_IDS` (100) and `ISSUE_RECOVERY_BACKSTOP_MS` (5 minutes). - `server/src/services/recovery/work.ts`: the task queues resolve a graph hint when they load it (shared for 2 seconds), remember the last full pass per company, and gate the backstop hint on it. `registerIssueRecoveryWork` takes an optional `backstopMs`. - `server/src/services/recovery/assigned-work-sweep.ts`: `listSuspects` accepts `issueIds`. - `server/src/services/scoped-deadline-work.ts`: an optional `backstop(scope)` that returns the earliest time of a backstop hint. A pending backstop hint keeps its deadline but does not count as pending work or as unreconciled. - Producers: `issue-recovery-actions.ts`, `execution-control-notifications.ts`, `run-dispatch-notifications.ts`, `native-status-reassessment-notifications.ts`, `external-conversation-settlement-notifications.ts`, `work-intent-outbox.ts`, `run-cost-accounting.ts`, `heartbeat/run-lifecycle.ts`, `heartbeat/runtime-execution.ts`, `heartbeat/retries.ts`, `heartbeat.ts`, `legacy-execution-recovery.ts`, `issues.ts` (checkout), `documents.ts` (task document writes), `modules/wake-queue/adapters/postgres.ts` (recovery runs for a task), `heartbeat/queue.ts` (wake enqueue), `recovery/service.ts`, `native-runtime/native-provider-capacity-retry.ts`, `native-runtime/native-safe-replacement.ts`, `modules/run-dispatch/adapters/workspace-busy-wait.ts` (scheduled retries). - `bounds subsidiary scans for100 assignment candidates`: a resolved recovery action now adds one scoped load per task queue (bound 8 to 11), and the coalescing check sends one company hint before the burst of 100, because the first full pass after the resolve is now a backstop pass with its own key. - `checks only blocked tasks whose blockers are done`: uses the shared recording harness and runs out the backstop before its quiet check, because the blocker's status change is now a graph hint (its 300 dependents overflow to a company load). - Tests. `issue-recovery.test-fixture.ts` and `live-recovery-work.test.ts` register the queues with `backstopMs: 0`, so their quiet checks keep the earlier timing. The new tests use the production value. ## Verification New tests. I saw each red test fail before the change. - `issue-recovery-deadlines.test.ts` `re-checks only the tasks a run lifecycle event can affect, whatever the backlog` (red before): a run of the agent on a task with a parent and a dependent, 1,000 backlog tasks of another agent, and a second open task of the same agent. Seven real producers (`notifyNativeStatusReassessment`, `notifyExecutionRunWork`, `notifyRunDispatch`, `promoteDeferredWorkIntents` lock release and accounting settlement, recovery action create and resolve) check exactly the 3 tasks of the graph. The recovery action steps were red before the third commit. With 4,000 more backlog tasks the event issues the same number of statements. Before the change it checked 1,004 tasks. - `resolves a run's task graph through index lookups, not the backlog` (red before the second commit, from a Greptile finding): with 2,000 backlog tasks the graph lookup read 2,005 issue rows (`pg_stat_xact_user_tables`) because it compared `id::text`. It now validates and casts the saved id, reads fewer than 50 rows, and returns exactly the run's graph. - `finds a stranded task outside the affected set within the backstop bound` (red before): a task inserted without a hint is not checked by the run event, and is checked at most 5 minutes after the last full pass. After 20 quiet minutes, a run event checks a new unrelated task within 5 seconds, because the last full pass is older than 5 minutes. Then the queues are quiet. - `keeps the company pass for hold releases that can admit any task` (guard, passes before and after): accounting settlement with a hard-stop policy and a lifted pause still check every task. - `falls back to the company pass when a run affects more tasks than a hint names` (guard): a run task that blocks 100 more tasks checks the whole company. - `limits an ordinary comment to its issue among one thousand open assignments`: the old final assertion (a company hint checks all 1,000 tasks) stays, and the test now also runs out the backstop and ends quiet. - `issue-recovery-assignments.test.ts`, real heartbeat, real producers, production backstop (guards; they also pass with the old company hint): a task whose run failed, a task whose run the system cancelled, a run that vanished without a final event and is found when its controller lease lapses, and an agent's queued task that starts when its previous run ends. Each one recovers within 15 seconds, well before the backstop. - `scoped-deadline-work.test.ts` `keeps a backstop hint's deadline without holding the worker busy` (red before). Suites, each file alone, in `server/` (issue recovery, live recovery, recovery action and attention suites against dedicated local `_test` databases): `issue-recovery-deadlines` (13/13), `issue-recovery-assignments` (7/7), `issue-recovery-work-lifecycle` (14/14), `scoped-deadline-work` (24/24), `live-recovery-work` (51/51), `assigned-work-invariant` (32/32), `assigned-work-sweep-round-trips` (2/2), `saved-work-recovery-overdue` (4/4), `issue-recovery-dependencies` (5/5), `issue-recovery-conversations` (3/3), `issue-recovery-actions` (112/112), `attention-retention-work` (55/55). `recovery-deadline-acceptance` skips without its external database. `pnpm check:module-boundaries` passes. Local benchmark. The real server ran against PostgreSQL with `log_statement=all` and instrumented counters (not committed). Fixture: 1 company, 60 agents, open tasks at 150 / 1,500 / 5,000 (52% in review, 39% blocked behind open blockers, 3% in progress, 2% to do), with process agents that fail at once so recovery re-dispatches runs all the time. The tables are analyzed after loading. Each window is 180 s, starting 150 s after the server is ready, so each "after" window contains one backstop pass. Base is `master` at 54c3616ad9; after is this branch at dcd170e29f. The last commit (graph hints without the 30-second gate, task updates and checkout releases scoped) is covered by the tests below but not re-measured. The machine was shared (load average 9-16, one base window at 45). Run churn differs between runs, so the table gives counts per run event (runs created in the window). | Open tasks | Runs created (/s) base → after | Stranded checks per run base → after | Assigned-work checks per run base → after | `agent_task_sessions` reads (/s, 4 shapes, stranded check) | Statements per run event base → after | | --- | --- | --- | --- | --- | --- | | 150 | 0.08 → 0.14 | 45.1 → 6.2 | 2.00 → 0.96 | 3.75 → 1.27 | 2,260 → 1,257 | | 1,500 | 1.09 → 1.00 | 22.0 → 3.9 | 1.24 → 1.53 | 26.5 → 7.2 | 1,313 → 1,060 | | 5,000 | 1.12 → 1.99 | 20.4 → 1.6 | 4.10 → 0.91 | 29.3 → 8.1 | 1,400 → 829 | New statements: the task graph lookup (`with seed(id) ...`) at 0.8 / 9.3 / 18.5 per second, and scoped loads of the task queues (`select "id", "company_id" from "issues" ...` grew from 0.7 / 6.6 / 7.8 to 2.9 / 20.6 / 34.4 per second, each a lookup of at most 100 ids). Stale-lock checks grew from 0 / 50 / 52 to 22 / 190 / 445 per window: each run event now checks the locks of its own task at once instead of waiting for the next full pass. In an earlier round the graph lookup ran in every producer transaction: 34/s at 1,500 and 70/s at 5,000. With no activity the server issues no statements before and after this change (quiet checks in `issue-recovery-deadlines`, `issue-recovery-assignments`, `live-recovery-work`). ## Risks - A task outside the graph of the run whose state the event changes is now found by the backstop, at most 5 minutes later, instead of within 30 seconds. One known case: from #21427, `assigned-work-invariant` counts a held recovery wake as pending while its agent has queued recovery runs. When the last one starts, the continuation queue delivers the held wake; the invariant check of that task waits for the backstop. - A producer that names a task but changes something wider would now miss the wider effect. Producers that change eligibility for many tasks (pause, budget, agent and company configuration, tree holds) still send the company hint. - The graph is resolved after commit, from the written state. A parent change is not a run event and keeps its company hint. - The live-recovery and issue-recovery suites opt out of the backstop deadline with `backstopMs: 0`. - The execution-control deadline writes and legacy run terminalization now pass the run id. `writeExecutionControl` also forwards that scope to the live-run queues (`active-run-silence`, `native-process-sessions` and others), so those hints now name the run instead of the company. Those queues already handle run-scoped hints from native finalization. - Test-only option: `registerIssueRecoveryWork(..., { backstopMs })`. The shared recovery fixtures pass `0` so their quiet checks keep the earlier timing; the new tests use the production value. - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../issue-recovery-assignments.test.ts | 58 ++++- .../issue-recovery-deadlines.test.ts | 227 ++++++++++++++---- .../__tests__/issue-recovery.test-fixture.ts | 11 +- .../src/__tests__/live-recovery-work.test.ts | 2 +- .../__tests__/scoped-deadline-work.test.ts | 24 ++ .../adapters/workspace-busy-wait.ts | 2 +- .../modules/wake-queue/adapters/postgres.ts | 4 +- server/src/services/documents.ts | 8 +- .../execution-control-notifications.ts | 11 +- ...l-conversation-settlement-notifications.ts | 5 +- server/src/services/heartbeat.ts | 7 +- server/src/services/heartbeat/queue.ts | 2 +- server/src/services/heartbeat/retries.ts | 4 +- .../src/services/heartbeat/run-lifecycle.ts | 10 +- .../services/heartbeat/runtime-execution.ts | 4 +- server/src/services/issue-recovery-actions.ts | 22 +- .../services/issue-recovery-notifications.ts | 61 ++++- server/src/services/issues.ts | 9 +- .../src/services/legacy-execution-recovery.ts | 2 +- .../native-provider-capacity-retry.ts | 2 +- .../native-runtime/native-safe-replacement.ts | 4 +- ...ative-status-reassessment-notifications.ts | 4 +- .../services/recovery/assigned-work-sweep.ts | 4 +- server/src/services/recovery/service.ts | 4 +- server/src/services/recovery/work.ts | 75 +++++- server/src/services/run-cost-accounting.ts | 12 +- .../services/run-dispatch-notifications.ts | 7 +- server/src/services/scoped-deadline-work.ts | 17 +- .../services/slack-conversation-lifecycle.ts | 2 +- server/src/services/work-intent-outbox.ts | 13 +- 30 files changed, 478 insertions(+), 139 deletions(-) diff --git a/server/src/__tests__/issue-recovery-assignments.test.ts b/server/src/__tests__/issue-recovery-assignments.test.ts index e91b0b5adfe..9f6544d824a 100644 --- a/server/src/__tests__/issue-recovery-assignments.test.ts +++ b/server/src/__tests__/issue-recovery-assignments.test.ts @@ -1,7 +1,10 @@ -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { expect, it, vi } from "vitest"; -import { heartbeatRuns, issues } from "@paperclipai/db"; +import { randomUUID } from "node:crypto"; +import { heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db"; import { issueService } from "../services/issues.js"; +import { notifyExecutionRunWork } from "../services/execution-control-notifications.js"; +import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js"; import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; describeIssueRecovery("issue recovery production producers and assignments", () => { @@ -51,4 +54,55 @@ describeIssueRecovery("issue recovery production producers and assignments", () await completed(issue.id); await finish(issue.id); await quiet(); }, 90_000); + async function scopedStart() { + const f = await fixture(); await start({}); await settled({ backstopPending: true }); + const task = async (status: "todo" | "in_progress" | "done") => (await state.db.insert(issues).values({ companyId: f.companyId, + title: `Task ${status}`, status, assigneeAgentId: f.agentId }).returning())[0]; + const run = async (issueId: string, values: Partial) => (await state.db.insert(heartbeatRuns) + .values({ companyId: f.companyId, agentId: f.agentId, contextSnapshot: { issueId }, ...values }).returning())[0]; + return { f, task, run }; + } + async function recovered(issueId: string, sourceRunId: string) { + await vi.waitFor(async () => { + const runs = await state.db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`); + const actions = await state.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId)); + expect(runs.filter(row => row.id !== sourceRunId).length + actions.length).toBeGreaterThan(0); + }, { timeout: 15_000 }); + } + it("restarts a task whose run failed from that run's own hint", async () => { + const { f, task, run } = await scopedStart(); + const issue = await task("in_progress"); + const failed = await run(issue.id, { status: "failed", errorCode: "adapter_failed", finishedAt: new Date() }); + await state.db.transaction(tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId: failed.id, agentId: f.agentId })); + await recovered(issue.id, failed.id); await finish(issue.id); + }, 90_000); + it("starts the agent's queued task when its run ends and frees the agent", async () => { + const { f, task, run } = await scopedStart(); + const previous = await task("done"); + const ended = await run(previous.id, { status: "succeeded", finishedAt: new Date() }); + const next = await task("todo"); + await run(next.id, { status: "queued", invocationSource: "assignment", triggerDetail: "system" }); + await state.db.transaction(tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId: ended.id, agentId: f.agentId })); + await completed(next.id); await finish(next.id); + }, 90_000); + it("restarts a task whose run the system cancelled", async () => { + const { f, task, run } = await scopedStart(); + const issue = await task("in_progress"); + const cancelled = await run(issue.id, { status: "cancelled", finishedAt: new Date() }); + await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: cancelled.id })); + await recovered(issue.id, cancelled.id); await finish(issue.id); + }, 90_000); + it("restarts a task whose run vanished without a final event once its lease lapses", async () => { + const f = await fixture(); + const [issue] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Lost run", status: "in_progress", + assigneeAgentId: f.agentId }).returning(); + const [lost] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + runtimeMode: "legacy", controllerBootId: randomUUID(), controllerLeaseExpiresAt: new Date(Date.now() + 5_000), + contextSnapshot: { issueId: issue.id }, processPid: 2_000_000_000, startedAt: new Date() }).returning(); + await state.db.update(issues).set({ executionRunId: lost.id, checkoutRunId: lost.id }).where(eq(issues.id, issue.id)); + await start({}); + await recovered(issue.id, lost.id); + expect((await state.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, lost.id)))[0].status).not.toBe("running"); + await finish(issue.id); + }, 90_000); }); diff --git a/server/src/__tests__/issue-recovery-deadlines.test.ts b/server/src/__tests__/issue-recovery-deadlines.test.ts index 0908b997296..f87ab9e9564 100644 --- a/server/src/__tests__/issue-recovery-deadlines.test.ts +++ b/server/src/__tests__/issue-recovery-deadlines.test.ts @@ -3,12 +3,18 @@ import { idleWorkSnapshot } from "../services/task-admission.js"; import { randomUUID } from "node:crypto"; import { and, eq, sql } from "drizzle-orm"; import { expect, it, vi } from "vitest"; -import { agents, heartbeatRuns, issueRecoveryActions, issueRelations, issues, issueWatchdogs } from "@paperclipai/db"; +import { agents, budgetPolicies, heartbeatRuns, issueRecoveryActions, issueRelations, issues, issueWatchdogs } from "@paperclipai/db"; import { heartbeatService } from "../services/heartbeat.js"; import { issueService } from "../services/issues.js"; import { issueRecoveryActionService } from "../services/issue-recovery-actions.js"; import { registerIssueRecoveryWork } from "../services/recovery/work.js"; -import { notifyIssueRecovery } from "../services/issue-recovery-notifications.js"; +import { recoveryService } from "../services/recovery/service.js"; +import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_MAX_ISSUE_IDS, notifyIssueRecovery, resolveIssueGraph } + from "../services/issue-recovery-notifications.js"; +import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js"; +import { notifyExecutionRunWork } from "../services/execution-control-notifications.js"; +import { notifyRunDispatch } from "../services/run-dispatch-notifications.js"; +import { promoteDeferredWorkIntents } from "../services/work-intent-outbox.js"; import { taskWatchdogService } from "../services/task-watchdogs.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; @@ -49,11 +55,12 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => return query; }) as typeof state.db.select); await start(); await settled(); - expect(scans.actions).toBe(1); expect(scans.blockers).toBe(0); expect(scans.loads).toBeLessThanOrEqual(8); + expect(scans.actions).toBe(1); expect(scans.blockers).toBe(0); expect(scans.loads).toBeLessThanOrEqual(11); expect((await originalSelect().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id)))[0].status).toBe("resolved"); const [foreignSource] = await state.db.insert(issues).values({ companyId: foreign.companyId, title: "Foreign done", status: "done" }).returning(); const [foreignAction] = await state.db.insert(issueRecoveryActions).values({ companyId: foreign.companyId, sourceIssueId: foreignSource.id, kind: "stranded_assigned_issue", ownerType: "board", cause: "stranded_assigned_issue", fingerprint: "foreign-query-budget", nextAction: "Inspect" }).returning(); + await state.db.transaction(tx => notifyIssueRecovery(tx, { companyId: f.companyId })); await settled(); const before = { ...scans }; for (let index = 0; index < 100; index++) await state.db.transaction(tx => notifyIssueRecovery(tx, { companyId: f.companyId })); await new Promise(resolve => setTimeout(resolve, 100)); @@ -64,12 +71,8 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => expect((await originalSelect().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, foreignAction.id)))[0].status).toBe("active"); expect(await originalSelect().from(heartbeatRuns)).toHaveLength(0); await quiet(); }); - it("limits an ordinary comment to its issue among one thousand open assignments", async () => { - const f = await fixture(); - const rows = await state.db.insert(issues).values(Array.from({ length: 1000 }, (_, index) => ({ - companyId: f.companyId, title: `Open work ${index}`, status: "todo", assigneeAgentId: f.agentId, - }))).returning({ id: issues.id }); - const checked: string[] = []; + async function recordedRecovery(owner: Partial[2]>, + options?: Parameters[4]) { vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); state.coordinator = createDeliveryWorkCoordinator({ owner: state.db, canRun: () => true, onError: error => state.errors.push(error) }); const register = state.coordinator.register.bind(state.coordinator); @@ -78,38 +81,181 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => void pass.then(() => state.passes.delete(pass), () => state.passes.delete(pass)); return pass; } }); - // Observe the actual paged reconstruction boundary without executing one - // thousand adapters. The producer, transaction, coordinator and SQL are real; - // the other acceptance cases exercise the resulting recovery decisions. state.worker = registerIssueRecoveryWork(state.db, state.coordinator, { - stranded: async scope => { checked.push(scope.issueId); }, - orphanBlockers: async () => {}, recoveryActions: async () => {}, + stranded: async () => {}, orphanBlockers: async () => {}, recoveryActions: async () => {}, dependencies: async () => ({ enqueueFailed: 0 }), locks: async () => {}, - watchdogs: async () => ({ incomplete: 0 }), schedulingSuppressed: async () => false, - }, () => true); + watchdogs: async () => ({ incomplete: 0 }), schedulingSuppressed: async () => false, ...owner, + }, () => true, options); await state.worker.ready; - async function settleWork() { - for (let step = 0; step < 120; step++) { - await vi.advanceTimersByTimeAsync(1000); - await Promise.allSettled([...state.passes]); await immediate(); - if (state.coordinator.nextWakeAt() === null && idleWorkSnapshot().active === 0) return; - } - throw new Error("Recovery did not settle its committed work within two virtual minutes"); + } + async function settleWork(options: { backstopPending?: boolean } = {}) { + for (let step = 0; step < 120; step++) { + await vi.advanceTimersByTimeAsync(1000); + await Promise.allSettled([...state.passes]); await immediate(); + const next = state.coordinator.nextWakeAt(); + const settledNow = next === null || (options.backstopPending === true && next > Date.now() + 60_000); + if (settledNow && idleWorkSnapshot().active === 0) return; } + throw new Error("Recovery did not settle its committed work within two virtual minutes"); + } + async function runGraph(companyId: string, agentId: string) { + const [other] = await state.db.insert(agents).values({ companyId, name: "Other agent", role: "engineer", status: "idle", + adapterType: "process", adapterConfig: {} }).returning({ id: agents.id }); + const [parent] = await state.db.insert(issues).values({ companyId, title: "Parent", status: "in_progress", assigneeAgentId: agentId }) + .returning({ id: issues.id }); + const [task] = await state.db.insert(issues).values({ companyId, title: "Run task", status: "in_progress", assigneeAgentId: agentId, + parentId: parent.id }).returning({ id: issues.id }); + const [dependent] = await state.db.insert(issues).values({ companyId, title: "Waits on the run task", status: "todo", + assigneeAgentId: other.id }).returning({ id: issues.id }); + const [sibling] = await state.db.insert(issues).values({ companyId, title: "Next task of the agent", status: "todo", + assigneeAgentId: agentId }).returning({ id: issues.id }); + await state.db.insert(issueRelations).values({ companyId, issueId: task.id, relatedIssueId: dependent.id, type: "blocks" }); + const [run] = await state.db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", finishedAt: new Date(), + contextSnapshot: { issueId: task.id } }).returning({ id: heartbeatRuns.id }); + const backlog = async (count: number) => (await state.db.insert(issues).values(Array.from({ length: count }, (_, index) => ({ + companyId, title: `Backlog ${index}`, status: "todo", assigneeAgentId: other.id, + }))).returning({ id: issues.id })).map(row => row.id); + return { runId: run.id, taskId: task.id, siblingId: sibling.id, backlog, affected: [parent.id, task.id, dependent.id].sort() }; + } + it("limits an ordinary comment to its issue among one thousand open assignments", async () => { + const f = await fixture(); + const rows = await state.db.insert(issues).values(Array.from({ length: 1000 }, (_, index) => ({ + companyId: f.companyId, title: `Open work ${index}`, status: "todo", assigneeAgentId: f.agentId, + }))).returning({ id: issues.id }); + const checked: string[] = []; + await recordedRecovery({ stranded: async scope => { checked.push(scope.issueId); } }); await settleWork(); expect(new Set(checked).size).toBe(1000); checked.length = 0; await issueService(state.db).addComment(rows[0].id, "New evidence on this task", { userId: "recovery-user" }); - await settleWork(); + await settleWork({ backstopPending: true }); expect(checked).toEqual([rows[0].id]); - // Company eligibility changes still reconstruct all assignments. Narrowing - // comment hints must not hide unrelated work after an operator resumes it. checked.length = 0; await state.db.transaction(tx => notifyIssueRecovery(tx, { companyId: f.companyId })); - await settleWork(); + await settleWork({ backstopPending: true }); expect(new Set(checked).size).toBe(1000); + await vi.advanceTimersByTimeAsync(ISSUE_RECOVERY_BACKSTOP_MS); + await settleWork(); await quiet(); }); + it("re-checks only the tasks a run lifecycle event can affect, whatever the backlog", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + await graph.backlog(1000); + const checked: string[] = []; + const assigned: string[] = []; + await recordedRecovery({ + stranded: async scope => { checked.push(scope.issueId); }, + assignedWork: { + listSuspects: (scope, cursor, limit) => recoveryService(state.db, { enqueueWakeup: async () => null }) + .assignedWork.listSuspects(scope, cursor, limit), + checkIssue: async scope => { assigned.push(scope.issueId); }, + }, + }, { backstopMs: 60 * 60_000 }); + await settleWork({ backstopPending: true }); + expect(new Set(checked).size).toBe(1004); + expect(checked).toContain(graph.siblingId); + async function lifecycleEvent(producer: (tx: object) => Promise, standalone?: () => Promise) { + checked.length = 0; assigned.length = 0; + const statements: string[] = [], prior = state.db.$client.options.debug; + state.db.$client.options.debug = (_connection, query) => { statements.push(query); }; + try { + if (standalone) await standalone(); else await state.db.transaction(tx => producer(tx)); + await settleWork({ backstopPending: true }); + } finally { state.db.$client.options.debug = prior; } + expect([...new Set(checked)].sort()).toEqual(graph.affected); + expect(assigned.every(id => graph.affected.includes(id))).toBe(true); + await vi.advanceTimersByTimeAsync(31_000); + return statements.length; + } + const finished = () => (tx: object) => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId }); + const first = await lifecycleEvent(finished()); + await lifecycleEvent(tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId: graph.runId, agentId: f.agentId })); + await lifecycleEvent(tx => notifyRunDispatch(tx, { companyId: f.companyId, issueId: graph.taskId })); + await lifecycleEvent(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "lock_released", issueId: graph.taskId })); + await lifecycleEvent(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "accounting_settled", runId: graph.runId })); + const recoveryActions = issueRecoveryActionService(state.db); + await lifecycleEvent(async () => {}, () => recoveryActions.upsertSourceScoped({ companyId: f.companyId, sourceIssueId: graph.taskId, + kind: "stranded_assigned_issue", ownerType: "board", cause: "stranded_assigned_issue", fingerprint: "run-failed", + nextAction: "Choose the next step", evidence: {} })); + await lifecycleEvent(async () => {}, () => recoveryActions.resolveActiveForIssue({ companyId: f.companyId, sourceIssueId: graph.taskId, + status: "resolved", outcome: "restored", resolutionNote: "Recovered" })); + await graph.backlog(4000); + expect(await lifecycleEvent(finished())).toBe(first); + }); + it("resolves a run's task graph through index lookups, not the backlog", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + await graph.backlog(2000); + await state.db.execute(sql`analyze issues`); + await state.db.execute(sql`analyze heartbeat_runs`); + const [read] = await state.db.transaction(async tx => { + expect(await resolveIssueGraph(tx as unknown as typeof state.db, { companyId: f.companyId, runId: graph.runId })).toEqual(graph.affected); + return tx.execute<{ rows: number }>(sql`select (coalesce(seq_tup_read, 0) + coalesce(idx_tup_fetch, 0))::int as rows + from pg_stat_xact_user_tables where relname = 'issues'`); + }); + expect(read.rows).toBeLessThan(50); + }); + it("finds a stranded task outside the affected set within the backstop bound", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + await graph.backlog(50); + const checkedAt = new Map(); + await recordedRecovery({ stranded: async scope => { checkedAt.set(scope.issueId, Date.now()); } }); + await settleWork({ backstopPending: true }); + const fullPassAt = Date.now(); + const [unrelated] = await graph.backlog(1); + checkedAt.clear(); + await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId })); + await settleWork({ backstopPending: true }); + expect(checkedAt.has(unrelated)).toBe(false); + expect(state.coordinator.nextWakeAt()).toBeLessThanOrEqual(fullPassAt + ISSUE_RECOVERY_BACKSTOP_MS); + await vi.advanceTimersByTimeAsync(ISSUE_RECOVERY_BACKSTOP_MS); + await settleWork(); + expect(checkedAt.get(unrelated)! - fullPassAt).toBeLessThanOrEqual(ISSUE_RECOVERY_BACKSTOP_MS + 5_000); + checkedAt.clear(); + await vi.advanceTimersByTimeAsync(20 * 60_000); + expect(checkedAt.size).toBe(0); + const [later] = await graph.backlog(1); + const eventAt = Date.now(); + await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId })); + await settleWork(); + expect(checkedAt.get(later)! - eventAt).toBeLessThanOrEqual(5_000); + await quiet(); + }); + it("keeps the company pass for hold releases that can admit any task", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + const backlog = await graph.backlog(150); + const checked: string[] = []; + await recordedRecovery({ stranded: async scope => { checked.push(scope.issueId); } }); + await settleWork({ backstopPending: true }); + const everything = new Set([...graph.affected, graph.siblingId, ...backlog]); + await state.db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType: "company", scopeId: f.companyId, + metric: "billed_cents", windowKind: "calendar_month_utc", amount: 1000, hardStopEnabled: true, isActive: true }); + for (const input of [{ trigger: "accounting_settled" as const, runId: graph.runId }, { trigger: "pause_lifted" as const }]) { + checked.length = 0; + await state.db.transaction(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, ...input })); + await settleWork({ backstopPending: true }); + expect(new Set(checked)).toEqual(everything); + await vi.advanceTimersByTimeAsync(31_000); + } + }); + it("falls back to the company pass when a run affects more tasks than a hint names", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + const backlog = await graph.backlog(200); + const checked: string[] = []; + await recordedRecovery({ stranded: async scope => { checked.push(scope.issueId); } }); + await settleWork({ backstopPending: true }); + const dependents = await graph.backlog(ISSUE_RECOVERY_MAX_ISSUE_IDS); + await state.db.insert(issueRelations).values(dependents.map(id => ({ companyId: f.companyId, issueId: graph.taskId, + relatedIssueId: id, type: "blocks" as const }))); + checked.length = 0; + await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId })); + await settleWork({ backstopPending: true }); + expect(new Set(checked)).toEqual(new Set([...graph.affected, graph.siblingId, ...backlog, ...dependents])); + }); it("checks only blocked tasks whose blockers are done, however many still wait", async () => { const f = await fixture(); const [openBlocker, doneBlocker] = await state.db.insert(issues).values([ @@ -126,28 +272,7 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => { companyId: f.companyId, issueId: doneBlocker.id, relatedIssueId: ready.id, type: "blocks" as const }, ]); const checked: string[] = []; - vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); - state.coordinator = createDeliveryWorkCoordinator({ owner: state.db, canRun: () => true, onError: error => state.errors.push(error) }); - const register = state.coordinator.register.bind(state.coordinator); - state.coordinator.register = (queue, task) => register(queue, { ...task, run: signal => { - const pass = task.run(signal); state.passes.add(pass); - void pass.then(() => state.passes.delete(pass), () => state.passes.delete(pass)); - return pass; - } }); - state.worker = registerIssueRecoveryWork(state.db, state.coordinator, { - stranded: async () => {}, orphanBlockers: async () => {}, recoveryActions: async () => {}, - dependencies: async scope => { checked.push(scope.issueId); return { enqueueFailed: 0 }; }, locks: async () => {}, - watchdogs: async () => ({ incomplete: 0 }), schedulingSuppressed: async () => false, - }, () => true); - await state.worker.ready; - async function settleWork() { - for (let step = 0; step < 120; step++) { - await vi.advanceTimersByTimeAsync(1000); - await Promise.allSettled([...state.passes]); await immediate(); - if (state.coordinator.nextWakeAt() === null && idleWorkSnapshot().active === 0) return; - } - throw new Error("Recovery did not settle its committed work within two virtual minutes"); - } + await recordedRecovery({ dependencies: async scope => { checked.push(scope.issueId); return { enqueueFailed: 0 }; } }); await settleWork(); expect(checked).toEqual([ready.id]); checked.length = 0; @@ -156,8 +281,10 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => expect(checked).toEqual([ready.id]); checked.length = 0; await issueService(state.db).update(openBlocker.id, { status: "done" }); - await settleWork(); + await settleWork({ backstopPending: true }); expect(new Set(checked)).toEqual(new Set([ready.id, ...waiting.map(row => row.id)])); + await vi.advanceTimersByTimeAsync(ISSUE_RECOVERY_BACKSTOP_MS); + await settleWork(); await quiet(); }); it("uses ordinary watchdog configuration and subtree closure to dispatch a reusable review", async () => { diff --git a/server/src/__tests__/issue-recovery.test-fixture.ts b/server/src/__tests__/issue-recovery.test-fixture.ts index 31a71917260..da4485f62e4 100644 --- a/server/src/__tests__/issue-recovery.test-fixture.ts +++ b/server/src/__tests__/issue-recovery.test-fixture.ts @@ -50,7 +50,7 @@ export function issueRecoveryFixture() { expect(errors).toEqual([]); }); afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); }); - async function start() { + async function start(options: { backstopMs?: number } = { backstopMs: 0 }) { coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, canReconcile: () => true, onError: error => errors.push(error) }); tasks.clear(); @@ -63,7 +63,7 @@ export function issueRecoveryFixture() { return work; } }); }; - worker = heartbeat.registerIssueStateRecoveryWork(coordinator, () => !draining); + worker = heartbeat.registerIssueStateRecoveryWork(coordinator, () => !draining, options); dispatch = heartbeat.registerRunDispatchWork(coordinator, () => !draining); cancellation = heartbeat.registerScheduledRetryCancellationWork(coordinator, () => !draining); await Promise.all([worker.ready, dispatch.ready, cancellation.ready]); @@ -77,7 +77,7 @@ export function issueRecoveryFixture() { void pass.then(() => passes.delete(pass), () => passes.delete(pass)); return pass; } }); - const work = other.registerIssueStateRecoveryWork(competing, () => true); + const work = other.registerIssueStateRecoveryWork(competing, () => true, { backstopMs: 0 }); extraStops.push(() => competing.stop()); extraDeadlines.push(competing.nextWakeAt); await work.ready; } async function fixture() { @@ -115,11 +115,12 @@ export function issueRecoveryFixture() { .where(eq(agents.id, f.agentId)); return failures; } - async function settled() { + async function settled(options: { backstopPending?: boolean } = {}) { await vi.waitFor(async () => { await Promise.allSettled([...passes]); await heartbeat.drainActiveRunExecutions(); - const wake = coordinator.nextWakeAt(); + const next = coordinator.nextWakeAt(); + const wake = options.backstopPending && next !== null && next > Date.now() + 60_000 ? null : next; const detail = wake === null ? "" : JSON.stringify({ now: Date.now(), tasks: await Promise.all([...tasks].map(async ([queue, task]) => ({ queue, at: task.nextRunAt?.(), pending: await task.hasPending() }))), runs: (await db.select().from(heartbeatRuns)).map(run => ({ id: run.id, status: run.status, error: run.errorCode, lease: run.controllerLeaseExpiresAt, reason: run.contextSnapshot?.wakeReason })) }); expect(wake, detail).toBeNull(); diff --git a/server/src/__tests__/live-recovery-work.test.ts b/server/src/__tests__/live-recovery-work.test.ts index 495b581de55..a3c1bfee699 100644 --- a/server/src/__tests__/live-recovery-work.test.ts +++ b/server/src/__tests__/live-recovery-work.test.ts @@ -104,7 +104,7 @@ describe("residual recovery production matrix", () => { const admitted = () => !draining && !standby; await heartbeat.registerResidualRecoveryWork(coordinator, admitted).ready; await heartbeat.registerActiveRunSilenceWork(coordinator, admitted).ready; - await heartbeat.registerIssueStateRecoveryWork(coordinator, admitted).ready; + await heartbeat.registerIssueStateRecoveryWork(coordinator, admitted, { backstopMs: 0 }).ready; await heartbeat.registerDeferredReceiptWork(coordinator, admitted).ready; await heartbeat.registerRunDispatchWork(coordinator, admitted).ready; await heartbeat.registerScheduledRetryCancellationWork(coordinator, admitted).ready; diff --git a/server/src/__tests__/scoped-deadline-work.test.ts b/server/src/__tests__/scoped-deadline-work.test.ts index a5a430a2410..d886f7a1fab 100644 --- a/server/src/__tests__/scoped-deadline-work.test.ts +++ b/server/src/__tests__/scoped-deadline-work.test.ts @@ -697,3 +697,27 @@ it("drops an entry that vanished from a keyed scope and keeps other companies' s expect(coordinator.nextWakeAt()).toBeNull(); expect(onError).not.toHaveBeenCalled(); }); + +it("keeps a backstop hint's deadline without holding the worker busy", async () => { + vi.useFakeTimers(); + const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []), transaction: vi.fn(async () => undefined) }); + coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => true, onError: vi.fn() }); + const backstopAt = Date.now() + 300_000; + const load = vi.fn(async (_scope?: string) => []); + const worker = registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.externalObjectRefresh, minimumPassIntervalMs: 0, + decodeScope: hint => hint === "*" ? undefined : hint, + backstop: scope => scope === "backstop" ? backstopAt : null, + matches: () => true, load, check: async () => null, + }, () => true); + await worker.ready; + load.mockClear(); + worker.invalidate("backstop"); + await vi.advanceTimersByTimeAsync(1); + expect(load).not.toHaveBeenCalled(); + expect(coordinator.nextWakeAt()).toBe(backstopAt); + expect(worker.reconciliationSnapshot().reconciled).toBe(true); + await vi.advanceTimersByTimeAsync(300_000); + expect(load).toHaveBeenCalledWith("backstop", expect.anything()); + expect(coordinator.nextWakeAt()).toBeNull(); +}); diff --git a/server/src/modules/run-dispatch/adapters/workspace-busy-wait.ts b/server/src/modules/run-dispatch/adapters/workspace-busy-wait.ts index 96b5548e87f..b9cdf5e13d7 100644 --- a/server/src/modules/run-dispatch/adapters/workspace-busy-wait.ts +++ b/server/src/modules/run-dispatch/adapters/workspace-busy-wait.ts @@ -158,7 +158,7 @@ export async function wakeWorkspaceBusyWaitersInTx(tx: Db, input: { ); const waiters = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(waiting).for("update"); if (waiters.length === 0) return 0; - await notifyScheduledRetryDispatch(tx, { companyId: input.companyId }); + await notifyScheduledRetryDispatch(tx, { companyId: input.companyId, runId: input.runId }); const woken = await tx .update(heartbeatRuns) .set({ scheduledRetryAt: input.now, updatedAt: input.now }) diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 471e7a00088..857ecb5ee4f 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -732,7 +732,7 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru .returning() .then((rows) => rows[0]); - await notifyRunDispatch(tx, { companyId }); + await notifyRunDispatch(tx, { companyId, issueId: issue.id }); const queuedRun = await tx .insert(heartbeatRuns) .values({ @@ -811,7 +811,7 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru .returning() .then((rows) => rows[0]); - await notifyRunDispatch(tx, { companyId }); + await notifyRunDispatch(tx, { companyId, issueId: issue.id }); const queuedRun = await tx .insert(heartbeatRuns) .values({ diff --git a/server/src/services/documents.ts b/server/src/services/documents.ts index b5c4fafa07b..e6a4e34589d 100644 --- a/server/src/services/documents.ts +++ b/server/src/services/documents.ts @@ -1,6 +1,6 @@ import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; import { assertAgentInteraction } from "./agent-interaction-policy.js"; -import { notifyIssueRecovery } from "./issue-recovery-notifications.js"; +import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js"; import { randomUUID } from "node:crypto"; import { and, asc, desc, eq, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -290,7 +290,7 @@ export function documentService(db: Db) { .where(eq(issueDocuments.issueId, issue.id)); const fallbackKey = nextAvailableDocumentKey(key, issueDocumentKeys.map((row) => row.key)); - await notifyIssueRecovery(tx, { companyId: issue.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id }); const [document] = await tx .insert(documents) .values({ @@ -392,7 +392,7 @@ export function documentService(db: Db) { }); } - await notifyIssueRecovery(tx, { companyId: issue.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id }); const nextRevisionNumber = existing.latestRevisionNumber + 1; const [revision] = await tx .insert(documentRevisions) @@ -455,7 +455,7 @@ export function documentService(db: Db) { throw conflict("Document does not exist yet", { key }); } - await notifyIssueRecovery(tx, { companyId: issue.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id }); const [document] = await tx .insert(documents) .values({ diff --git a/server/src/services/execution-control-notifications.ts b/server/src/services/execution-control-notifications.ts index 218e7e1508a..a94ac36ec91 100644 --- a/server/src/services/execution-control-notifications.ts +++ b/server/src/services/execution-control-notifications.ts @@ -1,5 +1,5 @@ import { notifyLiveRunRecovery, notifyLiveResourceRecovery } from "./live-run-recovery-notifications.js"; -import { notifyAttentionRetentionWork } from "./retention-work-notifications.js"; +import { notifyAttentionRetentionWork, notifyIssueAttentionRetentionWork } from "./retention-work-notifications.js"; import { notifyDeferredExecutionEligibility } from "./deferred-execution-notifications.js"; import { notifyRunDispatch } from "./run-dispatch-notifications.js"; import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; @@ -9,9 +9,14 @@ import { DELIVERY_QUEUES, notifyDeliveryWork, type DeliveryQueue } from "./deliv export type ExecutionWorkScope = { companyId: string; agentId?: string; runId?: string; issueId?: string }; +async function notifyExecutionAttentionRetention(transaction: object, scope: ExecutionWorkScope) { + if (scope.issueId) await notifyIssueAttentionRetentionWork(transaction, { companyId: scope.companyId, issueId: scope.issueId }); + else await notifyAttentionRetentionWork(transaction, scope); +} + export async function notifyExecutionRunWork(transaction: object, scope?: ExecutionWorkScope) { if (scope) { - await notifyAttentionRetentionWork(transaction, scope); + await notifyExecutionAttentionRetention(transaction, scope); await notifyRunDispatch(transaction, scope); await notifyStatusCardIssueChange(transaction, scope.companyId); await notifyDeferredExecutionEligibility(transaction, scope); @@ -36,7 +41,7 @@ export function writeExecutionControl( await notifyRunDispatch(transaction, scope); if (scope) { await notifyStatusCardIssueChange(transaction, scope.companyId); - await notifyAttentionRetentionWork(transaction, scope); + await notifyExecutionAttentionRetention(transaction, scope); await notifyRoutineExecutionStatus(transaction, scope.issueId, scope.companyId); await notifyDeferredExecutionEligibility(transaction, scope); await notifyLiveRunRecovery(transaction, scope); diff --git a/server/src/services/external-conversation-settlement-notifications.ts b/server/src/services/external-conversation-settlement-notifications.ts index d5e4cdd506c..7a93afbf4ce 100644 --- a/server/src/services/external-conversation-settlement-notifications.ts +++ b/server/src/services/external-conversation-settlement-notifications.ts @@ -1,9 +1,10 @@ -import { notifyIssueRecovery } from "./issue-recovery-notifications.js"; +import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import type { ExternalConversationSettlementScope } from "./slack-conversation-lifecycle.js"; export async function notifyExternalConversationSettlement(tx: object, scope?: ExternalConversationSettlementScope) { - await notifyIssueRecovery(tx, scope); + if (scope?.issueId || scope?.runId) await notifyIssueGraphRecovery(tx, scope); + else await notifyIssueRecovery(tx, scope); return notifyDeliveryWork(tx, DELIVERY_QUEUES.externalConversationSettlement, scope ? JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }) : "*"); } diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 6dc109a8501..7f51a4b089d 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -4121,7 +4121,7 @@ export function heartbeatService( await writeExecutionControl(db, DELIVERY_QUEUES.executionFinalization, tx => tx .update(heartbeatRuns) .set({ executionControlDeadlineAt: null }) - .where(eq(heartbeatRuns.id, run.id)), { companyId: run.companyId }); + .where(eq(heartbeatRuns.id, run.id)), { companyId: run.companyId, runId: run.id }); } nativeOwnershipHeld = nativeOwnershipHeld || @@ -4725,7 +4725,8 @@ export function heartbeatService( schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed, prepareChatRetry, }, () => canRun() && readTaskDrain(new Date()) === null), - registerIssueStateRecoveryWork: (coordinator: Parameters[1], canRun: () => boolean) => + registerIssueStateRecoveryWork: (coordinator: Parameters[1], canRun: () => boolean, + options?: Parameters[4]) => registerIssueRecoveryWork(db, coordinator, { stranded: scope => reconcileStrandedAssignedIssues({ ...scope, skipExternalConversationSettlement: true, skipRelatedRecovery: true }), orphanBlockers: recovery.reconcileUnassignedBlockingIssues, @@ -4739,7 +4740,7 @@ export function heartbeatService( checkIssue: recovery.assignedWork.checkIssue, }, schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed, - }, () => canRun() && readTaskDrain(new Date()) === null), + }, () => canRun() && readTaskDrain(new Date()) === null, options), registerRunDispatchWork: (coordinator: Parameters[0], canRun: () => boolean) => registerRunDispatchWork(coordinator, { promoteDueScheduledRetries, diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 18606daa274..92aa415c07d 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -5355,7 +5355,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } const queueOutcome = await db.transaction(async (tx) => { - await notifyRunDispatch(tx, { companyId: agent.companyId }); + await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId) }); await tx.execute( sql`select id from agents where id = ${agentId} and company_id = ${agent.companyId} for update`, ); diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index ec839348aee..c463a458a5b 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -1210,7 +1210,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen } await notifyAttentionRetentionWork(tx, { companyId: run.companyId }); - await notifyScheduledRetryDispatch(tx, { companyId: run.companyId }); + await notifyScheduledRetryDispatch(tx, { companyId: run.companyId, runId: run.id }); const wakeupRequest = await tx .insert(agentWakeupRequests) .values({ @@ -2068,7 +2068,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen }; const updated = await db.transaction(async (tx) => { - await notifyScheduledRetryDispatch(tx, { companyId: scheduled.run.companyId }); + await notifyScheduledRetryDispatch(tx, { companyId: scheduled.run.companyId, runId: scheduled.run.id }); const row = await tx .update(heartbeatRuns) .set({ diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index edae7168010..e4cfaa222cc 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -1557,11 +1557,15 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl ) { if (!wakeupRequestId) return; await db.transaction(async tx => { - const [current] = await tx.select({ companyId: agentWakeupRequests.companyId, agentId: agentWakeupRequests.agentId, status: agentWakeupRequests.status }) + const [current] = await tx.select({ companyId: agentWakeupRequests.companyId, agentId: agentWakeupRequests.agentId, status: agentWakeupRequests.status, + runId: agentWakeupRequests.runId, issueId: sql`${agentWakeupRequests.payload}->>'issueId'` }) .from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeupRequestId)).for("update"); if (!current || current.status === "cancelled") return; if (current.status !== (patch?.status ?? status) || patch?.payload !== undefined || patch?.runId !== undefined) { - await notifyExternalConversationSettlement(tx, { companyId: current.companyId }); + const runId = patch?.runId ?? current.runId; + const issueId = current.issueId && /^[0-9a-f-]{36}$/i.test(current.issueId) ? current.issueId : undefined; + await notifyExternalConversationSettlement(tx, issueId || runId + ? { companyId: current.companyId, issueId, runId: runId ?? undefined } : { companyId: current.companyId }); } await notifyStrandedAgentStatus(tx, { companyId: current.companyId, agentId: current.agentId }); await tx.update(agentWakeupRequests) @@ -2605,7 +2609,7 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl .returning() .then((rows) => rows[0]); - await notifyRunDispatch(tx, { companyId: run.companyId }); + await notifyRunDispatch(tx, { companyId: run.companyId, issueId }); const queuedRun = await tx .insert(heartbeatRuns) .values({ diff --git a/server/src/services/heartbeat/runtime-execution.ts b/server/src/services/heartbeat/runtime-execution.ts index 6dd198dcbc6..5eb74902d72 100644 --- a/server/src/services/heartbeat/runtime-execution.ts +++ b/server/src/services/heartbeat/runtime-execution.ts @@ -1054,7 +1054,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "running"), ), - ), { companyId: run.companyId }); + ), { companyId: run.companyId, runId: run.id }); const workspaceFinalizeStatus = hasWorkspaceRestoreFailure(adapterResult.resultJson) ? "failed" : "succeeded"; await recordWorkspaceFinalize(workspaceFinalizeStatus); if (adapterResult.nativeFinalization) { @@ -1135,7 +1135,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "running"), ), - ), { companyId: run.companyId }); + ), { companyId: run.companyId, runId: run.id }); } catch (writeError) { if (adapterErr instanceof NativeStartupCleanupPendingError) throw adapterErr; throw writeError; diff --git a/server/src/services/issue-recovery-actions.ts b/server/src/services/issue-recovery-actions.ts index f98c639e8dd..f9509f33210 100644 --- a/server/src/services/issue-recovery-actions.ts +++ b/server/src/services/issue-recovery-actions.ts @@ -1,5 +1,5 @@ import { notifyAttentionRetentionWork } from "./retention-work-notifications.js"; -import { notifyIssueRecovery } from "./issue-recovery-notifications.js"; +import { notifyIssueGraphRecovery } from "./issue-recovery-notifications.js"; import { notifyNativeRecoveryNotices } from "./native-recovery-notice-notifications.js"; import { notifyUnsafeWorkspaceExportRecovery } from "./unsafe-workspace-export-notifications.js"; import { writeExecutionControl } from "./execution-control-notifications.js"; @@ -345,7 +345,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { try { const created = await db.transaction(async (tx) => { await notifyAttentionRetentionWork(tx, { companyId: input.companyId }); - await notifyIssueRecovery(tx, { companyId: input.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionDisposition); await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionContinuation); @@ -417,7 +417,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { const [updated] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], tx => tx.update(issueRecoveryActions).set({ nextAction: input.nextAction, updatedAt: now }) .where(and(eq(issueRecoveryActions.id, existing.id), inArray(issueRecoveryActions.status, [...ACTIVE_RECOVERY_ACTION_STATUSES]), - sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`)).returning(), { companyId: input.companyId }); + sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`)).returning(), { companyId: input.companyId, issueId: input.sourceIssueId }); if (updated) return toReadModel(updated); } return existing; @@ -438,7 +438,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { Math.min(nextAttemptCount, effectiveMaxAttempts), ); const [exhausted] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => { - await notifyIssueRecovery(tx, { companyId: input.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); if ((!input.preserveExistingOwner && existing.cause !== input.cause) || (input.evidence?.runId !== undefined && input.evidence.runId !== existing.evidence?.runId)) { @@ -493,14 +493,14 @@ export function issueRecoveryActionService(db: DbOrTransaction) { ), ) .returning(); - }, { companyId: input.companyId }); + }, { companyId: input.companyId, issueId: input.sourceIssueId }); if (!exhausted) { return retryUpsertSourceScoped(input, retryCount); } return toReadModel(exhausted); } const [updated] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => { - await notifyIssueRecovery(tx, { companyId: input.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); if ((!input.preserveExistingOwner && existing.cause !== input.cause) || (input.evidence?.runId !== undefined && input.evidence.runId !== existing.evidence?.runId)) { @@ -566,7 +566,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { ), ) .returning(); - }, { companyId: input.companyId }); + }, { companyId: input.companyId, issueId: input.sourceIssueId }); if (!updated) { return retryUpsertSourceScoped(input, retryCount); } @@ -575,14 +575,14 @@ export function issueRecoveryActionService(db: DbOrTransaction) { try { const [created] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => { - await notifyIssueRecovery(tx, { companyId: input.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); return tx .insert(issueRecoveryActions) .values(buildInsertValues(input, ownerType, now)) .returning(); - }, { companyId: input.companyId }); + }, { companyId: input.companyId, issueId: input.sourceIssueId }); return toReadModel(created!); } catch (error) { if (!isUniqueRecoveryActionConflict(error)) throw error; @@ -632,7 +632,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { isNotNull(nativeRunFinalizations.leaseOwner), inArray(heartbeatRuns.status, ["failed", "timed_out", "interrupted"]), )).limit(1); if (waiter) await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionFinalization); - await notifyIssueRecovery(tx, { companyId: input.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); return tx @@ -646,7 +646,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { }) .where(and(...predicates)) .returning(); - }, { companyId: input.companyId }); + }, { companyId: input.companyId, issueId: input.sourceIssueId }); return updated ? toReadModel(updated) : null; } diff --git a/server/src/services/issue-recovery-notifications.ts b/server/src/services/issue-recovery-notifications.ts index 42c095b35b7..ec3770b7c4d 100644 --- a/server/src/services/issue-recovery-notifications.ts +++ b/server/src/services/issue-recovery-notifications.ts @@ -1,9 +1,20 @@ -import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { DELIVERY_QUEUES, notifyDeliveryWork, type DeliveryQueue } from "./delivery-work-notifications.js"; /** An issue hint is reserved for local facts such as comments. Lifecycle, * graph, run and eligibility changes retain company scope because their * consequences can include ancestors and shared execution references. */ -export type IssueRecoveryScope = { companyId: string; issueId?: string }; +export type IssueRecoveryScope = { companyId: string; issueId?: string; graphRunId?: string; graphIssueId?: string; backstop?: true; + issueIds?: string[]; wholeCompany?: boolean }; + +export const ISSUE_RECOVERY_MAX_ISSUE_IDS = 100; +export const ISSUE_RECOVERY_BACKSTOP_MS = 5 * 60_000; +const UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; + +const COMPANY_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, DELIVERY_QUEUES.taskWatchdogs]; +const TASK_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.assignedWorkInvariant, + DELIVERY_QUEUES.resolvedDependencies, DELIVERY_QUEUES.staleIssueLocks]; export async function notifyIssueRecovery(transaction: object, scope?: IssueRecoveryScope) { const companyHint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*"; @@ -14,3 +25,49 @@ export async function notifyIssueRecovery(transaction: object, scope?: IssueReco queue === DELIVERY_QUEUES.strandedAssignments || queue === DELIVERY_QUEUES.staleIssueLocks ? issueHint : companyHint); } } + +export function decodeIssueRecoveryHint(hint: string): IssueRecoveryScope | undefined { + return hint === "*" ? undefined : JSON.parse(hint) as IssueRecoveryScope; +} + +export function issueRecoveryScopeMatches(entry: { id: string; companyId: string }, scope?: IssueRecoveryScope) { + if (!scope) return true; + if (entry.companyId !== scope.companyId) return false; + if (scope.issueId) return entry.id === scope.issueId; + if (scope.graphRunId || scope.graphIssueId) return scope.wholeCompany === true || (scope.issueIds?.includes(entry.id) ?? false); + return true; +} + +export async function notifyIssueGraphRecovery(transaction: object, + scope: { companyId: string; runId?: string | null; issueId?: string | null }) { + if (!scope.runId && !scope.issueId) return notifyIssueRecovery(transaction, { companyId: scope.companyId }); + const companyHint = JSON.stringify({ companyId: scope.companyId }); + for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint); + const graphHint = JSON.stringify({ companyId: scope.companyId, graphRunId: scope.runId ?? undefined, graphIssueId: scope.issueId ?? undefined }); + for (const queue of TASK_QUEUES) { + await notifyDeliveryWork(transaction, queue, graphHint); + await notifyDeliveryWork(transaction, queue, JSON.stringify({ companyId: scope.companyId, backstop: true })); + } +} + +export async function resolveIssueGraph(db: Db, scope: { companyId: string; runId?: string; issueId?: string }): Promise { + const company = sql`${scope.companyId}::uuid`; + const run = scope.runId ? sql`${scope.runId}::uuid` : sql`null::uuid`; + const rows = await db.execute<{ id: string }>(sql`with seed(id) as ( + select id from issues where company_id = ${company} and id = ${scope.issueId ?? null}::uuid + union select issue_id from heartbeat_runs where company_id = ${company} and id = ${run} and issue_id is not null + union select native_issue_id from heartbeat_runs where company_id = ${company} and id = ${run} and native_issue_id is not null + union select issue.id from heartbeat_runs run + cross join lateral (select coalesce(run.context_snapshot->>'issueId', run.context_snapshot->>'taskId') as saved) context + inner join issues issue on issue.company_id = run.company_id + and issue.id = case when context.saved ~* ${UUID_PATTERN} then context.saved::uuid end + where run.company_id = ${company} and run.id = ${run} + ), affected(id) as ( + select id from seed + union select parent_id from issues where company_id = ${company} and id in (select id from seed) and parent_id is not null + union (select related_issue_id from issue_relations where company_id = ${company} and type = 'blocks' + and issue_id in (select id from seed) limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}) + ) select id::text as id from affected limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}`); + const issueIds = rows.map(row => row.id).sort(); + return issueIds.length && issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null; +} diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index c2cf51ce77a..0081222eb52 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -12196,7 +12196,8 @@ export function issueService(db: Db) { || patch.hiddenAt !== undefined || patch.conversationAgentId !== undefined || patch.parentId !== undefined || patch.executionState !== undefined || patch.executionRunId !== undefined || patch.checkoutRunId !== undefined || blockedByIssueIds !== undefined) { - await notifyRunDispatch(tx, { companyId: receiptExisting.companyId }); + await notifyRunDispatch(tx, patch.parentId !== undefined && patch.parentId !== receiptExisting.parentId + ? { companyId: receiptExisting.companyId } : { companyId: receiptExisting.companyId, issueId: id }); await notifyDeferredExecutionEligibility(tx, { companyId: receiptExisting.companyId }); await notifyActiveRunSilence(tx, { companyId: receiptExisting.companyId, issueId: id }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); @@ -12827,7 +12828,7 @@ export function issueService(db: Db) { await notifyStatusCardIssueChange(tx, issueCompany.companyId); await notifyIssueAttentionRetentionWork(tx, { companyId: issueCompany.companyId, issueId: id }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); - await notifyRunDispatch(tx, { companyId: issueCompany.companyId }); + await notifyRunDispatch(tx, { companyId: issueCompany.companyId, issueId: id }); await notifyDeferredExecutionEligibility(tx, { companyId: issueCompany.companyId }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); await notifyRoutineExecutionStatus(tx, id); @@ -13238,7 +13239,7 @@ export function issueService(db: Db) { await notifyNativeStatusReassessment(tx, { companyId: existing.companyId, issueId: id }); await notifyIssueAttentionRetentionWork(tx, { companyId: existing.companyId, issueId: id }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); - await notifyRunDispatch(tx, { companyId: existing.companyId }); + await notifyRunDispatch(tx, { companyId: existing.companyId, issueId: id }); await notifyDeferredExecutionEligibility(tx, { companyId: existing.companyId }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); await notifyRoutineExecutionStatus(tx, id); @@ -13303,7 +13304,7 @@ export function issueService(db: Db) { await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: existing.companyId, issueId: id }); } await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); - await notifyRunDispatch(tx, { companyId: existing.companyId }); + await notifyRunDispatch(tx, { companyId: existing.companyId, issueId: id }); await notifyDeferredExecutionEligibility(tx, { companyId: existing.companyId }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); await notifyRoutineExecutionStatus(tx, id); diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index b786d4cf7f0..6d48112de2d 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -158,7 +158,7 @@ export async function terminalizeLegacyExecution(input: { }; if (issueId) await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: current.companyId, issueId }); await notifyInstructionCollection(tx, { companyId: current.companyId, runId: current.id }); - await notifyExecutionRunWork(tx, { companyId: current.companyId }); + await notifyExecutionRunWork(tx, { companyId: current.companyId, runId: current.id }); let [updated] = await tx .update(heartbeatRuns) .set({ diff --git a/server/src/services/native-runtime/native-provider-capacity-retry.ts b/server/src/services/native-runtime/native-provider-capacity-retry.ts index cb05729dcc5..334e5880226 100644 --- a/server/src/services/native-runtime/native-provider-capacity-retry.ts +++ b/server/src/services/native-runtime/native-provider-capacity-retry.ts @@ -52,7 +52,7 @@ export async function materializeNativeProviderCapacityRetry(input: { executionRetryAccounting: accountingForScheduledRetry(run, NATIVE_PROVIDER_OVERLOADED_CODE, attempt), }; await notifyAttentionRetentionWork(input.tx, { companyId: input.companyId }); - await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId }); + await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId, runId: run.id }); const [wake] = await input.tx.insert(agentWakeupRequests).values({ companyId: run.companyId, agentId: run.agentId, source: "automation", triggerDetail: "system", reason: NATIVE_PROVIDER_OVERLOADED_CODE, status: "queued", runId: retryId, diff --git a/server/src/services/native-runtime/native-safe-replacement.ts b/server/src/services/native-runtime/native-safe-replacement.ts index a84c35446b6..397dd7a674a 100644 --- a/server/src/services/native-runtime/native-safe-replacement.ts +++ b/server/src/services/native-runtime/native-safe-replacement.ts @@ -775,8 +775,8 @@ export async function reconcileSafeNativeReplacements( idempotencyKey: `native-safe-replacement:${run.id}`, }) .returning(); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); - await notifyScheduledRetryDispatch(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); + await notifyScheduledRetryDispatch(tx, { companyId: run.companyId, runId: run.id }); await tx.insert(heartbeatRuns).values({ id: successorRunId, companyId: run.companyId, diff --git a/server/src/services/native-status-reassessment-notifications.ts b/server/src/services/native-status-reassessment-notifications.ts index 3fb378c7605..6189a7f73dd 100644 --- a/server/src/services/native-status-reassessment-notifications.ts +++ b/server/src/services/native-status-reassessment-notifications.ts @@ -1,6 +1,6 @@ import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; import { notifyIssueAttentionRetentionWork } from "./retention-work-notifications.js"; -import { notifyIssueRecovery } from "./issue-recovery-notifications.js"; +import { notifyIssueGraphRecovery } from "./issue-recovery-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; export type NativeStatusReassessmentScope = { companyId: string; issueId?: string; runId?: string; agentId?: string }; @@ -8,7 +8,7 @@ export type NativeStatusReassessmentScope = { companyId: string; issueId?: strin export async function notifyNativeStatusReassessment(tx: object, scope: NativeStatusReassessmentScope) { await notifyStatusCardIssueChange(tx, scope.companyId); await notifyIssueAttentionRetentionWork(tx, { companyId: scope.companyId, issueId: scope.issueId, runId: scope.runId }); - await notifyIssueRecovery(tx, scope ? { companyId: scope.companyId } : undefined); + await notifyIssueGraphRecovery(tx, scope); return notifyDeliveryWork(tx, DELIVERY_QUEUES.nativeStatusReassessment, JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId, runId: scope.runId, agentId: scope.agentId })); } diff --git a/server/src/services/recovery/assigned-work-sweep.ts b/server/src/services/recovery/assigned-work-sweep.ts index 5559500dc9f..9317316ab80 100644 --- a/server/src/services/recovery/assigned-work-sweep.ts +++ b/server/src/services/recovery/assigned-work-sweep.ts @@ -505,7 +505,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { order by lr.created_at desc limit 1), false)`; } - async function listSuspects(scope: { companyId?: string; issueId?: string; createdAfter?: Date | null }, cursor: string | null, limit: number) { + async function listSuspects(scope: { companyId?: string; issueId?: string; issueIds?: string[]; createdAfter?: Date | null }, + cursor: string | null, limit: number) { const at = now(); const liveRun = sql`exists (select 1 from heartbeat_runs r where r.company_id = ${issues.companyId} and (r.context_snapshot->>'issueId') = ${issues.id}::text @@ -521,6 +522,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) { return db.select({ id: issues.id, companyId: issues.companyId, updatedAt: issues.updatedAt }).from(issues).where(and( scope.companyId ? eq(issues.companyId, scope.companyId) : undefined, scope.issueId ? eq(issues.id, scope.issueId) : undefined, + scope.issueIds ? inArray(issues.id, scope.issueIds) : undefined, cursor ? sql`${issues.id} > ${cursor}` : undefined, scope.createdAfter ? gte(issues.createdAt, scope.createdAfter) : undefined, inArray(issues.status, [...OPEN_STATUSES]), diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 96ba761bb7e..cd12fdcd29c 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -2832,7 +2832,7 @@ export function recoveryService( const now = new Date(); const retryAt = readProviderQuotaRetryAt(input.latestRun, now); return database.transaction(async (tx) => { - await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId }); + await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId, issueId: input.issue.id }); const wakeup = await tx .insert(agentWakeupRequests) .values({ @@ -3429,7 +3429,7 @@ export function recoveryService( created = Boolean(enqueuedRun); } else { scheduledRun = await db.transaction(async (tx) => { - await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId }); + await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId, issueId: input.issue.id }); const wakeup = await tx .insert(agentWakeupRequests) .values({ diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index 00f3dbd0eb4..06a9baf803a 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -3,7 +3,8 @@ import { and, asc, eq, gt, inArray, isNotNull, isNull, or, sql, type SQL } from import { issueRecoveryActions, issueRelations, issues, type Db } from "@paperclipai/db"; import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notifications.js"; -import type { IssueRecoveryScope } from "../issue-recovery-notifications.js"; +import { decodeIssueRecoveryHint, ISSUE_RECOVERY_BACKSTOP_MS, issueRecoveryScopeMatches, resolveIssueGraph, type IssueRecoveryScope } + from "../issue-recovery-notifications.js"; import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; import { recoveryActionSweepCondition } from "./blocker-stall-wakeups.js"; @@ -31,29 +32,69 @@ export function registerIssueRecoveryWork( schedulingSuppressed(): Promise; /** The assigned-work invariant (assigned-work-sweep.ts). */ assignedWork?: { - listSuspects(scope: { companyId?: string; issueId?: string }, cursor: string | null, limit: number): + listSuspects(scope: { companyId?: string; issueId?: string; issueIds?: string[] }, cursor: string | null, limit: number): Promise>; checkIssue(scope: Scope): Promise; }; }, canRun: () => boolean, + options: { backstopMs?: number } = {}, ) { + function fullPasses() { + const completedAt = new Map(); + return { + backstop: (scope: IssueRecoveryScope | undefined) => scope?.backstop + ? Math.max(completedAt.get("*") ?? 0, completedAt.get(scope.companyId) ?? 0) + (options.backstopMs ?? ISSUE_RECOVERY_BACKSTOP_MS) + : null, + loaded(scope: IssueRecoveryScope | undefined, complete: boolean) { + if (complete && !scope?.issueId && (!isGraph(scope) || scope?.wholeCompany)) completedAt.set(scope?.companyId ?? "*", Date.now()); + }, + }; + } + const reconstructionIntervalMs = (scope: IssueRecoveryScope | undefined) => scope?.backstop || scope?.graphRunId || scope?.graphIssueId ? 0 : 30_000; + const scopeKey = (scope: IssueRecoveryScope | undefined) => scope + ? JSON.stringify([scope.companyId, scope.issueId, scope.graphRunId, scope.graphIssueId, scope.backstop]) : "*"; + const isGraph = (scope: IssueRecoveryScope | undefined) => Boolean(scope?.graphRunId || scope?.graphIssueId); + const graphs = new Map }>(); + async function resolveGraph(scope: IssueRecoveryScope | undefined) { + if (!scope || !isGraph(scope)) return; + const key = scopeKey(scope); + for (const [other, cached] of graphs) if (cached.at < Date.now() - 2_000) graphs.delete(other); + let cached = graphs.get(key); + if (!cached) { + cached = { at: Date.now(), ids: resolveIssueGraph(db, { companyId: scope.companyId, runId: scope.graphRunId, issueId: scope.graphIssueId }) }; + graphs.set(key, cached); + } + const ids = await cached.ids.catch(error => { graphs.delete(key); throw error; }); + scope.issueIds = ids ?? undefined; + scope.wholeCompany = ids === null; + } + async function toCompany(scope: IssueRecoveryScope | undefined, worker: { invalidate(hint?: string): void }) { + await resolveGraph(scope); + if (!scope?.wholeCompany) return false; + worker.invalidate(JSON.stringify({ companyId: scope.companyId })); + return true; + } function register(queue: DeliveryQueue, statuses: string[] | null, check: (scope: Scope) => Promise, eligible?: SQL) { const cursors = new Map(); + const passes = fullPasses(); let enabled = false; - return registerScopedDeadlineWork(coordinator, { + const worker: ReturnType> = registerScopedDeadlineWork(coordinator, { queue, - reconstructionIntervalMs: 30_000, + reconstructionIntervalMs, + backstop: passes.backstop, beforePass: async () => { enabled = !(await owner.schedulingSuppressed()); }, - decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as IssueRecoveryScope, - matches: (entry, scope) => !scope || (entry.companyId === scope.companyId && (!scope.issueId || entry.id === scope.issueId)), + decodeScope: decodeIssueRecoveryHint, + matches: issueRecoveryScopeMatches, load: async scope => { - const key = scope ? JSON.stringify([scope.companyId, scope.issueId]) : "*"; + const key = scopeKey(scope); if (!enabled) { cursors.delete(key); return []; } + if (await toCompany(scope, worker)) return { rows: null, complete: true }; const cursor = cursors.get(key); const rows = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(and( scope ? eq(issues.companyId, scope.companyId) : undefined, scope?.issueId ? eq(issues.id, scope.issueId) : undefined, + scope?.issueIds ? inArray(issues.id, scope.issueIds) : undefined, cursor ? gt(issues.id, cursor) : undefined, statuses ? inArray(issues.status, statuses) : or(isNotNull(issues.checkoutRunId), isNotNull(issues.executionRunId)), statuses ? isNull(issues.hiddenAt) : undefined, @@ -63,6 +104,7 @@ export function registerIssueRecoveryWork( )).orderBy(asc(issues.id)).limit(PAGE_SIZE); const complete = rows.length < PAGE_SIZE; if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); + passes.loaded(scope, complete); return { rows: rows.map(row => ({ ...row, dueAt: Date.now() })), complete }; }, check: async entry => { @@ -73,6 +115,7 @@ export function registerIssueRecoveryWork( return next === null ? null : { ...entry, dueAt: next }; }, }, canRun); + return worker; } /** Event-driven: run terminal states, hold settlements and boot mark the * company dirty; checks schedule their own grace and back-off deadlines. @@ -80,22 +123,27 @@ export function registerIssueRecoveryWork( function registerAssignedWork(sweep: NonNullable) { type Suspect = Entry & { updatedAt: number }; const cursors = new Map(); + const passes = fullPasses(); let enabled = false; - return registerScopedDeadlineWork(coordinator, { + const worker: ReturnType> = registerScopedDeadlineWork(coordinator, { queue: DELIVERY_QUEUES.assignedWorkInvariant, - reconstructionIntervalMs: 30_000, + reconstructionIntervalMs, + backstop: passes.backstop, batchSize: 25, beforePass: async () => { enabled = !(await owner.schedulingSuppressed()); }, - decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as IssueRecoveryScope, - matches: (entry, scope) => !scope || (entry.companyId === scope.companyId && (!scope.issueId || entry.id === scope.issueId)), + decodeScope: decodeIssueRecoveryHint, + matches: issueRecoveryScopeMatches, priority: entry => entry.updatedAt, mergeEntry: (pending, loaded) => ({ ...loaded, dueAt: Math.max(pending.dueAt, loaded.dueAt) }), load: async scope => { - const key = scope ? JSON.stringify([scope.companyId, scope.issueId]) : "*"; + const key = scopeKey(scope); if (!enabled) { cursors.delete(key); return []; } - const rows = await sweep.listSuspects(scope ?? {}, cursors.get(key) ?? null, PAGE_SIZE); + if (await toCompany(scope, worker)) return { rows: null, complete: true }; + const rows = await sweep.listSuspects(scope ? { companyId: scope.companyId, issueId: scope.issueId, + issueIds: scope.issueIds } : {}, cursors.get(key) ?? null, PAGE_SIZE); const complete = rows.length < PAGE_SIZE; if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); + passes.loaded(scope, complete); return { rows: rows.map(row => ({ id: row.id, companyId: row.companyId, updatedAt: row.updatedAt.getTime(), dueAt: Date.now() })), complete }; }, check: async entry => { @@ -106,6 +154,7 @@ export function registerIssueRecoveryWork( return next === null ? null : { ...entry, dueAt: next }; }, }, canRun); + return worker; } function registerCompany(queue: DeliveryQueue, kind: "blockers" | "actions", check: (scope: { companyId: string }) => Promise) { const cursors = new Map(); diff --git a/server/src/services/run-cost-accounting.ts b/server/src/services/run-cost-accounting.ts index bbd5f090b10..fcf5d0062cf 100644 --- a/server/src/services/run-cost-accounting.ts +++ b/server/src/services/run-cost-accounting.ts @@ -166,8 +166,8 @@ const nativeProviderWorkNeverStarted = sql`${heartbeatRuns.runtimeMode} = 'nativ /** A run's accounting settled: an admission hold may have cleared. Held work * (queued runs, saved messages and Retries, and tasks whose start or * continuation was refused) waits passively, so wake its owners. */ -async function notifyAccountingHoldRelease(tx: object, companyId: string) { - await promoteDeferredWorkIntents(tx, { companyId, trigger: "accounting_settled" }); +async function notifyAccountingHoldRelease(tx: object, companyId: string, runId: string) { + await promoteDeferredWorkIntents(tx, { companyId, trigger: "accounting_settled", runId }); } export const ACCOUNTING_CLOSURE_TIMEOUT_MS = REMOTE_RUNNER_RECONNECT_GRACE_MS + 3 * 60_000; @@ -289,11 +289,11 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService if (run.costAccountedAt) { if (object(run.usageJson).accountingLateReceiptPending === true) { // Clearing late debt can release an admission hold too. - await notifyAccountingHoldRelease(tx, run.companyId); + await notifyAccountingHoldRelease(tx, run.companyId, run.id); return reconcileLateRunUsageReceiptInTransaction(tx, run, publications); } await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: run.agentId }); - await notifyAccountingHoldRelease(tx, run.companyId); + await notifyAccountingHoldRelease(tx, run.companyId, run.id); await tx.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, run.id)); await queueBudgetEvaluation(tx, { companyId: run.companyId, agentId: run.agentId, projectId: text(object(object(run.usageJson).ledgerScope).projectId) }); @@ -333,7 +333,7 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService // Acknowledgement is part of the same transaction. Budget checks inside // this transaction must not mistake this receipt for missing accounting. await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: run.agentId }); - await notifyAccountingHoldRelease(tx, run.companyId); + await notifyAccountingHoldRelease(tx, run.companyId, run.id); await tx.update(heartbeatRuns).set({ costAccountingPending: false, costAccountedAt: new Date() }).where(eq(heartbeatRuns.id, run.id)); await tx.update(budgetReservations).set({ state: preProviderFailure ? "released" : "settled", settledAt: new Date() }) .where(and(eq(budgetReservations.companyId, run.companyId), eq(budgetReservations.runId, run.id), eq(budgetReservations.state, "held"))); @@ -426,7 +426,7 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService await queueBudgetEvaluation(tx, { companyId: run.companyId, agentId: run.agentId, projectId: text(scope.projectId) }); // Late usage reported by a later run can arrive before this charge posts. const lateDebt = usage.accountingLateReceiptPending === true; - if (!lateDebt) await notifyAccountingHoldRelease(tx, run.companyId); + if (!lateDebt) await notifyAccountingHoldRelease(tx, run.companyId, run.id); await tx.update(heartbeatRuns).set({ costAccountingPending: lateDebt, costAccountedAt: new Date(), accountingProjectionVersion: "v2", accountingLastError: lateDebt ? "late_usage_requires_reconciliation" : null, accountingLastAttemptAt: new Date(), // A complete receipt arriving later may price this charge (see usage-receipts). diff --git a/server/src/services/run-dispatch-notifications.ts b/server/src/services/run-dispatch-notifications.ts index 36fad0e81a3..4b0f9fe6556 100644 --- a/server/src/services/run-dispatch-notifications.ts +++ b/server/src/services/run-dispatch-notifications.ts @@ -1,7 +1,7 @@ -import { notifyIssueRecovery } from "./issue-recovery-notifications.js"; +import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; -export type RunDispatchScope = { companyId: string }; +export type RunDispatchScope = { companyId: string; issueId?: string | null; runId?: string | null }; export async function notifyQueuedRunDispatch(transaction: object, scope?: RunDispatchScope) { await notifyDeliveryWork(transaction, DELIVERY_QUEUES.queuedRunDispatch, @@ -9,7 +9,8 @@ export async function notifyQueuedRunDispatch(transaction: object, scope?: RunDi } export async function notifyRunDispatch(transaction: object, scope?: RunDispatchScope) { - await notifyIssueRecovery(transaction, scope ? { companyId: scope.companyId } : undefined); + if (scope?.issueId || scope?.runId) await notifyIssueGraphRecovery(transaction, scope); + else await notifyIssueRecovery(transaction, scope ? { companyId: scope.companyId } : undefined); const hint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*"; await notifyDeliveryWork(transaction, DELIVERY_QUEUES.nativeProcessSessions, hint); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.executionReplacement, hint); diff --git a/server/src/services/scoped-deadline-work.ts b/server/src/services/scoped-deadline-work.ts index b750d3426c4..b6ad70881c6 100644 --- a/server/src/services/scoped-deadline-work.ts +++ b/server/src/services/scoped-deadline-work.ts @@ -26,6 +26,7 @@ export function registerScopedDeadlineWork( admitDueWhileActive?: boolean; }; reconstructionIntervalMs?: number | ((scope: Scope | undefined) => number); + backstop?(scope: Scope | undefined): number | null; beforePass?(): Promise; decodeScope(hint: string): Scope | undefined; matches(entry: Entry, scope?: Scope): boolean; @@ -67,6 +68,12 @@ export function registerScopedDeadlineWork( decodedScopes.set(hint, scope); return scope; } + function backstopAt(hint: string) { + if (!options.backstop) return null; + try { return options.backstop(decode(hint)); } catch { return null; } + } + const holdsIdle = (hint: string) => backstopAt(hint) === null; + const gate = (hint: string) => Math.max(reconstructAfter.get(hint) ?? 0, backstopAt(hint) ?? 0); function forgetDecoded() { for (const hint of decodedScopes.keys()) if (!dirty.has(hint) && !scans.has(hint)) decodedScopes.delete(hint); } @@ -92,14 +99,14 @@ export function registerScopedDeadlineWork( function dirtyScopes() { return [...dirty].filter(hint => hint !== "*" || !scopeFailures.has(hint)) .filter(hint => !scans.has(hint) || scopeFailures.has(hint)) - .filter(hint => (reconstructAfter.get(hint) ?? 0) <= Date.now() || scopeFailures.has(hint)) + .filter(hint => gate(hint) <= Date.now() || scopeFailures.has(hint)) .map(hint => { try { return decode(hint); } catch { return undefined; } }); } function next() { if (!canRun()) return dirty.size > 0 || entries.size > 0 ? Date.now() + 30_000 : null; let nextAt: number | null = null; const take = (at: number) => { nextAt = nextAt === null ? at : Math.min(nextAt, at); }; - for (const hint of dirty) take(Math.max(earliest, reconstructAfter.get(hint) ?? 0, scopeFailures.get(hint)?.retryAt ?? 0)); + for (const hint of dirty) take(Math.max(earliest, gate(hint), scopeFailures.get(hint)?.retryAt ?? 0)); const unavailable = matcher(dirtyScopes()); for (const entry of entries.values()) if (!unavailable(entry)) take(Math.max(earliest, entry.dueAt, failures.get(entry.id)?.retryAt ?? 0)); @@ -119,7 +126,7 @@ export function registerScopedDeadlineWork( for (const [hint, until] of reconstructAfter) { if (until <= Date.now()) reconstructAfter.delete(hint); } - const ready = [...dirty].filter(hint => Math.max(reconstructAfter.get(hint) ?? 0, scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now()); + const ready = [...dirty].filter(hint => Math.max(gate(hint), scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now()); if (ready.length === 0 && ![...entries.values()].some(entry => Math.max(entry.dueAt, failures.get(entry.id)?.retryAt ?? 0) <= Date.now())) return; earliest = Date.now() + (options.minimumPassIntervalMs ?? 1000); try { await options.beforePass?.(); } catch (error) { @@ -325,7 +332,7 @@ export function registerScopedDeadlineWork( }, // Retain scopes/deadlines for resume without retaining a settled write's // idle hold during drain. The coordinator still fences unresolved XIDs. - hasPending: async () => canRun() && dirty.size > 0, + hasPending: async () => canRun() && [...dirty].some(holdsIdle), nextRunAt: next, nextRunAtOnError: next, }); @@ -337,7 +344,7 @@ export function registerScopedDeadlineWork( return { ...worker, reconciliationSnapshot: (): DeadlineReconciliationSnapshot => ({ revision: `${ownerRevision}:${revision}`, - reconciled: !stopped && !running && !lastRunFailed && dirty.size === 0 && scans.size === 0 + reconciled: !stopped && !running && !lastRunFailed && ![...dirty].some(holdsIdle) && scans.size === 0 && failures.size === 0 && scopeFailures.size === 0, }), wake() { revision++; worker.wake(); }, diff --git a/server/src/services/slack-conversation-lifecycle.ts b/server/src/services/slack-conversation-lifecycle.ts index 611f07f1a41..1ed652390a4 100644 --- a/server/src/services/slack-conversation-lifecycle.ts +++ b/server/src/services/slack-conversation-lifecycle.ts @@ -6,7 +6,7 @@ import { and, asc, desc, eq, gt, inArray, isNull, sql } from "drizzle-orm"; import { chatConversations, chatEndpoints, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db"; import { persistActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; -export type ExternalConversationSettlementScope = { companyId: string; issueId?: string }; +export type ExternalConversationSettlementScope = { companyId: string; issueId?: string; runId?: string }; diff --git a/server/src/services/work-intent-outbox.ts b/server/src/services/work-intent-outbox.ts index 54d0eef5c39..39da2efca12 100644 --- a/server/src/services/work-intent-outbox.ts +++ b/server/src/services/work-intent-outbox.ts @@ -1,5 +1,5 @@ import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; -import { agentWakeupRequests, issueComments, issues, type Db } from "@paperclipai/db"; +import { agentWakeupRequests, budgetPolicies, issueComments, issues, type Db } from "@paperclipai/db"; import { notifyDeferredExecutionEligibility, notifyDeferredExecutionWork, notifyDeferredWakesForIssue } from "./deferred-execution-notifications.js"; import { withQueuedCommentIdsInWakePayload } from "./issue-queued-comment-queue.js"; import { deliveredQueuedCommentIds } from "./queued-comment-delivery.js"; @@ -65,12 +65,17 @@ const DEFERRED_RETRY_BACKOFF = sql`interval '30 seconds'`; * issue by id. All notifications publish on commit. */ export async function promoteDeferredWorkIntents(tx: object, input: { - companyId: string; trigger: WorkIntentHoldTrigger; issueId?: string | null; + companyId: string; trigger: WorkIntentHoldTrigger; issueId?: string | null; runId?: string | null; }) { + const hardStop = input.trigger === "accounting_settled" && input.runId ? (await (tx as Pick) + .select({ id: budgetPolicies.id }).from(budgetPolicies).where(and(eq(budgetPolicies.companyId, input.companyId), + eq(budgetPolicies.isActive, true), eq(budgetPolicies.hardStopEnabled, true))).limit(1)).length > 0 : true; + const scope = input.trigger === "lock_released" && input.issueId ? { companyId: input.companyId, issueId: input.issueId } + : input.trigger === "accounting_settled" && input.runId && !hardStop ? { companyId: input.companyId, runId: input.runId } : null; // Register the work signals before the write they announce. - await notifyRunDispatch(tx, { companyId: input.companyId }); + await notifyRunDispatch(tx, scope ?? { companyId: input.companyId }); await notifyDeferredExecutionEligibility(tx, { companyId: input.companyId }); - await notifyIssueRecovery(tx, { companyId: input.companyId }); + if (!scope) await notifyIssueRecovery(tx, { companyId: input.companyId }); if (input.issueId) await notifyDeferredWakesForIssue(tx, { companyId: input.companyId, issueId: input.issueId }); const db = tx as Pick; await db.update(agentWakeupRequests).set({ From a1c37b5cc4d758c8194a8102f0250a7ff08f574b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:05:45 -0600 Subject: [PATCH 3/8] perf(chat): rebuild GitHub response sweeps for company-wide hints at most every 30 seconds (#21580) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The GitHub chat channel has two background sweeps for request response comments: acknowledgements, and terminal responses. Each sweep rebuilds its candidate set when a hint arrives, and it reads the latest run of each candidate request (`readGitHubResponseRun`) on each rebuild > - A run milestone for a run with no task sends a company-wide hint to both sweeps. Examples: each status change of a run without a task (`setRunStatus`), and a comment merged into an active run in the wake queue. In a busy company these hints arrive more than once a second > - So both sweeps rebuild the whole company about once a second (their minimum pass interval). Each rebuild reads every parked request again, although nothing about those requests changed. On a hosted test database, `readGitHubResponseRun` ran 6.7 times a second > - This pull request rebuilds a GitHub response sweep for a company-wide hint at most once every 30 seconds. Issue, request, conversation, endpoint and lease hints still rebuild immediately. `external-objects.ts` uses the same rule for its refresh sweep > - The benefit is that a steady stream of company-wide hints no longer makes each sweep read every parked request every second ## Linked Issues or Issue Description Refs #21577 (makes each `readGitHubResponseRun` call cheap; this pull request reduces how often the sweeps call it). Refs #18384 (the same reconstruction interval for company-wide external-object hints). **What existing behavior does this improve?** The candidate rebuild of `registerGitHubAcknowledgementWork` (`acknowledgement-work.ts`) and `registerGitHubTerminalResponseWork` (`terminal-response-work.ts`) for company-wide hints. **Subsystem affected** GitHub chat channel: request acknowledgement and terminal-response recovery sweeps. **Current behavior** `notifyChatRunMilestones` calls `notifyChatResponseAvailability` with its scope. When the scope has no issue (only a company, or a company and a run), the hint for both GitHub response queues is company-wide (`{"companyId": ...}`), because the response scope has no run field. Each company-wide hint makes each sweep load every candidate of the company and call `readGitHubResponseRun` for each one. Passes are limited to one a second, so with a steady hint stream the cost is about (parked candidates) reads a second. **Proposed behavior** Both sweeps set `reconstructionIntervalMs`. A company-wide scope (company ID only) waits 30 seconds after its last rebuild before it rebuilds again. All narrower scopes, the startup scope (`*`), and saved deadlines are not changed. Entries that are already loaded stay available for dispatch while a company-wide hint waits, and each check still reads the request again from the database. **Reason and benefit** On the hosted test database, `readGitHubResponseRun` ran 6.7 times a second for no change in state. In a local reproduction, the call rate drops from about one call for each parked request each second to one call for each parked request each 30 seconds. **Breaking changes** None. ## What Changed - Add `response-sweep-scope.ts` with the shared scope type of the two GitHub response sweeps and `githubResponseReconstructionIntervalMs`: 30 seconds for a company-wide scope, 0 for all other scopes. - Use it as `reconstructionIntervalMs` in the acknowledgement sweep and the terminal-response sweep. Both files now import the shared scope type instead of declaring it. - Add `response-sweep-scope.test.ts`. It registers both real sweeps on a real database with 6 parked requests (3 for each sweep) and a controlled clock. It sends company-wide hints and issue hints, and counts `readGitHubResponseRun` statements on each pass. ## Verification Cause, from a local reproduction with the real delivery coordinator and both real sweeps on embedded PostgreSQL 18.1, with 8 parked requests (4 for each sweep), each with a succeeded native run that waits for its presentation: | Hints | Hints a second | `readGitHubResponseRun` calls a second | | --- | --- | --- | | None | 0 | 0 | | Company-wide run milestone (`{ companyId, runId }`) | 9.7 | 8.75 | | Company-wide run milestone | 1.0 | 7.98 | | Run milestone for an unrelated issue | 9.7 | 0 | So the call rate is about one call for each parked request each second, from company-wide hints only. The hosted rate (6.7 a second) is consistent with about 7 parked GitHub requests in one company. Red/green regression test: - `cd server && npx vitest run src/services/chat-channels/github/response-sweep-scope.test.ts` - Red (without the two `reconstructionIntervalMs` lines): `expected [ 6, 6, 6, 6, 6 ] to deeply equal [ 6, +0, +0, +0, +0 ]`. Each of 5 company-wide hints rebuilt all 6 parked requests. - Green: 2 of 2 pass. The first company-wide hint rebuilds once (6 reads). The next 4 hints read nothing. After 30 seconds, the waiting hint rebuilds (6 reads). Issue hints still read exactly the one request of that issue at once, and a hint for another company reads nothing. No acknowledgement is sent for a parked request. Other checks: - `cd server && npx vitest run src/__tests__/chat-channels.integration.test.ts -t ithub`: 104 passed (all GitHub chat-channel integration tests, including the acknowledgement and terminal-response sweeps). - `cd server && npx tsc --noEmit`: passed. - After the rebase onto #21577: both new test files pass (4 of 4), and the server typecheck passes. - `pnpm verify` selected most of the server suite, because the sweep modules are imported widely. I stopped that broad local run. Required CI supplies that coverage. ## Risks - A change that only a company-wide hint reports can take up to 30 seconds to rebuild a GitHub response sweep. I checked the callers. Changes to one request use issue, delivery, conversation or lease hints: run status changes with a task, native presentation commits (`status-decision-committer.ts`, `native-run-finalizer.ts`, `native-chat-review-presentation.ts`), publications, fast responses, and the publication lease. Those stay immediate. Company-wide hints come from runs with no task, from a comment merged into an active run (the wake queue sends only the run ID), and from company authority changes. A run with no task cannot change the latest run of a GitHub request's task. For a merged comment, the active run's next status change sends an issue hint, and staging the request's response sends a delivery hint; both rebuild at once. Only a mid-run ownership update can wait up to 30 seconds. For an authority change, each check reads the request and its authority again before it acts. - The deadline reconciliation snapshot reports these two sweeps as not reconciled while a company-wide hint waits (up to 30 seconds). This is the same as the external-object refresh sweep. - The startup rebuild (`*`) and failure retries do not change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic. Used through Claude Code with tool use (shell, file edits, and local PostgreSQL reproductions). ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../github/acknowledgement-work.ts | 5 +- .../github/response-sweep-scope.test.ts | 118 ++++++++++++++++++ .../github/response-sweep-scope.ts | 10 ++ .../github/terminal-response-work.ts | 5 +- 4 files changed, 132 insertions(+), 6 deletions(-) create mode 100644 server/src/services/chat-channels/github/response-sweep-scope.test.ts create mode 100644 server/src/services/chat-channels/github/response-sweep-scope.ts diff --git a/server/src/services/chat-channels/github/acknowledgement-work.ts b/server/src/services/chat-channels/github/acknowledgement-work.ts index 6bd60b0ed78..60e0db1cb7a 100644 --- a/server/src/services/chat-channels/github/acknowledgement-work.ts +++ b/server/src/services/chat-channels/github/acknowledgement-work.ts @@ -5,10 +5,8 @@ import { chatActions, chatConversations, chatEndpointLeases, chatEndpointResourc chatPublications, fastResponseRequests, chatEndpoints, chatMessageLinks, type Db } from "@paperclipai/db"; import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; -import type { ChatResponseScope } from "../../chat-response-availability.js"; import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js"; - -type Scope = ChatResponseScope & { endpointId?: string; repositoryId?: string; number?: number }; +import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js"; type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string; issueId: string | null; conversationId: string | null; repositoryId: string | null; number: number | null; dueAt: number }; type FastResponse = { status: string; expiresAt: string; publicationState: string | null }; @@ -83,6 +81,7 @@ export function registerGitHubAcknowledgementWork( } return registerScopedDeadlineWork(coordinator, { queue: DELIVERY_QUEUES.chatGitHubAcknowledgements, + reconstructionIntervalMs: githubResponseReconstructionIntervalMs, decodeScope: (hint: string): Scope | undefined => hint === "*" ? undefined : JSON.parse(hint), matches: (value: Entry, scope?: Scope) => !scope || (value.companyId === scope.companyId && (!scope.issueId || value.issueId === scope.issueId) && (!scope.deliveryId || value.deliveryId === scope.deliveryId) && diff --git a/server/src/services/chat-channels/github/response-sweep-scope.test.ts b/server/src/services/chat-channels/github/response-sweep-scope.test.ts new file mode 100644 index 00000000000..f162a1689ec --- /dev/null +++ b/server/src/services/chat-channels/github/response-sweep-scope.test.ts @@ -0,0 +1,118 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { createDb, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js"; +import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js"; +import { GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS } from "./response-sweep-scope.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; + +type Task = { run(signal: AbortSignal): Promise; onSettled?(hints?: ReadonlySet): void }; + +suite("GitHub response sweep scopes", () => { + let db!: Db; + let temporary: Awaited> | null = null; + let companyId = ""; + const parkedIssues: string[] = []; + let clock = Date.now(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-github-response-sweep-scope-"); + db = createDb(temporary.connectionString); + const client = db.$client; + const [{ company }] = await client.unsafe(`insert into companies (name, issue_prefix) values ('Sweep', 'SW') returning id as company`); + companyId = company; + const [{ agent }] = await client.unsafe(`insert into agents (company_id, name) values ($1, 'GitHub agent') returning id as agent`, [company]); + const [{ application }] = await client.unsafe(`insert into tool_applications (company_id, application_key, name, type) + values ($1, 'github', 'GitHub', 'chat') returning id as application`, [company]); + const [{ connection }] = await client.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose) + values ($1, $2, 'GitHub', 'github-sweep', 'chat_sdk', 'channel') returning id as connection`, [company, application]); + const [{ endpoint }] = await client.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status) + values ($1, $2, 'github', 'sweep', $3, 'active') returning id as endpoint`, [company, connection, agent]); + for (let n = 1; n <= 6; n++) { + const [{ issue }] = await client.unsafe(`insert into issues (company_id, title, status) values ($1, $2, 'in_progress') returning id as issue`, + [company, `Issue ${n}`]); + parkedIssues.push(issue); + const [{ conversation }] = await client.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id, + external_conversation_id, external_label, external_thread_id) values ($1, $2, $3, $4, $4, $4) returning id as conversation`, + [company, endpoint, issue, `github:paperclipai/paperclip:${n}`]); + const [{ delivery }] = await client.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id, deduplication_key, + event_kind, normalized_event, conversation_id, state) values ($1, $2, $3, $3, 'message', '{}', $4, 'processed') returning id as delivery`, + [company, endpoint, `event-${n}`, conversation]); + const [{ comment }] = await client.unsafe(`insert into issue_comments (company_id, issue_id, body) values ($1, $2, 'Request') + returning id as comment`, [company, issue]); + await client.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id, + provider_message_id, direction) values ($1, $2, $3, $4, $5, $6, 'inbound')`, + [company, endpoint, conversation, delivery, comment, `in-${n}`]); + await client.unsafe(`insert into chat_actions (company_id, endpoint_id, delivery_id, conversation_id, kind, provider_action_id, status, result) + values ($1, $2, $3, $4, 'github_response_comment', $5, $6, $7::jsonb)`, + [company, endpoint, delivery, conversation, `github_response:${delivery}`, n % 2 ? "received" : "processed", + n % 2 ? null : JSON.stringify({ id: `IC_${n}`, final: false })]); + await client.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, runtime_mode, scope_kind, issue_id, native_issue_id, + context_snapshot, finished_at) values ($1, $2, 'succeeded', 'native', 'issue', $3, $3, $4::jsonb, now())`, + [company, agent, issue, JSON.stringify({ issueId: issue, wakeCommentId: comment })]); + } + }, 120_000); + + afterEach(() => { vi.restoreAllMocks(); }); + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + function sweeps() { + let reads = 0; + const counted = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + selection.execute = (async () => { + if (selection.toSQL().sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) reads += 1; + return execute(); + }) as typeof selection.execute; + return selection; + }) as typeof builder.from; + return builder; + }; + } }) as Db; + const tasks: Task[] = []; + const coordinator = { register: (_queue: unknown, task: Task) => { tasks.push(task); return { wake() {}, stop: async () => {} }; } }; + const acknowledge = vi.fn(async () => undefined); + registerGitHubAcknowledgementWork(counted, coordinator as never, acknowledge, () => true); + registerGitHubTerminalResponseWork(counted, coordinator as never, acknowledge, () => true); + vi.spyOn(Date, "now").mockImplementation(() => clock); + const pass = async (hint?: string) => { + clock += 2_000; + const before = reads; + for (const task of tasks) { + if (hint) task.onSettled?.(new Set([hint])); + await task.run(new AbortController().signal); + } + return reads - before; + }; + return { pass, acknowledge }; + } + + it("rebuilds parked requests once per interval for company-wide hints", async () => { + const { pass, acknowledge } = sweeps(); + expect(await pass()).toBe(parkedIssues.length); + const companyHint = JSON.stringify({ companyId }); + const repeated = []; + for (let index = 0; index < 5; index++) repeated.push(await pass(companyHint)); + expect(repeated).toEqual([parkedIssues.length, 0, 0, 0, 0]); + clock += GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS; + expect(await pass()).toBe(parkedIssues.length); + expect(acknowledge).not.toHaveBeenCalled(); + }, 60_000); + + it("still rebuilds an issue, request or other company immediately", async () => { + const { pass } = sweeps(); + await pass(); + await pass(JSON.stringify({ companyId })); + expect(await pass(JSON.stringify({ companyId, issueId: parkedIssues[0] }))).toBe(1); + expect(await pass(JSON.stringify({ companyId, issueId: parkedIssues[1] }))).toBe(1); + expect(await pass(JSON.stringify({ companyId, issueId: parkedIssues[0] }))).toBe(1); + expect(await pass(JSON.stringify({ companyId: randomUUID() }))).toBe(0); + }, 60_000); +}); diff --git a/server/src/services/chat-channels/github/response-sweep-scope.ts b/server/src/services/chat-channels/github/response-sweep-scope.ts new file mode 100644 index 00000000000..b4d0290c48e --- /dev/null +++ b/server/src/services/chat-channels/github/response-sweep-scope.ts @@ -0,0 +1,10 @@ +import type { ChatResponseScope } from "../../chat-response-availability.js"; + +export type GitHubResponseSweepScope = ChatResponseScope & { endpointId?: string; repositoryId?: string; number?: number }; + +export const GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS = 30_000; + +export function githubResponseReconstructionIntervalMs(scope: GitHubResponseSweepScope | undefined) { + return scope && !scope.issueId && !scope.deliveryId && !scope.conversationId && !scope.endpointId + && !scope.repositoryId && !scope.number ? GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS : 0; +} diff --git a/server/src/services/chat-channels/github/terminal-response-work.ts b/server/src/services/chat-channels/github/terminal-response-work.ts index cb1f240bb9e..fd60d7538e5 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.ts @@ -3,12 +3,10 @@ import { chatActions, chatConversations, chatDeliveries, chatEndpointLeases, cha chatEndpoints, chatMessageLinks, heartbeatRuns, issues, type Db } from "@paperclipai/db"; import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; -import type { ChatResponseScope } from "../../chat-response-availability.js"; import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js"; import { githubResponseExecution } from "./response-execution.js"; +import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js"; import { HttpError } from "../../../errors.js"; - -type Scope = ChatResponseScope & { endpointId?: string; repositoryId?: string; number?: number }; type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string; issueId: string; conversationId: string; repositoryId: string | null; number: number | null; dueAt: number }; @@ -87,6 +85,7 @@ export function registerGitHubTerminalResponseWork( return registerScopedDeadlineWork(coordinator, { queue: DELIVERY_QUEUES.chatGitHubTerminalResponses, + reconstructionIntervalMs: githubResponseReconstructionIntervalMs, decodeScope: (hint: string): Scope | undefined => hint === "*" ? undefined : JSON.parse(hint), matches: (value: Entry, scope?: Scope) => !scope || (value.companyId === scope.companyId && (!scope.issueId || value.issueId === scope.issueId) && (!scope.deliveryId || value.deliveryId === scope.deliveryId) && From e8c79235ca34387fe7983e35249bc8fe8df04787 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:17:21 -0600 Subject: [PATCH 4/8] perf(attention): scope run lifecycle retention hints and read only used columns (#21579) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The `attention-retention` queue archives old attention items (failed runs, reviews, questions, recovery actions, blocked tasks). A company hint makes it reload every candidate of the company, 100 per page, with eligibility reads for each page. > - Several run lifecycle producers sent that company hint: every agent status change after a run, the execution-control writes and legacy run terminalization when they name only a run, scheduled retries, and the Runner's task monitor tool. > - Each page also read whole rows it did not use: full `heartbeat_runs` rows (recent ones carry tens of KB of `context_snapshot` and `runner_profile_json`), full `issues` rows (descriptions), and the whole agent roster with its configuration. > - This pull request names the task graph or the source kind in those hints, and reads only the columns each eligibility decision uses. > - The benefit is fewer company reloads per run event and far fewer result bytes per reconstruction, with the same decisions. ## Linked Issues or Issue Description No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. Stacked on #21552 (it builds on that pull request's change to `execution-control-notifications.ts`); review that one first. **What existing behavior does this improve?** The attention retention queue (`server/src/services/attention-retention.ts`) and the producers that wake it on run lifecycle paths. **Subsystem affected** Server background retention (`attention-retention.ts`, `retention-work-notifications.ts`, `execution-control-notifications.ts`, `heartbeat/agent-status.ts`, `heartbeat/retries.ts`, `native-runtime/paperclip-runner-tool-authority.ts`). **Current behavior** - `heartbeat/agent-status.ts` sends `{ companyId }` on every agent status change after a run (two places). `heartbeat/retries.ts` sends it for each scheduled retry. `writeExecutionControl` and `notifyExecutionRunWork` send it when the scope names only a run. The Runner's `set_task_monitor` tool sends it for one task. - On a local fixture with 1,500 open tasks and run churn, the queue loaded 47 company candidate rows per second from these hints. - `pageEvidence` read `select *` from `heartbeat_runs`, `issue_recovery_actions` and (through `getTableColumns`) `issues`; `reviewEligibility` read `select *` from `issues`; `interactionEligibility` read the full agent roster; the per-entry `check` repeated full-row reads. **Proposed behavior** - Agent status changes send `{ companyId, sourceKind: "agent_error_alert" }`. The status moves between `running`, `idle` and `error`. All three are invokable for blocker attention (`BLOCKER_ATTENTION_INVOKABLE_AGENT_STATUSES`) and for questions (`agent-eligibility.ts`). Failed-run attention only excludes terminated agents, and this path never sets that. So only agent error alerts can change. - Run-scoped execution-control writes, legacy run terminalization and scheduled retries use `notifyIssueAttentionRetentionWork` with the run id (the run's task, its parents and the tasks it blocks; company fallback past 100). This is the same helper as #21521. The task monitor tool scopes to its task. - `notifyIssueAttentionRetentionWork` matched the run's saved task id with `issue.id::text = …`. It now validates and casts the id, so the primary key is used, as #21552 does for recovery. - Narrow reads, same decisions: - runs: `id`, `agent_id`, `created_at` and the saved task id computed in SQL with the same rules as `readRunIssueId` (`issueId` unless it is absent or JSON null, then `taskId`; only non-empty strings). - recovery actions: `id`, `source_issue_id`. - issues for evidence and `visibleIssue`: the blocker-attention input columns plus `unblock_descriptor` and `blocked_transition_at`. - review issues: `id`, `company_id`, `status`, `execution_state`, `assignee_user_id`. - agent roster for question addressees: `id`, `company_id`, `name`, `reports_to`, `status` (the `AgentOrgRow` that `evaluateAgentInvokability` takes). **Reason and benefit** A run event no longer reloads every attention candidate of the company. A reconstruction no longer transfers whole run, task and agent rows. ## What Changed - `server/src/services/attention-retention.ts`: column lists for runs, recovery actions, issues and the roster; the run probe type replaces whole rows. - `server/src/services/heartbeat/agent-status.ts`, `heartbeat/retries.ts`, `execution-control-notifications.ts`, `native-runtime/paperclip-runner-tool-authority.ts`: scoped attention hints. - `server/src/services/retention-work-notifications.ts`: indexed lookup of a run's saved task. - `server/src/__tests__/attention-retention-work.test.ts`: two tests. ## Verification - `reads only the fields its decisions use from large runs, reviews and agents` (I saw it fail first): 50 failed runs, 50 tasks in review with large descriptions, 10 questions to a paused agent, about 40 KB of payload in each run's snapshot, profile and stdout and in the agents' configuration. It loads the three kinds with the full-size response capture (`full-database-response-capture.ts`). Before: `heartbeat_runs` 6,317,700 bytes, `agents` 84,336 bytes, `issues` 4,235,810 bytes. After: under the test bounds of 20,000, 5,000 and 60,000 bytes. The decisions are the same before and after: 50 failed runs, 40 reviews and 10 questions. - `scopes run lifecycle attention hints to the run's task graph and agent status to agent alerts` (I saw it fail first): `writeExecutionControl` and `notifyExecutionRunWork` with a run id send the hint for the task and its parent. `finalizeAgentStatus` sends the agent-alert hint. Before, all three sent `{ companyId }`. - `attention-retention-work` (57 tests), `attention-retention-candidates`, `attention-service`, `execution-control-work` and `heartbeat-agent-status-recovery` pass, each file run alone (in `server/`, against a dedicated local `_test` database). - `pnpm check:module-boundaries` passes. Not done in this pull request, and why: - I did not reproduce `syncItems` re-syncing unchanged rows from the retention `check`. On my fixture (300 stalled blocked tasks, 4,500 old recovery-action and blocker retention rows, run churn), `syncItems` ran 0 times in a 180-second window and `decision_retention` reads were 0 per second. `check` calls `syncItems` only for entries that are already due (older than the 90-day archive delay), and a due entry is archived and leaves the candidates. So I did not batch `syncItems` or skip checks of unchanged rows. - `readIssues` still selects the `issues` columns that blocker attention needs. I did not narrow `issueService.listBlockerAttentionBatch`. ## Risks - A producer that changes more than the run's task graph would now miss the wider effect. Company-level changes (agent configuration, company status, budgets) keep their company hints. The 90-day archive delay makes a missed reload cheap: the item is reloaded on the next hint that covers it. - The saved task id now comes from SQL. The SQL mirrors `readRunIssueId` for strings, absent keys and JSON null. A non-string `issueId` value now yields no task, as before. - No schema change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../2026-11-13-thousand-concurrent-agents.md | 17 ++++++ .../attention-retention-work.test.ts | 61 ++++++++++++++++++- server/src/services/attention-retention.ts | 48 +++++++++------ .../execution-control-notifications.ts | 2 +- server/src/services/heartbeat/agent-status.ts | 4 +- server/src/services/heartbeat/retries.ts | 4 +- .../paperclip-runner-tool-authority.ts | 4 +- .../services/retention-work-notifications.ts | 8 ++- 8 files changed, 120 insertions(+), 28 deletions(-) diff --git a/doc/plans/2026-11-13-thousand-concurrent-agents.md b/doc/plans/2026-11-13-thousand-concurrent-agents.md index a17a2113b99..0d40f80967f 100644 --- a/doc/plans/2026-11-13-thousand-concurrent-agents.md +++ b/doc/plans/2026-11-13-thousand-concurrent-agents.md @@ -276,6 +276,23 @@ turn, so memory per session counts for idle agents too. | 1g | Size the shared limiters (log uploads, checkpoint pool, recovery pass) from the active run count | no fixed slot count below the run count | | 1h | Keep one frozen, parsed tool catalog per catalog hash and company, shared by the sessions that use it, in place of two private copies per session (`assigned-mcp-tools.ts:146`) | server memory per live or warm session from about 5–11 MB (measured at 400–800 tools) to near zero; at 1,000 agents that is 5–11 GB | +### Background recovery sweeps + +Run events used to send a company recovery hint, so the stranded-assignment +and assigned-work queues re-checked every open task of the company on each +run event (#21552). Local fixture: 1,500 open tasks, 60 agents, process agents +that fail at once, 180-second window that includes one 5-minute backstop pass. + +| Build | Runs created (/s) | Stranded checks per window | Assigned-work checks per window | `agent_task_sessions` reads (/s) | Statements (/s) | +| --- | --- | --- | --- | --- | --- | +| Before #21552 (54c3616ad9) | 1.09 | 4,327 | 245 | 26.5 | 1,431 | +| #21552 at dcd170e29f | 1.00 | 702 | 276 | 7.2 | 1,060 | +| master at 340157d1d6 | 0.24 | 330 | 72 | 2.5 | 409 | + +The master row has much less run churn than the earlier rows, so compare the +per-window totals with care. In that window the one backstop pass loaded 260 +tasks into the stranded queue; run events loaded 147. + ### Phase 2: several controller processes (target: 1,000) | # | Change | diff --git a/server/src/__tests__/attention-retention-work.test.ts b/server/src/__tests__/attention-retention-work.test.ts index cb08a3de0e8..fbbae5a232e 100644 --- a/server/src/__tests__/attention-retention-work.test.ts +++ b/server/src/__tests__/attention-retention-work.test.ts @@ -9,7 +9,8 @@ import { attentionRetentionService, registerAttentionRetentionWork } from "../se import { workspaceOperationService } from "../services/workspace-operations.js"; import * as workspaceOperationLogs from "../services/workspace-operation-log-store.js"; import { budgetService, flushBudgetEvaluationWork } from "../services/budgets.js"; -import { writeExecutionControl } from "../services/execution-control-notifications.js"; +import { notifyExecutionRunWork, writeExecutionControl } from "../services/execution-control-notifications.js"; +import { createHeartbeatAgentStatus } from "../services/heartbeat/agent-status.js"; import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; import { attentionService } from "../services/attention.js"; import { companyService } from "../services/companies.js"; @@ -26,6 +27,7 @@ import { idleWorkSnapshot } from "../services/task-admission.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js"; const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_ATTENTION_RETENTION_TEST_DATABASE_URL"); const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); @@ -249,6 +251,45 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; expect(await db.select().from(decisionArchiveNotificationOutbox)).toHaveLength(0); }); + it("reads only the fields its decisions use from large runs, reviews and agents", async () => { + const payload = "saved-execution-input".repeat(2_000); + await db.update(agents).set({ adapterConfig: { instructions: payload }, runtimeConfig: { notes: payload } }).where(eq(agents.id, agentId)); + const origins = await db.insert(issues).values(Array.from({ length: 50 }, () => ({ companyId, + title: randomUUID(), status: "in_review", assigneeAgentId: agentId, description: payload, updatedAt: old() }))).returning(); + const runs = await db.insert(heartbeatRuns).values(origins.map(origin => ({ companyId, agentId, status: "failed", + contextSnapshot: { issueId: origin.id, prompt: payload }, runnerProfileJson: { instructions: payload }, + stdoutExcerpt: payload, createdAt: old(), finishedAt: old() }))).returning({ id: heartbeatRuns.id }); + await db.insert(heartbeatRunEvents).values(runs.map(run => ({ companyId, agentId, runId: run.id, + seq: 1, eventType: "lifecycle", message: "Bounded retry exhausted: byte fixture" }))); + const [paused] = await db.insert(agents).values({ companyId, name: "Paused", role: "engineer", status: "paused", + adapterConfig: { instructions: payload } }).returning({ id: agents.id }); + await db.insert(issueThreadInteractions).values(origins.slice(0, 10).map(row => ({ companyId, issueId: row.id, + kind: "ask_user_questions" as const, addresseeAgentId: paused.id, payload: { version: 1 as const, questions: [] } }))); + const observed = createDb(externalUrl ?? temporary!.connectionString), events: Array> = [], now = Date.now(); + const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns, issues, agents }, capture); + const decisions = new Map(); + try { + const service = attentionRetentionService(observed); + for (const sourceKind of ["failed_run", "review", "issue_thread_interaction"] as const) { + for (let page = 0; page < 3; page++) { + const loaded = await service.load({ companyId, sourceKind }); + for (const entry of loaded.rows ?? []) decisions.set(entry.id, `${entry.sourceKind}:${entry.dueAt}:${entry.activityAt}`); + if (loaded.complete) break; + } + } + capture.flush(); + } finally { capture.flush(); await observed.$client.end(); } + const bytes = (table: string) => events.filter(event => event.table === table && event.operation === "select") + .reduce((total, event) => total + Number(event.responseValueBytes), 0); + const kinds = [...decisions.values()].reduce((counts, value) => { + const kind = value.split(":")[0]; counts[kind] = (counts[kind] ?? 0) + 1; return counts; }, {} as Record); + expect(kinds).toEqual({ failed_run: 50, review: 40, issue_thread_interaction: 10 }); + expect(bytes("heartbeat_runs")).toBeLessThan(20_000); + expect(bytes("agents")).toBeLessThan(5_000); + expect(bytes("issues")).toBeLessThan(60_000); + }); + it("batches 100 failed runs and rechecks late visibility and supersession before archive", async () => { const origins = await db.insert(issues).values(Array.from({ length: 100 }, () => ({ companyId, title: randomUUID(), status: "todo", updatedAt: old() }))).returning(); @@ -877,6 +918,24 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; expect(hints).toEqual([scoped, scoped]); }); + it("scopes run lifecycle attention hints to the run's task graph and agent status to agent alerts", async () => { + const parent = await insertIssue("blocked"); + const issue = await insertIssue("todo", { parentId: parent.id }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", + contextSnapshot: { issueId: issue.id } }).returning(); + const hints: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.attentionRetention, (event, values) => { + if (event === "settled") hints.push(...values ?? []); + }); + try { + await writeExecutionControl(db, DELIVERY_QUEUES.executionFinalization, async () => undefined, { companyId, runId: run.id }); + await db.transaction(tx => notifyExecutionRunWork(tx, { companyId, runId: run.id })); + await createHeartbeatAgentStatus(db).finalizeAgentStatus(agentId, "failed"); + } finally { unsubscribe(); } + const scoped = JSON.stringify({ companyId, issueIds: [issue.id, parent.id].sort() }); + expect(hints).toEqual([scoped, scoped, JSON.stringify({ companyId, sourceKind: "agent_error_alert" })]); + }); + it("accepts ordinary liveness incident creation and completion with a none leaf sentinel", async () => { const source = await insertIssue("blocked", { responsibleUserId: "board" }); const service = issueService(db); diff --git a/server/src/services/attention-retention.ts b/server/src/services/attention-retention.ts index 568247e329f..930d27eeba6 100644 --- a/server/src/services/attention-retention.ts +++ b/server/src/services/attention-retention.ts @@ -1,8 +1,8 @@ -import { and, eq, getTableColumns, inArray, isNull, sql, type SQL } from "drizzle-orm"; +import { and, eq, inArray, isNull, sql, type SQL } from "drizzle-orm"; import { agents, decisionRetention, decisions, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, issues, approvals, type Db } from "@paperclipai/db"; import { evaluateAgentInvokability } from "./agent-invokability.js"; -import { HUMAN_RECOVERY_OWNER_TYPES, ATTENTION_BUDGET_WARNING_PERCENT, ATTENTION_AGENT_ERROR_STATUS, collapsePendingConfirmationsToNewest, listFailedRunsWithNewerRun, loadNewestSettledConfirmationAt, readRunIssueId, requiresReviewAttention, terminalBlockerRequiresAttention } from "./attention-source-eligibility.js"; +import { HUMAN_RECOVERY_OWNER_TYPES, ATTENTION_BUDGET_WARNING_PERCENT, ATTENTION_AGENT_ERROR_STATUS, collapsePendingConfirmationsToNewest, listFailedRunsWithNewerRun, loadNewestSettledConfirmationAt, requiresReviewAttention, terminalBlockerRequiresAttention } from "./attention-source-eligibility.js"; import { decisionRetentionService, DEFAULT_DECISION_ARCHIVE_DAYS } from "./decision-retention.js"; import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; @@ -23,12 +23,22 @@ type Candidate = { sourceKind: Kind; sourceId: string; companyId: string; activi type Entry = Candidate & { id: string; dueAt: number; rootId: string; variant?: "owner" | "terminal" }; type Cursor = { sourceKind: string; sourceId: string }; -type PageIssue = typeof issues.$inferSelect & { activityAt: string; deadlineAt: number; +const pageIssueColumns = { id: issues.id, companyId: issues.companyId, parentId: issues.parentId, identifier: issues.identifier, + title: issues.title, status: issues.status, assigneeAgentId: issues.assigneeAgentId, assigneeUserId: issues.assigneeUserId, + executionRunId: issues.executionRunId, unblockDescriptor: issues.unblockDescriptor, blockedTransitionAt: issues.blockedTransitionAt }; +const contextSnapshot = heartbeatRuns.contextSnapshot; +const runProbeColumns = { id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, createdAt: heartbeatRuns.createdAt, + issueId: sql`case when jsonb_typeof(${contextSnapshot}->'issueId') is not null and jsonb_typeof(${contextSnapshot}->'issueId') <> 'null' + then case when jsonb_typeof(${contextSnapshot}->'issueId') = 'string' then nullif(${contextSnapshot}->>'issueId', '') end + else case when jsonb_typeof(${contextSnapshot}->'taskId') = 'string' then nullif(${contextSnapshot}->>'taskId', '') end end` }; +type VisibleIssue = { [K in keyof typeof pageIssueColumns]: (typeof issues.$inferSelect)[K] }; +type PageIssue = VisibleIssue & { activityAt: string; deadlineAt: number; blockedActivityAt: string | null; blockedDeadlineAt: number | null }; +type RunProbe = { id: string; agentId: string; createdAt: Date; issueId: string | null }; type PageEvidence = { decisions: Map; - recoveries: Map; - runs: Map; + recoveries: Map; + runs: Map; agents: Set; visibleIssues: Map; newerRuns: Set; @@ -127,7 +137,7 @@ export function attentionRetentionService(db: Db) { const candidates = listAttentionRetentionCandidates; async function visibleIssue(database: Db, companyId: string, issueId: string, conversations = false) { - const [row] = await database.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId), + const [row] = await database.select(pageIssueColumns).from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId), attentionIssueCondition(conversations))); return row; } @@ -149,7 +159,8 @@ export function attentionRetentionService(db: Db) { const visible = await database.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, rows.map(row => row.issueId)), attentionIssueCondition(true))); const visibleIds = new Set(visible.map(row => row.id)); - const roster = await database.select().from(agents).where(eq(agents.companyId, companyId)); + const roster = await database.select({ id: agents.id, companyId: agents.companyId, name: agents.name, + reportsTo: agents.reportsTo, status: agents.status }).from(agents).where(eq(agents.companyId, companyId)); const boardAddressed = (row: typeof issueThreadInteractions.$inferSelect) => !row.addresseeAgentId || !evaluateAgentInvokability(roster.find(agent => agent.id === row.addresseeAgentId), roster).invokable; const confirmationIssueIds = rows.filter(row => row.kind === "request_confirmation").map(row => row.issueId); @@ -175,7 +186,8 @@ export function attentionRetentionService(db: Db) { byCompany.set(candidate.companyId, ids); } for (const [companyId, ids] of byCompany) { - const rows = await database.select().from(issues).where(and(eq(issues.companyId, companyId), + const rows = await database.select({ id: issues.id, companyId: issues.companyId, status: issues.status, + executionState: issues.executionState, assigneeUserId: issues.assigneeUserId }).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, ids), attentionIssueCondition(false))); const pendingApprovals = await database.select({ issueId: issueApprovals.issueId }).from(issueApprovals) .innerJoin(approvals, eq(approvals.id, issueApprovals.approvalId)).where(and( @@ -209,14 +221,15 @@ export function attentionRetentionService(db: Db) { const decisionIds = ids("decision"), recoveryIds = ids("recovery_action"), runIds = ids("failed_run"), blockerIds = ids("blocker_attention"); const decisionRows = decisionIds.length ? await database.select({ id: decisions.id, originIssueId: decisions.originIssueId }) .from(decisions).where(and(eq(decisions.companyId, companyId), inArray(decisions.id, decisionIds), eq(decisions.status, "open"))) : []; - const recoveryRows = recoveryIds.length ? await database.select().from(issueRecoveryActions).where(and( + const recoveryRows = recoveryIds.length ? await database.select({ id: issueRecoveryActions.id, + sourceIssueId: issueRecoveryActions.sourceIssueId }).from(issueRecoveryActions).where(and( eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.id, recoveryIds))) : []; - const runRows = runIds.length ? await database.select().from(heartbeatRuns).where(and( + const runRows: RunProbe[] = runIds.length ? await database.select(runProbeColumns).from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, runIds))) : []; const runAgents = runRows.length ? await database.select({ id: agents.id }).from(agents).where(and( eq(agents.companyId, companyId), inArray(agents.id, [...new Set(runRows.map(row => row.agentId))]), sql`${agents.status} <> 'terminated'`)) : []; - const readIssues = async (issueIds: string[]) => issueIds.length ? database.select({ ...getTableColumns(issues), + const readIssues = async (issueIds: string[]) => issueIds.length ? database.select({ ...pageIssueColumns, activityAt: sql`${issues.updatedAt}::text`, deadlineAt: sql`ceil(extract(epoch from ${issues.updatedAt}) * 1000 + ${archiveDelay})`.mapWith(Number), blockedActivityAt: sql`${issues.blockedTransitionAt}::text`, @@ -224,7 +237,7 @@ export function attentionRetentionService(db: Db) { }).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, [...new Set(issueIds)]), attentionIssueCondition(false))) : []; const issueIds = [...blockerIds, ...decisionRows.map(row => row.originIssueId), ...recoveryRows.map(row => row.sourceIssueId), - ...runRows.map(row => readRunIssueId(row.contextSnapshot))].filter((id): id is string => Boolean(id)); + ...runRows.map(row => row.issueId)].filter((id): id is string => Boolean(id)); const visibleRows = await readIssues(issueIds); const visible = new Map(visibleRows.map(row => [row.id, row])); const blockerRoots = visibleRows.filter(row => blockerIds.includes(row.id)); @@ -238,7 +251,7 @@ export function attentionRetentionService(db: Db) { decisions: new Map(decisionRows.map(row => [row.id, row])), recoveries: new Map(recoveryRows.map(row => [row.id, row])), runs: new Map(runRows.map(row => [row.id, row])), agents: new Set(runAgents.map(row => row.id)), visibleIssues: visible, newerRuns: await listFailedRunsWithNewerRun(database, companyId, - runRows.map(run => ({ ...run, issueId: readRunIssueId(run.contextSnapshot) }))), blockers, deferredRoots: blockerBatch.deferredRootIds, + runRows), blockers, deferredRoots: blockerBatch.deferredRootIds, }); } return result; @@ -261,7 +274,8 @@ export function attentionRetentionService(db: Db) { const attention = interactionAttention ?? await interactionEligibility(database, [candidate]); if (!attention.get(sourceId)) return null; } else if (candidate.sourceKind === "recovery_action") { - const row = evidence ? evidence.recoveries.get(sourceId) : (await database.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, candidate.companyId), eq(issueRecoveryActions.id, sourceId))))[0]; + const row = evidence ? evidence.recoveries.get(sourceId) : (await database.select({ id: issueRecoveryActions.id, + sourceIssueId: issueRecoveryActions.sourceIssueId }).from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, candidate.companyId), eq(issueRecoveryActions.id, sourceId))))[0]; if (!row || !(evidence ? evidence.visibleIssues.has(row.sourceIssueId) : await visibleIssue(database, candidate.companyId, row.sourceIssueId))) return null; } else if (candidate.sourceKind === "review") { @@ -297,14 +311,14 @@ export function attentionRetentionService(db: Db) { eq(decisionRetention.sourceKind, candidate.sourceKind), eq(decisionRetention.sourceId, sourceId))); if (retention?.keep || retention?.archivedAt) return null; } else if (candidate.sourceKind === "failed_run") { - const run = evidence ? evidence.runs.get(sourceId) : (await database.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, sourceId))))[0]; + const run: RunProbe | undefined = evidence ? evidence.runs.get(sourceId) : (await database.select(runProbeColumns).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, sourceId))))[0]; if (!run) return null; const agent = evidence ? evidence.agents.has(run.agentId) : (await database.select({ id: agents.id }).from(agents).where(and(eq(agents.companyId, candidate.companyId), eq(agents.id, run.agentId), sql`${agents.status} <> 'terminated'`)))[0]; - const issueId = readRunIssueId(run.contextSnapshot); + const issueId = run.issueId; if (!agent || issueId && !(evidence ? evidence.visibleIssues.has(issueId) : await visibleIssue(database, candidate.companyId, issueId))) return null; - if ((evidence ? evidence.newerRuns : await listFailedRunsWithNewerRun(database, candidate.companyId, [{ ...run, issueId }])).has(run.id)) return null; + if ((evidence ? evidence.newerRuns : await listFailedRunsWithNewerRun(database, candidate.companyId, [run])).has(run.id)) return null; } return { ...candidate, sourceId, activityAt, rootId: candidate.sourceId, variant, id: `${candidate.sourceKind}:${candidate.sourceId}:${variant ?? "source"}`, dueAt }; diff --git a/server/src/services/execution-control-notifications.ts b/server/src/services/execution-control-notifications.ts index a94ac36ec91..d01592d1da4 100644 --- a/server/src/services/execution-control-notifications.ts +++ b/server/src/services/execution-control-notifications.ts @@ -10,7 +10,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork, type DeliveryQueue } from "./deliv export type ExecutionWorkScope = { companyId: string; agentId?: string; runId?: string; issueId?: string }; async function notifyExecutionAttentionRetention(transaction: object, scope: ExecutionWorkScope) { - if (scope.issueId) await notifyIssueAttentionRetentionWork(transaction, { companyId: scope.companyId, issueId: scope.issueId }); + if (scope.issueId || scope.runId) await notifyIssueAttentionRetentionWork(transaction, { companyId: scope.companyId, issueId: scope.issueId, runId: scope.runId }); else await notifyAttentionRetentionWork(transaction, scope); } diff --git a/server/src/services/heartbeat/agent-status.ts b/server/src/services/heartbeat/agent-status.ts index 622e796b700..0d03f6ac828 100644 --- a/server/src/services/heartbeat/agent-status.ts +++ b/server/src/services/heartbeat/agent-status.ts @@ -94,7 +94,7 @@ export function createHeartbeatAgentStatus(db: Db) { const nextStatus = running ? "running" : settledStatus(outcome, options?.keepIdleOnFailure); const now = new Date(); await notifyStrandedAgentStatus(tx, { companyId: existing.companyId, agentId }); - await notifyAttentionRetentionWork(tx, { companyId: existing.companyId }); + await notifyAttentionRetentionWork(tx, { companyId: existing.companyId, sourceKind: "agent_error_alert" }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); const [updated] = await tx.update(agents).set({ status: nextStatus, @@ -152,7 +152,7 @@ export function createHeartbeatAgentStatus(db: Db) { eq(heartbeatRuns.agentId, candidate.id))) .orderBy(desc(heartbeatRuns.finishedAt), desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1); const nextStatus = settledStatus(lastRun?.status); - await notifyAttentionRetentionWork(tx, { companyId: candidate.companyId }); + await notifyAttentionRetentionWork(tx, { companyId: candidate.companyId, sourceKind: "agent_error_alert" }); const [agent] = await tx.update(agents).set({ status: nextStatus, errorReason: nextStatus === "error" ? errorReason(lastRun?.error) : null, updatedAt: now, }).where(and(eq(agents.id, candidate.id), eq(agents.companyId, candidate.companyId), diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index c463a458a5b..7425f402af0 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -3,7 +3,7 @@ import { runOwnerFenceHeldSql } from "../remote-workspace-writer-hold.js"; import { AGENT_DIRECTORY_BUSY_ERROR_CODE, AGENT_DIRECTORY_BUSY_MAX_DEFERRALS, AGENT_DIRECTORY_BUSY_RETRY_REASON, AGENT_DIRECTORY_BUSY_RETRY_WAKE_REASON, agentDirectoryBusyRetryDelayMs, type AgentDirectoryPreparationDeferral } from "./agent-directory-busy.js"; import { isInterruptedNativePreparation } from "../cancelled-native-startup.js"; import { isPreDispatchExecutionWaitVerified } from "../pre-dispatch-execution-wait.js"; -import { notifyAttentionRetentionWork } from "../retention-work-notifications.js"; +import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js"; import { normalizeAgentNameKey } from "../agent-name-key.js"; import { notifyStatusCardIssueChange } from "../status-card-notifications.js"; import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js"; @@ -1209,7 +1209,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen } } - await notifyAttentionRetentionWork(tx, { companyId: run.companyId }); + await notifyIssueAttentionRetentionWork(tx, { companyId: run.companyId, runId: run.id }); await notifyScheduledRetryDispatch(tx, { companyId: run.companyId, runId: run.id }); const wakeupRequest = await tx .insert(agentWakeupRequests) 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 61f790329f4..8b61d8fcb8a 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -10,7 +10,7 @@ import { createCostEventInTransaction } from "../costs.js"; import { withOperationAccountingTransaction } from "../accounting-transaction.js"; import { notifyStatusCardIssueChange } from "../status-card-notifications.js"; import { nativeRunKeyScope, nativeSkillTestToolAllowed, assertNativeSkillTestTool } from "./native-skill-test-scope.js"; -import { notifyAttentionRetentionWork } from "../retention-work-notifications.js"; +import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js"; import { requiredQualityReviewSchema, type RequestCheckboxConfirmationOption } from "@paperclipai/shared"; import { priorRecoveryApiReceipt } from "../recovery-effect-receipts.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; @@ -2560,7 +2560,7 @@ export class PaperclipRunnerToolAuthority { replayMonitor = summarizeIssueMonitor(target, normalizeIssueExecutionPolicy(target.executionPolicy)); return { taskId: target.id, status: target.status, monitor: replayMonitor }; } - await notifyAttentionRetentionWork(tx, { companyId: this.binding.companyId }); + await notifyIssueAttentionRetentionWork(tx, { companyId: this.binding.companyId, issueId: target.id }); const patch = prepareIssueMonitorUpdate(target, input.monitor, actor); await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); await notifyStatusCardIssueChange(tx, this.binding.companyId); diff --git a/server/src/services/retention-work-notifications.ts b/server/src/services/retention-work-notifications.ts index 79cffd624a8..e395e5fe4b4 100644 --- a/server/src/services/retention-work-notifications.ts +++ b/server/src/services/retention-work-notifications.ts @@ -6,6 +6,7 @@ import type { AttentionSourceKind } from "@paperclipai/shared"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; export const ATTENTION_RETENTION_MAX_ISSUE_IDS = 100; +const UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; export type AttentionRetentionScope = { companyId?: string; sourceKind?: AttentionSourceKind; issueId?: string; issueIds?: string[]; sourceId?: string }; @@ -27,9 +28,10 @@ export async function notifyIssueAttentionRetentionWork(transaction: object, where company_id = ${scope.companyId}::uuid and id = ${scope.runId}::uuid and issue_id is not null union select native_issue_id::text from heartbeat_runs where company_id = ${scope.companyId}::uuid and id = ${scope.runId}::uuid and native_issue_id is not null - union select issue.id::text from heartbeat_runs run inner join issues issue - on issue.company_id = run.company_id - and issue.id::text = coalesce(run.context_snapshot->>'issueId', run.context_snapshot->>'taskId') + union select issue.id::text from heartbeat_runs run + cross join lateral (select coalesce(run.context_snapshot->>'issueId', run.context_snapshot->>'taskId') as saved) context + inner join issues issue on issue.company_id = run.company_id + and issue.id = case when context.saved ~* ${UUID_PATTERN} then context.saved::uuid end where run.company_id = ${scope.companyId}::uuid and run.id = ${scope.runId}::uuid`); for (const row of rows) seeds.push(row.id as string); } From f452b449fd1893a0d46e6a63c5d54ccba6ef2e6e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:29:23 -0600 Subject: [PATCH 5/8] fix(recovery): stop re-checking settled native runs that cannot be released (#21590) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The server releases the process identity (`process_pid`, `process_group_id`, `process_started_at`) of a finished native run when it can prove that the runner process stopped (#17374) > - A background queue (`settledNativeProcesses`) finds these runs and checks them. A check that cannot finish ("skipped" or "pending") writes nothing, so the run stays in the queue and every recovery hint checks it again > - A finished run that a replaced container recorded can never pass the check, because only the host that recorded the process can prove that it stopped. Each deploy adds more of these runs > - On one hosted instance this loop ran about 10 checks per second and about 55 SQL statements per second, and the server main thread was about 95% busy with only a few live runs > - This pull request moves each "cannot make progress" reason into the queue's SQL predicate, adds a growing backoff for "pending" runs, and makes one check cost one locking statement > - The benefit is that runs which cannot progress cost nothing until something that can change the answer happens, and a run that becomes releasable is still released at once ## Linked Issues or Issue Description No public issue exists. Bug report: **What happened?** The settled native process recovery queue checks the same finished native runs again on every recovery hint and every 30 seconds, forever. With 300 such runs and one company-wide hint per second it ran 9 checks per second and 84 SQL statements per second (9.4 statements per check, 2.2 ms of server CPU per check) on embedded PostgreSQL. A hosted instance showed the same rates. The runs that never finish are: runs recorded by a host that is gone (each redeploy starts a new container with a new hostname), runs whose coordinator phase is not settled, runs with no checkpoint and no provider evidence, and runs whose local process is still alive (they defer 30 seconds with no limit). Startup discovery (`discoverSettledNativeRunProcesses`) also opens one transaction for every such run on every boot. **Expected behavior** A run that cannot make progress is not read again until something that can change the answer happens. A run that becomes releasable (its phase settles, provider evidence arrives, its own host checks it, its sandbox receipt arrives, its process exits) is released promptly. **Steps to reproduce** 1. Create a failed native run with a recorded local process identity from another host (or an unsettled coordinator phase, or no checkpoint and no provider evidence, or a live process). 2. Register the residual recovery work and send company-wide `notifyLiveRunRecovery` hints. 3. Count the run's `for update` checks: on `master` every hint checks the run again. `server/src/__tests__/settled-native-process-rechecks.test.ts` automates these steps. **Paperclip version or commit** `master` at 3c3e6c2d75. **Deployment mode** Any. The cost grows with every deploy of a hosted instance. ## What Changed - `server/src/services/native-local-process-stop.ts` - New `settledNativeProcessCandidates`: one fixed-text statement that finds releasable runs. It reads only runs recorded in this server's PID space (`process_host_hash`), sandbox runs (`remote`, with a non-local lease), and rows saved before the hash (their latest identity event must name this host). It excludes runs with an unsettled coordinator phase and runs with no checkpoint and no provider evidence. Each PID-space branch reads its own range of the new partial index. - `releaseSettledNativeRunProcess` now reads the run, phase, evidence, lease facts and identity match in one `for update` statement (it was 6 statements). It reads the lease rows again only for a sandbox run. The new `inspectSettledNativeRunProcess` also returns whether a remote stop acknowledgement can apply. - Startup discovery uses the same candidate statement, so it opens no transaction for an excluded run. - `server/src/services/heartbeat/live-recovery-work.ts` (settled kind only) - The load runs the candidate statement and a separate indexed statement for cancelled `cursor_cloud_api` runs whose Stop is still `requested`. - The check uses the loaded entry. It no longer runs the load again for each entry. - A "pending" run backs off 30 s, 60 s, 120 s, up to 15 min. A run-scoped hint (identity event, lease cleanup, stop receipt) resets the backoff. - A "skipped" run that the predicate cannot exclude (for example a birth time mismatch on this host) waits for a run-scoped hint or a restart. - `server/src/services/heartbeat/recovery.ts` (the settled handler only): returns the outcome. It calls `acknowledgeRemoteStop` only when the run has a non-local lease or is a cancelled `cursor_cloud_api` run. For any other run that function reads two rows and writes nothing. - `packages/db`: migration 0487 builds `heartbeat_runs_settled_process_identity_idx` and `heartbeat_runs_pending_api_stop_idx` with `CREATE INDEX CONCURRENTLY IF NOT EXISTS`. The migration is `online_compatible` and is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`. `doc/DATABASE.md` describes both indexes. End state for each reason that a check cannot finish: | Reason | Before | After | What re-admits the run | | --- | --- | --- | --- | | Recorded by another PID space | checked on every hint | not read | only a server in that PID space reads it (a live older server in a deploy overlap still releases its own runs) | | Coordinator phase not settled | checked on every hint | not read | the phase write; the finalizer sends a company hint in the same transaction | | No checkpoint and no provider evidence | checked on every hint | not read | the next hint after a provider or turn event | | Live local process, unreleased lease, missing sandbox receipt | every hint and every 30 s | backoff 30 s to 15 min | a run-scoped hint resets the backoff | | Other same-host skip | checked on every hint | parked | a run-scoped hint (an identity event sends one) or a restart | ## Verification - `pnpm exec vitest run src/__tests__/settled-native-process-rechecks.test.ts` (new, 12 tests, real PostgreSQL, real queue and coordinator, fake clock): - each exclusion: replaced container, unsettled phase, no evidence: 0 checks over 4 hints (red on `master`: 3 to 5 checks); - a live older server and a stopped older server (different hash): the new server never reads the run and writes no receipt; this server's own run is released at start; - re-admission: phase settles, late provider evidence, legacy rows with no hash (this host released, another host not read), sandbox run released from any server with its receipt; - live process: at most 4 checks over 8 hints (red: 17), released on the run-scoped hint after the process exits; - one check is BEGIN, one `for update` statement and COMMIT (3 statements); the next hints do not check it; a run-scoped hint checks it once more (red: 5 statements and a check on every hint); - a restart costs one check for each pending run; startup discovery with 50 excluded runs sends 1 statement (red: 302). - On `master` 11 of the 12 tests fail. - Measurement on embedded PostgreSQL, 300 stuck runs, one company hint per second for 300 s (fake clock), same harness before and after: - before: 9.0 checks/s, 84.3 statements/s, 9.4 statements per check, 5.9 s CPU (2.2 ms per check); - after: 0 checks/s, 3.2 statements/s for all seven residual queues together, 0.16 s CPU. - Load plan with 12,000 excluded finished runs (10% without a hash) in a 31,000-row `heartbeat_runs`: the candidate statement reads only index entries for this server's hash, `remote` and `unknown`, and a bitmap scan of the 1,200 legacy rows: 2.7 ms, 4,416 buffers. Without the index the same exclusion read all 31,000 rows (31,127 buffers). - Existing suites, one file at a time: all pass. `live-recovery-work.test.ts` 51/51 (an earlier run under machine load hit the `afterAll` hook timeout after all tests passed; the rerun passed clean, and `native-safe-replacement.test.ts` hits the same hook timeout on the base commit), `native-settled-process-release.test.ts` 31/31, `native-local-process-stop.test.ts` 5/5, `heartbeat/recovery.test.ts` 107/107, `native-runner-restart-recovery.integration.test.ts` 231 passed / 14 skipped, `native-restart-recovery.test.ts` 49/49, `native-controller-recovery.integration.test.ts` 30/30, `retained-native-session-cleanup-work.test.ts` 29/29, `native-provider-failure.integration.test.ts` 16/16, `native-safe-replacement.test.ts` 70/70 (with the `afterAll` hook timeout that also occurs on the base commit), `native-remote-retry-admission.test.ts` 93/93. - `pnpm check:module-boundaries`, `pnpm check:migrations` (packages/db), server typecheck: pass. - Not run: the full suite and browser suites. ## Risks - Unresolved by design: a finished run whose server was replaced keeps its process fields indefinitely and is never released, because only the host that recorded a process can prove that it stopped, and the shared prover refuses a controller-lease proof for a run with a process group. This pull request only stops paying for it. These runs keep no stop receipt (`native.local_process_stopped`), so what waits for that receipt still waits: accounting close of the run's usage source, retained native session cleanup, and instruction or directory working copies that wait for proof that the run stopped. A follow-up must decide the ownership rule for a replaced container. - Rows saved before `process_host_hash` exist are read through the legacy branch, which checks the latest identity event for each of them on each load. On an instance with many such rows the load costs one index lookup per row. The count can be measured with `select count(*) from heartbeat_runs where process_host_hash is null and process_pid is not null and status in ('failed','cancelled','timed_out','interrupted')`. - A run that this server recorded but whose `process_host_hash` changed (a new PID namespace on the same host, for example a container restart) is no longer read here. Before, it was read and skipped, so no release is lost. - The backoff and parked state live in memory. A restart checks each pending run once. - The migration builds two partial indexes concurrently on `heartbeat_runs`. It holds no long lock. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use and code execution. ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- doc/DATABASE.md | 10 + packages/db/src/client.ts | 1 + ...heartbeat_runs_settled_process_indexes.sql | 5 + ...{0482_snapshot.json => 0487_snapshot.json} | 458 +++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/heartbeat_runs.ts | 10 + .../settled-native-process-rechecks.test.ts | 296 +++++++++++ .../services/heartbeat/live-recovery-work.ts | 83 +++- server/src/services/heartbeat/recovery.ts | 9 +- .../src/services/native-local-process-stop.ts | 165 ++++--- .../native-runtime/native-session-resume.ts | 2 +- 11 files changed, 965 insertions(+), 81 deletions(-) create mode 100644 packages/db/src/migrations/0487_heartbeat_runs_settled_process_indexes.sql rename packages/db/src/migrations/meta/{0482_snapshot.json => 0487_snapshot.json} (99%) create mode 100644 server/src/__tests__/settled-native-process-rechecks.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 99f28b85a3b..197b10cb495 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -507,6 +507,16 @@ indexes also serve the comment and delivery `on delete set null` actions. Issue lists share one external review-wait read per issue between the review and blocked-inbox attention maps. +Migration 0487 builds two partial `heartbeat_runs` indexes concurrently for the +settled-process recovery queue. `heartbeat_runs_settled_process_identity_idx` +keys settled native runs that still hold a process identity by +`process_host_hash`, company and id. Each server reads only the runs recorded in +its own PID space, sandbox runs (`remote`) and rows saved before the hash, so +finished runs from replaced containers are not read at all. +`heartbeat_runs_pending_api_stop_idx` keys cancelled `cursor_cloud_api` runs +whose Stop is still `requested`. Without them, the queue reads every finished +run of a company on each hint. + Migration 0476 builds `agent_wakeup_requests_company_run_idx` concurrently. It keys wake requests by company and `run_id`, partial on a non-null run. Queued-run dispatch finds the person wakes that joined or were adopted by each queued run diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 2860e95c383..4145a5ecb1d 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -748,6 +748,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0472_runner_api_capture_pending_deletes.sql", "0476_wakeup_request_run_index.sql", "0486_heartbeat_runs_company_finished_index.sql", + "0487_heartbeat_runs_settled_process_indexes.sql", "0469_zippy_photon.sql", diff --git a/packages/db/src/migrations/0487_heartbeat_runs_settled_process_indexes.sql b/packages/db/src/migrations/0487_heartbeat_runs_settled_process_indexes.sql new file mode 100644 index 00000000000..1e1cd989a68 --- /dev/null +++ b/packages/db/src/migrations/0487_heartbeat_runs_settled_process_indexes.sql @@ -0,0 +1,5 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_settled_process_identity_idx" ON "heartbeat_runs" USING btree ("process_host_hash","company_id","id") WHERE "heartbeat_runs"."runtime_mode" = 'native' and "heartbeat_runs"."status" in ('failed', 'cancelled', 'timed_out', 'interrupted') + and "heartbeat_runs"."finished_at" is not null + and ("heartbeat_runs"."process_pid" is not null or "heartbeat_runs"."process_group_id" is not null or "heartbeat_runs"."process_started_at" is not null);--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_pending_api_stop_idx" ON "heartbeat_runs" USING btree ("company_id","id") WHERE "heartbeat_runs"."status" = 'cancelled' and "heartbeat_runs"."driver_kind" = 'cursor_cloud_api' + and ("heartbeat_runs"."result_json"->'executionCancellation'->>'state') = 'requested'; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0482_snapshot.json b/packages/db/src/migrations/meta/0487_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0482_snapshot.json rename to packages/db/src/migrations/meta/0487_snapshot.json index fe3c626a03e..c9758d85553 100644 --- a/packages/db/src/migrations/meta/0482_snapshot.json +++ b/packages/db/src/migrations/meta/0487_snapshot.json @@ -1,6 +1,6 @@ { - "id": "8b353a38-62df-4834-be55-7e9ebefad5c5", - "prevId": "41eacc6a-6eab-4f01-965a-62aa0cd6778f", + "id": "73c8fa97-70fc-49c0-804e-e49cfdffd156", + "prevId": "0c3e74be-7936-4c97-9798-505daf53c16b", "version": "7", "dialect": "postgresql", "tables": { @@ -6582,6 +6582,111 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.automatic_run_brakes": { + "name": "automatic_run_brakes", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'closed'" + }, + "reason": { + "name": "reason", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "state_changed_at": { + "name": "state_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "opened_at": { + "name": "opened_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_probe_at": { + "name": "next_probe_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "probe_run_id": { + "name": "probe_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "probe_successes": { + "name": "probe_successes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "release_window_started_at": { + "name": "release_window_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "release_window_starts": { + "name": "release_window_starts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_creation_at": { + "name": "next_creation_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "automatic_run_brakes_company_id_companies_id_fk": { + "name": "automatic_run_brakes_company_id_companies_id_fk", + "tableFrom": "automatic_run_brakes", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.board_api_keys": { "name": "board_api_keys", "schema": "", @@ -36029,6 +36134,78 @@ "method": "btree", "with": {} }, + "heartbeat_runs_company_finished_idx": { + "name": "heartbeat_runs_company_finished_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "finished_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"finished_at\" is not null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_settled_process_identity_idx": { + "name": "heartbeat_runs_settled_process_identity_idx", + "columns": [ + { + "expression": "process_host_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"runtime_mode\" = 'native' and \"heartbeat_runs\".\"status\" in ('failed', 'cancelled', 'timed_out', 'interrupted')\n and \"heartbeat_runs\".\"finished_at\" is not null\n and (\"heartbeat_runs\".\"process_pid\" is not null or \"heartbeat_runs\".\"process_group_id\" is not null or \"heartbeat_runs\".\"process_started_at\" is not null)", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_pending_api_stop_idx": { + "name": "heartbeat_runs_pending_api_stop_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" = 'cancelled' and \"heartbeat_runs\".\"driver_kind\" = 'cursor_cloud_api'\n and (\"heartbeat_runs\".\"result_json\"->'executionCancellation'->>'state') = 'requested'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_created_at_desc_idx": { "name": "heartbeat_runs_company_created_at_desc_idx", "columns": [ @@ -59607,6 +59784,12 @@ "primaryKey": false, "notNull": false }, + "progress": { + "name": "progress", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -60113,6 +60296,277 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.tool_mcp_elicitations": { + "name": "tool_mcp_elicitations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "invocation_id": { + "name": "invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "catalog_tool_name": { + "name": "catalog_tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "call_identity": { + "name": "call_identity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "era": { + "name": "era", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sealed_request_state": { + "name": "sealed_request_state", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "questions": { + "name": "questions", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "arguments_identity": { + "name": "arguments_identity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "claimed_until": { + "name": "claimed_until", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_elicitations_call_idx": { + "name": "tool_mcp_elicitations_call_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "call_identity", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_elicitations_invocation_idx": { + "name": "tool_mcp_elicitations_invocation_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invocation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_elicitations_waiting_uq": { + "name": "tool_mcp_elicitations_waiting_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "dedupe_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"tool_mcp_elicitations\".\"status\" = 'waiting'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_elicitations_company_id_companies_id_fk": { + "name": "tool_mcp_elicitations_company_id_companies_id_fk", + "tableFrom": "tool_mcp_elicitations", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_elicitations_invocation_id_tool_invocations_id_fk": { + "name": "tool_mcp_elicitations_invocation_id_tool_invocations_id_fk", + "tableFrom": "tool_mcp_elicitations", + "tableTo": "tool_invocations", + "columnsFrom": [ + "invocation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_elicitations_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_elicitations_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_elicitations", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.tool_mcp_gateway_tokens": { "name": "tool_mcp_gateway_tokens", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index f3774187bbb..9790c0d8fc3 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3396,6 +3396,13 @@ "when": 1794623177597, "tag": "0486_heartbeat_runs_company_finished_index", "breakpoints": true + }, + { + "idx": 487, + "version": "7", + "when": 1794639469687, + "tag": "0487_heartbeat_runs_settled_process_indexes", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.ts index 0b424df776d..72ce4e56c22 100644 --- a/packages/db/src/schema/heartbeat_runs.ts +++ b/packages/db/src/schema/heartbeat_runs.ts @@ -250,6 +250,16 @@ export const heartbeatRuns = pgTable( ), companyFinishedIdx: index("heartbeat_runs_company_finished_idx").on(table.companyId, table.finishedAt.desc()) .where(sql`${table.finishedAt} is not null`).concurrently(), + settledProcessIdentityIdx: index("heartbeat_runs_settled_process_identity_idx") + .on(table.processHostHash, table.companyId, table.id) + .where(sql`${table.runtimeMode} = 'native' and ${table.status} in ('failed', 'cancelled', 'timed_out', 'interrupted') + and ${table.finishedAt} is not null + and (${table.processPid} is not null or ${table.processGroupId} is not null or ${table.processStartedAt} is not null)`) + .concurrently(), + pendingApiStopIdx: index("heartbeat_runs_pending_api_stop_idx").on(table.companyId, table.id) + .where(sql`${table.status} = 'cancelled' and ${table.driverKind} = 'cursor_cloud_api' + and (${table.resultJson}->'executionCancellation'->>'state') = 'requested'`) + .concurrently(), companyCreatedAtDescIdx: index("heartbeat_runs_company_created_at_desc_idx").on( table.companyId, table.createdAt.desc(), diff --git a/server/src/__tests__/settled-native-process-rechecks.test.ts b/server/src/__tests__/settled-native-process-rechecks.test.ts new file mode 100644 index 00000000000..b4616bcfe9d --- /dev/null +++ b/server/src/__tests__/settled-native-process-rechecks.test.ts @@ -0,0 +1,296 @@ +import { randomUUID } from "node:crypto"; +import os from "node:os"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { setImmediate as immediate } from "node:timers/promises"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { agents, applyPendingMigrations, authUsers, closeCheckpointDb, closeLivenessDb, companies, companyMemberships, + controllerInstances, createDb, environmentLeases, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { heartbeatService } from "../services/heartbeat.js"; +import { notifyLiveRunRecovery } from "../services/live-run-recovery-notifications.js"; +import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js"; +import { persistHeartbeatRunProcessMetadata } from "../services/heartbeat/run-lifecycle.js"; +import { discoverSettledNativeRunProcesses } from "../services/native-local-process-stop.js"; +import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; + +vi.setConfig({ testTimeout: 300_000, hookTimeout: 180_000 }); + +describe("settled native process re-checks", () => { + let temporary: Awaited> | undefined; + let db: ReturnType; + let meter: ReturnType; + let heartbeat: ReturnType; + let coordinator: ReturnType; + const errors: unknown[] = []; + const passes = new Set>(); + const children: number[] = []; + const checks = new Map(); + const stops: Array<() => Promise> = []; + + beforeAll(async () => { + const external = resolveExternalTestDatabaseUrl("PAPERCLIP_SETTLED_RECHECK_TEST_DATABASE_URL"); + if (!external) temporary = await startEmbeddedPostgresTestDatabase("settled-recheck-"); + else await applyPendingMigrations(external); + const url = external ?? temporary!.connectionString; + db = createDb(url, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + meter = meterDatabaseStatements(db, url); + await Promise.all(Array.from({ length: 4 }, () => db.execute(sql`select pg_sleep(0.01)`))); + db.$client.options.debug = (_connection, query, parameters) => { + if (!/for update/i.test(query) || !query.includes("sessionCheckpoint")) return; + const runId = (parameters as unknown[]).find(value => typeof value === "string" && checks.has(value)) as string | undefined; + if (runId) checks.set(runId, checks.get(runId)! + 1); + }; + }); + beforeEach(async () => { + await db.execute(sql`truncate companies, controller_instances cascade`); + errors.length = 0; checks.clear(); + heartbeat = heartbeatService(db); + coordinator = newCoordinator(); + }); + afterEach(async () => { + for (const stop of stops.splice(0)) await stop(); + await coordinator.stop(); await heartbeat.drainActiveRunExecutions(); + for (const pid of children.splice(0)) { try { process.kill(-pid, "SIGKILL"); } catch { } } + vi.useRealTimers(); vi.restoreAllMocks(); expect(errors).toEqual([]); + }); + afterAll(async () => { + meter?.uninstall(); + if (db) { await closeLivenessDb(db, 1); await closeCheckpointDb(db, 1); } + await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); + }); + + function newCoordinator() { + const created = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, + onError: error => errors.push(error) }); + const register = created.register.bind(created); + created.register = (queue, task) => register(queue, { ...task, run: signal => { + const pass = Promise.resolve(task.run(signal)); passes.add(pass); + void pass.finally(() => passes.delete(pass)); return pass; + } }); + return created; + } + + async function fixture() { + const companyId = randomUUID(), actorId = "settled-recheck-user"; + await db.insert(authUsers).values({ id: actorId, name: "Owner", email: `${actorId}@example.test`, + createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing(); + await db.insert(companies).values({ id: companyId, name: "Settled", issuePrefix: `SR${companyId.slice(0, 6)}`, + requireBoardApprovalForNewAgents: false, defaultResponsibleUserId: actorId }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: actorId, + status: "active", membershipRole: "owner" }); + const [agent] = await db.insert(agents).values({ companyId, name: "Worker", status: "idle", adapterType: "process", + adapterConfig: {}, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } } }).returning(); + const [issue] = await db.insert(issues).values({ companyId, title: "Work", status: "done", assigneeAgentId: agent.id }).returning(); + return { companyId, agentId: agent.id, issueId: issue.id }; + } + type Fixture = Awaited>; + + async function exitedPid() { + const child = spawn(process.execPath, ["-e", "0"], { detached: true, stdio: "ignore" }); + const pid = child.pid!; await once(child, "exit"); return pid; + } + function livePid() { + const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + child.unref(); children.push(child.pid!); return child.pid!; + } + async function kill(pid: number) { + try { process.kill(-pid, "SIGKILL"); } catch { } + for (let attempt = 0; attempt < 100; attempt++) { + try { process.kill(pid, 0); } catch { return; } + await new Promise(resolve => setImmediate(resolve)); + } + } + + type Seed = { host?: { hostname: string; hash: string | null }; phase?: string | null; checkpoint?: boolean; live?: boolean; + birthMismatch?: boolean; remote?: "stopped" | "unconfirmed" }; + async function seed(f: Fixture, options: Seed = {}) { + const pid = options.live ? livePid() : await exitedPid(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, runtimeMode: "native", + nativeIssueId: f.issueId, status: "running", invocationSource: "assignment", triggerDetail: "system", + runnerProfileJson: options.checkpoint === false ? {} : { sessionCheckpoint: { providerSessionId: "thread" } } }).returning(); + if (options.host || options.birthMismatch) { + const startedAt = new Date(); + const host = options.host ?? { hostname: os.hostname(), hash: null }; + await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: run.id, agentId: f.agentId, + eventType: "native.process_identity_recorded", stream: "system", level: "info", message: "identity", + payload: { targetKind: options.remote ? "remote" : "local", hostname: host.hostname, processPid: pid, processGroupId: pid, + processStartedAt: new Date(startedAt.getTime() - (options.birthMismatch ? 5_000 : 0)).toISOString() }, + runUpdate: { processPid: pid, processGroupId: pid, processStartedAt: startedAt, processHostHash: host.hash } }); + } else { + await persistHeartbeatRunProcessMetadata(db, run.id, { pid, processGroupId: pid, startedAt: new Date().toISOString(), targetKind: "local" }); + } + if (options.phase !== null) await db.insert(nativeRunFinalizations).values({ companyId: f.companyId, issueId: f.issueId, + runId: run.id, phase: options.phase ?? "committed", controllerBootId: randomUUID() }); + const [lease] = await db.insert(environmentLeases).values({ companyId: f.companyId, issueId: f.issueId, heartbeatRunId: run.id, + provider: options.remote ? "daytona" : "local", providerLeaseId: options.remote ? randomUUID() : null, leasePolicy: "ephemeral", + status: "released", releasedAt: new Date(), cleanupStatus: "success" }).returning(); + if (options.remote === "stopped") await db.update(environmentLeases).set({ metadata: { + remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }), + } }).where(eq(environmentLeases.id, lease.id)); + await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id)); + checks.set(run.id, 0); + return { runId: run.id, pid }; + } + + async function start(target = coordinator) { + if (!vi.isFakeTimers()) vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + await heartbeat.registerResidualRecoveryWork(target, () => true).ready; + await advance(2_000); + } + async function advance(ms: number) { + const until = Date.now() + ms; + while (Date.now() < until) { + await vi.advanceTimersByTimeAsync(Math.min(1_000, until - Date.now())); + await Promise.allSettled([...passes]); await immediate(); + } + } + const companyHint = (companyId: string) => db.transaction(tx => notifyLiveRunRecovery(tx, { companyId })); + const runHint = (companyId: string, runId: string) => db.transaction(tx => notifyLiveRunRecovery(tx, { companyId, runId })); + async function hints(companyId: string, count: number) { + for (let index = 0; index < count; index++) { await companyHint(companyId); await advance(31_000); } + } + const processPid = async (id: string) => (await db.select({ pid: heartbeatRuns.processPid }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, id)))[0]!.pid; + const stopReceipts = async (id: string) => (await db.select().from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.runId, id), eq(heartbeatRunEvents.eventType, "native.local_process_stopped")))).length; + + it.each([ + ["recorded by a replaced container", { host: { hostname: "replaced-container", hash: "replaced-container-space" } }], + ["whose coordinator phase is unsettled", { phase: "workspace_finalizing" }], + ["without a checkpoint or provider evidence", { checkpoint: false }], + ] as const)("never re-reads a terminal run %s on company hints", async (_name, options) => { + const f = await fixture(); + const { runId, pid } = await seed(f, options as Seed); + await start(); + await hints(f.companyId, 4); + expect(checks.get(runId)).toBe(0); + expect(await processPid(runId)).toBe(pid); + }); + + it.each(["live", "stopped"] as const)("leaves a %s older server's runs to that server", async state => { + const f = await fixture(); + const bootId = randomUUID(); + await db.insert(controllerInstances).values({ bootId, processSpace: "older-server-space", pid: 4242, + leaseExpiresAt: new Date(Date.now() + (state === "live" ? 60_000 : -600_000)), + stoppedAt: state === "stopped" ? new Date() : null }); + const { runId, pid } = await seed(f, { host: { hostname: "older-server", hash: "older-server-space" } }); + await db.update(nativeRunFinalizations).set({ controllerBootId: bootId, controllerHostHash: "older-server-space" }) + .where(eq(nativeRunFinalizations.runId, runId)); + const own = await seed(f); + await start(); + expect(await processPid(own.runId)).toBeNull(); + await hints(f.companyId, 2); + expect(checks.get(runId)).toBe(0); + expect(await processPid(runId)).toBe(pid); + expect(await stopReceipts(runId)).toBe(0); + }); + + it("re-admits a run once its coordinator phase settles", async () => { + const f = await fixture(); + const { runId } = await seed(f, { phase: "workspace_finalizing" }); + await start(); + await hints(f.companyId, 1); + expect(await processPid(runId)).not.toBeNull(); + await db.update(nativeRunFinalizations).set({ phase: "committed" }).where(eq(nativeRunFinalizations.runId, runId)); + await hints(f.companyId, 1); + expect(await processPid(runId)).toBeNull(); + expect(checks.get(runId)).toBe(1); + expect(await stopReceipts(runId)).toBe(1); + }); + + it("re-admits a run once late provider evidence arrives", async () => { + const f = await fixture(); + const { runId } = await seed(f, { checkpoint: false }); + await start(); + await hints(f.companyId, 1); + expect(await processPid(runId)).not.toBeNull(); + await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId, agentId: f.agentId, eventType: "harness.ready", + stream: "system", level: "info", message: "ready" }); + await hints(f.companyId, 1); + expect(await processPid(runId)).toBeNull(); + expect(checks.get(runId)).toBe(1); + }); + + it("releases legacy rows without a PID-space hash only when this host recorded them", async () => { + const f = await fixture(); + const own = await seed(f, { host: { hostname: os.hostname(), hash: null } }); + const foreign = await seed(f, { host: { hostname: "legacy-other-host", hash: null } }); + await start(); + expect(await processPid(own.runId)).toBeNull(); + await hints(f.companyId, 2); + expect(checks.get(foreign.runId)).toBe(0); + expect(await processPid(foreign.runId)).toBe(foreign.pid); + }); + + it("releases a sandbox run from any server once its termination receipt exists", async () => { + const f = await fixture(); + const pending = await seed(f, { host: { hostname: "replaced-container", hash: "remote" }, remote: "unconfirmed" }); + const stopped = await seed(f, { host: { hostname: "replaced-container", hash: "remote" }, remote: "stopped" }); + await start(); + expect(await processPid(stopped.runId)).toBeNull(); + expect(await processPid(pending.runId)).not.toBeNull(); + const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, pending.runId)); + await db.update(environmentLeases).set({ metadata: { + remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }), + } }).where(eq(environmentLeases.id, lease.id)); + await runHint(f.companyId, pending.runId); + await advance(2_000); + expect(await processPid(pending.runId)).toBeNull(); + }); + + it("backs off a live local process and releases it on the next run-scoped hint after it exits", async () => { + const f = await fixture(); + const { runId, pid } = await seed(f, { live: true }); + await start(); + expect(checks.get(runId)).toBe(1); + await hints(f.companyId, 8); + expect(checks.get(runId)).toBeLessThanOrEqual(4); + expect(await processPid(runId)).toBe(pid); + await kill(pid); + await runHint(f.companyId, runId); + await advance(2_000); + expect(await processPid(runId)).toBeNull(); + expect(await stopReceipts(runId)).toBe(1); + }); + + it("checks a same-host skip once with one locking statement, then only on its own trigger", async () => { + const f = await fixture(); + const { runId } = await seed(f, { birthMismatch: true, host: { hostname: os.hostname(), hash: null } }); + meter.startLog(); + await start(); + const log = meter.stopLog(); + expect(checks.get(runId)).toBe(1); + const inCheck = log.filter(entry => entry.inTransaction || /^\s*begin/i.test(entry.sql)); + expect(inCheck.filter(entry => /for update/i.test(entry.sql))).toHaveLength(1); + expect(inCheck.length).toBeLessThanOrEqual(3); + await hints(f.companyId, 3); + expect(checks.get(runId)).toBe(1); + await runHint(f.companyId, runId); + await advance(2_000); + expect(checks.get(runId)).toBe(2); + }); + + it("checks a pending run at most once after a restart and discovers no excluded run at startup", async () => { + const f = await fixture(); + const { runId } = await seed(f, { live: true }); + for (let index = 0; index < 50; index++) await seed(f, { host: { hostname: "replaced-container", hash: "replaced-container-space" } }); + await start(); + expect(checks.get(runId)).toBe(1); + await coordinator.stop(); + const restarted = newCoordinator(); + stops.push(() => restarted.stop()); + await start(restarted); + expect(checks.get(runId)).toBe(2); + vi.useRealTimers(); + const before = meter.read(); + const counted = [...checks.values()].reduce((sum, value) => sum + value, 0); + await discoverSettledNativeRunProcesses(db, { skip: id => id === runId }); + expect(meter.read().statements - before.statements).toBe(1); + expect([...checks.values()].reduce((sum, value) => sum + value, 0)).toBe(counted); + }); +}); diff --git a/server/src/services/heartbeat/live-recovery-work.ts b/server/src/services/heartbeat/live-recovery-work.ts index 4c2ec0d6376..07bc8d14950 100644 --- a/server/src/services/heartbeat/live-recovery-work.ts +++ b/server/src/services/heartbeat/live-recovery-work.ts @@ -1,6 +1,6 @@ import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js"; import { legacyWorkspaceRecoveryNotMigrated } from "../legacy-workspace-recovery-migration.js"; -import { settledNativeProcessIdentityCondition } from "../native-local-process-stop.js"; +import { settledNativeProcessCandidates } from "../native-local-process-stop.js"; import { and, asc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; import { agents, environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db"; import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; @@ -9,6 +9,8 @@ import type { LiveResourceRecoveryScope, LiveRunRecoveryScope } from "../live-ru import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; const TERMINAL = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"]; +const SETTLED_PENDING_BASE_DELAY_MS = 30_000; +const SETTLED_PENDING_MAX_DELAY_MS = 15 * 60_000; type Scope = LiveRunRecoveryScope & LiveResourceRecoveryScope; type Entry = { id: string; companyId: string; runId?: string | null; dueAt: number }; type CheckScope = { companyId: string; runId?: string; leaseId?: string; agentId?: string; @@ -27,6 +29,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType boolean) { function register(queue: DeliveryQueue, kind: RunKind | "orphanLease" | "shutdown" | "agent") { const cursors = new Map(); + const settledOutcomes = new Map(); + const settledScans = new Map>(); let enabled = false; async function load(scope?: Scope) { const key = scope ? JSON.stringify({ companyId: scope.companyId, runId: scope.runId, @@ -63,12 +67,11 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType)?.deadlineAt)) || Date.now(), })); + } else if (kind === "settled") { + const page = await loadSettled(scope, cursor); + if (page.complete) cursors.delete(key); else cursors.set(key, page.rows.at(-1)!.id); + return { complete: page.complete, rows: applySettledOutcomes(key, scope, page.rows, page.complete) }; } else { - // Retirement may commit before Stop acknowledgement. This is only a - // work hint; the owner rechecks the complete provider/process proof. - const pendingApiStop = and(eq(heartbeatRuns.status, "cancelled"), eq(heartbeatRuns.driverKind, "cursor_cloud_api"), - sql`${heartbeatRuns.runnerProfileJson}->>'backend' = 'cursor_cloud_api'`, - sql`${heartbeatRuns.resultJson}->'executionCancellation'->>'state' = 'requested'`); const candidates = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, nextAttemptAt: nativeRunFinalizations.nextAttemptAt, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt }) .from(heartbeatRuns).leftJoin(nativeRunFinalizations, and(eq(nativeRunFinalizations.runId, heartbeatRuns.id), @@ -83,12 +86,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType'nativeQuestionCancellation' is not null`) - : kind === "active" ? and(eq(heartbeatRuns.status, "running"), - sql`${heartbeatRuns.contextSnapshot}->'nativeQuestionCancellation' is null`) - : and(eq(heartbeatRuns.runtimeMode, "native"), inArray(heartbeatRuns.status, ["failed", "cancelled", "timed_out", "interrupted"]), - isNotNull(heartbeatRuns.finishedAt), or(pendingApiStop, - and(or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), - isNotNull(heartbeatRuns.processStartedAt)), settledNativeProcessIdentityCondition(db)))), + : and(eq(heartbeatRuns.status, "running"), + sql`${heartbeatRuns.contextSnapshot}->'nativeQuestionCancellation' is null`), )).orderBy(asc(heartbeatRuns.id)).limit(100); rows = candidates.map(row => ({ id: row.id, companyId: row.companyId, dueAt: kind === "native" ? Math.max(Date.now(), row.nextAttemptAt?.getTime() ?? 0, row.leaseExpiresAt?.getTime() ?? 0) : Date.now() })); @@ -97,6 +96,50 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType) => db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId }) + .from(heartbeatRuns).where(and(bounds, condition)).orderBy(asc(heartbeatRuns.id)).limit(100); + const processes = await settledNativeProcessCandidates(db, { companyId: scope?.companyId, runId: scope?.runId, + after: cursor, limit: 100 }); + const stops = await select(and(eq(heartbeatRuns.status, "cancelled"), eq(heartbeatRuns.driverKind, "cursor_cloud_api"), + sql`(${heartbeatRuns.resultJson}->'executionCancellation'->>'state') = 'requested'`, + eq(heartbeatRuns.runtimeMode, "native"), isNotNull(heartbeatRuns.finishedAt), + sql`${heartbeatRuns.runnerProfileJson}->>'backend' = 'cursor_cloud_api'`)); + const merged = [...new Map([...processes, ...stops].map(row => [row.id, row])).values()] + .sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0); + const complete = processes.length < 100 && stops.length < 100 && merged.length <= 100; + return { complete, rows: merged.slice(0, 100).map(row => ({ ...row, dueAt: Date.now() })) }; + } + function applySettledOutcomes(key: string, scope: Scope | undefined, rows: Entry[], complete: boolean) { + if (scope?.runId) settledOutcomes.delete(scope.runId); + const seen = settledScans.get(key) ?? new Set(); + for (const row of rows) seen.add(row.id); + if (!complete) settledScans.set(key, seen); + else { + settledScans.delete(key); + if (!scope?.runId) for (const [id, outcome] of settledOutcomes) + if ((!scope || outcome.companyId === scope.companyId) && !seen.has(id)) settledOutcomes.delete(id); + } + return rows.flatMap(row => { + const outcome = settledOutcomes.get(row.id); + if (outcome?.parked) return []; + return [{ ...row, dueAt: Math.max(row.dueAt, outcome?.notBefore ?? 0) }]; + }); + } + function recordSettledOutcome(entry: Entry, outcome: unknown): Entry | null | undefined { + if (outcome === "released") { settledOutcomes.delete(entry.id); return null; } + if (outcome === "skipped") { + settledOutcomes.set(entry.id, { companyId: entry.companyId, parked: true, attempts: 0, notBefore: 0 }); + return null; + } + if (outcome !== "pending") return undefined; + const attempts = (settledOutcomes.get(entry.id)?.attempts ?? 0) + 1; + const notBefore = Date.now() + Math.min(SETTLED_PENDING_MAX_DELAY_MS, SETTLED_PENDING_BASE_DELAY_MS * 2 ** (attempts - 1)); + settledOutcomes.set(entry.id, { companyId: entry.companyId, parked: false, attempts, notBefore }); + return { ...entry, dueAt: notBefore }; + } return registerScopedDeadlineWork(coordinator, { queue, reconstructionIntervalMs: 30_000, @@ -114,10 +157,12 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType row.id === entry.id); - if (!current) return null; - if (current.dueAt > Date.now()) return current; + if (kind !== "settled") { + const loaded = await load(currentScope); + const current = (Array.isArray(loaded) ? loaded : loaded.rows).find(row => row.id === entry.id); + if (!current) return null; + if (current.dueAt > Date.now()) return current; + } let next: number | null = null; const errors: unknown[] = []; const scope: CheckScope = { companyId: entry.companyId, @@ -126,8 +171,12 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType { next = next === null ? at : Math.min(next, at); }, onError: error => { errors.push(error); }, }; - await owner[kind](scope); + const outcome = await owner[kind](scope); if (errors.length) throw new AggregateError(errors, `Recovery obligation ${entry.id} failed`); + if (kind === "settled") { + const settled = recordSettledOutcome(entry, outcome); + if (settled !== undefined) return settled; + } if (kind === "native") { const refreshed = await load(currentScope); const remaining = (Array.isArray(refreshed) ? refreshed : refreshed.rows).find(row => row.id === entry.id); diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 191f1ef963b..b2a866808bd 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -39,7 +39,7 @@ import { hasStopOnlyCleanup, settleStopOnlyCleanup, } from "../sandbox-stop-and-retain.js"; -import { discoverSettledNativeRunProcesses, PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, recordNativeLocalProcessStopInTransaction, releaseSettledNativeRunProcess, retryPendingSettledNativeRunProcesses } from "../native-local-process-stop.js"; +import { discoverSettledNativeRunProcesses, inspectSettledNativeRunProcess, PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, recordNativeLocalProcessStopInTransaction, retryPendingSettledNativeRunProcesses } from "../native-local-process-stop.js"; import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js"; import { portableTaskPreparationLeaseId } from "../plugin-task-ownership.js"; import { retireInheritedRemoteRunnerIdentity } from "../native-runtime/native-inherited-runner-retry.js"; @@ -3109,10 +3109,11 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD if (!scope.runId || activeRunExecutions.has(scope.runId) || runningProcesses.has(scope.runId) || adapterExecutionControls.has(scope.runId)) { scope.onDeferredDeadline(Date.now() + 30_000); - return; + return "deferred"; } - const outcome = await releaseSettledNativeRunProcess(db, scope.runId, scope); - if (outcome !== "pending") await acknowledgeRemoteStop(scope.runId, scope.companyId); + const { outcome, remoteStop } = await inspectSettledNativeRunProcess(db, scope.runId, scope); + if (outcome !== "pending" && remoteStop) await acknowledgeRemoteStop(scope.runId, scope.companyId); + return outcome; }, orphanLease: scope => sweepOrphanedActiveLeases({ ...scope, backoffMs: 5 * 60_000 }), shutdown: scope => sweepLegacyShutdownWorkspaceSettlements(db, new Date(), scope), diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.ts index 479d524c611..7c7a5e39546 100644 --- a/server/src/services/native-local-process-stop.ts +++ b/server/src/services/native-local-process-stop.ts @@ -1,13 +1,13 @@ import { notifyLiveRunRecovery } from "./live-run-recovery-notifications.js"; -import { and, asc, desc, eq, exists, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; -import { environmentLeases, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db"; +import { and, desc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import { notifyRetainedNativeSessionCleanup } from "./retained-native-session-cleanup-notifications.js"; import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; -import { nativeSessionProviderEvidence } from "./native-runtime/native-session-resume.js"; import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; +import { NATIVE_SESSION_PROVIDER_EVENT_TYPES } from "./native-runtime/native-session-resume.js"; import os from "node:os"; -import { currentProcessSpaceHash } from "./controller-process-identity.js"; +import { currentProcessSpaceHash, UNKNOWN_PROCESS_SPACE } from "./controller-process-identity.js"; import { proveOwnerGone } from "./owner-proof.js"; export const PROCESS_START_REQUESTED = "native.process_start_requested"; @@ -69,6 +69,12 @@ export async function recordNativeLocalProcessStop(db: Db, run: Pick lease.provider !== "local")) return false; if ((run.processPid && !absent(run.processPid)) || (run.processGroupId && !absent(-run.processGroupId))) return false; + await appendLocalProcessStop(db, { ...run, processStartedAt: run.processStartedAt?.toISOString() ?? null }); + return true; +} + +async function appendLocalProcessStop(db: Db, run: { id: string; companyId: string; agentId: string; + processPid: number | null; processGroupId: number | null; processStartedAt: string | null }) { await notifyDeliveryWork(db, DELIVERY_QUEUES.executionReplacement, JSON.stringify({ companyId: run.companyId, runId: run.id })); await appendHeartbeatRunEvent(db, { @@ -79,10 +85,8 @@ export async function recordNativeLocalProcessStop(db: Db, run: Pick 'local'`))), - and(gt(heartbeatRuns.processPid, 1), eq(heartbeatRuns.processPid, heartbeatRuns.processGroupId), - exists(db.select({ payload: identity.payload }).from(identity).where(and( - sql`${identity.payload}->>'targetKind' = 'local'`, sql`${identity.payload}->>'hostname' = ${os.hostname()}`, - sql`${identity.payload}->>'processPid' = ${heartbeatRuns.processPid}::text`, - sql`${identity.payload}->>'processGroupId' = ${heartbeatRuns.processGroupId}::text`, - ))))); +const providerEventTypes = () => sql.join(NATIVE_SESSION_PROVIDER_EVENT_TYPES.map(type => sql`${type}`), sql`, `); + +function settledNativeProcessReleaseCondition() { + const processSpace = currentProcessSpaceHash(); + const ownSpace = processSpace === UNKNOWN_PROCESS_SPACE ? undefined : eq(heartbeatRuns.processHostHash, processSpace); + const remoteLease = sql`exists (select 1 from environment_leases settled_lease where settled_lease.company_id = ${heartbeatRuns.companyId} + and settled_lease.heartbeat_run_id = ${heartbeatRuns.id} and settled_lease.provider is distinct from 'local')`; + const unrecordedSpace = or(isNull(heartbeatRuns.processHostHash), eq(heartbeatRuns.processHostHash, UNKNOWN_PROCESS_SPACE)); + return and(eq(heartbeatRuns.runtimeMode, "native"), inArray(heartbeatRuns.status, SETTLED_RUN_STATUSES), + isNotNull(heartbeatRuns.finishedAt), + or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), isNotNull(heartbeatRuns.processStartedAt)), + or(ownSpace, eq(heartbeatRuns.processHostHash, "remote"), isNull(heartbeatRuns.processHostHash), + eq(heartbeatRuns.processHostHash, UNKNOWN_PROCESS_SPACE)), + or(ownSpace, remoteLease, and(unrecordedSpace, sql`(select settled_identity.payload->>'hostname' from heartbeat_run_events settled_identity + where settled_identity.company_id = ${heartbeatRuns.companyId} and settled_identity.run_id = ${heartbeatRuns.id} + and settled_identity.event_type = ${PROCESS_IDENTITY_RECORDED} and settled_identity.source_event_id is null + order by settled_identity.seq desc limit 1) = ${os.hostname()}::text`)), + sql`not exists (select 1 from native_run_finalizations settled_coordinator + where settled_coordinator.run_id = ${heartbeatRuns.id} and settled_coordinator.phase not in ('committed', 'terminal_failure'))`, + sql`(coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb + or exists (select 1 from heartbeat_run_events settled_evidence where settled_evidence.company_id = ${heartbeatRuns.companyId} + and settled_evidence.run_id = ${heartbeatRuns.id} and settled_evidence.event_type in (${providerEventTypes()})))`); +} + +export async function settledNativeProcessCandidates(db: Pick, input: { + companyId?: string; runId?: string; after?: string | null; limit: number; +}): Promise> { + const processSpace = currentProcessSpaceHash(); + const condition = and(input.companyId ? eq(heartbeatRuns.companyId, input.companyId) : undefined, + input.runId ? eq(heartbeatRuns.id, input.runId) : undefined, input.after ? gt(heartbeatRuns.id, input.after) : undefined, + settledNativeProcessReleaseCondition()); + const spaces = [processSpace === UNKNOWN_PROCESS_SPACE ? null : eq(heartbeatRuns.processHostHash, processSpace), + eq(heartbeatRuns.processHostHash, "remote"), eq(heartbeatRuns.processHostHash, UNKNOWN_PROCESS_SPACE), + isNull(heartbeatRuns.processHostHash)].filter(space => space !== null); + const branches = spaces.map(space => sql`(select ${heartbeatRuns.id} as id, ${heartbeatRuns.companyId} as company_id + from ${heartbeatRuns} where ${and(space, condition)} offset 0)`); + return await db.execute(sql`select id, company_id as "companyId" from (${sql.join(branches, sql` union all `)}) candidates + order by id limit ${input.limit}`) as unknown as Array<{ id: string; companyId: string }>; +} + +type SettledProcessFacts = { + companyId: string; agentId: string; runtimeMode: string; status: string; finished: boolean; + processPid: number | null; processGroupId: number | null; processStartedAt: string | null; apiDriver: boolean | null; + hasSessionCheckpoint: boolean; phase: string | null; providerEvidence: boolean; remoteLeases: boolean; + localLeasePending: boolean; identityMatches: boolean | null; +}; + +function readSettledProcessFacts(tx: Db, runId: string) { + return tx.execute(sql`select r.company_id as "companyId", r.agent_id as "agentId", r.runtime_mode as "runtimeMode", + r.status, r.finished_at is not null as "finished", r.process_pid as "processPid", r.process_group_id as "processGroupId", + to_char(r.process_started_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') as "processStartedAt", + r.driver_kind = 'cursor_cloud_api' as "apiDriver", + coalesce(r.runner_profile_json->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb as "hasSessionCheckpoint", + (select f.phase from native_run_finalizations f where f.run_id = r.id limit 1) as "phase", + exists (select 1 from heartbeat_run_events e where e.company_id = r.company_id and e.run_id = r.id + and e.event_type in (${providerEventTypes()})) as "providerEvidence", + exists (select 1 from environment_leases l where l.company_id = r.company_id and l.heartbeat_run_id = r.id + and l.provider is distinct from 'local') as "remoteLeases", + exists (select 1 from environment_leases l where l.company_id = r.company_id and l.heartbeat_run_id = r.id + and (l.released_at is null or l.status = 'pending_cleanup' or l.cleanup_status = 'failed')) as "localLeasePending", + (select identity.payload->>'targetKind' = 'local' and identity.payload->>'hostname' = ${os.hostname()}::text + and identity.payload ? 'processPid' and identity.payload->'processPid' = coalesce(to_jsonb(r.process_pid), 'null'::jsonb) + and identity.payload ? 'processGroupId' and identity.payload->'processGroupId' = coalesce(to_jsonb(r.process_group_id), 'null'::jsonb) + and case when r.process_started_at is not null + then identity.payload->>'processStartedAt' = to_char(r.process_started_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') + else coalesce(r.process_pid > 1 and r.process_group_id = r.process_pid, false) end + from (select e.payload from heartbeat_run_events e where e.company_id = r.company_id and e.run_id = r.id + and e.event_type = ${PROCESS_IDENTITY_RECORDED}::text and e.source_event_id is null order by e.seq desc limit 1) identity + ) as "identityMatches" + from heartbeat_runs r where r.id = ${runId}::uuid for update of r`) as unknown as Promise; } export async function releaseSettledNativeRunProcess(db: Db, runId: string, options: { onDeferredDeadline?: (at: number) => void } = {}): Promise { + return (await inspectSettledNativeRunProcess(db, runId, options)).outcome; +} + +export async function inspectSettledNativeRunProcess(db: Db, runId: string, options: { onDeferredDeadline?: (at: number) => void } = {}): Promise { + let remoteStop = false; const outcome = await db.transaction(async transaction => { const tx = transaction as unknown as Db; - const [run] = await tx.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, - runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt, - processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, processStartedAt: heartbeatRuns.processStartedAt, - hasSessionCheckpoint: sql`coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb`, - }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).for("update").limit(1); - if (!run || run.runtimeMode !== "native" || !SETTLED_RUN_STATUSES.includes(run.status) || !run.finishedAt || + const [run] = await readSettledProcessFacts(tx, runId); + if (!run) return "skipped"; + remoteStop = run.remoteLeases || (run.status === "cancelled" && run.apiDriver === true); + if (run.runtimeMode !== "native" || !SETTLED_RUN_STATUSES.includes(run.status) || !run.finished || (run.processPid === null && run.processGroupId === null && run.processStartedAt === null)) return "skipped"; - const [coordinator] = await tx.select({ phase: nativeRunFinalizations.phase }).from(nativeRunFinalizations) - .where(eq(nativeRunFinalizations.runId, run.id)).limit(1); - if (coordinator && !SETTLED_COORDINATOR_PHASES.includes(coordinator.phase)) return "skipped"; - if (!run.hasSessionCheckpoint && - !(await nativeSessionProviderEvidence(tx, [run.id])).has(run.id)) return "skipped"; - const leases = await tx.select().from(environmentLeases).where(and( - eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), - )); - if (leases.some(lease => lease.provider !== "local")) { + if (run.phase !== null && !SETTLED_COORDINATOR_PHASES.includes(run.phase)) return "skipped"; + if (!run.hasSessionCheckpoint && !run.providerEvidence) return "skipped"; + if (run.remoteLeases) { + const leases = await tx.select().from(environmentLeases).where(and( + eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, runId), + )); if (!leases.every(hasRemoteTerminationReceipt)) return "pending"; } else { - if (leases.some(lease => !lease.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return "pending"; - const [identity] = await tx.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and( - eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), - eq(heartbeatRunEvents.eventType, PROCESS_IDENTITY_RECORDED), isNull(heartbeatRunEvents.sourceEventId), - )).orderBy(desc(heartbeatRunEvents.seq)).limit(1); - if (identity?.payload?.targetKind !== "local" || identity.payload.hostname !== os.hostname() || - identity.payload.processPid !== run.processPid || identity.payload.processGroupId !== run.processGroupId || - (run.processStartedAt ? identity.payload.processStartedAt !== run.processStartedAt.toISOString() - : !Number.isSafeInteger(run.processPid) || run.processPid! <= 1 || run.processGroupId !== run.processPid)) return "skipped"; - if (!(await recordNativeLocalProcessStop(tx, run))) { + if (run.localLeasePending) return "pending"; + if (run.identityMatches !== true) return "skipped"; + if ((!run.processPid && !run.processGroupId) || (run.processPid && !absent(run.processPid)) + || (run.processGroupId && !absent(-run.processGroupId))) { options.onDeferredDeadline?.(Date.now() + 30_000); return "pending"; } + await appendLocalProcessStop(tx, { id: runId, companyId: run.companyId, agentId: run.agentId, + processPid: run.processPid, processGroupId: run.processGroupId, processStartedAt: run.processStartedAt }); } - await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId: run.id, agentId: run.agentId }); - await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId: run.id }); + await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId, agentId: run.agentId }); + await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId }); // Local and remote stops both close the run's usage source. await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId); await tx.update(heartbeatRuns).set({ processPid: null, processGroupId: null, processStartedAt: null, updatedAt: new Date(), - }).where(eq(heartbeatRuns.id, run.id)); + }).where(eq(heartbeatRuns.id, runId)); return "released" as const; }); if (outcome !== "pending") pendingSettledProcessReleases.delete(runId); - return outcome; + return { outcome, remoteStop }; } const MAX_SETTLED_PROCESS_RELEASE_ATTEMPTS = 20; @@ -473,13 +530,7 @@ export async function discoverSettledNativeRunProcesses(db: Db, input: { let after: string | null = null; let released = 0; do { - const candidates: Array<{ id: string }> = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( - eq(heartbeatRuns.runtimeMode, "native"), - inArray(heartbeatRuns.status, SETTLED_RUN_STATUSES), - isNotNull(heartbeatRuns.finishedAt), - or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), isNotNull(heartbeatRuns.processStartedAt)), - ...(after ? [gt(heartbeatRuns.id, after)] : []), - )).orderBy(asc(heartbeatRuns.id)).limit(limit); + const candidates: Array<{ id: string }> = await settledNativeProcessCandidates(db, { after, limit }); for (const candidate of candidates) { if (input.skip?.(candidate.id)) continue; if (await settleNativeRunProcess(db, candidate.id) === "released") released += 1; diff --git a/server/src/services/native-runtime/native-session-resume.ts b/server/src/services/native-runtime/native-session-resume.ts index 5b10620f53c..61c5ef5bc31 100644 --- a/server/src/services/native-runtime/native-session-resume.ts +++ b/server/src/services/native-runtime/native-session-resume.ts @@ -210,7 +210,7 @@ export function selectNativeSessionResumeRun< return null; } -const NATIVE_SESSION_PROVIDER_EVENT_TYPES = [ +export const NATIVE_SESSION_PROVIDER_EVENT_TYPES = [ "harness.ready", "session.started", "session.resumed", From c3f9a0c0409762c7d827eda267215ce0a04bc34b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:47:01 -0600 Subject: [PATCH 6/8] fix(retention): evaluate native retention blockers for many sessions in one statement (#21588) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs keep runner checkpoints and harness backups so that a session can resume. Retention expires them after the session can no longer resume. > - A retention blocker decides whether a session can still resume: a live or recent run, an open or recently closed task, an unsettled finalization, or a live lease. > - The startup checkpoint pass evaluated that blocker in its own transaction, once for each retained checkpoint, with three reads. A session that stays blocked (for example, a long-lived open task) was evaluated again for each of its runs on every server start. On a hosted instance with frequent deploys and a 40-minute overlap of two servers, this pass ran almost continuously at about 7 checkpoints/s, about 21 statements/s. > - Backup reconciliation also used four reads and a transaction for each run hint that reached a backup. > - This pull request evaluates the blocker for many sessions in one fixed-text statement. Only candidates that are not blocked enter the existing locked transaction. > - The benefit: a restart costs 2 statements for each page of 200 blocked checkpoints instead of 5 statements and 1 transaction for each checkpoint, and a backup hint costs 2 statements with no transaction. ## Linked Issues or Issue Description No public issue exists. Bug description: **What happened?** A hosted instance had only a handful of live agent runs, but its server main thread was about 95% busy. An analysis of its most-called SQL found three retention-blocker reads (`company_id, agent_id from heartbeat_runs`; the session's runs; the session's issues) at exactly 7.0/s each, each in its own transaction. The startup checkpoint pass sent them once for each retained checkpoint older than 7 days whose session was still blocked, and it repeated the full pass after every start. **Expected behavior** A checkpoint or backup that is blocked from expiring costs no transaction and no statements of its own, because one statement evaluates its session together with the rest of its page. It expires as soon as its blocker clears: checkpoints on the next startup pass (the current design), and backups at their exact deadline. **Steps to reproduce** 1. Create 100 native sessions with 3 finished runs each (finished 10 days ago), settled finalizations, a checkpoint header for each run, and an open task. 2. Register the startup checkpoint expiration and count statements. Then register it again, as a restart. 3. On master each start costs 1,502 statements and 300 transactions, and nothing expires. **Paperclip version or commit** `origin/master` at 3c3e6c2d75. ## What Changed - `SESSION_RETENTION_BLOCKERS_SQL` (new module `native-runtime/native-session-retention-blockers.ts`) is one fixed-text statement, sent through `$client.unsafe`. It takes a JSON list of sessions and returns, for each one, the same blocker reasons as `sessionRetentionBlocker`, in the same order: missing run, live run, incomplete native recovery, recent run (checkpoint mode), unknown, open, executing or recently closed task, pending finalization, live lease. It also returns the session's resume pointer, run, task and lease dependencies, and the latest close time. - `expireCheckpoints` and `expireDurableBackups` evaluate each page of candidates with this statement. They skip blocked candidates and candidates whose session still has a resume pointer. A candidate that is not blocked still enters the existing transaction. That transaction checks the blocker again under row locks before it retires anything. - `reconcileBackup` uses the statement for its dependencies and its deadline. It replaces three dependency reads plus a blocker transaction. The lease references use one index-backed arm for each reference kind (run, backup stamp, task, identity lease). - The unused `lock: false` path of `sessionRetentionBlocker` and the `backupDependencies` helper are removed. - The existing index test now checks the plan of the new statement. Every arm that reads `environment_leases` uses an index in both the custom and the generic plan. ## Verification - New suite `server/src/__tests__/native-retention-blocker-batch.test.ts` (embedded PostgreSQL, real coordinator registration, statement meter): - 300 blocked checkpoints: a start costs 4 statements and 0 transactions, and a restart costs the same. On master it is 1,502 statements and 300 transactions for each start. The checkpoints are kept. - When a session's task is closed long enough ago, its checkpoints expire on the next startup pass. The other sessions are not touched. - A session with a resume pointer keeps its checkpoints for 2 statements in total. - Two servers that run the startup pass at the same time expire every checkpoint exactly once with no failures, because the locked transaction checks again and the retirement header is compared before deletion. - 50 run hints that reach 50 blocked backups: at most 2 statements for each hint (the scope lookup and one blocker statement) and no transaction. On master it is 9 statements and 1 transaction for each hint. The backups are kept. - Existing suites, one at a time: `native-harness-backup-expiration` (109/109, including the backup expiry flows for task close, reopen and lease release), `native-harness-backup-expiration-config` (7/7), `native-harness-backup-storage.integration` (73/73), `native-harness-backup-publication` (4/4), `native-retired-backup-source.integration` (38/38). - `pnpm check:module-boundaries` passes. ## Risks - The startup pass still runs on every server start. It also runs on both servers during the deploy overlap. Its new cost is 2 statements for each page of 200 candidates (the candidate page and one blocker statement). A page of candidates that are not blocked still uses one locked transaction for each candidate, as before. - Two servers can run the pass at the same time. They cannot retire the same session twice or retire a blocked one: the unlocked statement only filters, and the existing transaction locks the finalizations, checks the blocker again, and compares the retirement header before it deletes. The concurrency test covers this. - If the SQL blocker and the TypeScript blocker ever disagree in the "not blocked" direction, the locked transaction still refuses. If they disagree in the "blocked" direction, retention is only delayed. When more than one task blocks a session, the reported reason can differ from the TypeScript loop, which reads the tasks in no fixed order. - Checkpoints keep their current design: they are considered again on the next startup, not at a deadline. Backups keep their exact deadline after a task closes. - No schema change and no migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as a coding agent with tool use (shell, file edits, local test runs). ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../native-harness-backup-expiration.test.ts | 27 +-- .../native-retention-blocker-batch.test.ts | 164 ++++++++++++++++++ .../native-harness-backup-expiration.ts | 54 +++--- .../native-session-retention-blockers.ts | 84 +++++++++ 4 files changed, 291 insertions(+), 38 deletions(-) create mode 100644 server/src/__tests__/native-retention-blocker-batch.test.ts create mode 100644 server/src/services/native-runtime/native-session-retention-blockers.ts diff --git a/server/src/__tests__/native-harness-backup-expiration.test.ts b/server/src/__tests__/native-harness-backup-expiration.test.ts index 28740b3bf9c..4c956f5de5b 100644 --- a/server/src/__tests__/native-harness-backup-expiration.test.ts +++ b/server/src/__tests__/native-harness-backup-expiration.test.ts @@ -1020,22 +1020,29 @@ describeEmbeddedPostgres("native harness backup expiration", () => { // Every arm of the company's lease lookup must be index-backed, or the // planner reads each lease's metadata (environment_leases_native_backup_scope_idx). - const lookup = queries.find(query => query.text.startsWith('select "id" from "environment_leases"') - && query.text.includes("sessionScopeSha256")); + const lookup = queries.find(query => query.text.includes("jsonb_to_recordset") && query.text.includes("sessionScopeSha256")); expect(lookup).toBeDefined(); - const custom = JSON.stringify(await db.$client.unsafe(`explain (format json) ${lookup!.text}`, lookup!.params as never[])); - // A reused prepared statement gets a generic plan; the bound digest must - // still prove the partial index predicate. - const generic = JSON.stringify(await db.$client.begin(async tx => { + const leaseScans = (plan: unknown): string[] => { + const nodes: string[] = []; + const visit = (node: Record) => { + if (String(node["One-Time Filter"] ?? "") === "$3") return; + if (node["Relation Name"] === "environment_leases" || String(node["Index Name"] ?? "").startsWith("environment_leases")) + nodes.push(`${node["Node Type"]}:${node["Index Name"] ?? ""}`); + for (const child of (node.Plans as Record[] | undefined) ?? []) visit(child); + }; + visit(((plan as Array<{ "QUERY PLAN": Array<{ Plan: Record }> }>)[0]!["QUERY PLAN"][0]!).Plan); + return nodes; + }; + const custom = leaseScans(await db.$client.unsafe(`explain (format json) ${lookup!.text}`, lookup!.params as never[])); + const generic = leaseScans(await db.$client.begin(async tx => { await tx.unsafe("set local plan_cache_mode = force_generic_plan"); await tx.unsafe(`prepare backup_lease_lookup as ${lookup!.text}`); const values = lookup!.params.map(value => `'${String(value).replaceAll("'", "''")}'`).join(", "); return tx.unsafe(`explain (format json) execute backup_lease_lookup(${values})`); })); - for (const text of [custom, generic]) { - expect(text).toContain("environment_leases_native_backup_scope_idx"); - expect(text).toContain("BitmapOr"); - expect(text).not.toContain("Seq Scan"); + for (const scans of [custom, generic]) { + expect(scans.some(scan => scan.endsWith("environment_leases_native_backup_scope_idx"))).toBe(true); + expect(scans.filter(scan => scan.startsWith("Seq Scan"))).toEqual([]); } }); diff --git a/server/src/__tests__/native-retention-blocker-batch.test.ts b/server/src/__tests__/native-retention-blocker-batch.test.ts new file mode 100644 index 00000000000..bcfb995efd9 --- /dev/null +++ b/server/src/__tests__/native-retention-blocker-batch.test.ts @@ -0,0 +1,164 @@ +import { createHash, randomUUID } from "node:crypto"; +import os from "node:os"; +import path from "node:path"; +import { promises as fs } from "node:fs"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq } from "drizzle-orm"; +import { + agents, agentTaskSessions, companies, createDb, environmentLeases, heartbeatRuns, issues, + nativeRunFinalizations, nativeRunnerCheckpoints, +} from "@paperclipai/db"; +import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { nativeHarnessBackupExpirationService } from "../services/native-runtime/native-harness-backup-expiration.js"; +import { registerNativeHarnessBackupExpirationWork } from "../services/native-runtime/native-harness-backup-expiration-work.js"; +import { notifyRetainedNativeSessionCleanup } from "../services/retained-native-session-cleanup-notifications.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { idleWorkSnapshot } from "../services/task-admission.js"; + +const DAY_MS = 24 * 60 * 60 * 1000; +const describeEmbeddedPostgres = recoveryPostgresSupport.supported ? describe : describe.skip; + +describeEmbeddedPostgres("native retention blockers", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + let meter!: ReturnType; + let stateBase = ""; + const now = new Date(); + + beforeAll(async () => { + tempDb = await startRecoveryPostgres("paperclip-native-retention-blockers-"); + db = createDb(tempDb.connectionString); + meter = meterDatabaseStatements(db, tempDb.connectionString); + }, 30_000); + afterEach(async () => { + vi.useRealTimers(); vi.restoreAllMocks(); + await db.delete(nativeRunnerCheckpoints); + await db.delete(agentTaskSessions); + await db.delete(nativeRunFinalizations); + await db.delete(environmentLeases); + await db.delete(heartbeatRuns); + await db.delete(issues); + await db.delete(agents); + await db.delete(companies); + if (stateBase) await fs.rm(stateBase, { recursive: true, force: true }); + stateBase = ""; + }); + afterAll(async () => { + meter?.uninstall(); + await db?.$client.end({ timeout: 1 }); + await tempDb?.cleanup(); + }); + + async function seedSessions(count: number, input: { runsPerSession?: number; issueStatus?: string; closedDaysAgo?: number; backup?: boolean } = {}) { + if (!stateBase) stateBase = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-retention-blockers-")); + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Retention", issuePrefix: `R${companyId.slice(0, 6)}` }); + const [agent] = await db.insert(agents).values({ companyId, name: "Coder" }).returning(); + const finishedAt = new Date(now.getTime() - 10 * DAY_MS); + const status = input.issueStatus ?? "todo"; + const closedAt = new Date(now.getTime() - (input.closedDaysAgo ?? 10) * DAY_MS); + const sessions = []; + for (let index = 0; index < count; index++) { + const [issue] = await db.insert(issues).values({ companyId, title: "Work", status, + completedAt: status === "done" ? closedAt : null }).returning(); + const sessionId = randomUUID(); + const runs = await db.insert(heartbeatRuns).values(Array.from({ length: input.runsPerSession ?? 3 }, () => ({ + companyId, agentId: agent!.id, status: "succeeded", issueId: issue!.id, nativeIssueId: issue!.id, + nativeSessionId: sessionId, finishedAt, + }))).returning(); + await db.insert(nativeRunFinalizations).values(runs.map(run => ({ runId: run.id, companyId, issueId: issue!.id, phase: "committed" }))); + await db.insert(nativeRunnerCheckpoints).values(runs.map(run => ({ + companyId, issueId: issue!.id, runId: run.id, part: "header", material: { encrypted: true }, + }))); + const scope = createHash("sha256").update(randomUUID()).digest("hex"); + if (input.backup) { + const root = path.join(stateBase, scope); + const current = path.join(root, "failover-backups", "current"); + await fs.mkdir(path.join(root, "control-plane"), { recursive: true }); + await fs.writeFile(path.join(root, "control-plane", "control-plane-state.json"), + JSON.stringify({ identity: { runId: runs[0]!.id, normalizedSessionId: sessionId } })); + await fs.mkdir(current, { recursive: true }); + await fs.writeFile(path.join(current, "manifest.json"), "{}"); + await fs.utimes(current, finishedAt, finishedAt); + } + sessions.push({ companyId, agentId: agent!.id, issueId: issue!.id, sessionId, scope, runIds: runs.map(run => run.id) }); + } + return sessions; + } + + function service() { + return nativeHarnessBackupExpirationService(db, { stateBase, closedForDays: 7, isSessionBusy: () => false }); + } + + async function startup() { + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => {} }); + const before = meter.read(); + try { + await service().registerCheckpointExpiration(coordinator).ready; + await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 60_000 }); + } finally { await coordinator.stop(); } + const after = meter.read(); + return { statements: after.statements - before.statements, transactions: after.transactions - before.transactions }; + } + + it("evaluates blocked checkpoint sessions in one statement per page and repeats nothing per checkpoint on restart", async () => { + await seedSessions(100); + const first = await startup(); + const second = await startup(); + expect(first).toEqual({ statements: 4, transactions: 0 }); + expect(second).toEqual(first); + expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toHaveLength(300); + }, 120_000); + + it("expires the checkpoints of a session on the next startup once its blocker clears", async () => { + const [blocked] = await seedSessions(1); + const cleared = await seedSessions(2, { issueStatus: "done", closedDaysAgo: 9 }); + await startup(); + const remaining = await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints); + expect(remaining.map(row => row.runId).sort()).toEqual([...blocked!.runIds].sort()); + expect(cleared.flatMap(session => session.runIds).some(runId => remaining.some(row => row.runId === runId))).toBe(false); + await db.update(issues).set({ status: "done", completedAt: new Date(now.getTime() - 8 * DAY_MS) }).where(eq(issues.id, blocked!.issueId)); + await startup(); + expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toEqual([]); + }, 120_000); + + it("keeps a checkpoint whose session still has a resume pointer", async () => { + const [session] = await seedSessions(1, { issueStatus: "done", closedDaysAgo: 9 }); + await db.insert(agentTaskSessions).values({ companyId: session!.companyId, agentId: session!.agentId, adapterType: "paperclip_runner", + taskKey: session!.issueId, sessionParamsJson: { sessionId: session!.sessionId }, lastRunId: session!.runIds[0]! }); + expect(await startup()).toEqual({ statements: 2, transactions: 0 }); + expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toHaveLength(3); + }, 120_000); + + it("lets two servers run the startup pass at once without duplicate or conflicting retirement", async () => { + const sessions = await seedSessions(20, { issueStatus: "done", closedDaysAgo: 9 }); + const [left, right] = await Promise.all([service().tickCheckpoints(), service().tickCheckpoints()]); + expect(left.failed + right.failed).toBe(0); + expect(left.expiredCheckpoints + right.expiredCheckpoints).toBe(sessions.length * 3); + expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toEqual([]); + }, 120_000); + + it("reads a blocked backup in one statement for each run hint that reaches it", async () => { + const sessions = await seedSessions(50, { backup: true, runsPerSession: 1 }); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: () => {} }); + const worker = registerNativeHarnessBackupExpirationWork(coordinator, db, { stateBase, isSessionBusy: () => false }, () => true); + try { + await worker.ready; + await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(1000); expect(idleWorkSnapshot().active).toBe(0); }); + const before = meter.read(); + meter.startLog(); + for (const session of sessions) await db.transaction(tx => notifyRetainedNativeSessionCleanup(tx, { companyId: session.companyId, runId: session.runIds[0]! })); + await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(1000); expect(idleWorkSnapshot().active).toBe(0); }, { timeout: 30_000 }); + await vi.advanceTimersByTimeAsync(5000); + const log = meter.stopLog(); + const after = meter.read(); + const hintWrites = sessions.length * 3; + expect(after.transactions - before.transactions).toBe(sessions.length); + expect(after.statements - before.statements - hintWrites).toBeLessThanOrEqual(sessions.length * 2); + expect(log.filter(entry => entry.sql.includes("jsonb_to_recordset")).length).toBe(sessions.length); + for (const session of sessions) expect(await fs.lstat(path.join(stateBase, session.scope, "failover-backups", "current")).then(() => true)).toBe(true); + } finally { await worker.stop(); await coordinator.stop(); } + }, 120_000); +}); diff --git a/server/src/services/native-runtime/native-harness-backup-expiration.ts b/server/src/services/native-runtime/native-harness-backup-expiration.ts index c51bcbd30ff..6f10184e23e 100644 --- a/server/src/services/native-runtime/native-harness-backup-expiration.ts +++ b/server/src/services/native-runtime/native-harness-backup-expiration.ts @@ -16,6 +16,7 @@ import { type Db, } from "@paperclipai/db"; import { logger } from "../../middleware/logger.js"; +import { assessSessionRetention } from "./native-session-retention-blockers.js"; import { nativeHarnessStateBase } from "./native-harness-backup-stamp.js"; import { nativeSessionScopeDigestIsBusy } from "./native-session-executor.js"; import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; @@ -185,7 +186,7 @@ type Tx = Parameters[0]>[0]; async function sessionRetentionBlocker( tx: Tx, - input: { scopeDigest: string | null; identity: SessionIdentity; closedBefore: Date; checkpoint?: boolean; lock?: boolean }, + input: { scopeDigest: string | null; identity: SessionIdentity; closedBefore: Date; checkpoint?: boolean }, ): Promise<{ reason: string } | { companyId: string; agentId: string; runIds: string[]; issueIds: string[]; closedAt: number }> { const [owner] = await tx .select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId }) @@ -225,7 +226,7 @@ async function sessionRetentionBlocker( }) .from(issues) .where(and(eq(issues.companyId, owner.companyId), inArray(issues.id, issueIds))); - const issueRows = await (input.lock === false ? issueQuery : issueQuery.for("share")); + const issueRows = await issueQuery.for("share"); if (issueRows.length !== issueIds.length) return { reason: "issue_unknown" }; for (const issue of issueRows) { if (!CLOSED_ISSUE_STATUSES.includes(issue.status)) return { reason: "issue_open" }; @@ -314,6 +315,11 @@ export function nativeHarnessBackupExpirationService( .where(and(durableBackupCursor ? gt(nativeHarnessBackups.id, durableBackupCursor) : undefined, or(eq(nativeHarnessBackups.status, "retired"), lt(nativeHarnessBackups.createdAt, options.closedBefore)))) .orderBy(asc(nativeHarnessBackups.id)).limit(options.maxEntries + 1); + const assessments = await assessSessionRetention(db, candidates.slice(0, options.maxEntries) + .filter(candidate => candidate.survivingRunId && candidate.sessionId && !["retired", "pending", "superseded"].includes(candidate.status)) + .map(candidate => ({ key: candidate.id, scopeDigest: candidate.scopeDigest, + identity: { runId: candidate.runId, normalizedSessionId: candidate.sessionId!, environmentLeaseId: null } })), + { closedBefore: options.closedBefore, checkpoint: true }); let processed = 0; for (const candidate of candidates) { if (!options.shouldContinue() || processed++ >= options.maxEntries || result.expired >= options.maxRemovals) { @@ -321,6 +327,7 @@ export function nativeHarnessBackupExpirationService( } durableBackupCursor = candidate.id; if (candidate.survivingRunId && !candidate.sessionId) continue; + if (assessments.get(candidate.id)?.reason) continue; try { const retired = candidate.status === "retired" || await db.transaction(async tx => { if (["pending", "superseded"].includes(candidate.status)) { @@ -385,6 +392,11 @@ export function nativeHarnessBackupExpirationService( isNull(nativeRunFinalizations.leaseOwner), isNull(nativeRunFinalizations.recoveryState), )) .orderBy(asc(nativeRunnerCheckpoints.runId)).limit(options.maxEntries + 1); + const assessments = await assessSessionRetention(db, candidates.slice(0, options.maxEntries) + .filter(candidate => candidate.sessionId && !candidate.retirement) + .map(candidate => ({ key: candidate.runId, scopeDigest: null, + identity: { runId: candidate.runId, normalizedSessionId: candidate.sessionId!, environmentLeaseId: null } })), + { closedBefore: options.closedBefore, checkpoint: true }); let processed = 0; let removed = 0; for (const candidate of candidates) { @@ -395,6 +407,9 @@ export function nativeHarnessBackupExpirationService( processed++; checkpointCursor = candidate.runId; if (!candidate.sessionId) continue; // Unknown identity is never expiration evidence. + const assessment = assessments.get(candidate.runId); + if (assessment && (assessment.reason || assessment.resumable + || assessment.runIds.length > MAX_NATIVE_CHECKPOINT_RETIREMENT_RUNS)) continue; try { const previousRetirement = readNativeCheckpointRetirement(candidate.retirement, candidate); if (previousRetirement && previousRetirement.sessionId !== candidate.sessionId) throw new Error("native_runner_checkpoint_retirement_invalid"); @@ -861,25 +876,6 @@ export function nativeHarnessBackupExpirationService( }); } - async function backupDependencies(scopeDigest: string, identity: SessionIdentity): Promise { - const [owner] = await db.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, - issueId: sql`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`, - }).from(heartbeatRuns).where(eq(heartbeatRuns.id, identity.runId)); - if (!owner) return null; - const runs = await db.select({ id: heartbeatRuns.id, - issueId: sql`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`, - }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId), - eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.nativeSessionId, identity.normalizedSessionId))); - const runIds = [...new Set([identity.runId, ...runs.map(run => run.id)])]; - const issueIds = [...new Set([owner.issueId, ...runs.map(run => run.issueId)].filter((id): id is string => Boolean(id)))]; - const leases = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( - eq(environmentLeases.companyId, owner.companyId), or(inArray(environmentLeases.heartbeatRunId, runIds), - sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'sessionScopeSha256' = ${scopeDigest}`, - identity.environmentLeaseId ? eq(environmentLeases.id, identity.environmentLeaseId) : undefined))); - return { companyId: owner.companyId, agentId: owner.agentId, sessionId: identity.normalizedSessionId, - runIds, issueIds, leaseIds: leases.map(lease => lease.id) }; - } - async function resolveBackupScope(scope: NativeHarnessBackupExpirationScope) { let runId = scope.runId; let issueId = scope.issueId; @@ -910,18 +906,20 @@ export function nativeHarnessBackupExpirationService( if (!stat?.isDirectory() || stat.isSymbolicLink()) return null; const identity = await readSessionIdentity(root); if (!identity) return null; - const dependencies = await backupDependencies(scopeDigest, identity); - if (!dependencies) return null; + const assessment = (await assessSessionRetention(db, [{ key: scopeDigest, identity, scopeDigest }], + { closedBefore: "infinity", checkpoint: false })).get(scopeDigest); + if (!assessment?.companyId || !assessment.agentId) return null; + const dependencies: NativeHarnessBackupDependencies = { companyId: assessment.companyId, agentId: assessment.agentId, + sessionId: identity.normalizedSessionId, runIds: [...new Set([identity.runId, ...assessment.runIds])], + issueIds: [...new Set([assessment.ownerIssueId, ...assessment.issueIds].filter((id): id is string => Boolean(id)))], + leaseIds: assessment.leaseIds }; const source = { id: scopeDigest, companyId: dependencies.companyId, agentId: dependencies.agentId, dependencies }; if (await fs.lstat(path.join(root, "cleanup-activation.json")).then(() => true, () => false)) { return { ...source, dueAt: null }; } - const blocker = await db.transaction(tx => sessionRetentionBlocker(tx, { - scopeDigest, identity, closedBefore: new Date(8_000_000_000_000_000), lock: false, - })); - if ("reason" in blocker) return { ...source, dueAt: null }; + if (assessment.reason || assessment.closedAt === null) return { ...source, dueAt: null }; const retentionMs = Math.max(1, defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS) * DAY_MS; - return { ...source, dueAt: Math.max(stat!.mtime.getTime(), blocker.closedAt) + retentionMs + 1 }; + return { ...source, dueAt: Math.max(stat!.mtime.getTime(), assessment.closedAt) + retentionMs + 1 }; } async function backupScopes(after?: string, limit = 100) { diff --git a/server/src/services/native-runtime/native-session-retention-blockers.ts b/server/src/services/native-runtime/native-session-retention-blockers.ts new file mode 100644 index 00000000000..9d44a386002 --- /dev/null +++ b/server/src/services/native-runtime/native-session-retention-blockers.ts @@ -0,0 +1,84 @@ +import type { Db } from "@paperclipai/db"; + +const SESSION_RETENTION_BLOCKERS_SQL = ` +with input as ( + select * from jsonb_to_recordset($1::jsonb) as i(key text, run_id uuid, session_id uuid, scope_digest text, lease_id uuid) +), owner as ( + select i.*, r.company_id, r.agent_id, coalesce(r.native_issue_id, r.issue_id) as owner_issue_id + from input i join heartbeat_runs r on r.id = i.run_id +), sessions as ( + select o.key, o.run_id, o.session_id, o.scope_digest, o.lease_id, o.company_id, o.agent_id, o.owner_issue_id, + coalesce(array_agg(r.id order by r.id) filter (where r.id is not null), '{}') as run_ids, + coalesce(array_agg(distinct coalesce(r.native_issue_id, r.issue_id)) filter (where coalesce(r.native_issue_id, r.issue_id) is not null), '{}') as issue_ids, + coalesce(bool_or(r.status in ('queued', 'scheduled_retry', 'running') or r.finished_at is null), false) as live, + coalesce(bool_or((r.runner_profile_json->'nativeControllerRecovery'->>'schema' = 'paperclip.native-controller-recovery.v1' + and r.runner_profile_json->'nativeControllerRecovery'->'checkpoint' = 'null'::jsonb) is true), false) as incomplete, + coalesce(bool_or(r.finished_at >= $2::timestamptz), false) as recent + from owner o + left join heartbeat_runs r on r.company_id = o.company_id and r.agent_id = o.agent_id and r.native_session_id = o.session_id + group by o.key, o.run_id, o.session_id, o.scope_digest, o.lease_id, o.company_id, o.agent_id, o.owner_issue_id +), assessed as ( + select s.*, + (select count(*) from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids)) as issues_found, + exists (select 1 from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids) + and x.status not in ('done', 'cancelled')) as issue_open, + exists (select 1 from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids) + and x.execution_run_id is not null) as issue_executing, + exists (select 1 from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids) + and (coalesce(x.completed_at, x.cancelled_at) is null or coalesce(x.completed_at, x.cancelled_at) >= $2::timestamptz)) as issue_recent, + (select (extract(epoch from max(coalesce(x.completed_at, x.cancelled_at))) * 1000)::float8 from issues x + where x.company_id = s.company_id and x.id = any(s.issue_ids)) as closed_at, + (select count(*) from native_run_finalizations f where f.run_id = any(s.run_ids)) as finalizations, + exists (select 1 from native_run_finalizations f where f.run_id = any(s.run_ids) + and (f.phase not in ('committed', 'terminal_failure') or f.lease_owner is not null)) as finalization_pending, + exists (select 1 from ( + select l.status from environment_leases l where l.heartbeat_run_id = any(s.run_ids) + union all select l.status from environment_leases l + where l.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' = s.scope_digest + union all select l.status from environment_leases l where $3::boolean and l.company_id = s.company_id and l.issue_id = any(s.issue_ids) + union all select l.status from environment_leases l where $3::boolean and l.company_id = s.company_id + and l.metadata->'nativeHarnessBackup'->>'normalizedSessionId' = s.session_id::text + union all select l.status from environment_leases l where l.id = s.lease_id + ) referenced where referenced.status in ('active', 'released', 'retained', 'pending_cleanup')) as lease_live, + coalesce((select array_agg(distinct referenced.id order by referenced.id) from ( + select l.id from environment_leases l where l.company_id = s.company_id and l.heartbeat_run_id = any(s.run_ids || s.run_id) + union all select l.id from environment_leases l where l.company_id = s.company_id + and l.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' = s.scope_digest + union all select l.id from environment_leases l where l.company_id = s.company_id and l.id = s.lease_id + ) referenced), '{}') as lease_ids, + exists (select 1 from agent_task_sessions t where t.company_id = s.company_id and t.agent_id = s.agent_id + and (t.last_run_id = any(s.run_ids) or t.session_params_json->>'sessionId' = s.session_id::text)) as resumable + from sessions s +) +select i.key, a.company_id, a.agent_id, a.run_ids, a.issue_ids, a.owner_issue_id, a.lease_ids, a.closed_at, coalesce(a.resumable, false) as resumable, + case + when a.key is null then 'run_missing' + when a.live then 'live_run' + when a.incomplete then 'native_recovery_incomplete' + when $3::boolean and a.recent then 'recent_run' + when cardinality(a.issue_ids) = 0 or a.issues_found <> cardinality(a.issue_ids) then 'issue_unknown' + when a.issue_open then 'issue_open' + when $3::boolean and a.issue_executing then 'live_run' + when a.issue_recent then 'recently_closed' + when ($3::boolean and a.finalizations <> cardinality(a.run_ids)) or a.finalization_pending then 'pending_finalization' + when a.lease_live then 'live_lease' + end as reason +from input i left join assessed a on a.key = i.key`; + +export type SessionRetentionAssessment = { + reason: string | null; companyId: string | null; agentId: string | null; runIds: string[]; issueIds: string[]; + ownerIssueId: string | null; leaseIds: string[]; closedAt: number | null; resumable: boolean; +}; + +export async function assessSessionRetention(db: Db, sessions: Array<{ key: string; identity: { runId: string; normalizedSessionId: string; environmentLeaseId: string | null }; scopeDigest: string | null }>, + options: { closedBefore: Date | "infinity"; checkpoint: boolean }): Promise> { + if (sessions.length === 0) return new Map(); + const rows = await db.$client.unsafe>( + SESSION_RETENTION_BLOCKERS_SQL, [JSON.stringify(sessions.map(session => ({ key: session.key, run_id: session.identity.runId, + session_id: session.identity.normalizedSessionId, scope_digest: session.scopeDigest, lease_id: session.identity.environmentLeaseId }))), + options.closedBefore === "infinity" ? "infinity" : options.closedBefore.toISOString(), options.checkpoint]); + return new Map(rows.map(row => [row.key, { reason: row.reason, companyId: row.company_id, agentId: row.agent_id, + runIds: row.run_ids ?? [], issueIds: row.issue_ids ?? [], ownerIssueId: row.owner_issue_id, leaseIds: row.lease_ids ?? [], + closedAt: row.closed_at === null ? null : Number(row.closed_at), resumable: row.resumable }])); +} From 633dec7e43b7c135a046c3520ffda9a411a867c2 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:47:06 -0600 Subject: [PATCH 7/8] fix(instructions): back off working copies that cannot make progress (#21586) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each run gets a private working copy of the agent's instructions or agent files. Background queues collect the copy after the provider stops and clean up its scratch directory. > - When the queue cannot prove that the provider stopped, or cannot finish a cleanup, it re-arms the same copy every 30 seconds with no limit. The attempt count does not increase on the "stop not proven" branch. > - Every re-arm is a transaction that sends work signals to its own queue, to the stranded-agent-status queue and to the skill-retention queue. A self-signal also reloads the copy's scope. On a hosted instance with only a few live runs, these copies were one of the largest sources of SQL calls and kept the main thread busy. > - This pull request makes a copy that cannot progress wait on a growing, capped backoff. It also removes the work signals from a write that only moves a deadline later, and reads the copy once per check. > - The benefit: a copy that waits for proof of the provider stop costs about 1/350 of the old steady-state load, and a copy that becomes collectable is still collected automatically. ## Linked Issues or Issue Description No public issue exists. Bug description: **What happened?** A hosted instance had only a handful of live agent runs, but its server main thread was about 95% busy. An analysis of its most-called SQL found the instruction working-copy queues re-reading the same unresolved copies forever, at about 25–30 statements/s. A copy whose run is terminal but whose provider stop is not proven was re-armed every 30 s. A completed agent-files copy whose remote scratch cleanup cannot finish (its lease is released but not destroyed, or the lease row is gone) was also re-armed every 30 s. Each re-arm was a transaction with work signals that woke three queues. **Expected behavior** A copy that cannot progress is not re-read until a growing, capped backoff elapses. A write that only moves a deadline later does not wake other queues. A copy that becomes collectable is still collected automatically, and no data is lost. **Steps to reproduce** 1. Create working copies of terminal native runs that have no `native.local_process_stopped` event, and completed agent-files copies with `cleanupPending: true` whose remote lease does not exist. 2. Register the instruction-collection and directory-cleanup queues. 3. Count statements while time advances. With 300 + 300 such copies, master sends 252 statements/s, 38.7 transactions/s and 38.7 work signals/s. **Paperclip version or commit** `origin/master` at 3c3e6c2d75. ## What Changed - `instructionCopyRetryAt(waitingSince)` sets the next check to half of the time the copy has waited. The minimum is `INSTRUCTION_COPY_RETRY_MS` (30 s) and the maximum is `INSTRUCTION_COPY_MAX_RETRY_MS` (6 h). An unproven stop measures the wait from the run's `finished_at`. A cleanup measures it from `process_stopped_at`. The deadline stays in the existing `next_attempt_at` column, so a restart keeps it. There is no schema change. - The collection check now reads the copy once, checks the stop evidence, and then claims. For an unproven stop, the claim writes the backoff deadline (and the move from `prepared` to `pending_collection`) in the same UPDATE. Before, the check was two reads plus two signalling transactions. - `tryPatch` skips all work signals when a write only moves deadlines later and keeps the copy in the same queues (collection, cleanup, commit and the stranded-agent predicate). A write that changes queue membership or moves a deadline earlier still signals as before. The write stays in its own transaction, so the existing claim and race tests keep their hook. - A cleanup that cannot finish gets the same capped backoff after `release` re-arms it. The saved copy and its cleanup receipt are kept. The claim does not change `attempts`, because a concurrent foreground collection uses `attempts` in its compare-and-set. - A remote agent-files copy that stopped but was not destroyed, and an unavailable agent-files copy that waits for a destroy receipt, also get the capped backoff instead of a 30 s re-arm. - No copy is parked or dropped. A copy with an unproven stop stays in the queue with the 6 h cap. When proof of the stop arrives later (a `native.local_process_stopped` event, a lease termination receipt, or a recovery that records that the host is gone), the next backoff check collects it automatically. No manual call is necessary. ## Verification - New suite `server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts` (embedded PostgreSQL, real queue registration, statement meter): - The backoff constants and their values at 0 s, 30 min, 2 h, 12 h and 30 days. - A copy that has waited 2 days: two checks in 12 h, 5 statements and 1 transaction per check, and zero work signals. - A copy owned by a live older server (run finished 5 minutes ago): it is checked every few minutes. When the older server records the stop, the copy is collected within 10 minutes, without a manual call. - A copy that has waited 30 days: it is collected within one 6 h cap after the stop is recorded. - A backlog of 300 copies that have waited 30 days: one pass drains it with zero work signals, and the hour after it is silent. - A write that moves the deadline earlier, and a write that changes queue membership, both still send the signal. - A cleanup that cannot finish, with release returning and with release throwing: at most 32 deadline writes in the first 6 h, at most 4 in the next 6 h, zero work signals, and the copy is still saved with its cleanup pending. Before the fix, the throwing case made 74 writes in 6 h. - Red first: on master this suite fails 5 of 7 tests (the 30 s re-arm, 150 statements in the drain window, extra signals, a cleanup checked every 30 s). The two "collects after stop" tests pass on master and still pass: the positive behavior is kept. - Steady state with 300 unproven stops plus 300 stuck cleanups, each waiting for 1 day (10-minute window after warm-up): | | statements/s | transactions/s | work signals/s | stop checks/s | cleanup checks/s | | --- | --- | --- | --- | --- | --- | | master | 251.6 | 38.7 | 38.7 | 9.7 | 9.6 | | this PR | 0.45 | 0.10 | 0 | 0 | 0.03 | - Per check: an unproven stop goes from 12 statements, 2 transactions and 2 work signals to 5 statements, 1 transaction and 0 work signals. A stuck cleanup goes from about 14 statements, 2 transactions and 2 work signals to about 15 statements, 3 transactions and 0 work signals. Cleanup checks are exponentially less frequent. - Backlog drain: queue batches stay at 20 per pass, with one pass per second at most. An overdue copy moves to its long backoff on its first check. The first drain of N stuck copies therefore takes about N/20 seconds. For example, 17,000 copies drain in about 15 minutes with no work signals. - Existing suites, one at a time: `agent-instruction-working-copies` (50/50), `agent-directory-working-copies` (120/120), `heartbeat-instruction-working-copy` (4/4), `heartbeat-agent-directory-busy` (8/8), `agent-file-checkpoint-locking` (9 passed, 1 skipped), `agent-file-durability` (17/17), `idle-sleep-safety` (226/226), `heartbeat-process-recovery` (459/459), `agent-instructions-routes` (26/26), `services/heartbeat/agent-status` (42/42). - `pnpm check:module-boundaries` passes. ## Risks - Product-visible choice: the 6 h cap. A copy that has waited for a long time is collected at most 6 h after its stop proof arrives (half of the wait while the wait is shorter than 12 h). During that time, the uncollected candidate shows in the agent's instruction candidates (`pending_collection`, `INSTRUCTION_STOP_UNCONFIRMED`) for legacy copies, and in the run's agent-files diagnostics for agent-files copies. Its bytes are kept on disk. An explicit `collectStopped` from orchestration still collects immediately. - There is no seven-day park. A park at `attempts = 3` would leave the queue predicate, and a later stop proof would not reach the copy without changes in files that another fix owns. The copy therefore stays in the queue with the 6 h cap. The steady cost is about 5 statements per copy every 6 h. - During the 40-minute deploy overlap, a copy owned by a live older server waited only a short time, so its backoff is still 30 s to a few minutes. The test covers this case. - A write that only moves a deadline later no longer wakes the stranded-agent-status and skill-retention queues. The stranded-agent predicate is compared before and after the write, and any change still signals. - No schema change and no migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as a coding agent with tool use (shell, file edits, local test runs). ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ...ent-instruction-copy-retry-backoff.test.ts | 240 ++++++++++++++++++ .../agent-instruction-working-copies.ts | 135 ++++++---- 2 files changed, 329 insertions(+), 46 deletions(-) create mode 100644 server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts diff --git a/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts b/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts new file mode 100644 index 00000000000..ea54b58b6bb --- /dev/null +++ b/server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts @@ -0,0 +1,240 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { createHash, randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { eq } from "drizzle-orm"; +import { agents, agentInstructionWorkingCopies, authUsers, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; +import { + agentInstructionWorkingCopyService, + instructionCopyRetryAt, + INSTRUCTION_COPY_MAX_RETRY_MS, + INSTRUCTION_COPY_RETRY_MS, +} from "../services/agent-instruction-working-copies.js"; +import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js"; +import { idleWorkSnapshot } from "../services/task-admission.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_INSTRUCTION_COPY_TEST_DATABASE_URL"); +const AGENT_FILES = "paperclip.agent-files.v1"; +const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR; +const CONTENT = "# Instructions\n"; +const CONTENT_HASH = createHash("sha256").update(CONTENT).digest("hex"); + +describe("instruction working copies that cannot make progress", () => { + let database: Awaited>; + let db: ReturnType; + let meter: ReturnType; + let home: string; + let companyId: string, agentId: string, userId: string; + const previousHome = process.env.PAPERCLIP_HOME; + + beforeAll(async () => { + home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "instruction-copy-backoff-"))); + process.env.PAPERCLIP_HOME = home; + if (!external) database = await startEmbeddedPostgresTestDatabase("instruction-copy-backoff-db-"); + const url = external ?? database.connectionString; + db = createDb(url, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 20 * 24 * 3600, connectTimeoutSeconds: 3600 }); + meter = meterDatabaseStatements(db, url); + }, 90_000); + afterAll(async () => { + meter?.uninstall(); + if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome; + await db?.$client.end({ timeout: 1 }); + await database?.cleanup(); + if (home) await fs.rm(home, { recursive: true, force: true }); + }); + beforeEach(async () => { + companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Backoff", issuePrefix: randomUUID().slice(0, 8) }); + await db.insert(authUsers).values({ id: userId, name: "Editor", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(agents).values({ id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed" } }); + }); + afterEach(async () => { + vi.useRealTimers(); vi.restoreAllMocks(); + await db.delete(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.companyId, companyId)); + }); + + const clock = () => vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const coordinator = () => createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: () => {} }); + + async function runs(count: number, finishedAgo: number, runtimeMode = "native") { + const ids = Array.from({ length: count }, () => randomUUID()); + const finishedAt = new Date(Date.now() - finishedAgo); + await db.insert(heartbeatRuns).values(ids.map(id => ({ id, companyId, agentId, status: "failed", runtimeMode, + invocationSource: "on_demand", responsibleUserId: userId, startedAt: finishedAt, finishedAt }))); + return ids; + } + const entryPath = (runId: string) => path.join(home, "work", runId, ".paperclip-runtime", `instruction-edits-${runId}`, "instructions", "AGENTS.md"); + async function unprovenStops(count: number, finishedAgo: number) { + const ids = await runs(count, finishedAgo); + await db.insert(agentInstructionWorkingCopies).values(ids.map(runId => ({ runId, companyId, agentId, responsibleUserId: userId, + entryFile: "AGENTS.md", baseHash: CONTENT_HASH, localRoot: path.dirname(entryPath(runId)), executionRoot: path.dirname(entryPath(runId)), + location: "local", state: "prepared" }))); + for (const runId of ids) { + await fs.mkdir(path.dirname(entryPath(runId)), { recursive: true }); + await fs.writeFile(entryPath(runId), CONTENT); + } + return ids; + } + async function stuckCleanups(count: number, options: { lockRoot?: boolean } = {}) { + const ids = await runs(count, 0, "legacy"); + if (options.lockRoot !== false) for (const runId of ids) await fs.mkdir(path.join(home, "agents", agentId, "file-sync", "runs", runId, "live"), { recursive: true }); + await db.insert(agentInstructionWorkingCopies).values(ids.map(runId => { + const localRoot = path.join(home, "agents", agentId, "file-sync", "runs", runId, "live"); + return { runId, companyId, agentId, responsibleUserId: userId, entryFile: "AGENTS.md", baseHash: CONTENT_HASH, + localRoot, executionRoot: `/workspace/.paperclip-runtime/agent-files/${agentId}/${runId}`, + location: `remote:${randomUUID()}`, state: "saved", processStoppedAt: new Date(), receipt: { schema: AGENT_FILES, state: "saved", + cleanupPending: true, cleanup: { leaseId: randomUUID(), remoteCwd: "/workspace" }, materializationRunId: runId } }; + })); + return ids; + } + async function copy(runId: string) { + const [row] = await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.runId, runId)); + return row!; + } + async function settle() { + let last = -1; + for (let quiet = 0, turns = 0; quiet < 40 && turns < 20_000; turns++) { + await new Promise(resolve => setImmediate(resolve)); + const current = meter.read().statements; + quiet = current === last && idleWorkSnapshot().active === 0 ? quiet + 1 : 0; + last = current; + } + } + async function advance(ms: number, wakeAt: () => number | null) { + const before = meter.read(); + meter.startLog(); + const end = Date.now() + ms; + while (Date.now() < end) { + const next = wakeAt(); + const quietUntil = next === null || next > end ? end : Math.max(Date.now(), next - 1000); + if (quietUntil > Date.now()) await vi.advanceTimersByTimeAsync(quietUntil - Date.now()); + if (Date.now() >= end) break; + for (let step = 0; step < 3; step++) { await vi.advanceTimersByTimeAsync(1000); await settle(); } + } + await settle(); + const log = meter.stopLog(); + const after = meter.read(); + return { statements: after.statements - before.statements, transactions: after.transactions - before.transactions, + workSignals: log.filter(entry => entry.sql.includes("pg_current_xact_id")).length, + stopChecks: log.filter(entry => entry.sql.includes(`from "heartbeat_run_events"`)).length, + cleanupClaims: log.filter(entry => /^update "agent_instruction_working_copies" set "next_attempt_at" = \$1, "updated_at" = \$2 where/.test(entry.sql)).length }; + } + async function start(...queues: Array<"collection" | "cleanup">) { + const worker = coordinator(); + const service = agentInstructionWorkingCopyService(db); + if (queues.includes("collection")) await service.registerStoppedCollectionWork(worker, () => true, async () => true).ready; + if (queues.includes("cleanup")) await service.registerDirectoryCleanupWork(worker, () => true, async () => true).ready; + await settle(); + return worker; + } + + it("names a backoff that grows with the wait and stops growing at its cap", () => { + const now = Date.parse("2026-11-14T00:00:00Z"); + expect(INSTRUCTION_COPY_RETRY_MS).toBe(30_000); + expect(INSTRUCTION_COPY_MAX_RETRY_MS).toBe(6 * HOUR); + const delay = (waited: number) => instructionCopyRetryAt(new Date(now - waited), now).getTime() - now; + expect([0, 30 * MINUTE, 2 * HOUR, 12 * HOUR, 30 * DAY].map(delay)).toEqual([30_000, 15 * MINUTE, HOUR, 6 * HOUR, 6 * HOUR]); + }); + + it("re-reads an old unproven stop on the capped backoff with five statements and no work signal", async () => { + const [runId] = await unprovenStops(1, 2 * DAY); + clock(); const worker = await start("collection"); + try { + expect(await copy(runId!)).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", attempts: 0 }); + expect((await copy(runId!)).nextAttemptAt!.getTime() - Date.now()).toBeGreaterThan(6 * HOUR - MINUTE); + const window = await advance(12 * HOUR + MINUTE, worker.nextWakeAt); + expect(window.stopChecks).toBe(2); + expect(window.statements).toBe(10); + expect(window.transactions).toBe(2); + expect(window.workSignals).toBe(0); + expect(await copy(runId!)).toMatchObject({ state: "pending_collection", attempts: 0, processStoppedAt: null }); + } finally { await worker.stop(); } + }, 120_000); + + it("keeps re-checking a copy owned by a live older server and collects it once that server records the stop", async () => { + const [runId] = await unprovenStops(1, 5 * MINUTE); + clock(); const worker = await start("collection"); + try { + const early = await advance(10 * MINUTE, worker.nextWakeAt); + expect(early.stopChecks).toBeGreaterThanOrEqual(2); + expect(await copy(runId!)).toMatchObject({ state: "pending_collection", processStoppedAt: null }); + await appendHeartbeatRunEvent(db, { companyId, agentId, runId: runId!, eventType: "native.local_process_stopped", stream: "system" }); + await advance(10 * MINUTE, worker.nextWakeAt); + expect(await copy(runId!)).toMatchObject({ state: "unchanged", nextAttemptAt: null }); + expect((await copy(runId!)).processStoppedAt).not.toBeNull(); + } finally { await worker.stop(); } + }, 120_000); + + it("collects a copy that waited for weeks within one capped backoff of its stop being recorded", async () => { + const [runId] = await unprovenStops(1, 30 * DAY); + clock(); const worker = await start("collection"); + try { + await advance(HOUR, worker.nextWakeAt); + await appendHeartbeatRunEvent(db, { companyId, agentId, runId: runId!, eventType: "native.local_process_stopped", stream: "system" }); + await advance(INSTRUCTION_COPY_MAX_RETRY_MS, worker.nextWakeAt); + expect(await copy(runId!)).toMatchObject({ state: "unchanged", nextAttemptAt: null }); + } finally { await worker.stop(); } + }, 120_000); + + it("drains a backlog of old unproven stops in bounded batches without work signals", async () => { + await unprovenStops(300, 30 * DAY); + const signals: string[] = []; + const unsubscribe = [DELIVERY_QUEUES.instructionCollection, DELIVERY_QUEUES.strandedAgentStatus, DELIVERY_QUEUES.skillVersionRetention] + .map(queue => subscribeDeliveryWork(db, queue, () => signals.push(queue))); + clock(); const worker = coordinator(); + try { + const before = meter.read(); + await agentInstructionWorkingCopyService(db).registerStoppedCollectionWork(worker, () => true, async () => true).ready; + const drain = await advance(60_000, () => Date.now() + 1000); + const rows = await db.select({ next: agentInstructionWorkingCopies.nextAttemptAt }).from(agentInstructionWorkingCopies) + .where(eq(agentInstructionWorkingCopies.companyId, companyId)); + expect(rows.every(row => row.next!.getTime() - Date.now() > 5 * HOUR)).toBe(true); + expect(meter.read().transactions - before.transactions).toBeLessThanOrEqual(300); + expect(drain.stopChecks).toBeLessThanOrEqual(300); + expect(drain.workSignals).toBe(0); + expect(signals).toEqual([]); + expect((await advance(HOUR, worker.nextWakeAt)).statements).toBe(0); + } finally { unsubscribe.forEach(stop => stop()); await worker.stop(); } + }, 120_000); + + it("still signals when a write moves the deadline earlier or changes queue membership", async () => { + const [earlier, missing] = await unprovenStops(2, 2 * DAY); + clock(); const worker = await start("collection"); + await worker.stop(); + const service = agentInstructionWorkingCopyService(db); + const signals: string[] = []; + const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.instructionCollection, () => signals.push("collection")); + try { + await fs.rm(entryPath(earlier!)); await fs.mkdir(entryPath(earlier!)); + await service.collectStopped({ companyId, runId: earlier! }); + expect(await copy(earlier!)).toMatchObject({ state: "pending_collection", attempts: 1, errorCode: "INSTRUCTION_COLLECTION_FAILED" }); + expect((await copy(earlier!)).nextAttemptAt!.getTime() - Date.now()).toBeLessThanOrEqual(INSTRUCTION_COPY_RETRY_MS); + await vi.waitFor(() => expect(signals).toHaveLength(1)); + await fs.rm(entryPath(missing!)); + await service.collectStopped({ companyId, runId: missing! }); + expect(await copy(missing!)).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_FILE_MISSING" }); + await vi.waitFor(() => expect(signals).toHaveLength(2)); + } finally { unsubscribe(); } + }, 60_000); + + it.each([true, false])("backs off a cleanup that cannot finish and keeps the saved copy (cleanup throws: %s)", async throws => { + const [runId] = await stuckCleanups(1, { lockRoot: !throws }); + clock(); const worker = await start("cleanup"); + try { + const window = await advance(6 * HOUR, worker.nextWakeAt); + expect(window.cleanupClaims).toBeGreaterThan(0); + expect(window.workSignals).toBe(0); + expect(window.cleanupClaims).toBeLessThanOrEqual(32); + expect((await advance(6 * HOUR, worker.nextWakeAt)).cleanupClaims).toBeLessThanOrEqual(4); + const row = await copy(runId!); + expect(row).toMatchObject({ state: "saved", receipt: expect.objectContaining({ cleanupPending: true }) }); + expect(row.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now()); + } finally { await worker.stop(); } + }, 120_000); +}); diff --git a/server/src/services/agent-instruction-working-copies.ts b/server/src/services/agent-instruction-working-copies.ts index a3161d2e347..7f2d98b98b6 100644 --- a/server/src/services/agent-instruction-working-copies.ts +++ b/server/src/services/agent-instruction-working-copies.ts @@ -35,6 +35,15 @@ const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("h const quote = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`; const completed = new Set(["saved", "unchanged", "resolved"]); const MAX_COLLECTION_ATTEMPTS = 3; +export const INSTRUCTION_COPY_RETRY_MS = 30_000; +export const INSTRUCTION_COPY_MAX_RETRY_MS = 6 * 60 * 60_000; +const settledStates = new Set(["saved", "unchanged", "resolved", "unavailable", "conflict"]); + +export function instructionCopyRetryAt(waitingSince: Date, now = Date.now()) { + const waited = Math.max(0, now - waitingSince.getTime()); + return new Date(now + Math.min(INSTRUCTION_COPY_MAX_RETRY_MS, Math.max(INSTRUCTION_COPY_RETRY_MS, Math.floor(waited / 2)))); +} + // Only orchestration can register a live target; tools and HTTP callers cannot // supply one. These handles are optional: durable captured bytes survive restart. const liveTargets = new Map(); @@ -100,20 +109,25 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen return row ?? null; } async function tryPatch(row: Copy, values: Partial, requireDue = false, condition?: SQL) { - const signalsCollection = collectionCandidate(row) || collectionCandidate({ ...row, ...values }); - const signalsCleanup = directoryCleanupEntry(row) !== null || directoryCleanupEntry({ ...row, ...values }) !== null; + const next = { ...row, ...values } as Copy; + const signalsCollection = collectionCandidate(row) || collectionCandidate(next); + const signalsCleanup = directoryCleanupEntry(row) !== null || directoryCleanupEntry(next) !== null; const signalsCommit = row.state === "pending_commit" || values.state === "pending_commit"; + const where = and( + scope(row.companyId, row.runId), eq(copies.state, row.state), eq(copies.attempts, row.attempts), eq(copies.baseHash, row.baseHash), eq(copies.localRoot, row.localRoot), + sql`${copies.receipt}->>'retainedByRunId' IS NOT DISTINCT FROM ${typeof row.receipt?.retainedByRunId === "string" ? row.receipt.retainedByRunId : null}`, + requireDue ? or(isNull(copies.nextAttemptAt), lte(copies.nextAttemptAt, new Date())) : undefined, condition, + ); + if (onlyDefers(row, next)) { + return db.transaction(async tx => (await tx.update(copies).set({ ...values, updatedAt: new Date() }).where(where).returning())[0]); + } const write = async (tx: Db) => { await notifyStrandedAgentStatus(tx, { companyId: row.companyId, agentId: row.agentId }); if (signalsCommit) await notifyInstructionCommit(tx, { companyId: row.companyId, runId: row.runId }); if (signalsCleanup) await notifyDirectoryCleanup(tx, { companyId: row.companyId, runId: row.runId }); if (signalsCollection) await notifyInstructionCollection(tx, { companyId: row.companyId, runId: row.runId }); - const [updated] = await tx.update(copies).set({ ...values, updatedAt: new Date() }).where(and( - scope(row.companyId, row.runId), eq(copies.state, row.state), eq(copies.attempts, row.attempts), eq(copies.baseHash, row.baseHash), eq(copies.localRoot, row.localRoot), - sql`${copies.receipt}->>'retainedByRunId' IS NOT DISTINCT FROM ${typeof row.receipt?.retainedByRunId === "string" ? row.receipt.retainedByRunId : null}`, - requireDue ? or(isNull(copies.nextAttemptAt), lte(copies.nextAttemptAt, new Date())) : undefined, condition, - )).returning(); + const [updated] = await tx.update(copies).set({ ...values, updatedAt: new Date() }).where(where).returning(); return updated; }; return db.transaction(tx => write(tx as unknown as Db)); @@ -128,15 +142,12 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen return { type: "agent", companyId: row.companyId, agentId: row.agentId, runId: row.runId, onBehalfOfUserId: row.responsibleUserId }; } const directories = agentDirectoryWorkingCopyService(db, get, patch, options.environmentRuntime); - async function recoverDirectoryCleanup(row: Copy, cleanup: () => Promise) { - // Reserve a later retry before I/O, including lock waits. A blocked owner - // must not occupy every sweep or prevent other copies from being reclaimed. + async function recoverDirectoryCleanup(row: Copy, retryAt: Date, cleanup: () => Promise) { try { - await patch(row, { nextAttemptAt: new Date(Date.now() + 30_000) }); await cleanup(); } catch (error) { - try { await patch(row, { nextAttemptAt: new Date(Date.now() + 30_000) }); } + try { await patch(row, { nextAttemptAt: retryAt }); } catch (retryError) { logger.warn({ err: retryError, runId: row.runId }, "Agent file cleanup retry could not be scheduled"); } @@ -380,6 +391,19 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen || row.state === "preparing" && isAgentDirectoryCopy(row)) || row.state === "unavailable" && !row.processStoppedAt && row.location.startsWith("remote:") && isAgentDirectoryCopy(row)); } + function strandsAgent(row: Copy) { + return !settledStates.has(row.state) || !row.processStoppedAt || row.nextAttemptAt !== null + || Object.hasOwn(row.receipt ?? {}, "baseline") || row.receipt?.cleanupPending === true; + } + function onlyDefers(row: Copy, next: Copy) { + const due = (copy: Copy) => copy.nextAttemptAt?.getTime() ?? 0; + const deferred = (before: boolean, after: boolean) => before === after && (!after || due(next) >= due(row)); + return deferred(collectionCandidate(row), collectionCandidate(next)) + && deferred(directoryCleanupEntry(row) !== null, directoryCleanupEntry(next) !== null) + && deferred(commitEntry(row) !== null, commitEntry(next) !== null) + && (row.state === "pending_commit") === (next.state === "pending_commit") + && strandsAgent(row) === strandsAgent(next); + } function collectionPredicate() { return and(sql`NOT (coalesce(${copies.receipt}, '{}'::jsonb) ? 'retainedByRunId') AND ( (${copies.attempts} < 3 AND (${copies.state} IN ('prepared', 'pending_collection', 'unchanged_turn', 'warm_saved') @@ -388,39 +412,41 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen AND ${copies.location} LIKE 'remote:%' AND ${copies.receipt}->>'schema' = 'paperclip.agent-files.v1'))`, inArray(heartbeatRuns.status, ["succeeded", "failed", "cancelled", "timed_out", "interrupted"])); } - async function collectRecovered(row: Copy, runtimeMode: string | null) { - if (row.state === "unavailable" && isAgentDirectoryCopy(row)) { - await recoverDirectoryCleanup(row, () => directories.recoverUnavailable(row)); - } else if (row.state === "preparing" && isAgentDirectoryCopy(row)) { - - + type StopEvidence = "directory_unavailable" | "directory_preparing" | "local" | "remote" | null; + async function stopEvidence(row: Copy, runtimeMode: string | null): Promise { + if (row.state === "unavailable" && isAgentDirectoryCopy(row)) return "directory_unavailable"; + if (row.state === "preparing" && isAgentDirectoryCopy(row)) return "directory_preparing"; + if (row.location === "local") return row.processStoppedAt || runtimeMode === "native" && + await hasNativeLocalProcessStop(db, row.companyId, row.runId) ? "local" : null; + return await remoteExecutionHasStopped(db, row.companyId, row.runId) ? "remote" : null; + } + function awaitingStop(row: Copy, waitingSince: Date): Partial { + return { ...(row.state === "prepared" ? { state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", + errorMessage: "The provider's stop has not been confirmed. Instruction collection is pending; no save is claimed." } : {}), + nextAttemptAt: instructionCopyRetryAt(waitingSince) }; + } + async function collectRecovered(row: Copy, evidence: Exclude, retryAt: Date): Promise { + if (evidence === "directory_unavailable") { + await recoverDirectoryCleanup(row, retryAt, () => directories.recoverUnavailable(row)); + } else if (evidence === "directory_preparing") { await directories.release(await patch(row, { state: "unavailable", processStoppedAt: new Date(), errorCode: "AGENT_FILES_PREPARE_FAILED", errorMessage: "Agent-file preparation was interrupted. The temporary copy was discarded.", nextAttemptAt: null })); - } else if (row.location === "local" && (row.processStoppedAt || runtimeMode === "native" && - await hasNativeLocalProcessStop(db, row.companyId, row.runId))) { + } else if (evidence === "local") { const result = await collectStopped({ companyId: row.companyId, runId: row.runId }); if (result && isAgentDirectoryCopy(result) && completed.has(result.state)) await directories.release(result); - } else if (row.location !== "local" && await remoteExecutionHasStopped(db, row.companyId, row.runId)) { - if (row.receipt?.warm === true) { - const unavailable = row.receipt?.warm === true - ? await patch(row, { state: "unavailable", errorCode: "AGENT_FILES_FINAL_COLLECTION_UNAVAILABLE", - errorMessage: "The last completed checkpoint remains saved. Files changed afterwards could not be collected after remote termination.", nextAttemptAt: null }) - : await reportUnavailable(row.companyId, row.runId); - if (unavailable && isAgentDirectoryCopy(unavailable)) { + } else if (row.receipt?.warm === true) { + const unavailable = await patch(row, { state: "unavailable", errorCode: "AGENT_FILES_FINAL_COLLECTION_UNAVAILABLE", + errorMessage: "The last completed checkpoint remains saved. Files changed afterwards could not be collected after remote termination.", nextAttemptAt: null }); + if (isAgentDirectoryCopy(unavailable)) { await directories.release(await patch(unavailable, { processStoppedAt: unavailable.processStoppedAt ?? new Date() })); } - } else { - if (isAgentDirectoryCopy(row)) await directories.recoverStoppedRemote(row); - else await reportUnavailable(row.companyId, row.runId); + } else if (isAgentDirectoryCopy(row)) { + const result = await directories.recoverStoppedRemote(row); + if (result && collectionCandidate(result) && !result.processStoppedAt && (result.nextAttemptAt?.getTime() ?? 0) < retryAt.getTime()) { + return patch(result, { nextAttemptAt: retryAt }); } - } else if (row.state === "prepared") { - await patch(row, { state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", - errorMessage: "The provider's stop has not been confirmed. Instruction collection is pending; no save is claimed.", nextAttemptAt: new Date(Date.now() + 30_000) }); - } else if (["warm_saved", "pending_collection", "unchanged_turn"].includes(row.state)) { - - - await patch(row, { nextAttemptAt: new Date(Date.now() + 30_000) }); - } + } else await reportUnavailable(row.companyId, row.runId); + return undefined; } type CollectionEntry = { id: string; companyId: string; dueAt: number }; async function loadCollection(scope: InstructionCollectionScope | undefined, admitted: () => boolean) { @@ -439,7 +465,8 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen throw new Error("Instruction collection reconstruction stopped"); } async function readCollection(entry: CollectionEntry) { - const [current] = await db.select({ copy: copies, runtimeMode: heartbeatRuns.runtimeMode }).from(copies) + const [current] = await db.select({ copy: copies, runtimeMode: heartbeatRuns.runtimeMode, + waitingSince: sql`(extract(epoch from coalesce(${heartbeatRuns.finishedAt}, ${copies.createdAt})) * 1000)::float8`.mapWith(value => new Date(Number(value))) }).from(copies) .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, copies.companyId), eq(heartbeatRuns.id, copies.runId))) .where(and(collectionPredicate(), scope(entry.companyId, entry.id))); return current; @@ -450,14 +477,18 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen const dueAt = current.copy.nextAttemptAt?.getTime() ?? 0; if (dueAt > Date.now()) return { ...entry, dueAt }; if (!admitted()) throw new Error("Instruction collection recovery stopped"); - const claimed = await tryPatch(current.copy, { nextAttemptAt: new Date(Date.now() + 30_000) }, true, + const evidence = await stopEvidence(current.copy, current.runtimeMode); + const retryAt = instructionCopyRetryAt(current.waitingSince); + const claimed = await tryPatch(current.copy, evidence === null ? awaitingStop(current.copy, current.waitingSince) + : { nextAttemptAt: evidence === "directory_unavailable" ? retryAt : new Date(Date.now() + INSTRUCTION_COPY_RETRY_MS) }, true, sql`EXISTS (SELECT 1 FROM ${heartbeatRuns} WHERE ${heartbeatRuns.id} = ${copies.runId} AND ${heartbeatRuns.companyId} = ${copies.companyId} AND ${heartbeatRuns.status} IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted'))`); - if (claimed) await collectRecovered(claimed, current.runtimeMode); - const remaining = await readCollection(entry); + const settled = claimed && evidence !== null ? await collectRecovered(claimed, evidence, retryAt) : claimed; + const remaining = settled === undefined || settled === null ? (await readCollection(entry))?.copy + : collectionCandidate(settled) ? settled : null; if (!remaining) return null; - const next = { ...entry, dueAt: remaining.copy.nextAttemptAt?.getTime() ?? 0 }; + const next = { ...entry, dueAt: remaining.nextAttemptAt?.getTime() ?? 0 }; if (next.dueAt <= Date.now()) throw new Error("Instruction collection remains unresolved without a future retry"); return next; } @@ -522,9 +553,21 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen const current = directoryCleanupEntry(row); if (!row || !current || current.dueAt > Date.now()) return current; if (!admitted()) throw new Error("Directory cleanup recovery stopped"); - const claimed = await tryPatch(row, { nextAttemptAt: new Date(Date.now() + 30_000) }, true); - if (claimed) await directories.release(claimed); - const remaining = directoryCleanupEntry(await get(entry.companyId, entry.id)); + const retryAt = instructionCopyRetryAt(row.processStoppedAt ?? row.updatedAt); + const claimed = await tryPatch(row, { nextAttemptAt: new Date(Date.now() + INSTRUCTION_COPY_RETRY_MS) }, true); + const deferCleanup = async () => { + const latest = await get(entry.companyId, entry.id); + const pending = directoryCleanupEntry(latest); + return claimed && latest && pending && pending.dueAt < retryAt.getTime() ? patch(latest, { nextAttemptAt: retryAt }) : latest; + }; + if (claimed) { + try { await directories.release(claimed); } + catch (error) { + await deferCleanup(); + throw error; + } + } + const remaining = directoryCleanupEntry(await deferCleanup()); if (remaining && remaining.dueAt <= Date.now()) throw new Error("Directory cleanup remains unresolved without a future retry"); return remaining; } From cf09024292136a07c47a65f8d31c928240e6e0d5 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 03:02:25 -0600 Subject: [PATCH 8/8] fix(heartbeat): count an early native hand-off only after its suspend commits (#21572) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A server restart hands each live Runner run to the next server, so the agent keeps working without a retry > - At shutdown start, the outgoing server hands off native runs early, in parallel with the rest of shutdown > - The early hand-off put a run in the "handed off" set before its suspend finished, and the drain counted every run in that set as suspended without waiting > - The early hand-off shares the 20 s pre-drain budget, and one Runner detach can take 20-30 s, so the process could exit with the suspend unfinished > - Then the finalization lease stays live, the next server gets no hand-over signal, and the run waits for lease expiry or the reaper > - This pull request makes the drain wait for each in-flight early hand-off, and fall back to its own hand-off when the early one failed or did not finish > - The benefit is that a run counts as handed over only after its hand-over is committed, so the next server can always reach it at once ## Linked Issues or Issue Description **What happened?** A passing zero-downtime swap test showed a latent race in the shutdown hand-off. `handOffNativeRunsForShutdown` added a run to `nativeRunsHandedOffEarly` before `suspendNativeRunForShutdown` finished. `drainRunningRunsForShutdown` then reported every run in that set as `restartSuspended` without awaiting it. Because the early hand-off shares the 20 s pre-drain budget and a Runner detach can wait 20-30 s, the process can exit before the lease release commits. Also, a timed-out `prepareHotRestartShutdown` could still write the hot-restart snapshot and detach sessions after the fallback drain started. In the same test, swap 1's early hand-off took 2.08 s, and no log showed which phase was slow. **Expected behavior** A run counts as handed over only after its suspend commits. If the early suspend fails or does not finish, the drain hands the run off itself. A timed-out hot-restart preparation does no further work after the drain starts. The hand-off logs its phase timings. **Steps to reproduce** 1. Start a native Runner run on a remote sandbox. 2. Send SIGTERM while the Runner detach is slow (or fails). 3. The drain reports the run as restart-suspended while its suspend is still pending, and the process can exit before the lease release. **Paperclip version or commit** `master` at bbed32450c. **Deployment mode** Hosted, zero-downtime release swap. ## What Changed - `nativeRunsHandedOffEarly` now holds each run's in-flight suspend promise, not only its id. - The shutdown drain awaits that promise (bounded at 30 s). If it fails, returns false or does not finish, the drain runs its own suspend, as it does for a run without an early hand-off. - `runBoundedShutdownStep` and the pre-drain budget pass an `AbortSignal` to each step and abort it on timeout. - `prepareHotRestartShutdown` takes that signal and stops before the snapshot write, the run events, and the session detach when the step timed out. - `handOffNativeRunsForShutdown` logs one structured line, "native run shutdown hand-off phase timings": intent read, controller identity, select, max per-run detach, max per-run transaction, and total. ## Verification - Red, then green (each failed against `master` source and passes with the fix), all through the public shutdown functions in `server/src/services/heartbeat/recovery.test.ts`: - `does not count an early hand-off as suspended while its detach is still pending at the shutdown drain` - `hands off a run at the shutdown drain when its pending early hand-off fails` - `writes no hot-restart snapshot and detaches nothing after a timed-out preparation hands over to the drain` - New test in `server/src/shutdown.test.ts`: `aborts the signal of a step that outlives its bound, and only that step`. - `pnpm vitest run src/shutdown.test.ts src/services/heartbeat/recovery.test.ts src/__tests__/heartbeat-native-early-hand-off.test.ts` passes (145 tests). - `tsc --noEmit` for `server` passes. `pnpm verify` passes for the selected tests. ## Risks - When an early hand-off does not finish within 30 s, the drain starts a second suspend. The second detach joins the first, because the session memoizes its restart detach. The run can then get two "suspended" run events. That is preferred to reporting a hand-over that did not happen. - The drain can now wait up to 30 s for a slow early hand-off before the process exits. Before, it exited without the hand-over. - The abort signal only stops work between steps of the preparation. A snapshot write that already started still completes. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use (shell, file edits, test runs). ## 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 (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/src/index.ts | 6 +- .../src/services/heartbeat/recovery.test.ts | 119 ++++++++++++++++++ server/src/services/heartbeat/recovery.ts | 70 +++++++++-- server/src/shutdown.test.ts | 15 +++ server/src/shutdown.ts | 8 +- 5 files changed, 200 insertions(+), 18 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index ad8fde47768..340b576632c 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1303,7 +1303,7 @@ async function startServerWithDatabaseTeardown( ) => Promise) | null = null; let drainHeartbeatExecutionFinalizers: (() => Promise) | null = null; let handOffNativeRunsForShutdown: ((signal: "SIGINT" | "SIGTERM") => Promise) | null = null; - let prepareHotRestartShutdown: ((signal: "SIGINT" | "SIGTERM") => Promise<{ + let prepareHotRestartShutdown: ((signal: "SIGINT" | "SIGTERM", now?: Date, abort?: AbortSignal) => Promise<{ skipDrain: boolean; drainRunIds?: string[]; }>) | null = null; @@ -2281,8 +2281,8 @@ async function startServerWithDatabaseTeardown( signal, prepareHotRestartShutdown: prepareHotRestart ? async (preparationSignal) => { - const preparation = await preDrain.run("hot_restart_prepare", () => - prepareHotRestart(preparationSignal)); + const preparation = await preDrain.run("hot_restart_prepare", abort => + prepareHotRestart(preparationSignal, undefined, abort)); if (preparation.outcome === "completed") return preparation.value; if (preparation.outcome === "failed") throw preparation.error; throw new Error("hot-restart shutdown preparation timed out"); diff --git a/server/src/services/heartbeat/recovery.test.ts b/server/src/services/heartbeat/recovery.test.ts index f1336e9c1ad..dc7683b7dc9 100644 --- a/server/src/services/heartbeat/recovery.test.ts +++ b/server/src/services/heartbeat/recovery.test.ts @@ -31,6 +31,7 @@ import { persistHeartbeatRunProcessMetadata } from "./run-lifecycle.js"; import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; import { hasNativeLocalProcessStop, PROCESS_START_REQUESTED, releaseSettledNativeRunProcess } from "../native-local-process-stop.js"; import { legacyControllerBootId } from "../legacy-controller-lease.js"; +import { runBoundedShutdownStep } from "../../shutdown.js"; type Run = typeof heartbeatRuns.$inferSelect; @@ -44,10 +45,12 @@ const native = vi.hoisted(() => ({ })); const hotRestart = vi.hoisted(() => ({ read: vi.fn<() => Promise>(async () => null), + write: vi.fn(async () => undefined), })); vi.mock("../hot-restart.js", async (importOriginal) => ({ ...await importOriginal(), readHotRestartIntent: hotRestart.read, + writeHotRestartShutdownSnapshot: hotRestart.write, })); vi.mock("../native-runtime/index.js", async (importOriginal) => ({ ...await importOriginal(), @@ -1500,6 +1503,122 @@ describePostgres("heartbeat recovery module ownership", () => { } }); + async function seedOwnedNativeRun() { + const run = await seedRun(); + const identity = await currentNativeControllerIdentity(); + await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, run.agentId)); + const [nativeRun] = await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: run.issueId, nativeSessionId: randomUUID() }) + .where(eq(heartbeatRuns.id, run.id)).returning(); + await db.insert(nativeRunFinalizations).values({ runId: run.id, companyId: run.companyId, issueId: run.issueId!, + phase: "observed", controllerBootId: identity.bootId, leaseOwner: "departing-server", leaseExpiresAt: new Date(Date.now() + 60_000) }); + return nativeRun; + } + async function removeNativeRun(runId: string) { + await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + } + const finalization = async (runId: string) => + (await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0]; + const drainHasStarted = () => new Promise(resolve => setTimeout(resolve, 250)); + + it("does not count an early hand-off as suspended while its detach is still pending at the shutdown drain", async () => { + const run = await seedOwnedNativeRun(), recovery = createHeartbeatRecovery(db, callbacks(db)); + let finishDetach!: () => void; + native.detach.mockImplementationOnce(() => new Promise(resolve => { finishDetach = () => resolve(0); })); + try { + const early = recovery.handOffNativeRunsForShutdown("SIGTERM"); + await vi.waitFor(() => expect(native.detach).toHaveBeenCalledTimes(1)); + let drained = false; + const drain = recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id]).finally(() => { drained = true; }); + await drainHasStarted(); + expect(drained).toBe(false); + expect((await finalization(run.id)).recoveryState).toBeNull(); + finishDetach(); + expect(await early).toEqual([run.id]); + expect((await drain).restartSuspendedRunIds).toEqual([run.id]); + expect(native.detach).toHaveBeenCalledTimes(1); + expect(await finalization(run.id)).toMatchObject({ recoveryState: "awaiting_runner_reattach" }); + } finally { + finishDetach?.(); + await removeNativeRun(run.id); + } + }); + + it("hands off a run at the shutdown drain when its pending early hand-off fails", async () => { + const run = await seedOwnedNativeRun(), recovery = createHeartbeatRecovery(db, callbacks(db)); + let failDetach!: (error: Error) => void; + native.detach.mockImplementationOnce(() => new Promise((_resolve, reject) => { failDetach = reject; })); + try { + const early = recovery.handOffNativeRunsForShutdown("SIGTERM"); + await vi.waitFor(() => expect(native.detach).toHaveBeenCalledTimes(1)); + const drain = recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id]); + await drainHasStarted(); + failDetach(new Error("runner detach failed")); + expect(await early).toEqual([]); + expect((await drain).restartSuspendedRunIds).toEqual([run.id]); + expect(native.detach).toHaveBeenCalledTimes(2); + expect(await finalization(run.id)).toMatchObject({ recoveryState: "awaiting_runner_reattach" }); + } finally { + await removeNativeRun(run.id); + } + }); + + it("writes no hot-restart snapshot and detaches nothing after a timed-out preparation hands over to the drain", async () => { + const run = await seedOwnedNativeRun(), recovery = createHeartbeatRecovery(db, callbacks(db)); + hotRestart.read.mockResolvedValue({ version: 1, requestedAt: new Date().toISOString(), previousServerPid: process.pid, + previousServerVersion: null, drainRequired: false, requestedByRunId: null, preflightActiveRunIds: [] }); + let finishIdleClose!: () => void; + native.closeIdle.mockImplementationOnce(() => new Promise(resolve => { finishIdleClose = () => resolve({ closed: 0, failed: 0 }); })); + let preparation: ReturnType | undefined; + try { + const step = await runBoundedShutdownStep({ step: "hot_restart_prepare", signal: "SIGTERM", timeoutMs: 50, + log: { info: vi.fn(), error: vi.fn() }, + run: abort => (preparation = recovery.prepareHotRestartShutdown("SIGTERM", new Date(), abort)) }); + expect(step.outcome).toBe("timed_out"); + expect((await recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id])).restartSuspendedRunIds).toEqual([run.id]); + expect(native.detach).toHaveBeenCalledTimes(1); + finishIdleClose(); + await expect(preparation).rejects.toThrow("timed out"); + expect(hotRestart.write).not.toHaveBeenCalled(); + expect(native.detach).toHaveBeenCalledTimes(1); + } finally { + finishIdleClose?.(); + await preparation?.catch(() => undefined); + await removeNativeRun(run.id); + } + }); + + it("records no more hot-restart run events after the preparation times out during its first event", async () => { + const runs = [await seedOwnedNativeRun(), await seedOwnedNativeRun(), await seedOwnedNativeRun()]; + const deps = callbacks(db), recovery = createHeartbeatRecovery(db, deps); + hotRestart.read.mockResolvedValue({ version: 1, requestedAt: new Date().toISOString(), previousServerPid: process.pid, + previousServerVersion: null, drainRequired: false, requestedByRunId: null, preflightActiveRunIds: [] }); + let finishFirstEvent!: () => void; + const firstEvent = new Promise(resolve => { finishFirstEvent = () => resolve(undefined); }); + deps.appendRunEvent.mockImplementationOnce(() => firstEvent); + const hotRestartEvents = () => deps.appendRunEvent.mock.calls + .filter(([, event]) => event.message?.startsWith("Hot restart requested") === true).length; + let preparation: ReturnType | undefined; + try { + const step = await runBoundedShutdownStep({ step: "hot_restart_prepare", signal: "SIGTERM", timeoutMs: 2_000, + log: { info: vi.fn(), error: vi.fn() }, + run: abort => (preparation = recovery.prepareHotRestartShutdown("SIGTERM", new Date(), abort)) }); + expect(step.outcome).toBe("timed_out"); + expect(hotRestartEvents()).toBe(1); + const runIds = runs.map(run => run.id); + expect((await recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), runIds)).restartSuspendedRunIds.sort()) + .toEqual([...runIds].sort()); + finishFirstEvent(); + await expect(preparation).rejects.toThrow("timed out"); + expect(hotRestartEvents()).toBe(1); + expect(native.detach).toHaveBeenCalledTimes(runs.length); + } finally { + finishFirstEvent?.(); + await preparation?.catch(() => undefined); + for (const run of runs) await removeNativeRun(run.id); + } + }); + it("does not dispatch recovery for a run still preparing in this heartbeat process", async () => { const run = await seedRun(); await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, run.agentId)); diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index b2a866808bd..210ab21ff02 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -213,6 +213,8 @@ export const DETACHED_PROCESS_ERROR_CODE = "process_detached"; const NATIVE_OWNERSHIP_UNVERIFIED_MESSAGE = "Native execution ownership could not be verified; automatic recovery is blocked"; +const EARLY_NATIVE_HAND_OFF_DRAIN_WAIT_MS = 30_000; + // The reaper sweeps at most this many pending_cleanup leases per tick. const PENDING_CLEANUP_SWEEP_PAGE_SIZE = 20; // An environment delete tries each of that environment's cleanups once, from @@ -490,12 +492,14 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD async function prepareHotRestartShutdown( signal: "SIGINT" | "SIGTERM", now = new Date(), + abort?: AbortSignal, ) { enterShutdown(); const idleSessions = await closeIdleWarmNativeSessionsForRestart(); if (idleSessions.failed > 0) { logger.warn({ idleSessions }, "idle native session cleanup failed before controller shutdown"); } + abort?.throwIfAborted(); let intent: Awaited>; try { intent = await readHotRestartIntent(); @@ -544,6 +548,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD .from(heartbeatRuns) .innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)) .where(eq(heartbeatRuns.status, "running")); + abort?.throwIfAborted(); const snapshotRuns = activeRuns.map(toHotRestartIntentRun); const intentWithVersion = { ...intent, @@ -589,8 +594,8 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD activeRuns: snapshotRuns, capturedAt: now, }); - for (const { run } of activeRuns) { + abort?.throwIfAborted(); await appendRunEvent(run, { eventType: "lifecycle", stream: "system", @@ -614,6 +619,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD isNativeSessionId(run.nativeSessionId), ) .map(({ run }) => run.id); + abort?.throwIfAborted(); for (const runId of nativeRunIds) markHandedOffByThisController(runId); const detachedNativeSessions = await detachNativeSessionsForRestart(nativeRunIds); @@ -1158,10 +1164,27 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD } } - const nativeRunsHandedOffEarly = new Set(); + const nativeRunsHandedOffEarly = new Map>(); + + async function settleEarlyNativeHandOff(runId: string, handOff: Promise) { + let timer: ReturnType | undefined; + try { + const outcome = await Promise.race([handOff, new Promise<"unfinished">(resolve => { + timer = setTimeout(() => resolve("unfinished"), EARLY_NATIVE_HAND_OFF_DRAIN_WAIT_MS); + timer.unref?.(); + })]); + if (outcome === "unfinished") { + logger.warn({ runId, waitedMs: EARLY_NATIVE_HAND_OFF_DRAIN_WAIT_MS }, + "early native run hand-off is unfinished at the shutdown drain; the drain hands it off"); + } + return outcome === true; + } finally { + clearTimeout(timer); + } + } async function suspendNativeRunForShutdown(run: typeof heartbeatRuns.$inferSelect, signal: "SIGINT" | "SIGTERM", - now: Date, controllerBootId: string) { + now: Date, controllerBootId: string, timing?: { detachMs: number; transactionMs: number }) { const [owner] = await db.select({ bootId: nativeRunFinalizations.controllerBootId }) .from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id)); if (owner?.bootId && owner.bootId !== controllerBootId) return false; @@ -1170,7 +1193,9 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD // finalizer interrupt/suspend Claude while the next server is adopting // the same turn. markHandedOffByThisController(run.id); + const detachStartedAt = performance.now(); await detachNativeSessionsForRestart([run.id]); + if (timing) timing.detachMs = Math.round(performance.now() - detachStartedAt); const recoveryHistoryEntry = JSON.stringify({ at: now.toISOString(), restartKind: "graceful", @@ -1183,6 +1208,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD // execution lease must still be released: the detached executor will // not finalize, and the next controller's reconciler skips leased rows. // A finalizer lease belongs to finalization already in progress here. + const transactionStartedAt = performance.now(); const released = await db.transaction(async tx => { await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId: run.id }); await notifyReattachHandOver(tx, run.id); @@ -1217,6 +1243,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD ) .returning({ resultId: nativeRunFinalizations.resultId, leaseOwner: nativeRunFinalizations.leaseOwner }); }); + if (timing) timing.transactionMs = Math.round(performance.now() - transactionStartedAt); const resultAccepted = Boolean(released[0]?.resultId); const finalizerHeld = resultAccepted && Boolean(released[0]?.leaseOwner?.startsWith("native-finalizer:")); await appendRunEvent(run, { @@ -1243,25 +1270,40 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD } async function handOffNativeRunsForShutdown(signal: "SIGINT" | "SIGTERM", now = new Date()) { + const startedAt = performance.now(); + const elapsed = (from: number) => Math.round(performance.now() - from); const intent = await readHotRestartIntent().catch(() => null); + const intentReadMs = elapsed(startedAt); if (intent && !intent.drainRequired && shouldHonorHotRestartIntentForProcess(intent)) return []; + const identityStartedAt = performance.now(); const nativeController = await currentNativeControllerIdentity(); + const controllerIdentityMs = elapsed(identityStartedAt); + const selectStartedAt = performance.now(); const liveRuns = await db.select({ run: heartbeatRuns }).from(heartbeatRuns) .innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)) .where(and(eq(heartbeatRuns.status, "running"), eq(heartbeatRuns.runtimeMode, "native"), eq(agents.adapterType, "paperclip_runner"))); + const selectMs = elapsed(selectStartedAt); const handedOff: string[] = []; + let maxDetachMs = 0, maxTransactionMs = 0, failed = 0; await Promise.allSettled(liveRuns.map(async ({ run }) => { if (isNativeRunnerOwnershipHeld(run) || nativeRunsHandedOffEarly.has(run.id)) return; - nativeRunsHandedOffEarly.add(run.id); - try { - if (await suspendNativeRunForShutdown(run, signal, now, nativeController.bootId)) handedOff.push(run.id); - else nativeRunsHandedOffEarly.delete(run.id); - } catch (error) { - nativeRunsHandedOffEarly.delete(run.id); + const timing = { detachMs: 0, transactionMs: 0 }; + const handOff = suspendNativeRunForShutdown(run, signal, now, nativeController.bootId, timing).catch(error => { + failed += 1; logger.warn({ err: error, runId: run.id }, "early native run hand-off failed; the shutdown drain retries it"); - } + return false; + }); + nativeRunsHandedOffEarly.set(run.id, handOff); + const suspended = await handOff; + maxDetachMs = Math.max(maxDetachMs, timing.detachMs); + maxTransactionMs = Math.max(maxTransactionMs, timing.transactionMs); + if (suspended) handedOff.push(run.id); + else if (nativeRunsHandedOffEarly.get(run.id) === handOff) nativeRunsHandedOffEarly.delete(run.id); })); + logger.info({ signal, liveRuns: liveRuns.length, handedOff: handedOff.length, failed, intentReadMs, + controllerIdentityMs, selectMs, maxDetachMs, maxTransactionMs, totalMs: elapsed(startedAt) }, + "native run shutdown hand-off phase timings"); return handedOff; } @@ -1311,8 +1353,12 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD run.runtimeMode === "native" && agent.adapterType === "paperclip_runner" ) { - if (nativeRunsHandedOffEarly.has(run.id) - || await suspendNativeRunForShutdown(run, signal, now, nativeController.bootId)) restartSuspendedRunIds.push(run.id); + const earlyHandOff = nativeRunsHandedOffEarly.get(run.id); + if (earlyHandOff && await settleEarlyNativeHandOff(run.id, earlyHandOff)) { + restartSuspendedRunIds.push(run.id); + return; + } + if (await suspendNativeRunForShutdown(run, signal, now, nativeController.bootId)) restartSuspendedRunIds.push(run.id); return; } if (agent.adapterType === "paperclip_runner" && run.runtimeMode === "legacy" && run.scopeKind === "issue" && diff --git a/server/src/shutdown.test.ts b/server/src/shutdown.test.ts index 728896f0535..43e2147c77a 100644 --- a/server/src/shutdown.test.ts +++ b/server/src/shutdown.test.ts @@ -410,6 +410,21 @@ describe("runBoundedShutdownStep", () => { } }); + it("aborts the signal of a step that outlives its bound, and only that step", async () => { + vi.useFakeTimers(); + try { + const signals: AbortSignal[] = []; + const budget = createPreDrainShutdownBudget({ signal: "SIGTERM", budgetMs: 250, log: stubLogger() }); + await budget.run("delivery_work_stop", async abort => { signals.push(abort); }); + const pending = budget.run("hot_restart_prepare", abort => { signals.push(abort); return new Promise(() => undefined); }); + await vi.advanceTimersByTimeAsync(250); + await expect(pending).resolves.toMatchObject({ outcome: "timed_out" }); + expect(signals.map(signal => signal.aborted)).toEqual([false, true]); + } finally { + vi.useRealTimers(); + } + }); + it("logs a step that rejects and does not reject the shutdown", async () => { const log = stubLogger(); const error = new Error("skill sync stop failed"); diff --git a/server/src/shutdown.ts b/server/src/shutdown.ts index 894a05f2e35..63f7f1e2905 100644 --- a/server/src/shutdown.ts +++ b/server/src/shutdown.ts @@ -23,18 +23,19 @@ export async function runBoundedShutdownStep(input: { step: string; signal: "SIGINT" | "SIGTERM"; timeoutMs: number; - run: () => Promise; + run: (abort: AbortSignal) => Promise; log: ShutdownLogger; now?: () => number; }): Promise> { const now = input.now ?? Date.now; const startedAt = now(); const timeoutMs = Math.max(0, input.timeoutMs); + const abort = new AbortController(); let timer: NodeJS.Timeout | null = null; try { const result = await Promise.race([ Promise.resolve() - .then(input.run) + .then(() => input.run(abort.signal)) .then( (value) => ({ outcome: "completed" as const, value }), (error: unknown) => ({ outcome: "failed" as const, error }), @@ -54,6 +55,7 @@ export async function runBoundedShutdownStep(input: { input.log.error({ ...fields, err: result.error }, "shutdown step failed; continuing shutdown"); return { outcome: "failed", error: result.error, durationMs }; } + abort.abort(new Error(`shutdown step ${input.step} timed out`)); input.log.info(fields, "shutdown step timed out; continuing shutdown without it"); return { outcome: "timed_out", durationMs }; } finally { @@ -70,7 +72,7 @@ export function createPreDrainShutdownBudget(input: { const now = input.now ?? Date.now; const deadline = now() + (input.budgetMs ?? PRE_DRAIN_SHUTDOWN_BUDGET_MS); return { - run(step: string, run: () => Promise) { + run(step: string, run: (abort: AbortSignal) => Promise) { return runBoundedShutdownStep({ step, signal: input.signal,