From cec8c2b3f46b9b62da6614e50ac3454abdb7e8b9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 10:47:34 -0600 Subject: [PATCH] perf(recovery): name the run or task in run writers' recovery hints instead of the company (#21765) 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 on one Node main thread. The `stranded-assignments` and `assigned-work-invariant` queues check assigned tasks that have no live run. One stranded check costs about 19 database statements. > - #21552 scoped run hints to the run's task graph. #21729 made the 5-minute backstop re-check only changed tasks. A hint with only a company id still makes the queue re-check every open task of the company, 25 per pass. > - Under load on staging (7 native runs), the stranded check ran about 6.7 times per second, and its statement bundle was more than a third of all statements. An activity fixture shows the cause: ordinary run writers send a company-only hint once per run, and one company hint costs about 850 checks. At 1,000 agents this work never stops. > - This pull request makes those writers name the run (or the task) they already know. A run that has no task now resolves to no tasks instead of the whole company. The changed-tasks backstop no longer counts an agent's own run heartbeat as a change to every task of that agent. > - The benefit: with 7 runs a minute plus one taskless run, stranded checks drop from 18.4 to 1.0 per second and stranded-check statements from 344 to 7 per second. Real company-wide changes (pause lifted, budget, company status, tree holds) keep the full company pass. ## Linked Issues or Issue Description Refs #21729, #21552, #21676, #21724 **What existing behavior does this improve?** The issue recovery task queues (`stranded-assignments`, `assigned-work-invariant`, `resolved-dependencies`, `stale-issue-locks`) and the writers that wake them. **Subsystem affected** Server: issue recovery background work and the run lifecycle writers that publish recovery hints. **Current behavior** Many run lifecycle writers know the run but publish a company-only hint, for example `notifyExecutionRunWork(tx, { companyId })` in the native finalizer and projection, `settleNativeTerminalWake`, the claimed-wake settlement, and an environment lease release of a run without a task. A queued run without a task publishes a company hint. A graph hint for a run without a task resolves to "whole company". A comment sends a company hint to `assigned-work-invariant` and `resolved-dependencies`. Each of these re-checks all open tasks of the company. Also, the changed-tasks backstop treats any change to the assignee agent's row as a change to all of that agent's tasks, and every run start and finish writes that row. **Proposed behavior** A writer that knows the run sends the run's graph hint. A writer that knows the task sends the task hint. A run without a task affects no task queue entry. An agent row change that is only the agent's own run heartbeat does not mark its other tasks changed. Company-wide facts keep the company hint. **Reason and benefit** The work is now proportional to activity, not to (activity x history). See Verification. ## What Changed - `server/src/services/issue-recovery-notifications.ts`: - `notifyIssueRecovery` with a task sends the task hint to all four task queues (before: only to `stranded-assignments` and `stale-issue-locks`; `assigned-work-invariant` and `resolved-dependencies` got the company hint). Only comments (`issue-comment-writes.ts`) call it with a task. - `resolveIssueGraph` returns `[]` when a run-only graph has no task. A missing task seed still returns `null` (whole company). - `server/src/services/recovery/work.ts`: a load for an empty graph returns no rows. The `assigned-work-invariant` queue emits the same `check` debug event as `stranded-assignments` (with `PAPERCLIP_DEBUG_WORK_SIGNALS=assigned-work-invariant`), with the load reason. - `server/src/services/recovery/changed-tasks.ts`: the assignee-agent part of the changed-tasks condition skips an agent whose last write was its run heartbeat (`last_heartbeat_at = updated_at`). A resume, pause or configuration write (no heartbeat stamp) still counts. - `server/src/services/heartbeat/queue.ts`: a queued run without a task gets its id before the insert and publishes a run hint, not a company hint. The daily-cap comment release publishes the run's graph hint. - `server/src/services/environments.ts`, `work-intent-outbox.ts`, `chat-inbound-wake-notice-notifications.ts`: a lease release passes its run id. `promoteDeferredWorkIntents` scopes `lock_released` with only a run to that run's graph. `notifyChatInboundWakeNotices` accepts an optional `runId` for its settlement hint. - Native and recovery run writers now pass the run id they already have to `notifyExecutionRunWork`, `writeExecutionControl` or `notifyExternalConversationSettlement`: `native-run-finalizer.ts` (3), `native-run-projection.ts` (2), `native-session-executor.ts` (3), `wake-request-claimed-settlement.ts`, `native-superseded-retry.ts`, `native-safe-replacement.ts`, `native-restart-recovery.ts` (2), `native-failed-workspace-recovery.ts`, `native-recovery-preparation-failure.ts`, `execution-control-reconciliation.ts`, `execution-recovery-resolution.ts` (2). These are the native equivalents of the legacy run paths in `heartbeat/queue.ts`, which already pass the run id. - Tests: - `server/src/__tests__/issue-recovery-activity-hints.test.ts` (new): staging-shaped company (780 in-review tasks with succeeded native runs, 40 in progress, 30 to-do, 50 agents) on embedded PostgreSQL, the real recovery, dispatch and retry-cancellation workers, a fake clock, and real process-adapter runs. Each run is woken by a user comment through `heartbeat.wakeup`, starts, calls back to post an agent comment and move the task to `in_review`, and finishes. One (or five) taskless runs a minute run beside them. It counts checks by queue and reason, task-queue signals by caller, and statements by owner. It asserts the workload (runs started and succeeded, agent comments, run events, zero agent write failures, at most 10% failed runs), then no company check and no company-only task-queue signal. In CI it runs the 7-runs-a-minute workload for 4 minutes (about 1 minute of real time). With `RECOVERY_ACTIVITY_REPORT=` it runs both workloads at full length, attributes statements by stack, and writes the numbers below to that file. - `server/src/__tests__/issue-recovery-deadlines.test.ts`: pickup tests for each narrowed writer (see Verification). ### Publishers of company-only (or `*`) hints to the recovery task queues "Per" is how often the writer fires on a busy instance. "Known" says whether the run or task is known at the call site. Narrowed in this pull request: | Call site | Event | Per | Known | Now | | --- | --- | --- | --- | --- | | `heartbeat/queue.ts:5396` `enqueueWakeup` | queue a run without a task (timer, manual, chat without a task) | each taskless run | run (id generated) | run graph (no tasks) | | `environments.ts:1780` `releaseLease` -> `notifyChatInboundWakeNotices` | environment lease released | each run without a task | run | run graph | | `environments.ts:1792` `releaseLease` -> `promoteDeferredWorkIntents(lock_released)` | lease released | each run without a task | run | run graph | | `environments.ts:1934` `releaseLeasesForRun` | leases of a run released | each run without a task | run | run graph | | `issue-comment-writes.ts:12` (`assigned-work-invariant`, `resolved-dependencies` only) | comment | each comment | task | task | | `native-runtime/native-run-projection.ts:54` `settleNativeTerminalWake` | native run's wake claim settled | each native run finish | run | run graph | | `native-runtime/native-run-projection.ts:177` | native run status projected | each native run finish | run | run graph | | `native-runtime/native-run-finalizer.ts:408`, `:629`, `:2080` | native finalization terminal / failure / projection | each native run finish | run | run graph | | `native-runtime/native-session-executor.ts:13018`, `:13085`, `:13284` | native execution control deadline, cancelled retry, pre-result settlement | each native run end | run | run graph | | `recovery/wake-request-claimed-settlement.ts:67` | claimed wake settled after the run | each run whose claim is reconciled | run | run graph | | `heartbeat/queue.ts:590` | daily-cap comment key release | each run cancelled at the daily cap | run | run graph | | `native-runtime/native-superseded-retry.ts:42`, `native-safe-replacement.ts:613`, `native-restart-recovery.ts:1033`, `:1935`, `native-failed-workspace-recovery.ts:164`, `native-recovery-preparation-failure.ts:30`, `execution-control-reconciliation.ts:270`, `execution-recovery-resolution.ts:830`, `:965` | native recovery terminal writes | each recovered run | run | run graph | | `resolveIssueGraph` for any run-only hint of a run without a task (for example `setWakeupStatus`, `run-lifecycle.ts:1570`) | run lifecycle | each taskless run event | run | no tasks | Left with the company hint (company-wide fact, or the graph is not known): | Call site | Event | Per | Why kept | | --- | --- | --- | --- | | `budgets.ts:371`, `:386`, `:429`, `:437`, `:454` | budget policy changed, scope paused or resumed | operator or budget event | eligibility of every task can change | | `work-intent-outbox.ts:79` with `pause_lifted`, `tree_hold_released`, `scheduling_resumed`, `reconciler_backstop`, and `accounting_settled` with an active hard stop | hold release | operator event; `accounting_settled` once per run only with a hard-stop policy | can admit any task; guarded by "keeps the company pass for hold releases that can admit any task" | | `companies.ts:77`, `:350`, `:353`, `:361`, `:512`, `:522` | company created, paused, resumed, archived | operator | company-wide | | `agent-lifecycle.ts:65`, `:72`, `agent-lifecycle-driver.ts:29`, `agent-configuration.ts:130`, `:159`, `agent-deletion.ts:61` | agent paused, resumed, configured, deleted | operator | can change many tasks, and other agents' review paths | | `access.ts:570`, `:752`, `:912`, `:926`, `:960`, `:975`, `:1175`, `board-claim.ts:129`, `:142`, `middleware/auth.ts:706` | membership and authority changes | operator, first sign-in | company authority | | `chat-channels/endpoints.ts:461`, `identity-links.ts:323`, `resource-reconciliation.ts:290`, `slack/setup-services.ts:50`, `chat-github-management.ts:182`, `:352`, `chat-work-notifications.ts:50` | chat authority changes | operator | company authority | | `instance-settings.ts:666`, `:669`, `:680` (`*`) | instance setting changed | operator | instance-wide | | `issue-tree-control.ts:809`, `:889`, `:1236`, `:1339` | tree hold created or released | operator | many tasks | | `company-deletion.ts:83`, `company-portability.ts:6560` | company delete, import | rare | many tasks | | `issues.ts:8015` (blockers replaced), `:11165` (task created), `:12685`, `:12699` (task deleted), `:12991`, `:14618` | task graph changes | per task create or blocker edit | graph moves; #21552 kept these | | `documents.ts:615`, `:673`, `:757`, `:808`, `:860` | document delete and restore | rare | #21552 kept these | | `task-watchdogs.ts:854`, `:1841` | watchdog changes | rare | #21552 kept these | | `system-recovery.ts:17`, `:70`, `task-retry.ts:294`, `workspace-recovery-capture-policy.ts:59`, `workspace-recovery-stop-proof.ts:122` | system and workspace recovery | per recovery | not shown to stay in one graph | | `agent-conversations.ts:607`, `chat-channels/telegram/attachment-failure.ts:83`, `native-runtime/chat-attachment-reuse.ts:1754`, `native-runner-file-handoff.ts:1317` | conversation and attachment paths | per failure | not shown to stay in one graph | | `wake-queue/adapters/postgres.ts:376`, `:410`, `:555`, `:1169`, `routes/issues.ts:14552`, `issues.ts:12070`, `:12171`, `heartbeat/run-control.ts:1128`, `:1770`, `projects.ts:100`, `:1051`, `environments.ts:1617` (`notifyChatInboundWakeNotices` without a task) | saved notice and wake changes | per manual wake or project change | company admission state; not reached by run activity in the fixture | | `heartbeat/run-state.ts:1746`, `native-harness-backup-expiration.ts:356`, `:526`, `explicit-native-continuation.ts:705` | session goal clear, backup expiry, explicit continuation | rare | no run id at the call site | | `fast-responses.ts:201`, `:559`, `:672`, `:1053`, `chat-github-response-comments.ts:62`, `:229`, `:440`, `chat-github-reviews.ts:1063` (`notifyChatResponseAvailability` with a delivery only) | chat response availability | per chat response | no task at the call site; not measured here (chat paths are not in the fixture) | Per-run-event path: appending run events, saving native checkpoints, renewing leases and streaming deltas publish no recovery task-queue hint. `heartbeat-run-events.ts` reaches only live-run recovery queues (`native.process_*`, `turn.*` events), chat progress, response presentation, and `notifyNativeStatusReassessment` for control-plane evidence events only. Checkpoints and lease renewals reach `notifyLiveRunRecovery`, which does not include the task queues. A run's start and finish publish its graph hint from several writers (about 20 task-queue signals per legacy run in the fixture, for example `notifyChatRunMilestones` in `run-identity.ts` activation, `claimQueuedRun`, `run-completion.ts`, `setWakeupStatus`). They coalesce into about 3 checks of the run's own task per run. That is not one hint, but it is bounded by the run's graph. This pull request does not change it. ## Verification - Activity fixture (`issue-recovery-activity-hints.test.ts`), checks per second by queue and reason, and statements per second. Each workload minute is exactly 60 s of fake-clock time, and the rates use the elapsed fake-clock time. "Before" is this branch's test against the `origin/master` service files. Both versions did the same work (7 runs/min: 150 runs started, 143 to 145 succeeded, 133 to 135 agent comments, about 1,280 run events; 50 runs/min: 629 to 630 started, 620 to 622 succeeded, about 590 agent comments, about 5,550 run events). The test now asserts this workload and zero agent write failures before it accepts the counts. | | master | this branch | | --- | --- | --- | | 7 runs/min + 1 taskless run/min (600 s), stranded checks/s | 18.30 company + 0.07 hint | 0.91 hint + 0.06 backstop, 0 company | | 7 runs/min, statements/s in stranded checks | 343.9 | 7.2 | | 7 runs/min, all statements/s | 577.5 | 220.4 | | 7 runs/min, company-only task-queue signals | 710 | 0 | | 50 runs/min + 5 taskless runs/min (360 s), stranded checks/s | 16.86 company + 0.31 hint | 1.05 hint, 0 company | | 50 runs/min, statements/s in stranded checks | 314.0 | 7.4 | | 50 runs/min, all statements/s | 1,717.6 | 1,387.5 | | 50 runs/min, company-only task-queue signals | 2,864 | 0 | "Statements in stranded checks" counts statements whose stack includes `reconcileStrandedAssignedIssues`. The other statements are the runs themselves. Recovery load queries (graph lookups and hint loads) are 12.5 to 17.2/s at 7 runs and 69 to 72/s at 50 runs in both versions. `stale-issue-locks` saved deadlines check about 1 to 1.6 tasks/s in both versions. - Without the taskless runs, master already showed the backstop degrade under activity: with 7 runs a minute, 2.46 backstop checks/s, because every run writes its agent's row and marks all of that agent's tasks changed. With this branch: 0.27/s. - New tests in `issue-recovery-deadlines.test.ts`, red on `origin/master` service files and green here: - "re-checks a run's own tasks for its settlement, lease and dispatch writers, and nothing for a run without a task": for `notifyRunDispatch`, `notifyExecutionRunWork`, `notifyExternalConversationSettlement`, `notifyChatInboundWakeNotices` and `promoteDeferredWorkIntents(lock_released)` with a run id, the run's graph (task, parent, dependent) is checked within one pass and none of 300 backlog tasks is. For a run without a task, no task is checked. A comment checks only its task in `stranded-assignments` and `assigned-work-invariant`. - "counts an agent's own run heartbeat as no change to its other tasks, and a resume as a change". - "resolves a run without a task to no tasks and a missing task to the whole company". - Unchanged and passing: the #21729 pickup tests in `issue-recovery-idle-backstop.test.ts` (finished run, user comment, raised budget, resumed agent within a minute; missed hint within the backstop bound; outside change within the hourly pass), the #21552 tests in `issue-recovery-deadlines.test.ts` (including "keeps the company pass for hold releases that can admit any task" and "falls back to the company pass when a run affects more tasks than a hint names"). - Regression, embedded PostgreSQL: `issue-recovery-deadlines`, `issue-recovery-work-debug-attribution`, `issue-recovery-signal-fanout`, `issue-recovery-work-lifecycle` (42 tests); `native-run-projection-work`, `native-recovery-notice-work`, `muse-terminal-settlement`, `heartbeat-held-comment-wake`, `superseded-workspace-export-recovery`, `native-recovery-preparation-failure`, `upgrade-readiness-post-result`, `chat-wake-conversation-batch`, `environment-service`, `retained-native-session-cleanup-work`, `slack-conversation-lifecycle`, `workspace-recovery-dependency-finalize`, `native-failed-run-owner-release`, `chat-run-milestone-work` (462 tests). - `tsc --noEmit -p server/tsconfig.json` passes. ## Risks - **Recovery time bounds. The owner must see this.** No hint-driven pickup becomes slower for a task in the run's graph. Two missed-hint bounds change: - An agent change that sends no hint and is followed by a run heartbeat of the same agent inside the 5-minute window (for example a resume whose hint was lost, after which the agent ran another task) is now found by the hourly full pass, not the 5-minute changed-tasks pass. A normal resume sends `pause_lifted` and is checked at once (tested). - A task outside the run's graph whose recovery depended on the end of a taskless run, or on the native finish writers above, is now found by its own hint, the 5-minute changed-tasks pass (its own rows), or the hourly full pass. Before, any run finish re-checked the whole company. I found no recovery decision that waits on another run of the agent: concurrency waits are queued runs that dispatch resumes. - A run-only hint for a run row that does not exist resolves to no tasks (it was the whole company). A run row is not deleted while its tasks are open, except by company deletion, which sends the company hint. - Native finish writers now send run-scoped hints to the live-run recovery queues too (`notifyLiveRunRecovery`, `notifyLiveResourceRecovery`, attention retention). The legacy run paths already send these with the run id. - The fixture uses process-adapter runs, not native runs. The native writers are narrowed by code reading. Their effect on the hosted staging instance is not verified. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent 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 - [ ] 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 --- .../issue-recovery-activity-hints.test.ts | 215 ++++++++++++++++++ .../issue-recovery-deadlines.test.ts | 65 ++++++ .../chat-inbound-wake-notice-notifications.ts | 3 +- server/src/services/environments.ts | 7 +- .../execution-control-reconciliation.ts | 2 +- .../services/execution-recovery-resolution.ts | 4 +- server/src/services/heartbeat/queue.ts | 9 +- .../services/issue-recovery-notifications.ts | 10 +- .../native-failed-workspace-recovery.ts | 2 +- .../native-recovery-preparation-failure.ts | 2 +- .../native-runtime/native-restart-recovery.ts | 4 +- .../native-runtime/native-run-finalizer.ts | 6 +- .../native-runtime/native-run-projection.ts | 4 +- .../native-runtime/native-safe-replacement.ts | 2 +- .../native-runtime/native-session-executor.ts | 6 +- .../native-runtime/native-superseded-retry.ts | 2 +- server/src/services/recovery/changed-tasks.ts | 3 +- .../wake-request-claimed-settlement.ts | 2 +- server/src/services/recovery/work.ts | 16 +- server/src/services/work-intent-outbox.ts | 1 + 20 files changed, 329 insertions(+), 36 deletions(-) create mode 100644 server/src/__tests__/issue-recovery-activity-hints.test.ts diff --git a/server/src/__tests__/issue-recovery-activity-hints.test.ts b/server/src/__tests__/issue-recovery-activity-hints.test.ts new file mode 100644 index 00000000000..68accc0236e --- /dev/null +++ b/server/src/__tests__/issue-recovery-activity-hints.test.ts @@ -0,0 +1,215 @@ +import { appendFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { setImmediate as immediate } from "node:timers/promises"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { expect, it, vi } from "vitest"; +import { agents, heartbeatRunEvents, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import { trimWorkSignalStack, workSignalDebug } from "@paperclipai/db/work-signal-debug"; +import { issueService } from "../services/issues.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; +import { seedRecoveryPopulation } from "./helpers/recovery-population.js"; + +vi.hoisted(() => { process.env.PAPERCLIP_DEBUG_WORK_SIGNALS = "stranded-assignments:1,assigned-work-invariant:1"; }); + +const MINUTE = 60_000; +const measuring = Boolean(process.env.RECOVERY_ACTIVITY_REPORT); +const report = (label: string, summary: unknown) => { + if (process.env.RECOVERY_ACTIVITY_REPORT) appendFileSync(process.env.RECOVERY_ACTIVITY_REPORT, `${label} ${JSON.stringify(summary, null, 1)}\n`); +}; +const TASK_QUEUES = new Set(["stranded-assignments", "assigned-work-invariant", "resolved-dependencies", "stale-issue-locks"]); +type Recorded = { at: number; topic: string; name: string; fields: Record }; + +describeIssueRecovery("recovery checks while runs are active in a staging-shaped company", () => { + const state = issueRecoveryFixture({ meter: true }); + + async function advance(ms: number) { + const until = Date.now() + ms; + while (Date.now() < until) { + await vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())); + await Promise.allSettled([...state.passes]); await immediate(); + } + } + + function record() { + const events: Recorded[] = []; + vi.spyOn(workSignalDebug, "event").mockImplementation((topic, name, fields = {}) => { + if (name === "check") events.push({ at: Date.now(), topic, name, fields }); + }); + vi.spyOn(workSignalDebug, "signal").mockImplementation((topic, hint) => { + if (!TASK_QUEUES.has(topic)) return; + const holder: { stack?: string } = {}; + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 40; + Error.captureStackTrace(holder); + Error.stackTraceLimit = limit; + const frames = trimWorkSignalStack(holder.stack, 30).filter(line => !/issue-recovery-notifications|run-dispatch-notifications|external-conversation-settlement-notifications|native-status-reassessment-notifications|execution-control-notifications|issue-review-state-notifications|mockImplementation|spy|vitest/.test(line)); + const short = (line: string) => line.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")"); + const app = frames.filter(line => /services|modules|routes/.test(line)); + const caller = app.length ? app.slice(0, process.env.RECOVERY_ACTIVITY_FRAMES ? Number(process.env.RECOVERY_ACTIVITY_FRAMES) : 1).map(short).join(" < ") + : short(frames[0] ?? "unknown"); + const kind = hint === undefined || hint === "*" ? "all" : (() => { + const scope = JSON.parse(hint) as Record; + return scope.issueId ? "task" : scope.graphRunId || scope.graphIssueId ? "graph" : scope.backstop ? "backstop" : "company"; + })(); + events.push({ at: Date.now(), topic, name: "signal", fields: { kind, caller } }); + }); + return events; + } + + function summarize(events: Recorded[], seconds: number) { + const checks: Record> = {}, signals: Record = {}, scoped: Record = {}; + for (const event of events) { + if (event.name === "check") { + const byQueue = checks[event.topic] ??= {}; + byQueue[String(event.fields.wake)] = (byQueue[String(event.fields.wake)] ?? 0) + 1; + } else if (event.topic === "stranded-assignments" && (event.fields.kind === "task" || event.fields.kind === "graph")) { + const key = `${event.fields.kind} ${event.fields.caller}`; + scoped[key] = (scoped[key] ?? 0) + 1; + } else if (event.fields.kind !== "task" && event.fields.kind !== "graph") { + const key = `${event.topic} ${event.fields.kind} ${event.fields.caller}`; + signals[key] = (signals[key] ?? 0) + 1; + } + } + const perSecond = Object.fromEntries(Object.entries(checks).map(([queue, byReason]) => [queue, Object.fromEntries( + Object.entries(byReason).map(([reason, count]) => [reason, Number((count / seconds).toFixed(2))]))])); + const total = (queue: string) => Object.values(checks[queue] ?? {}).reduce((sum, count) => sum + count, 0); + return { checks, perSecond, signals, scoped, stranded: total("stranded-assignments"), assigned: total("assigned-work-invariant") }; + } + + async function provider(companyId: string, workerIds: string[]) { + const failures: unknown[] = []; + const listener = createServer(async (request, response) => { + try { + let body = ""; + for await (const chunk of request) body += chunk; + const { runId } = JSON.parse(body) as { runId: string }; + const [run] = await state.db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))); + if (!run!.contextSnapshot?.issueId) { response.end("ok"); return; } + const issueId = String(run!.contextSnapshot?.issueId); + const deadlocked = (error: unknown): boolean => typeof error === "object" && error !== null + && ((error as { code?: string }).code === "40P01" || deadlocked((error as { cause?: unknown }).cause)); + const retryDeadlock = async (write: () => Promise) => { + for (let attempt = 1; ; attempt++) { + try { return await write(); } catch (error) { if (attempt >= 3 || !deadlocked(error)) throw error; } + } + }; + await retryDeadlock(() => issueService(state.db).addComment(issueId, "Progress: done with this step", { agentId: run!.agentId, runId })); + await retryDeadlock(() => issueService(state.db).update(issueId, { status: "in_review" })); + response.end("ok"); + } catch (error) { failures.push(error); response.statusCode = 500; response.end("failed"); } + }); + await new Promise(resolve => listener.listen(0, "127.0.0.1", resolve)); + const port = (listener.address() as { port: number }).port; + const script = `fetch("http://127.0.0.1:${port}/progress",{method:"POST",body:JSON.stringify({runId:process.env.PAPERCLIP_RUN_ID})}).then(r=>{if(!r.ok)process.exitCode=1;console.log("ok")})`; + await state.db.update(agents).set({ adapterConfig: { command: process.execPath, args: ["-e", script], cwd: process.cwd() } }) + .where(inArray(agents.id, workerIds)); + return { failures, close: async () => { listener.closeAllConnections(); await new Promise(resolve => listener.close(() => resolve())); } }; + } + + async function measure(runsPerMinute: number, minutes: number, timerRunsPerMinute = 0) { + const f = await state.fixture(); + const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 780, inProgress: 40, todo: 30, + recoveryActions: 12, terminated: 3 }); + const workers = population.agentIds.slice(7, 7 + 41); + const fake = await provider(f.companyId, workers); + const events = record(); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + await state.start({}); + await advance(10 * MINUTE); + events.length = 0; + const counts = async () => { + const [runs] = await state.db.select({ finished: sql`count(*) filter (where ${heartbeatRuns.status} = 'succeeded')::int`, + failed: sql`count(*) filter (where ${heartbeatRuns.status} = 'failed')::int`, all: sql`count(*)::int` }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.runtimeMode, "legacy"))); + const [events] = await state.db.select({ n: sql`count(*)::int` }).from(heartbeatRunEvents) + .where(eq(heartbeatRunEvents.companyId, f.companyId)); + const [comments] = await state.db.select({ n: sql`count(*)::int` }).from(issueComments) + .where(and(eq(issueComments.companyId, f.companyId), sql`${issueComments.authorAgentId} is not null`)); + return { ...runs!, events: events!.n, agentComments: comments!.n }; + }; + const workBefore = await counts(); + const before = state.meter.read(); + const startedAt = Date.now(); + const byCheck: Record = {}, settingsCallers: Record = {}; + const tally = (log: ReturnType) => { + for (const entry of log) { + const stack = entry.stack ?? ""; + const owner = stack.includes("reconcileStrandedAssignedIssues") ? "stranded-assignments" + : /assigned-work-sweep|checkIssue/.test(stack) ? "assigned-work-invariant" + : stack.includes("sweepStaleIssueLocks") ? "stale-issue-locks" : stack.includes("recovery/work.ts") ? "recovery-loads" : "other"; + byCheck[owner] = (byCheck[owner] ?? 0) + 1; + if (/from "instance_settings"/.test(entry.sql)) { + const frame = stack.split("\n").map(line => line.trim()).find(line => /server\/src\/services\//.test(line) && !/instance-settings/.test(line)) ?? "unknown"; + const key = `${owner} ${frame.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")")}`; + settingsCallers[key] = (settingsCallers[key] ?? 0) + 1; + } + } + }; + if (measuring) state.meter.startLog({ stacks: true }); + let next = 12; + for (let minute = 0; minute < minutes; minute++) { + const minuteEnds = startedAt + (minute + 1) * MINUTE; + for (let started = 0; started < runsPerMinute; started++) { + const issueId = population.inReview[next++ % population.inReview.length]!; + const comment = await issueService(state.db).addComment(issueId, "Please take another pass", { userId: "recovery-user" }); + const [task] = await state.db.select({ assigneeAgentId: issues.assigneeAgentId }).from(issues).where(eq(issues.id, issueId)); + await state.heartbeat.wakeup(task!.assigneeAgentId!, { source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: comment.id, mutation: "comment" }, requestedByActorType: "user", requestedByActorId: "recovery-user", + contextSnapshot: { issueId, taskId: issueId, commentId: comment.id, wakeCommentId: comment.id, source: "issue.comment", + wakeReason: "issue_commented" } }); + await vi.advanceTimersByTimeAsync(Math.floor(MINUTE / runsPerMinute / 4)); + } + for (let timer = 0; timer < timerRunsPerMinute; timer++) { + await state.heartbeat.wakeup(workers[(minute * timerRunsPerMinute + timer) % workers.length]!, { source: "on_demand", triggerDetail: "manual", + reason: "manual", requestedByActorType: "user", requestedByActorId: "recovery-user", + contextSnapshot: { source: "scheduler", reason: "interval_elapsed", now: new Date().toISOString() } }); + } + await advance(minuteEnds - Date.now()); + await state.heartbeat.drainActiveRunExecutions(); + if (measuring) tally(state.meter.stopLog()); + if (measuring) state.meter.startLog({ stacks: true }); + } + const seconds = (Date.now() - startedAt) / 1000; + const after = state.meter.read(); + if (measuring) tally(state.meter.stopLog()); + const workAfter = await counts(); + const work = { started: workAfter.all - workBefore.all, finished: workAfter.finished - workBefore.finished, + failed: workAfter.failed - workBefore.failed, events: workAfter.events - workBefore.events, + agentComments: workAfter.agentComments - workBefore.agentComments }; + const summary = { ...summarize(events, seconds), seconds, work, + statementsPerSecond: Number(((after.statements - before.statements) / seconds).toFixed(1)), + agentWriteFailures: fake.failures.length, + statementsPerSecondBy: Object.fromEntries(Object.entries(byCheck).map(([owner, count]) => [owner, Number((count / seconds).toFixed(1))])), + instanceSettingsReads: settingsCallers }; + await fake.close(); + return summary; + } + + function expectWorkload(summary: Awaited>, taskRuns: number, tasklessRuns: number) { + expect(summary.agentWriteFailures).toBe(0); + expect(summary.work.started).toBeGreaterThanOrEqual(taskRuns + tasklessRuns); + expect(summary.work.finished).toBeGreaterThanOrEqual(taskRuns + tasklessRuns); + expect(summary.work.failed).toBeLessThanOrEqual(Math.ceil(0.1 * summary.work.started)); + expect(summary.work.agentComments).toBeGreaterThanOrEqual(taskRuns); + expect(summary.work.events).toBeGreaterThan(summary.work.finished); + } + + it("re-checks only the tasks seven runs a minute touch, among 850 open tasks", async () => { + const minutes = measuring ? 10 : 4; + const summary = await measure(7, minutes, 1); + report("7 runs/min", summary); + expectWorkload(summary, 7 * minutes, minutes); + expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0); + expect(summary.signals).toEqual({}); + expect(summary.stranded / summary.seconds).toBeLessThan(2); + }, 1_800_000); + + it.runIf(measuring)("re-checks only the tasks fifty runs a minute touch, among 850 open tasks", async () => { + const summary = await measure(50, 6, 5); + report("50 runs/min", summary); + expectWorkload(summary, 300, 30); + expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0); + expect(summary.signals).toEqual({}); + expect(summary.stranded / summary.seconds).toBeLessThan(3); + }, 1_800_000); +}); diff --git a/server/src/__tests__/issue-recovery-deadlines.test.ts b/server/src/__tests__/issue-recovery-deadlines.test.ts index a63b1e3a983..b2344c7c4fc 100644 --- a/server/src/__tests__/issue-recovery-deadlines.test.ts +++ b/server/src/__tests__/issue-recovery-deadlines.test.ts @@ -8,12 +8,15 @@ 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 { changedTaskCondition } from "../services/recovery/changed-tasks.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 { notifyExternalConversationSettlement } from "../services/external-conversation-settlement-notifications.js"; +import { notifyChatInboundWakeNotices } from "../services/chat-inbound-wake-notice-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"; @@ -183,6 +186,68 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => await graph.backlog(4000); expect(await lifecycleEvent(finished())).toBe(first); }); + it("re-checks a run's own tasks for its settlement, lease and dispatch writers, and nothing for a run without a task", async () => { + const f = await fixture(); + const graph = await runGraph(f.companyId, f.agentId); + await graph.backlog(300); + const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded", + finishedAt: new Date(), contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id }); + 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 }); + const writers = (runId: string): Array<(tx: object) => Promise> => [ + tx => notifyRunDispatch(tx, { companyId: f.companyId, runId }), + tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId }), + tx => notifyExternalConversationSettlement(tx, { companyId: f.companyId, runId }), + tx => notifyChatInboundWakeNotices(tx, { companyId: f.companyId, runId }), + tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "lock_released", issueId: null, runId }), + ]; + for (const [runId, expected] of [[graph.runId, graph.affected], [taskless.id, []]] as Array<[string, string[]]>) { + for (const writer of writers(runId)) { + checked.length = 0; assigned.length = 0; + await state.db.transaction(tx => writer(tx)); + await settleWork({ backstopPending: true }); + expect([...new Set(checked)].sort()).toEqual(expected); + expect(assigned.every(id => expected.includes(id))).toBe(true); + await vi.advanceTimersByTimeAsync(31_000); + } + } + checked.length = 0; assigned.length = 0; + await issueService(state.db).addComment(graph.siblingId, "A note on the next task", { userId: "recovery-user" }); + await settleWork({ backstopPending: true }); + expect(checked).toEqual([graph.siblingId]); + expect(assigned.every(id => id === graph.siblingId)).toBe(true); + }); + it("counts an agent's own run heartbeat as no change to its other tasks, and a resume as a change", async () => { + const f = await fixture(); + const old = new Date(Date.now() - 60 * 60_000); + const tasks = await state.db.insert(issues).values(Array.from({ length: 5 }, (_, index) => ({ companyId: f.companyId, + title: `Waiting ${index}`, status: "todo", assigneeAgentId: f.agentId, createdAt: old, updatedAt: old }))).returning({ id: issues.id }); + const since = new Date(Date.now() - 5 * 60_000); + const changed = async () => (await state.db.select({ id: issues.id }).from(issues) + .where(and(eq(issues.companyId, f.companyId), changedTaskCondition(since)))).map(row => row.id).sort(); + const heartbeatAt = new Date(); + await state.db.update(agents).set({ status: "idle", lastHeartbeatAt: heartbeatAt, updatedAt: heartbeatAt }).where(eq(agents.id, f.agentId)); + expect(await changed()).toEqual([]); + await state.db.update(agents).set({ status: "idle", updatedAt: new Date(heartbeatAt.getTime() + 1000) }).where(eq(agents.id, f.agentId)); + expect(await changed()).toEqual(tasks.map(row => row.id).sort()); + }); + it("resolves a run without a task to no tasks and a missing task to the whole company", async () => { + const f = await fixture(); + const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", + contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id }); + expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: taskless.id })).toEqual([]); + expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: randomUUID() })).toEqual([]); + expect(await resolveIssueGraph(state.db, { companyId: f.companyId, issueId: randomUUID() })).toBeNull(); + }); 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); diff --git a/server/src/services/chat-inbound-wake-notice-notifications.ts b/server/src/services/chat-inbound-wake-notice-notifications.ts index 9137e51b72f..7f38fd8b9a9 100644 --- a/server/src/services/chat-inbound-wake-notice-notifications.ts +++ b/server/src/services/chat-inbound-wake-notice-notifications.ts @@ -2,7 +2,8 @@ import { notifyExternalConversationSettlement } from "./external-conversation-se import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import type { InboundWakeNoticeScope } from "./chat-channels/inbound/wakeup-notices.js"; -export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope, options: { notifySettlement?: boolean } = {}) { +export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope & { runId?: string }, + options: { notifySettlement?: boolean } = {}) { if (options.notifySettlement !== false) await notifyExternalConversationSettlement(tx, scope); const hint = JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatInboundWakeNotices, hint); diff --git a/server/src/services/environments.ts b/server/src/services/environments.ts index b0d57b588f5..84eda427ec3 100644 --- a/server/src/services/environments.ts +++ b/server/src/services/environments.ts @@ -1778,7 +1778,7 @@ export function environmentService(db: Db) { (options?.cleanupStatus !== undefined && previous.cleanupStatus !== options.cleanupStatus) || (status !== "retained" && !previous.releasedAt))) { await notifyChatInboundWakeNotices(tx, { - companyId: previous.companyId, issueId: previous.issueId ?? undefined, + companyId: previous.companyId, issueId: previous.issueId ?? undefined, runId: previous.heartbeatRunId, }); } if (previous.heartbeatRunId && ["active", "pending_cleanup"].includes(previous.status) @@ -1789,7 +1789,8 @@ export function environmentService(db: Db) { // Messages saved behind a finished run wait for its cleanup to // settle. Reconsider them through normal deferred admission. await notifyDeferredExecutionWork(tx, { companyId: previous.companyId }); - await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId }); + await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId, + runId: previous.heartbeatRunId }); } if (previous.creationOperationId && previous.status === "pending_cleanup" && options?.cleanupStatus === "success" && status !== "pending_cleanup") { await tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: now }) @@ -1932,7 +1933,7 @@ export function environmentService(db: Db) { await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId: heartbeatRunId }); await notifyDeferredExecutionWork(tx, { companyId: run.companyId }); await promoteDeferredWorkIntents(tx, { companyId: run.companyId, trigger: "lock_released", - issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null }); + issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null, runId: heartbeatRunId }); } return tx.update(environmentLeases) .set({ diff --git a/server/src/services/execution-control-reconciliation.ts b/server/src/services/execution-control-reconciliation.ts index 8b8e6d41617..3bfc73d77c9 100644 --- a/server/src/services/execution-control-reconciliation.ts +++ b/server/src/services/execution-control-reconciliation.ts @@ -267,7 +267,7 @@ export async function reconcileAbandonedExecutionControl( await notifyNativeEnvironmentSettlement(tx, { companyId: run.companyId, runId: run.id }); await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id }); await notifyUnsafeWorkspaceExportRunChange(tx, run); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); const [updatedRun] = await tx .update(heartbeatRuns) .set({ diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.ts index 7b0cb23dd52..b1161d584f8 100644 --- a/server/src/services/execution-recovery-resolution.ts +++ b/server/src/services/execution-recovery-resolution.ts @@ -827,7 +827,7 @@ export async function settleUnrecoverableExecutions( companyId: run.companyId, issueId: task.id, runId: run.id, }).limit(1).for("update") : []; if (!hold) return void await continueNativeInterruption(tx as unknown as Db, { action, run, coordinator, now }); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); const note = "Exact session recovery stopped. The recorded workspace recovery holds this execution without replaying its actions."; await tx.update(issueRecoveryActions).set({ status: "cancelled", outcome: "cancelled", resolvedAt: now, updatedAt: now, wakePolicy: null, monitorPolicy: null, @@ -962,7 +962,7 @@ export async function settleUnrecoverableExecutions( replay: "not_authorized", }, }); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); await tx .update(heartbeatRuns) .set({ executionStatusDeliveryId: randomUUID() }) diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 221a9284839..74b219eb610 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -10,7 +10,7 @@ import { refreshRunStartYieldIfStale } from "../run-start-handover.js"; import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js"; import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js"; import { deferredWorkIntentWait } from "../work-intent-outbox.js"; -import { notifyIssueRecovery } from "../issue-recovery-notifications.js"; +import { notifyIssueGraphRecovery } from "../issue-recovery-notifications.js"; import { createHeartbeatTimerPolicy } from "./timer-policy.js"; import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, queuedRunDispatchClass } from "./queued-run-dispatch-order.js"; import { reserveAutomaticRunStart } from "../recovery/automatic-run-brake.js"; @@ -587,7 +587,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const receipts = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(owned).for("update"); if (!receipts.length) return; // Register the recovery signal before the write it announces. - await notifyIssueRecovery(tx, { companyId: run.companyId }); + await notifyIssueGraphRecovery(tx, { companyId: run.companyId, runId: run.id }); await tx.update(agentWakeupRequests).set({ idempotencyKey: null, payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) @@ -5392,8 +5392,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende return mergedRun; } + const queuedRunId = randomUUID(); const queueOutcome = await db.transaction(async (tx) => { - await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId) }); + await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId), + runId: readNonEmptyString(enrichedContextSnapshot.issueId) ? undefined : queuedRunId }); await tx.execute( sql`select id from agents where id = ${agentId} and company_id = ${agent.companyId} for update`, ); @@ -5463,6 +5465,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const newRun = await tx .insert(heartbeatRuns) .values({ + id: queuedRunId, companyId: agent.companyId, agentId, scopeKind: readNonEmptyString(enrichedContextSnapshot.issueId) ? "issue" : "company", diff --git a/server/src/services/issue-recovery-notifications.ts b/server/src/services/issue-recovery-notifications.ts index 5c5038d5425..37034c76bef 100644 --- a/server/src/services/issue-recovery-notifications.ts +++ b/server/src/services/issue-recovery-notifications.ts @@ -20,11 +20,8 @@ const TASK_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.strandedAssignments, DELIV export async function notifyIssueRecovery(transaction: object, scope?: IssueRecoveryScope) { const companyHint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*"; const issueHint = scope ? JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }) : "*"; - for (const queue of [DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.assignedWorkInvariant, DELIVERY_QUEUES.resolvedDependencies, - DELIVERY_QUEUES.taskWatchdogs, DELIVERY_QUEUES.staleIssueLocks]) { - await notifyDeliveryWork(transaction, queue, - queue === DELIVERY_QUEUES.strandedAssignments || queue === DELIVERY_QUEUES.staleIssueLocks ? issueHint : companyHint); - } + for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint); + for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, issueHint); } export function issueRecoveryBackstopHint(companyId: string) { @@ -71,5 +68,6 @@ export async function resolveIssueGraph(db: Db, scope: { companyId: string; runI 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; + if (issueIds.length === 0) return scope.issueId ? null : []; + return issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null; } diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.ts index bc37846ba7f..f693698265d 100644 --- a/server/src/services/native-runtime/native-failed-workspace-recovery.ts +++ b/server/src/services/native-runtime/native-failed-workspace-recovery.ts @@ -161,7 +161,7 @@ export async function preserveNativeFailedWorkspace(db: Db, selected: Pick, recoveryRequestId: string | null) { - await notifyExecutionRunWork(tx, { companyId: row.run.companyId }); + await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id }); await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null, nextAttemptAt: null, failureCode: "native_restart_recovery_blocked", failureDetail: { ...row.coordinator.failureDetail, reason, executorStopEvidence: "unverified" }, @@ -1932,7 +1932,7 @@ export async function claimNativeRestartRecoveries(input: { recycledProviderPids: providerProcesses.recycledPids, stderrTail: row.run.stderrExcerpt, }); - await notifyExecutionRunWork(tx, { companyId: row.run.companyId }); + await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id }); await tx .update(nativeRunFinalizations) .set({ diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index d9c07e2ab65..df6232eb978 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -405,7 +405,7 @@ export async function endSupersededNativeFinalizationRuns(db: Db, runIds?: reado : accepted === "succeeded" ? "succeeded" as const : accepted === "cancelled" ? "cancelled" as const : "failed" as const; await notifyNativeFinalizationWork(tx, { companyId: run.companyId, runId: run.id }); await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId }); await notifyInstructionCollection(tx, { companyId: run.companyId, runId: run.id }); await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id }); @@ -626,7 +626,7 @@ async function recordRetryableFailure(input: { if (phase === "terminal_failure" && failureCode === "native_workspace_sync_out_unsafe_archive") { await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId }); } - await notifyExecutionRunWork(tx, { companyId: input.run.companyId }); + await notifyExecutionRunWork(tx, { companyId: input.run.companyId, runId: input.run.id }); await notifyChatRunMilestones(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId }); await tx .update(nativeRunFinalizations) @@ -2077,7 +2077,7 @@ export async function finalizeNativeRun(input: { if (input.projectRunStatus) await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id }); if (input.projectRunStatus) await notifyUnsafeWorkspaceExportRunChange(tx, run); if (input.projectRunStatus) await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId); - await notifyExecutionRunWork(tx, { companyId: run.companyId }); + await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id }); await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId }); const [after] = await projectRun(tx); if (after && input.projectRunStatus) await settleNativeTerminalWake(tx, after); diff --git a/server/src/services/native-runtime/native-run-projection.ts b/server/src/services/native-runtime/native-run-projection.ts index c36e9b251dd..b480977eb23 100644 --- a/server/src/services/native-runtime/native-run-projection.ts +++ b/server/src/services/native-runtime/native-run-projection.ts @@ -51,7 +51,7 @@ export async function settleNativeTerminalWake(tx: Db, run: Pick= ${at}) or exists (select 1 from issue_comments c where c.company_id = ${issues.companyId} and c.issue_id = ${issues.id} and c.created_at >= ${at}) - or exists (select 1 from agents ag where ag.id = ${issues.assigneeAgentId} and ag.updated_at >= ${at}))`; + or exists (select 1 from agents ag where ag.id = ${issues.assigneeAgentId} and ag.updated_at >= ${at} + and (ag.last_heartbeat_at is null or ag.last_heartbeat_at < ag.updated_at)))`; } diff --git a/server/src/services/recovery/wake-request-claimed-settlement.ts b/server/src/services/recovery/wake-request-claimed-settlement.ts index 68ac1146803..d676ed543d5 100644 --- a/server/src/services/recovery/wake-request-claimed-settlement.ts +++ b/server/src/services/recovery/wake-request-claimed-settlement.ts @@ -64,7 +64,7 @@ export async function settleClaimedWakeRequest(db: Db, record: InProgressRecord, .where(claim).for("update"); if (!current) return { settled: false, reason: "claim_no_longer_held" }; // Work intents before the write they announce (sleep-aware background work). - await notifyExternalConversationSettlement(tx, { companyId: run.companyId }); + await notifyExternalConversationSettlement(tx, { companyId: run.companyId, runId: run.id }); await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: current.agentId }); const updated = await tx.update(agentWakeupRequests).set({ status: wakeStatusFor(run.status), diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index 9926f1c9fb8..53511dde244 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -76,6 +76,8 @@ export function registerIssueRecoveryWork( 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 loadOrigin = (scope: IssueRecoveryScope | undefined) => !workSignalDebug.enabled ? undefined : !scope ? "reload" as const + : scope.backstop ? "backstop" as const : scope.issueId || isGraph(scope) ? "hint" as const : "company" as const; const graphs = new Map }>(); async function resolveGraph(scope: IssueRecoveryScope | undefined) { if (!scope || !isGraph(scope)) return; @@ -115,6 +117,7 @@ export function registerIssueRecoveryWork( if (workSignalDebug.enabled) workSignalDebug.event(queue, "load", { scope: key }); if (!enabled) { cursors.delete(key); return []; } if (await toCompany(scope, worker)) return { rows: null, complete: true }; + if (scope?.issueIds?.length === 0) return { rows: [], complete: true }; const cursor = cursors.get(key); const changedSince = passes.changedSince(scope, key, !cursor); const rows = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(and( @@ -133,8 +136,7 @@ export function registerIssueRecoveryWork( if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); passes.loaded(scope, key, complete); const keepUnseen = changedSince ? { keepUnseen: true as const } : {}; - const origin = !workSignalDebug.enabled ? undefined : !scope ? "reload" as const : scope.backstop ? "backstop" as const - : scope.issueId || isGraph(scope) ? "hint" as const : "company" as const; + const origin = loadOrigin(scope); return { rows: rows.map(row => ({ ...row, dueAt: Date.now(), ...(origin ? { origin } : {}) })), complete, ...keepUnseen }; }, check: async entry => { @@ -172,22 +174,28 @@ export function registerIssueRecoveryWork( const key = scopeKey(scope); if (!enabled) { cursors.delete(key); return []; } if (await toCompany(scope, worker)) return { rows: null, complete: true }; + if (scope?.issueIds?.length === 0) return { rows: [], complete: true }; const changedSince = passes.changedSince(scope, key, !cursors.has(key)); const rows = await sweep.listSuspects(scope ? { companyId: scope.companyId, issueId: scope.issueId, issueIds: scope.issueIds, ...(changedSince ? { changedSince } : {}) } : {}, 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, key, complete); + const origin = loadOrigin(scope); return { rows: rows.map(row => ({ id: row.id, companyId: row.companyId, updatedAt: row.updatedAt.getTime(), dueAt: Date.now(), - ...(scope?.backstop ? { fromBackstop: true as const } : {}) })), complete, ...(changedSince ? { keepUnseen: true as const } : {}) }; + ...(scope?.backstop ? { fromBackstop: true as const } : {}), ...(origin ? { origin } : {}) })), complete, + ...(changedSince ? { keepUnseen: true as const } : {}) }; }, check: async entry => { if (!enabled) return null; + if (workSignalDebug.enabled) workSignalDebug.event(DELIVERY_QUEUES.assignedWorkInvariant, "check", { issueId: entry.id, + companyId: entry.companyId, wake: entry.fromDeadline ? "deadline" : entry.origin ?? "load", dueAt: entry.dueAt }); let next: number | null = null, unchanged = false; await sweep.checkIssue({ companyId: entry.companyId, issueId: entry.id, onDeferredDeadline: (at, detail) => { next = next === null ? at : Math.min(next, at); unchanged ||= detail?.unchanged === true; } }); const { unchanged: _previous, fromBackstop: _source, ...rest } = entry; - return next === null ? null : { ...rest, dueAt: next, ...(unchanged ? { unchanged: true as const } : {}) }; + return next === null ? null : { ...rest, dueAt: next, ...(unchanged ? { unchanged: true as const } : {}), + ...(workSignalDebug.enabled ? { fromDeadline: true as const } : {}) }; }, }, canRun); return worker; diff --git a/server/src/services/work-intent-outbox.ts b/server/src/services/work-intent-outbox.ts index 39da2efca12..7ec9e6dee10 100644 --- a/server/src/services/work-intent-outbox.ts +++ b/server/src/services/work-intent-outbox.ts @@ -71,6 +71,7 @@ export async function promoteDeferredWorkIntents(tx: object, input: { .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 === "lock_released" && input.runId ? { companyId: input.companyId, runId: input.runId } : 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, scope ?? { companyId: input.companyId });