From a8f21a171c760e9f015e77e9ee23cb92673a5432 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:41:27 -0600 Subject: [PATCH 1/5] fix(cases): hold direct case status writes to terminal handoff authority (#20686) 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 experimental Cases feature closes a case through a terminal handoff to `done` > - The terminal handoff lets an agent close a case only when the agent owns the case's primary task > - The direct case write routes (`PATCH /api/cases/:id` and the keyed upsert on `POST /api/companies/:companyId/cases`) also write `status` and `completedAt` > - These routes did not apply the primary-task ownership rule to agent status writes > - This pull request applies the same ownership rule to those routes, and sends `done` through the terminal handoff > - The benefit is that a case closes only through the authority and gates that the product describes ## Linked Issues or Issue Description No public issue exists. This is the bug description. **What happened** An agent that did not own a case's primary task tried `handoff_case` to `done` and got "Agents may complete only their own case work". The same agent then sent `PATCH /api/cases/:id` with `status: "done"`. The route returned 200 and closed the case. A chat eval (`cases.close-case`) recorded this sequence. **Expected behavior** An agent changes a case with a primary task to or from `done`/`cancelled` only with the authority that the terminal handoff requires. `done` goes through the terminal handoff, so primary-task completion keeps its normal gates (`doc/PRODUCT.md`, Cases section). The dedicated `update_case` tool already excludes `status`. **Steps to reproduce** 1. Create a case with a primary task that is assigned to agent A. 2. As agent B in the same company, send `PATCH /api/cases/:id` with `{"status":"done"}`. 3. Before this change, the response is 200 and the case status is `done`. ## What Changed - `server/src/services/case-handoffs.ts`: add `assertCaseStatusWriteAuthority`. For an agent actor, on a case that has a primary task, a status change into or out of `done`/`cancelled` must pass the same check as the terminal handoff (`authorizeTerminalTask`: the agent is the primary task's assignee). A change to `done` then returns 422 and names the terminal handoff. Board actors, non-terminal status changes and fact edits do not change. - `server/src/routes/cases.ts`: call the check inside the case write transaction in `PATCH /api/cases/:id` and in the keyed upsert branch of `POST /api/companies/:companyId/cases`. - The terminal ownership denial now names the owning agent and the primary task, and asks the caller to contact that agent on the task. The message keeps its old first sentence. - The keyed upsert falls back to the locked case row (not the pre-lock read), so an upsert without `status` cannot undo a concurrent close. - `server/src/routes/experimental-api-paths.ts`: add a catalog summary and description for `PATCH /api/cases/{id}` that states the closure rule. - `server/src/__tests__/cases-routes.test.ts`: regression test for non-owner `done`/`cancelled` through PATCH and upsert, the owner's `done` through PATCH (422), owner cancel, non-owner reopen, and board close. ## Verification - `cd server && npx vitest run src/__tests__/cases-routes.test.ts -t "terminal handoff's primary-task"`: fails before the route change (`expected 403, got 200`) and passes after it. - `cd server && npx vitest run src/__tests__/cases-routes.test.ts src/__tests__/case-mutation-fence.integration.test.ts src/__tests__/case-handoff-native.integration.test.ts src/__tests__/case-handoff-legacy.integration.test.ts src/services/case-handoffs.test.ts src/services/native-runtime/native-case-tools.integration.test.ts src/__tests__/heartbeat-case-terminal-handoff.test.ts src/__tests__/openapi-routes.test.ts src/__tests__/case-history-api-discovery.test.ts src/services/native-runtime/runner-api.test.ts`: all pass. (One local run of the legacy integration suite failed in fixture scratch preparation under load; two reruns with the change pass.) - `server` `tsc --noEmit`: no errors in the changed files. The fresh worktree had unrelated errors from unbuilt workspace packages; CI covers the full typecheck. - Live chat eval (`chat-features.runner-opencode.local.cases.close-case`, run 42936492869, at the first commit): the non-owner agent's terminal handoff was denied with the owner named, and the agent did not change case status through another route. The eval did not pass: the first chat turn did not finish inside the scenario's 180-second observation window. That is a separate latency issue in the eval. ## Risks - Behavior change for agents: an agent can no longer set `done` through PATCH on a case with a primary task, and a non-owner agent can no longer cancel or reopen it. The agent skill reference already says "Do not change case status separately". - Cases without a primary task keep the old behavior, because they have no owner to check and the terminal handoff does not apply to them. - The check reads the primary task without a row lock, to keep the task -> run -> case lock order. A concurrent reassignment can race one request. The terminal handoff itself still locks and rechecks. > 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`) in 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 - [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/__tests__/cases-routes.test.ts | 68 +++++++++++++++++++++ server/src/routes/cases.ts | 18 +++--- server/src/routes/experimental-api-paths.ts | 2 + server/src/services/case-handoffs.ts | 29 ++++++++- 4 files changed, 109 insertions(+), 8 deletions(-) diff --git a/server/src/__tests__/cases-routes.test.ts b/server/src/__tests__/cases-routes.test.ts index 055f56ff9b4..8aefa71e864 100644 --- a/server/src/__tests__/cases-routes.test.ts +++ b/server/src/__tests__/cases-routes.test.ts @@ -477,6 +477,74 @@ describeEmbeddedPostgres("cases routes", () => { expect(eventRows.filter((event) => event.runId === runId)).toHaveLength(eventRows.length); }); + it("holds direct case status writes to the terminal handoff's primary-task authority", async () => { + await enableCases(); + const company = await seedCompany("TRM"); + const owner = await seedAgent(company.id); + const other = await seedAgent(company.id); + const [primary] = await db.insert(issues).values({ + companyId: company.id, + identifier: `${company.issuePrefix.toUpperCase()}-1`, + title: "Primary case task", + status: "done", + assigneeAgentId: owner.id, + }).returning(); + const [caseRow] = await db.insert(cases).values({ + companyId: company.id, + caseNumber: 1, + identifier: `${company.issuePrefix.toUpperCase()}-C1`, + caseType: "customer", + key: "accepted-fix", + title: "Accepted fix", + status: "in_review", + workIssueId: primary!.id, + }).returning(); + const agentActor = (agentId: string): Express.Request["actor"] => ({ + type: "agent", + companyId: company.id, + agentId, + source: "agent_key", + keyId: `key-${agentId}`, + onBehalfOfUserId: null, + onBehalfOfMemberships: [], + }); + const otherHttp = request(app(agentActor(other.id))); + const readCase = async () => (await db.select().from(cases).where(eq(cases.id, caseRow!.id)))[0]!; + + for (const status of ["done", "cancelled"] as const) { + const denied = await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status }).expect(403); + expect(denied.body.error).toBe(`Agents may complete only their own case work. ${owner.name} (agent ${owner.id}) owns primary task ${primary!.identifier} and records the terminal handoff. Ask that agent on ${primary!.identifier} to close the case.`); + } + const upsert = await otherHttp + .post(`/api/companies/${company.id}/cases`) + .send({ caseType: "customer", key: "accepted-fix", title: "Accepted fix", status: "done" }) + .expect(403); + expect(upsert.body.error).toMatch(/^Agents may complete only their own case work\. /); + expect(await readCase()).toMatchObject({ status: "in_review", completedAt: null }); + + // Fact edits and non-terminal status remain ordinary case writes. + await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ title: "Accepted checkout fix" }).expect(200); + await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "in_progress" }).expect(200); + + // The owner still closes through the terminal handoff, not a raw status write. + const ownerHttp = request(app(agentActor(owner.id))); + await ownerHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "done" }).expect(422); + expect(await readCase()).toMatchObject({ status: "in_progress", completedAt: null }); + await ownerHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "cancelled" }).expect(200); + const reopen = await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "in_progress" }).expect(403); + expect(reopen.body.error).toMatch(/^Agents may complete only their own case work\. /); + + await request(app(boardActor)).patch(`/api/cases/${caseRow!.id}`).send({ status: "done" }).expect(200); + expect(await readCase()).toMatchObject({ status: "done", completedAt: expect.any(Date) }); + + // An upsert without status keeps the locked row's status and completion. + await otherHttp + .post(`/api/companies/${company.id}/cases`) + .send({ caseType: "customer", key: "accepted-fix", title: "Accepted checkout fix" }) + .expect(200); + expect(await readCase()).toMatchObject({ status: "done", completedAt: expect.any(Date) }); + }); + it("rejects cross-company agent access across the cases route surface", async () => { await enableCases(); const ownCompany = await seedCompany("OWN"); diff --git a/server/src/routes/cases.ts b/server/src/routes/cases.ts index db853f38e38..e6897b69a57 100644 --- a/server/src/routes/cases.ts +++ b/server/src/routes/cases.ts @@ -60,6 +60,7 @@ import { listIssueStatusBlockerAttention } from "../services/issue-status-presen import type { IssueBlockerAttention } from "@paperclipai/shared"; import { listCaseTaskDocuments } from "../services/case-task-documents.js"; import { authorizeCaseCreation, authorizeCaseMutation } from "../services/case-mutation-authorization.js"; +import { assertCaseStatusWriteAuthority } from "../services/case-handoffs.js"; import { logger } from "../middleware/logger.js"; import { assertCompanyAccess, getActorInfo, hasCompanyAccess } from "./authz.js"; @@ -694,19 +695,21 @@ export function caseRoutes(db: Db, storage: StorageService) { .then((rows) => rows[0] ?? null); if (existing) { - await authorizeCaseMutation(tx as unknown as Db, req.actor, existing.id, companyId); + const current = await authorizeCaseMutation(tx as unknown as Db, req.actor, existing.id, companyId); + await assertCaseStatusWriteAuthority(tx as unknown as Db, req.actor, current, body.status); if (body.projectId) await retainCaseAccessSource(tx, { companyId, caseId: existing.id, sourceKind: "project", sourceId: body.projectId, }); - const status = body.status ?? existing.status; + // Fall back to the locked row so a concurrent close or reopen is not undone. + const status = body.status ?? current.status; const [updated] = await tx.update(cases).set({ - projectId: body.projectId ?? existing.projectId, + projectId: body.projectId ?? current.projectId, title: body.title, - summary: body.summary ?? existing.summary, + summary: body.summary ?? current.summary, status, - fields: body.fields ?? existing.fields, - parentCaseId: body.parentCaseId ?? existing.parentCaseId, - completedAt: completedAtForStatus(status, existing.completedAt), + fields: body.fields ?? current.fields, + parentCaseId: body.parentCaseId ?? current.parentCaseId, + completedAt: completedAtForStatus(status, current.completedAt), updatedAt: now, }).where(eq(cases.id, existing.id)).returning(); await insertCaseEvent(tx, { @@ -1592,6 +1595,7 @@ export function caseRoutes(db: Db, storage: StorageService) { const nextLabelIds = body.labelIds ?? body.labels; const updated = await mutateCase(req, caseRow, async (tx, currentCase) => { + await assertCaseStatusWriteAuthority(tx as unknown as Db, req.actor, currentCase, body.status); await assertProjectBelongsToCompany(tx, { companyId: caseRow.companyId, projectId: body.projectId ?? null }); if (body.projectId) { if (!(await authorizationService(tx).decide({ actor: req.actor, action: "project:read", resource: { diff --git a/server/src/routes/experimental-api-paths.ts b/server/src/routes/experimental-api-paths.ts index 432f165d012..ca68a76181b 100644 --- a/server/src/routes/experimental-api-paths.ts +++ b/server/src/routes/experimental-api-paths.ts @@ -51,6 +51,8 @@ export const experimentalApiDocs: Record Date: Tue, 10 Nov 2026 20:44:09 -0600 Subject: [PATCH 2/5] fix(recovery): finish the passive recovery pass before restarting it (#20680) 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 workspace recovery worker saves the files of failed runs. One passive pass of the worker visits holds with obligations: saved input that waits, cleanup, and due re-arms and fallbacks of exhausted holds > - #17741 restarts that pass after each committed workspace-recovery change, so new work is found quickly > - On staging, changes commit continuously (stop receipts, new holds, recovery progress). Every pass restarted from the first candidates, which are settled holds whose saved input waits behind another hold, and it never reached later candidates > - After #20295, #20569 and #20661 were deployed, no due re-arm ran: five stop-proof holds and about twenty capture-policy holds kept their exhausted state, with no marker and no activity > - This pull request restarts the pass only after it reaches its tail, and it continues an unfinished pass on the next run > - The benefit is that every candidate is visited on a busy instance, so the exhausted holds re-arm, save their files and free their tasks without an administrator ## Linked Issues or Issue Description Refs #17741 Refs #20295 Refs #20569 Refs #20661 **What happened?** Exhausted workspace holds were not re-armed on staging, even after the fixes that add their re-arm were deployed. Their recovery actions stayed unchanged for days (`updatedAt` on Nov 5 or Nov 10). No `stopProofRecovery` or `capturePolicyRecovery` marker and no `issue.workspace_recovery_rearmed` activity was recorded. The worker did process new restore holds, which are selected by its unfinished pass. **What did you expect to happen?** The worker's passive pass reaches every hold with a due re-arm or fallback, re-arms it, and saves the files. **Steps to reproduce** 1. Create several settled holds with saved user input that waits, with action ids that sort before an exhausted stop-proof hold. 2. Start the real workspace recovery worker. 3. Commit a workspace-recovery notification every 50 ms, as stop receipts and new holds do on a busy instance. 4. The worker never re-arms the exhausted hold. Without the notifications, it re-arms the hold. ## What Changed - `workspace-recovery-work.ts`: a committed change marks the passive pass for restart (`restart`). It no longer resets the cursor. While a restart is pending, an unfinished pass that made progress continues on the next run. - `workspace-recovery.ts`: when the passive cursor passes the last candidate and a restart is pending, the same run starts a fresh pass from the first candidate, so a new change is not delayed by another run interval. Without a pending restart the pass records `complete` and does not wrap, so paused input does not keep the worker active. - `doc/execution-semantics.md`: document that a pass is never restarted midway. - `workspace-recovery-stop-proof.test.ts`: add a real-worker regression in the staging shape (six earlier settled holds with waiting user input, one exhausted stop-proof hold, continuous notifications). ## Verification - Red: on master, the new test "re-arms the hold on a busy instance whose passive sweep keeps selecting earlier settled holds" fails (`stopProofRecovery` stays undefined). Control: the same test without the notifications passes on master. This shows that the restarts cause the starvation. - Green: with the fix, the test passes. These suites pass: `workspace-recovery-stop-proof` (12), `execution-control-work` (27), which includes "visits a newly committed earlier Retry during a busy recovered-source pass, then becomes quiet", plus `workspace-recovery-capture-policy`, `workspace-recovery-preparation-dispatch`, `workspace-recovery-warm-handoff`, `workspace-recovery-preparation` and `server-startup-feedback-export` (279). The timing-sensitive `heartbeat-observed-workspace-preservation` suite passed 6 of 6 runs (an earlier revision that restarted only on the next run made it flaky). - Staging evidence (read-only GET requests): the 28 exhausted holds of the company have no re-arm marker and no fallback check. Many blocked tasks with settled holds have deferred wakes. ## Risks - A change committed during a pass is now picked up at the next pass, not at once. Unfinished physical work still uses its own pass first, so new recoveries are not delayed. Saved input in a passive obligation can wait up to one full pass. - Previous-release story: no persisted state changes. Holds saved by earlier releases are selected on the first full pass after deploy, with no migration. - Quiet behavior stays: a completed pass with no new change keeps the worker idle. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, code editing, browser GET reads) 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 - [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/execution-semantics.md | 5 +- .../workspace-recovery-stop-proof.test.ts | 73 ++++++++++++++++++- .../src/services/workspace-recovery-work.ts | 10 ++- server/src/services/workspace-recovery.ts | 13 +++- 4 files changed, 91 insertions(+), 10 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index e683dead6d6..4e604ccd82b 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3776,7 +3776,10 @@ infrastructure certification, and grants no agent or provider execution authorit Each completed export frees its own slot and wakes the next scan. A slow export does not hold a free slot. Completed cleanup and saved-input obligations receive one bounded pass through unvisited sources. The pass stops at its tail so paused -input does not keep the worker active; a committed change starts a fresh pass. +input does not keep the worker active; a committed change starts a fresh pass +once the current pass reaches its tail. A pass is never restarted midway, so on +a busy instance, where changes commit continuously, every candidate is still +visited: the due re-arms and fallbacks of older exhausted holds included. Shutdown joins this worker's exports before closing the database. Repeated Retry during physical preservation binds the canonical intent without changing the attempt's generation or revision. Progress writes preserve diff --git a/server/src/services/workspace-recovery-stop-proof.test.ts b/server/src/services/workspace-recovery-stop-proof.test.ts index e3ece5d881c..3546d1c845d 100644 --- a/server/src/services/workspace-recovery-stop-proof.test.ts +++ b/server/src/services/workspace-recovery-stop-proof.test.ts @@ -3,21 +3,25 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { eq } from "drizzle-orm"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { activityLog, environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; +import { activityLog, agentWakeupRequests, environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { readRemoteWorkspaceWriterHold, remoteWorkspaceHoldRefusesStart } from "./remote-workspace-writer-hold.js"; import { readSystemRecovery } from "./system-recovery-state.js"; import { adoptSystemRecovery } from "./system-recovery.js"; -import { DELIVERY_QUEUES, subscribeDeliveryWork } from "./delivery-work-notifications.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork, subscribeDeliveryWork } from "./delivery-work-notifications.js"; +import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { registerWorkspaceRecoveryWork } from "./workspace-recovery-work.js"; import { prepareSandboxStopAndRetain, settleStopOnlyCleanup } from "./sandbox-stop-and-retain.js"; import { nextWorkspaceRecoveryAt } from "./system-recovery.js"; import { RETAINED_SOURCE_FALLBACK_OUTCOME } from "./workspace-recovery-fallback.js"; import { readWorkspaceRecovery } from "./workspace-recovery-receipt.js"; -import { reconcileRetainedWorkspaces, recoverRetainedWorkspace, retainedWorkspaceCandidates } from "./workspace-recovery.js"; +import { reconcileRetainedWorkspaces, recoverRetainedWorkspace, retainedWorkspaceCandidates, type PassiveSweep } from "./workspace-recovery.js"; import { acceptedRemoteExport, action, connectionString, db, run, seed, useWorkspaceRecoveryFixture } from "./__tests__/workspace-recovery-fixture.js"; const targets = vi.hoisted(() => new Map()); +vi.mock("./execution-control-deadline.js", async importOriginal => ({ + ...await importOriginal(), EXECUTION_RECONCILIATION_INTERVAL_MS: 200 })); vi.mock("./environment-execution-target.js", async importOriginal => { const actual = await importOriginal(); return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters[0]) => @@ -292,6 +296,69 @@ describe("exhausted stop-proof holds", () => { expect((await retainedWorkspaceCandidates(db, undefined, false, true)).map(row => row.action.id)).toContain(f.actionId); }, 60_000); + async function waitingSettledHold(id: string) { + const f = await seed("native", true); + settledRuns.set(id, f.runId); + await adoptSystemRecovery(db, f); + const prior = await action(f.actionId); + const system = readSystemRecovery(prior.evidence)!; + await db.update(issueRecoveryActions).set({ id, status: "resolved", outcome: "blocked", ownerType: "system", evidence: { ...prior.evidence, + systemRecovery: { ...system, state: "complete", phase: "reconcile_effects", attempts: 1 }, + workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.runId, status: "recovered", stage: "saving_receipts", + attempt: 1, attemptLimit: 6, retryable: false, requestIds: [] }, + automaticRecovery: { runId: f.runId, policy: "preserve_without_replay_v1", replay: "blocked" } } }) + .where(eq(issueRecoveryActions.id, f.actionId)); + const source = await run(f.runId); + await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: source.agentId, source: "on_demand", + reason: "issue_commented", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "board", + payload: { issueId: f.issueId } }); + return f; + } + + const settledRuns = new Map(); + + it("restarts a finished passive pass when a change adds work both before and after its cursor", async () => { + const first = await waitingSettledHold("00000002-0000-4000-8000-000000000000"); + await waitingSettledHold("00000003-0000-4000-8000-000000000000"); + const visited: string[] = []; + const onRecovered = async (source: { id: string }) => { visited.push(source.id); }; + const sweep: PassiveSweep = {}; + for (let pass = 0; pass < 4 && !sweep.complete; pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, first.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(sweep.complete).toBe(true); + await waitingSettledHold("00000001-0000-4000-8000-000000000000"); + const f = await exhaustedStopProofHold(); + await db.update(issueRecoveryActions).set({ id: "ffffffff-0000-4000-8000-000000000000" }).where(eq(issueRecoveryActions.id, f.actionId)); + sweep.restart = true; + visited.length = 0; + await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(sweep).toMatchObject({ complete: false, restart: true }); + for (let pass = 0; pass < 6 && !(sweep.complete && !sweep.restart && visited.includes(settledRuns.get("00000001-0000-4000-8000-000000000000")!)); pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(visited).toContain(settledRuns.get("00000001-0000-4000-8000-000000000000")); + expect((await action("ffffffff-0000-4000-8000-000000000000")).evidence.stopProofRecovery).toMatchObject({ rearms: 1 }); + }, 60_000); + + it("re-arms the hold on a busy instance whose passive sweep keeps selecting earlier settled holds", async () => { + for (const prefix of ["00000001", "00000002", "00000003", "00000004", "00000005", "00000006"]) + await waitingSettledHold(`${prefix}-0000-4000-8000-000000000000`); + const f = await exhaustedStopProofHold(); + const holdId = "ffffffff-0000-4000-8000-000000000000"; + await db.update(issueRecoveryActions).set({ id: holdId }).where(eq(issueRecoveryActions.id, f.actionId)); + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: vi.fn() }); + const worker = registerWorkspaceRecoveryWork(db, coordinator, f.environmentRuntime, async () => undefined); + const busy = setInterval(() => { void db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.workspaceRecovery)).catch(() => undefined); }, 50); + try { + await worker.ready; + await vi.waitFor(async () => expect((await action(holdId)).evidence.stopProofRecovery).toMatchObject({ rearms: 1 }), + { timeout: 20_000, interval: 250 }); + } finally { + clearInterval(busy); + await worker.stop(); + await coordinator.stop(); + } + }, 60_000); + it("wakes the workspace recovery worker when a stop receipt is recorded", async () => { const f = await acceptedRemoteExport("retained"); const woken: string[] = []; diff --git a/server/src/services/workspace-recovery-work.ts b/server/src/services/workspace-recovery-work.ts index dea2bf28b46..279fa77cc00 100644 --- a/server/src/services/workspace-recovery-work.ts +++ b/server/src/services/workspace-recovery-work.ts @@ -3,7 +3,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; import { executionControlSchedule, registerExecutionControlWork } from "./execution-control-work.js"; import type { EnvironmentRuntimeService } from "./environment-runtime.js"; -import { reconcileRetainedWorkspaces } from "./workspace-recovery.js"; +import { reconcileRetainedWorkspaces, type PassiveSweep } from "./workspace-recovery.js"; export function registerWorkspaceRecoveryWork(db: Db, coordinator: ReturnType, runtime: EnvironmentRuntimeService, onRecovered: Parameters[2], @@ -12,15 +12,17 @@ export function registerWorkspaceRecoveryWork(db: Db, coordinator: ReturnType | undefined; let wakeWhileBusy = false; - let passiveSweep: { cursor?: string } = {}; + const passiveSweep: PassiveSweep = {}; const schedule = executionControlSchedule(db); const worker = registerExecutionControlWork(coordinator, [{ queue: DELIVERY_QUEUES.workspaceRecovery, - onSettled: () => { passiveSweep = {}; if (pending.size >= 2) wakeWhileBusy = true; }, + onSettled: () => { passiveSweep.restart = true; if (pending.size >= 2) wakeWhileBusy = true; }, run: () => scan = (async () => { + const sweep = passiveSweep, cursor = sweep.cursor; const work = await reconcileRetainedWorkspaces(db, runtime, onRecovered, true, continueSweep => { if (!stopped && (continueSweep || wakeWhileBusy)) { wakeWhileBusy = false; worker.wake(); } - }, passiveSweep); + }, sweep); + if (sweep.restart && !sweep.complete && sweep.cursor !== cursor && !stopped) worker.wake(); for (const job of work ?? []) { pending.add(job); const settled = () => { pending.delete(job); }; diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.ts index 101af1e339d..6c8712a031a 100644 --- a/server/src/services/workspace-recovery.ts +++ b/server/src/services/workspace-recovery.ts @@ -644,11 +644,13 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedO )).orderBy(asc(issueRecoveryActions.id)).limit(5); } +export type PassiveSweep = { cursor?: string; complete?: boolean; restart?: boolean }; + /** Bounded discovery shares the periodic recovery lifecycle. A repaired source * still owes cleanup even without saved input or after task reconciliation. */ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRuntimeService, onRecovered: (run: typeof heartbeatRuns.$inferSelect) => Promise, obligationsOnly = false, - onFinished?: (continueSweep: boolean) => void, passiveSweep?: { cursor?: string }) { + onFinished?: (continueSweep: boolean) => void, passiveSweep?: PassiveSweep) { await adoptHistoricalWorkspaceRecoveries(db); let pending = workInFlight.get(db); if (!pending) { pending = new Set(); workInFlight.set(db, pending); } @@ -659,7 +661,14 @@ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRu let rows = await retainedWorkspaceCandidates(db, unfinishedCursors.get(db), true, false, inFlightRunIds); if (!rows.length) rows = await retainedWorkspaceCandidates(db, undefined, true, false, inFlightRunIds); const unfinished = rows.length > 0; - if (!rows.length) rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds); + if (!rows.length) { + rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds); + if (passiveSweep && !rows.length && passiveSweep.restart) { + Object.assign(passiveSweep, { cursor: undefined, restart: false }); + rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); + } + if (passiveSweep) passiveSweep.complete = !rows.length; + } if (!rows.length && !passiveSweep) rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); const work: Promise[] = []; let hasUnvisited = false; From a1ec05a1a4b81d7780e7156928c7a91d7dd73e1f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:46:29 -0600 Subject: [PATCH 3/5] fix(native): read settled harness state again after a dropped sandbox connection (#20690) 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 Runner keeps one provider conversation across the per-turn runs of a task. After each turn, the controller reads the settled Runner and provider state out of the sandbox and saves it as the harness backup. > - A per-turn sandbox is released after the turn. The harness backup is then the only copy of the provider session. > - On staging, one dropped sandbox connection (`write ECONNRESET`) during that read lost the backup. The run itself succeeded, because its result was already accepted. > - The next run of the task could not resume the conversation: `PRP provider resume state is unavailable`. When the task was waiting for a reply, the run stopped at "Recovery needed" with no Retry. A person had to send a message to start a new conversation. > - This pull request reads the settled state again when the sandbox connection drops during that read. > - The benefit is that one network reset no longer loses a task's conversation. ## Linked Issues or Issue Description Refs #20627 (warm backup restore when the source sandbox is idle) and #20683 (relaunch of a settled runner). This PR changes a different step: the backup capture at the end of a turn. **What happened?** A per-turn OpenCode task ran on a remote Daytona sandbox with reuse disabled. 1. Run A accepted its result. The Runner suspended. 2. The controller read the settled state out of the sandbox. The read failed with `remote checkpoint failed: write ECONNRESET`. `harness_state.backup.persist` and `session.checkpoint.persist` failed. 3. Run A still finished as `succeeded`, because the result was durable. The sandbox was released. No harness backup of turn A existed. 4. Run B started in a new sandbox. It failed in 0.2 s with `native_session_recovery_failed: Error: PRP provider resume state is unavailable`. When the prior turn yielded for a reply, the checkpoint policy does not allow a replacement session, so the task showed "Recovery needed" with only inspect actions. On staging this happened on 4 tasks in 48 hours. In all 3 predecessor runs that I could inspect, the backup capture failed. 2 of them show the `ECONNRESET` in the run log. No deploy happened between run A and run B in one case, so a deploy is not the cause. **Expected behavior** A transient connection drop while reading settled state does not lose the provider conversation. The read is repeated, and the backup is saved. **Steps to reproduce** 1. Run the first durable turn of a remote OpenCode session. 2. Make the sandbox `syncOut` of the backup directories fail once with `ECONNRESET`. 3. Call the settled checkpoint. On `master` it throws `write ECONNRESET`, and no backup is saved. The new test `uses the bundled Linux image authority for remote opencode-new-durable-reset without controller overrides` runs these steps. **Paperclip version or commit** `master` at `7435abcc63`. ## What Changed - The settled-state capture (inspect plus `syncOut` of each persistence directory into a pending directory) is now one step that can repeat. The step writes nothing durable, so it is safe to repeat. - A dropped, reset or refused sandbox connection repeats the step, at most 3 attempts, with 1 s and 2 s delays. Each repeat clears the pending directory and inspects the live state again, so the copy always matches the inspected identity. - Any other failure fails at once, as before: a state mismatch, a missing directory, an unsafe archive, or a TLS failure. - The durable backup upload and the local publish run only after a complete capture. They did not change. - `isTransientRemoteCheckpointReadFailure` classifies the error with the existing `classifyRemoteConnectionError`, plus a message match for SDK errors that lose their `code`. - The first completeness inspection and its visibility-window re-reads use the same bounded retry (`retryTransientRemoteCheckpointRead`). A dropped provider-state read keeps its `provider_state_unreadable` refusal for every other caller, but the checkpoint retry looks through it to the dropped read. Undici `fetch failed` and `no response returned` also count as drops. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts`: 1343 passed. - Red on `master`: the new `opencode-new-durable-reset` case fails with `Error: write ECONNRESET`. Green with this change. - The `isTransientRemoteCheckpointReadFailure` test checks that state mismatches, unsafe archives and TLS failures do not repeat. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Low risk. The normal path has no added wait. A repeat adds at most 3 s, and only after a connection failure. - A repeated read inspects the live state again. If the state changed between attempts, the existing identity checks still refuse it. - A connection that stays down for all 3 attempts fails the same way as before. > 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 - 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 - [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 --- .../native-session-executor.test.ts | 61 +++++++++- .../native-runtime/native-session-executor.ts | 104 +++++++++++++++--- 2 files changed, 145 insertions(+), 20 deletions(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index b67247d57a4..dd961a60dc2 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -469,6 +469,9 @@ import { stageRemoteRunnerFile, steerNativeSession, syncRemoteRunnerDirectoryOut, + isTransientRemoteCheckpointReadFailure, + remoteProviderStateUnreadable, + retryTransientRemoteCheckpointRead, verifyNativeHarnessBackup, shouldRestoreNativeHarnessBackupIntoSandbox, } from "./native-session-executor.js"; @@ -2312,8 +2315,14 @@ describe("remote provider pack manifest", () => { return JSON.stringify(value); }; - it.each(["opencode", "opencode-new-durable", "opencode-continuation", "opencode-continuation-missing", "opencode-continuation-no-receipt", "opencode-continuation-replacement", "opencode-continuation-cold", "opencode-continuation-legacy-durable", "opencode-dirty", "opencode-diagnostics", "opencode-diagnostics-stale", "cursor", "claude-x64", "claude-arm64"] as const)("uses the bundled Linux image authority for remote %s without controller overrides", async provider => { - const firstDurable = provider === "opencode-new-durable"; + it.each(["opencode", "opencode-new-durable", "opencode-new-durable-reset", "opencode-new-durable-inspect-reset", "opencode-new-durable-provider-reset", "opencode-continuation", "opencode-continuation-missing", "opencode-continuation-no-receipt", "opencode-continuation-replacement", "opencode-continuation-cold", "opencode-continuation-legacy-durable", "opencode-dirty", "opencode-diagnostics", "opencode-diagnostics-stale", "cursor", "claude-x64", "claude-arm64"] as const)("uses the bundled Linux image authority for remote %s without controller overrides", async provider => { + const firstDurable = provider.startsWith("opencode-new-durable"); + // A sandbox connection drops once while the settled state is read out. + let checkpointReadResets = provider === "opencode-new-durable-reset" ? 1 : 0; + // Or while the checkpoint inspects the runner state, or reads the provider state, before any copy starts. + let inspectionResets = 0; + const inspectionReset = provider === "opencode-new-durable-inspect-reset" ? "runner-state.json" + : provider === "opencode-new-durable-provider-reset" ? "codex-provider-state.json" : null; const architecture = provider === "claude-arm64" ? "arm64" : "x64"; const claude = provider.startsWith("claude-"); const opencode = provider.startsWith("opencode"); @@ -2372,6 +2381,10 @@ describe("remote provider pack manifest", () => { const suspendedState = durableRunnerState({ runId: remoteExecution.binding.runId, runnerInstanceId: "bundled-image-runner", environmentLeaseId: "lease", normalizedSessionId: remoteExecution.session.normalizedSessionId }, "suspended"); const syncOut = vi.fn(async (operations: Array<{ files: Array<{ kind: string; targetPath: string }> }>) => { + if (checkpointReadResets > 0 && operations.some(operation => operation.files.some(file => file.targetPath.includes("/.pending-")))) { + checkpointReadResets--; + throw Object.assign(new Error("write ECONNRESET"), { code: "ECONNRESET" }); + } for (const operation of operations) for (const file of operation.files) { if (file.kind === "directory") { await mkdir(file.targetPath, { recursive: true }); @@ -2402,7 +2415,14 @@ describe("remote provider pack manifest", () => { }); onTestFinished(() => { storage.mockRestore(); owner.mockRestore(); validate.mockRestore(); retain.mockRestore(); capture.mockRestore(); backup.mockRestore(); }); } - const execute = vi.fn(async (command: { command: string; args?: string[] }) => ({ + const execute = vi.fn(async (command: { command: string; args?: string[] }) => { + const script = command.args?.[1] ?? ""; + if (inspectionResets > 0 && inspectionReset && script.includes("base64 <") && script.includes(inspectionReset) + && (inspectionReset === "runner-state.json" || !script.includes("runner-state.json"))) { + inspectionResets--; + throw Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }); + } + return { exitCode: 0, signal: null, timedOut: false, stderr: "", stdout: command.args?.[0] === "--build-metadata" ? JSON.stringify({ schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", @@ -2412,7 +2432,8 @@ describe("remote provider pack manifest", () => { }) : firstDurable && command.args?.[1]?.startsWith("const os=require") ? JSON.stringify({ home: "/home/runtime-account", uid: 1000 }) : firstDurable && command.args?.[1]?.includes("base64 <") ? Buffer.from(JSON.stringify(command.args[1].includes("codex-provider-state.json") && !command.args[1].includes("runner-state.json") ? providerState : suspendedState)).toString("base64") : "", - })); + }; + }); try { let coldAdmission: ReturnType = null; const prepare = createRunnerdBackend({ db: preparedDb, execution: remoteExecution, @@ -2492,8 +2513,11 @@ describe("remote provider pack manifest", () => { expect(exportSources.every(source => source.startsWith("/workspace/"))).toBe(true); expect(providerArtifactStorage.retainNativeProviderArtifacts).toHaveBeenCalledWith(expect.objectContaining({ owner: expect.objectContaining({ runId: remoteExecution.binding.runId }), source: expect.objectContaining({ manifest: installed, launchRoot, accountUid: 1000 }) })); + if (inspectionReset) inspectionResets = 1; await driver.mock.calls.at(-1)![0].checkpoint!("settled"); expect(harnessStorage.persistNativeHarnessBackup).toHaveBeenCalledTimes(1); + expect(checkpointReadResets).toBe(0); + expect(inspectionResets).toBe(0); return; } expect(execute.mock.calls.some(([call]) => call.args?.[0] === "-e" || call.args?.[0] === "--version")).toBe(false); @@ -21223,3 +21247,32 @@ describe("HTTP Stop during remote runner staging", () => { } finally { release(); await outcome; await stopping; await bundle.transport.detachControllerForRestart?.().catch(() => {}); await temporary.cleanup(); await rm(root, { recursive: true, force: true }); } }, 120000); }); + +describe("isTransientRemoteCheckpointReadFailure", () => { + it("repeats only a dropped sandbox connection, never a state or safety refusal", () => { + expect(isTransientRemoteCheckpointReadFailure(Object.assign(new Error("write ECONNRESET"), { code: "ECONNRESET" }))).toBe(true); + expect(isTransientRemoteCheckpointReadFailure(new Error("Daytona syncOut directory download failed: socket hang up"))).toBe(true); + expect(isTransientRemoteCheckpointReadFailure(new Error("runner_harness_state_mismatch: checkpoint_identity_incomplete"))).toBe(false); + expect(isTransientRemoteCheckpointReadFailure(new Error("Daytona syncOut refusing tarball member that escapes the extraction dir: ../x"))).toBe(false); + expect(isTransientRemoteCheckpointReadFailure(Object.assign(new Error("certificate expired"), { code: "CERT_HAS_EXPIRED" }))).toBe(false); + // A provider-state refusal is transient only when the read behind it dropped. + expect(isTransientRemoteCheckpointReadFailure(remoteProviderStateUnreadable(Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" })))).toBe(true); + expect(isTransientRemoteCheckpointReadFailure(remoteProviderStateUnreadable(new Error("runner_remote_provider_state_unavailable")))).toBe(false); + expect(isTransientRemoteCheckpointReadFailure(remoteProviderStateUnreadable(new SyntaxError("Unexpected token")))).toBe(false); + expect(remoteProviderStateUnreadable(new Error("read ECONNRESET")).message).toBe("runner_harness_state_mismatch: provider_state_unreadable"); + }); + + it("stops after three reads, and never repeats a refusal", async () => { + const reset = () => Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }); + const onRetry = vi.fn(); + const dropping = vi.fn(async () => { throw reset(); }); + await expect(retryTransientRemoteCheckpointRead(dropping, onRetry, 0)).rejects.toThrow("read ECONNRESET"); + expect(dropping).toHaveBeenCalledTimes(3); + expect(onRetry.mock.calls).toEqual([[1, 3], [2, 3]]); + const refusing = vi.fn(async () => { throw new Error("runner_harness_state_mismatch: runner_identity"); }); + await expect(retryTransientRemoteCheckpointRead(refusing, vi.fn(), 0)).rejects.toThrow("runner_identity"); + expect(refusing).toHaveBeenCalledTimes(1); + let drops = 2; + await expect(retryTransientRemoteCheckpointRead(async () => { if (drops-- > 0) throw reset(); return "settled"; }, vi.fn(), 0)).resolves.toBe("settled"); + }); +}); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index fb5c533b658..cc2d29953b0 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -295,6 +295,7 @@ import { } from "./status-arbiter.js"; import { conflict, HttpError } from "../../errors.js"; import { redactSensitiveText } from "../../redaction.js"; +import { classifyRemoteConnectionError } from "../remote-connection-failure.js"; import { resolvePaperclipRunnerBinary, resolveRemotePaperclipRunnerBinary } from "./native-codex-runner.js"; import { createNativeRunTrace, @@ -13735,6 +13736,55 @@ function assertSafeExtractedCheckpoint(root: string): void { } } +const REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS = 3; +const REMOTE_CHECKPOINT_CAPTURE_RETRY_MS = 1_000; +const TRANSIENT_REMOTE_READ_MESSAGE = /\b(?:ECONNRESET|EPIPE|ETIMEDOUT|ECONNREFUSED|socket hang up|fetch failed|no response returned)\b/; +/** `provider_state_unreadable` refusals whose underlying read was a dropped + * connection. The refusal keeps its message for every other caller; only the + * checkpoint read retry looks through it. */ +const providerStateReadTransportFailures = new WeakMap(); + +/** A dropped or refused sandbox connection while reading settled state. A + * mismatch, a missing directory or an unsafe archive is never transient. */ +export function isTransientRemoteCheckpointReadFailure(error: unknown): boolean { + if (error instanceof Error && providerStateReadTransportFailures.has(error)) { + return isTransientRemoteCheckpointReadFailure(providerStateReadTransportFailures.get(error)); + } + const reason = classifyRemoteConnectionError(error); + if (reason !== null) return reason !== "tls_failure"; + return error instanceof Error && !error.message.startsWith("runner_") + && TRANSIENT_REMOTE_READ_MESSAGE.test(error.message); +} + +/** The refusal `inspectRemoteHarnessState` throws when the provider state + * cannot be read, remembering the read failure behind it. */ +export function remoteProviderStateUnreadable(readFailure: unknown): Error { + const refusal = new Error("runner_harness_state_mismatch: provider_state_unreadable"); + providerStateReadTransportFailures.set(refusal, readFailure); + return refusal; +} + +/** + * Repeats a read of settled state out of the sandbox after a dropped + * connection, at most {@link REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS} times in all. + * Any other failure, and the last transient one, is thrown unchanged. + */ +export async function retryTransientRemoteCheckpointRead( + read: () => Promise, + onRetry: (attempt: number, attempts: number) => Promise | void, + retryDelayMs = REMOTE_CHECKPOINT_CAPTURE_RETRY_MS, +): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await read(); + } catch (error) { + if (attempt >= REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS || !isTransientRemoteCheckpointReadFailure(error)) throw error; + await onRetry(attempt, REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS); + await new Promise((resolveDelay) => setTimeout(resolveDelay, retryDelayMs * attempt)); + } + } +} + /** * Copy a remote runner directory into durable local state. * @@ -15754,8 +15804,8 @@ async function createRunnerdBackendWithinSessionClaim( stateDirectory: remoteStateDirectory, execution: input.execution, }); - } catch { - throw new Error("runner_harness_state_mismatch: provider_state_unreadable"); + } catch (error) { + throw remoteProviderStateUnreadable(error); } const providerSessionIdentity = providerSessionIdentityFromDurableProviderState({ @@ -16301,14 +16351,23 @@ async function createRunnerdBackendWithinSessionClaim( // `runner_harness_state_mismatch`. Only checkpoint a harness that runnerd // has proved complete. A malformed or identity-conflicting state still // throws from inspectRemoteHarnessState and therefore fails closed. - let checkpointable = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); + // A dropped sandbox connection repeats the read (bounded) instead of + // losing the only backup of the provider session. + const inspectForCheckpoint = () => retryTransientRemoteCheckpointRead( + () => measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()), + (attempt, attempts) => input.onLog?.( + "stderr", + `[paperclip-runner] remote checkpoint inspection interrupted (attempt ${attempt} of ${attempts}); reading the settled state again\n`, + ), + ); + let checkpointable = await inspectForCheckpoint(); // The remote runner writes its suspended lifecycle and provider state // before the outer process-owner RPC necessarily observes completion. // Allow a very small bounded visibility window without ever accepting an // active, incomplete, malformed, or identity-conflicting checkpoint. for (let attempt = 1; !checkpointable.complete && attempt < 3; attempt++) { await new Promise((resolve) => setTimeout(resolve, 100)); - checkpointable = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); + checkpointable = await inspectForCheckpoint(); } if (!checkpointable.complete) { const incompleteFailure = remoteCheckpointIncompleteFailure( @@ -16338,24 +16397,27 @@ async function createRunnerdBackendWithinSessionClaim( input.trace, "harness_state.backup.persist", async () => { - const verified = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); - if ( - !verified.complete || - !verified.runnerState || - !verified.providerSessionIdentity - ) { - throw new Error("runner_harness_state_mismatch: checkpoint_identity_incomplete"); - } - const providerSessionIdentity = verified.providerSessionIdentity; - const backupRoot = harnessBackupRoot(root); mkdirSync(backupRoot, { recursive: true, mode: 0o700 }); const pendingRoot = resolve( backupRoot, `.pending-${randomUUID()}`, ); - mkdirSync(pendingRoot, { recursive: true, mode: 0o700 }); - try { + // Reading the settled state out of the sandbox writes nothing + // durable, so a dropped sandbox connection can repeat the whole + // read. Without this, one reset loses the only copy of the + // provider session when the per-turn sandbox is released. + const captureSettledState = async () => { + rmSync(pendingRoot, { recursive: true, force: true }); + const verified = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); + if ( + !verified.complete || + !verified.runnerState || + !verified.providerSessionIdentity + ) { + throw new Error("runner_harness_state_mismatch: checkpoint_identity_incomplete"); + } + mkdirSync(pendingRoot, { recursive: true, mode: 0o700 }); for (const directory of persistenceProfile.directories) { const sourcePath = remotePersistencePath(directory); if (!sourcePath) @@ -16372,6 +16434,16 @@ async function createRunnerdBackendWithinSessionClaim( throw new Error("runner_harness_state_mismatch: checkpoint_directory_missing"); } } + return verified.providerSessionIdentity; + }; + try { + const providerSessionIdentity = await retryTransientRemoteCheckpointRead( + captureSettledState, + (attempt, attempts) => input.onLog?.( + "stderr", + `[paperclip-runner] remote checkpoint read interrupted (attempt ${attempt} of ${attempts}); reading the settled state again\n`, + ), + ); const manifest = buildNativeHarnessBackupManifest({ backupRoot: pendingRoot, execution: input.execution, From 8c0dbffa704b4d0cb4fd7acee7be906ea11692ea Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:54:53 -0600 Subject: [PATCH 4/5] fix(heartbeat): retry a legacy run whose lease this process lost before dispatch (#20694) 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 heartbeat orphan reaper settles legacy (non-native) runs that lost their controller lease > - #16355 taught the reaper to retry a legacy run that a restart stopped while setup was still `preparing`, because revocation fences the old controller and `preparing` proves no adapter dispatch > - That proof was applied only when the lapsed lease belonged to a different boot > - A stall can make the current process lose its own lease while setup is still `preparing`, and its executor can end without settling the row > - The reaper then wrote "retrying once" but recorded no bootstrap evidence, so the retry was refused and the task was blocked for reconciliation > - This pull request applies the same revocation proof to a lease from the current boot > - The benefit is that these tasks recover by themselves instead of waiting for a person to press Retry ## Linked Issues or Issue Description Refs #16355 **What happened?** On a hosted instance, one server process stalled for about 100 seconds (lease renewals were 42–46 s late). Several legacy `paperclip_runner` runs on a remote sandbox were still in setup (`executionStage: "preparing"`, no process id). Their controller leases expired. Some executors settled their own runs as `controller_lease_lost`. Two runs had no executor left, so the orphan reaper of the same process settled them 4 minutes later. Each run got `error: "Process lost -- server may have restarted; retrying once"` and `processLossDiagnostic.retryEligible: true`, but no `executionRecovery` evidence. `enqueueProcessLossRetry` then saw a run that needs reconciliation and scheduled nothing. The next sweep recorded `legacy_execution_requires_reconciliation` with `preserve_without_replay_v1`, and both tasks stayed `blocked` until a person pressed Retry. **Expected behavior** Revocation commits the stage. Renewal requires the old boot id, so no controller can move a revoked run to `dispatching`. A revoked run that is still `preparing` with no process identity did no provider work, whichever boot owned the lease. The reaper should record the bootstrap evidence and use the bounded retry. **Steps to reproduce** 1. Claim a legacy run in this process: `controllerBootId` is the current boot, `executionStage: "preparing"`, no process id. 2. Let its controller lease expire with no local executor (for example after an event-loop or database stall). 3. Run the orphan reaper. 4. Before this change: `process_lost; retrying once`, no `executionRecovery`, no retry, and a reconciliation hold. After this change: bootstrap evidence and a `scheduled_retry` successor. ## What Changed - `server/src/services/heartbeat/recovery.ts`: `restartInterruptedBeforeDispatch` no longer requires the lease to come from another boot. The other clauses stay: legacy runtime, a stamped controller boot id, and `preparing` with no process id or group in the state committed by the revocation. Locally tracked runs and runs with a live lease are still skipped before this point. - `server/src/__tests__/heartbeat-process-recovery.test.ts`: two cases in the hosted shape (assignment wake and due-monitor wake, `paperclip_runner`, prepared remote workspace, same-boot expired lease, `preparing`). They expect bootstrap evidence, a scheduled retry, no recovery hold after a second sweep, and no adapter call. A control case keeps a same-boot `dispatching` run held for reconciliation. ## Verification - Red on `origin/master` (source change reverted): both new cases fail. The monitor case shows the exact hosted shape: `retryEligible: true` with no `executionRecovery`. - Green with the change: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-process-recovery.test.ts -t "lease this process lost|this process dispatched held|restart stopped before adapter dispatch|reached adapter dispatch held|lost monitor|older build without a controller stamp|failure budget"` (10 passed). - Related files, run together: `heartbeat-process-recovery`, `live-recovery-work`, `interrupted-preparation-hold-settle`, `resource-wait-stop`, `legacy-controller-lease`, `execution-recovery-dead-controller`, `legacy-process-settlement`, `run-failure-report` (876 passed; 2 timing failures under load in unrelated setup-failure tests, both pass when run alone). - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. ## Risks - Low risk. The proof is the one #16355 already relies on across boots: the revocation compare-and-set replaces the boot id, so the in-memory controller of this process also fails its next renewal and cannot dispatch. - A same-boot run reaches this code only when it is not in `activeRunExecutions` or `runningProcesses` and its lease expired. If an executor is stalled before it registers, it aborts at its first renewal. Setup work can run again in the retry; provider work cannot. - Upgrade safety: no persisted shape changes. The reaper reads the same fields (`executionStage`, `controllerBootId`, process ids) that older releases write. Runs that older code already parked keep their hold and their working Retry. - Runs that reached `dispatching`, recorded a process, or have no controller stamp keep the current behavior. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use, shell, 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 (the code comment carries the contract) - [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 --- .../heartbeat-process-recovery.test.ts | 64 +++++++++++++++++++ server/src/services/heartbeat/recovery.ts | 5 +- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 74a0803bf67..559d9890075 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -3557,6 +3557,70 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { expect(mockAdapterExecute).not.toHaveBeenCalled(); }); + it.each([ + ["an assignment", {}], + ["a due monitor", { wakeReason: "issue_monitor_due" }], + ] as const)("retries %s run whose lease this process lost before adapter dispatch", async (_label, contextSnapshot) => { + const { companyId, runId, issueId } = await seedRunFixture({ + adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy", contextSnapshot, + }); + await db.update(heartbeatRuns).set({ + controllerBootId: controllerLeases.legacyControllerBootId, + controllerProcess: currentControllerProcessStamp(), + controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`, + executionStage: "preparing", + runnerProfileJson: { + adapterDispatch: { adapterType: "paperclip_runner" }, + remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", epoch: 6, state: "prepared", + leaseId: randomUUID(), providerLeaseId: randomUUID(), workspaceId: randomUUID(), + remoteCwd: "/home/daytona/paperclip-workspace", snapshotId: randomUUID() }, + }, + }).where(eq(heartbeatRuns.id, runId)); + + const heartbeat = heartbeatService(db); + expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 1, runIds: [runId] }); + + const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost", + error: "Process lost -- server may have restarted; retrying once" }); + expect(reaped?.resultJson).toMatchObject({ + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true }, + }); + expect(await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId), + ))).toEqual([expect.objectContaining({ status: "scheduled_retry" })]); + await heartbeat.reapOrphanedRuns(); + expect(await db.select().from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([]); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + }); + + it("keeps a run this process dispatched held for reconciliation after its lease lapses", async () => { + const { companyId, runId, issueId } = await seedRunFixture({ + adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy", + }); + await db.update(heartbeatRuns).set({ + controllerBootId: controllerLeases.legacyControllerBootId, + controllerProcess: currentControllerProcessStamp(), + controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`, + executionStage: "dispatching", + }).where(eq(heartbeatRuns.id, runId)); + + await heartbeatService(db).reapOrphanedRuns(); + + const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost" }); + expect(reaped?.resultJson).not.toHaveProperty("executionRecovery"); + expect(await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId), + ))).toEqual([]); + expect(await db.select().from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([ + expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }), + ]); + }); + it("keeps a lost preparation from an older build without a controller stamp in the charged lane", async () => { const { companyId, runId } = await seedRestartOrphanedLegacySetup("preparing"); await db.update(heartbeatRuns).set({ runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }) diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index b6482a6bc92..f6ea8aa8dae 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -2660,8 +2660,8 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD continue; } // A legacy controller persists "dispatching" in the same lease renewal - // that admits the adapter. An expired lease from another boot that is - // still "preparing" proves a restart stopped setup before provider work. + // that admits the adapter. An expired lease that is still "preparing" + // proves setup stopped before provider work. // Use the state committed with the revocation, not the earlier snapshot: // the old controller may have dispatched before its lease expired. // The revocation matched the snapshot's boot ID before replacing it. @@ -2669,7 +2669,6 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD run.runtimeMode === "legacy" && revokedState.executionStage === "preparing" && !!run.controllerBootId && - run.controllerBootId !== legacyControllerBootId && !revokedState.processPid && !revokedState.processGroupId; const shouldRetry = From a46b9ac7242b9ddcb8db8159be489742a725e9cb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:57:03 -0600 Subject: [PATCH 5/5] fix(native): wait out an ACP usage limit's reported reset, then Retry the task (#20692) 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 (Paperclip Runner with an ACP harness, such as Claude) can stop because the provider account runs out of its usage allowance > - The ACP harness reports this as a "terminal limit failure". Paperclip blocked the task behind a board hold that called the session state ambiguous, and the only way forward was a manual Retry > - The provider also says when the limit resets, for example "resets Nov 12, 6pm (UTC)" for a weekly limit. Paperclip read only clock-only resets ("resets 2am"), so the agent-level wait fell back to one hour. Each later wake for the agent then hit the limit again and blocked another task > - This pull request reads calendar resets, says on the hold when the limit resets, and requests the task's Retry itself at that time when the reset is reported and bounded > - The benefit is that a usage limit no longer needs a person to click Retry, and the agent's other tasks wait instead of failing one by one ## Linked Issues or Issue Description **What happened?** A native ACP run failed with `native_provider_usage_limit` ("ACP agent reported a terminal limit failure. You've hit your weekly limit · resets Nov 12, 6pm (UTC)"). The task went to `blocked` with a board-owned hold. The hold said "Inspect the original provider failure and explicitly resolve the ambiguous session state". Nothing resumed the task after the reset. The agent-level `provider_limit_wait` recorded "no reset time was reported, so Paperclip waits one hour", so every hour another wake dispatched, hit the limit, and blocked another task. In one 48-hour window on a staging instance, this blocked 7 tasks for one agent. **What did you expect?** When the provider reports a bounded reset, the task waits and continues after the reset, like the existing `provider_limit_wait` path. When the reset is unknown, the task fails with a clear message and a working Retry. **Steps to reproduce** 1. Run a native ACP agent until its provider reports a weekly or session limit with a reset time. 2. Look at the task: it is blocked with an "ambiguous session state" hold. 3. Wait past the reported reset: the task stays blocked until a person clicks Retry. Refs #20666 (other recovery work in the same staging census; not changed here) ## What Changed - `provider-quota-reset.ts`: parse calendar resets such as "resets Nov 12, 6pm (UTC)", "resets Jul 17th at 4:30 PM (America/Chicago)" and "Resets on August 2, 9am (UTC)". A past date rolls into next year. An impossible date (Nov 31) is refused. Clock-only parsing is unchanged. This also fixes the agent-level `provider_limit_wait` reset and the legacy `provider_quota` reset for these messages. - New `native-runtime/provider-limit-resume.ts`: - `readNativeUsageLimitReset` reads the reset only from the run's own durable events. The last turn event must be a provider-observed `turn.failed` with a `rate_limit` or `quota_exhausted` provider failure, and the reset must be at most eight days out. - `requestProviderLimitResumeRetry` asks for the task's Retry (`requestTaskRetry`, `initiatedBy: "provider_limit_reset"`) on behalf of the user who requested the run, or the run's accountable user for automatic wakes. It is idempotent per run and records its outcome on the hold. At most three automatic Retries follow one another without a successful run. - `registerProviderLimitResumeWork` is a scoped deadline owner (shared work scheduler, no polling). Each active usage-limit hold is due at its reset. Startup rebuilds it from the holds, and the executor notifies it in the hold's transaction. - `native-session-executor.ts`: for a terminal usage limit, the hold and run failure detail say when the limit resets and whether Paperclip retries then, instead of "ambiguous session state". The evidence records `providerLimitResetAt`. - `task-retry.ts`: accept `initiatedBy: "provider_limit_reset"`. Its activity is recorded as system actor `provider-limit-reset` on behalf of the user, like `restart_recovery`. - `doc/execution-semantics.md`: document the wait and its limits. Previous-release story: holds saved by the previous release carry forward. At startup the owner reads each active `native_provider_usage_limit` hold. It rewrites the hold's message with the reset when the reset is known and still ahead, and it requests the Retry at the reset. Holds whose reset is unknown, more than a day in the past, or that have no accountable user keep their Retry and are recorded as not requested, so they are not read again. ## Verification - `npx vitest run server/src/services/provider-quota-reset.test.ts` — 4 tests. Three fail on `origin/master` code (calendar resets return `null`), all pass with this change. - `npx vitest run server/src/services/native-runtime/native-provider-capacity.integration.test.ts` — 5 tests on embedded Postgres: - the existing usage-terminal test (both replay modes) still blocks with a Retry, and no automatic Retry is requested without a reported reset; - "waits for a reported usage-limit reset and then requests the task's Retry once": the hold says when the limit resets, an old-release hold is rewritten, nothing starts before the reset, one Retry receipt is created for the accountable user at the reset, and a second pass does nothing. Fails on `origin/master` executor code; - "starts the Retry from the hold's own deadline": a real delivery coordinator rebuilds the deadline from the hold and calls Retry dispatch once, after the reset; - "leaves a visible Retry when no user is accountable for the run". Fails on `origin/master` executor code. - Focused regression suites pass (642 tests): `task-retry`, `quarantined-task-retry`, `heartbeat-native-restart-suspension`, `native-startup-retry.integration`, `provider-failure-classification`, `heartbeat-provider-limit-wait`, `deferred-execution-receipt-work`, `chat-run-publications`, `native-runner-restart-recovery.integration`, `native-remote-retry-admission`. - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. - `pnpm verify` selected a broad run (exit 2, because the docs file is a global CI input). CI supplies the broad coverage. ## Risks - The automatic Retry uses the accountable user's authority for automatic (system) wakes. It is the same Retry the hold already offered that user, and dispatch still checks Retry authority, stop proof, saved work and action reconciliation. It is never broader than a click. - A provider that keeps reporting resets that do not restore capacity gets at most three automatic Retries in a row; then the Retry stays visible. - The deadline owner reads all active usage-limit holds at startup (limit 500 rows). The number of such holds is small. - Not changed: the agent-level wait still holds new wakes for at most one day, as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, read-only staging API reads). Extended reasoning enabled. ## 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 --- doc/execution-semantics.md | 21 +- .../server-startup-feedback-export.test.ts | 8 + server/src/index.ts | 7 +- .../services/delivery-work-notifications.ts | 1 + server/src/services/heartbeat.ts | 8 + .../heartbeat/restart-interrupted-turn.ts | 6 +- ...tive-provider-capacity.integration.test.ts | 662 +++++++++++++----- .../native-runtime/native-session-executor.ts | 25 +- .../native-runtime/provider-limit-resume.ts | 284 ++++++++ .../src/services/provider-quota-reset.test.ts | 43 ++ server/src/services/provider-quota-reset.ts | 77 +- .../provider-failure-classification.test.ts | 11 + server/src/services/recovery/service.ts | 3 +- server/src/services/task-retry.ts | 28 +- 14 files changed, 945 insertions(+), 239 deletions(-) create mode 100644 server/src/services/native-runtime/provider-limit-resume.ts create mode 100644 server/src/services/provider-quota-reset.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 4e604ccd82b..6c2c318e36b 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3062,9 +3062,28 @@ account at once. ACP harnesses report an exhausted allowance as a generic terminal limit failure; Runner adds the provider's typed session-failure title, and only a rate-limit or quota title becomes `rate_limit` or `quota_exhausted`. Context, turn and configured budget limits stay ordinary terminal failures. A -reset clock in the provider's wording, such as "resets 2am (UTC)", is used as +reset clock in the provider's wording, such as "resets 2am (UTC)", or a +calendar reset such as a weekly limit's "resets Nov 12, 6pm (UTC)", is used as the reset time. +A native run whose provider ends a turn with an exhausted allowance +(`native_provider_usage_limit`) still blocks its task with a recovery action. +When the run's last turn event is a provider-observed `turn.failed` that reports +a reset within eight days, the action says when the limit resets, and at that +time Paperclip requests the task's Retry itself, on behalf of the user who +requested the run or, for automatic wakes, the run's accountable user. That is +the same Retry the user would click: admission keeps every gate (stop proof, +saved-work recovery and action reconciliation), so it never starts work a +user's Retry could not. The request is idempotent per run, and at most three +automatic Retries follow one another without a successful run between them. +A hold whose reset is more than eight days out (for example a monthly limit) +still names its reset but leaves the Retry to the user. A hold whose reset is +unknown, more than a day in the past, or that has no accountable user keeps its +visible Retry, and its message says why. A connected chat conversation's Retry +is prepared through the chat service, as a user's is. The +reset deadline is rebuilt from the active holds at startup, so holds saved by an +earlier release are covered too. + An ingress endpoint failure can use that same bounded retry only when the environment provider returns a structured HTTP 429 or 5xx failure and the complete, encrypted controller checkpoint proves that this exact run never diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 944eb1dcc49..b7067d220fc 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -159,6 +159,7 @@ const { registerIssueStateRecoveryWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(), watchdogs: { reconciliationSnapshot: () => ({ revision: "startup-watchdogs:1", reconciled: true }), stop: vi.fn(async () => {}) } })), registerDeferredReceiptWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })), + registerProviderLimitResumeWork: vi.fn((_coordinator: unknown, _canRun: () => boolean, _prepareChatRetry?: () => unknown) => ({ ready: Promise.resolve() })), registerRunDispatchWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(), retries: { reconciliationSnapshot: () => ({ revision: "startup-retries:1", reconciled: true }), stop: vi.fn(async () => {}) } })), registerScheduledRetryCancellationWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })), @@ -1048,7 +1049,14 @@ describe("startServer feedback export wiring", () => { expect(heartbeatServiceMock.registerActiveRunSilenceWork).toHaveBeenCalledTimes(enabled ? 1 : 0); expect(heartbeatServiceMock.registerRunDispatchWork).toHaveBeenCalledTimes(enabled ? 1 : 0); expect(heartbeatServiceMock.registerDeferredReceiptWork).toHaveBeenCalledTimes(enabled ? 1 : 0); + expect(heartbeatServiceMock.registerProviderLimitResumeWork).toHaveBeenCalledTimes(enabled ? 1 : 0); expect(heartbeatServiceMock.resumeQueuedRuns).not.toHaveBeenCalled(); + if (enabled) { + const [limitCoordinator, limitAdmitted, chatRetry] = heartbeatServiceMock.registerProviderLimitResumeWork.mock.calls[0]; + expect(limitCoordinator).toBe((await createAppMock.mock.results.at(-1)!.value).locals.deliveryWork); + expect(limitAdmitted()).toBe(true); + expect(typeof chatRetry).toBe("function"); + } if (enabled) { const [coordinator, admitted] = heartbeatServiceMock.registerRunDispatchWork.mock.calls[0]; const app = await createAppMock.mock.results.at(-1)!.value; diff --git a/server/src/index.ts b/server/src/index.ts index 8e785370055..dfa92d5a9ad 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -951,7 +951,8 @@ async function startServerWithDatabaseTeardown( logger.warn({ scope: cloudQualification.scope, blockerCodes: cloudQualification.blockers.map((blocker) => blocker.code) }, "Cloud configuration and package qualification has blockers"); } const idleDeadlineOwners: IdleDeadlineOwners = {}; - // createApp fills the chat Retry callback; the continuation worker reads it. + // createApp fills the chat Retry callback; the continuation and + // provider-limit Retry workers read it. const budgetResumeDelivery: BudgetResumeDelivery = {}; const app = await createApp(db as any, { idleDeadlineOwners, @@ -1771,6 +1772,10 @@ async function startServerWithDatabaseTeardown( } if (config.heartbeatSchedulerEnabled) await heartbeat.registerDeferredReceiptWork(deliveryWork, () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready; + // A connected conversation's Retry needs the chat callback createApp registered. + if (config.heartbeatSchedulerEnabled) await heartbeat.registerProviderLimitResumeWork(deliveryWork, + () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped, + () => budgetResumeDelivery.prepareChatRetry).ready; if (config.heartbeatSchedulerEnabled) { const work = heartbeat.registerRunDispatchWork(deliveryWork, () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped); diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index c8ecc5a9ba6..cd0da16ca72 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -58,6 +58,7 @@ export const DELIVERY_QUEUES = { scheduledRetryCancellation: "scheduled-retry-cancellation", executionFinalization: "execution-finalization", workspaceRecovery: "workspace-recovery", + providerLimitResume: "provider-limit-resume", executionReplacement: "execution-replacement", executionContinuation: "execution-continuation", executionStatus: "execution-status", diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 7724e412126..baaaace2ea1 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -9,6 +9,7 @@ import { isContextCompactionRun } from "./context-compaction.js"; import { isUnstartedTaskQuestionAnswer } from "./unstarted-task-question-answer.js"; import { isVerifiedDependencyInteractionResponse } from "./queued-interaction-response.js"; import { registerDeferredReceiptWork } from "./heartbeat/deferred-receipt-work.js"; +import { registerProviderLimitResumeWork, type PrepareChatRetry } from "./native-runtime/provider-limit-resume.js"; import { reconcileTaskChatRetryReceipts } from "./task-retry.js"; import { registerIssueRecoveryWork } from "./recovery/work.js"; import { registerRunDispatchWork } from "./heartbeat/dispatch-work.js"; @@ -4522,6 +4523,13 @@ export function heartbeatService( }, }, () => canRun() && readTaskDrain(new Date()) === null), readIdleWatchdogSchedule: taskWatchdogs.readIdleSchedule, + registerProviderLimitResumeWork: (coordinator: Parameters[1], canRun: () => boolean, + prepareChatRetry?: () => PrepareChatRetry | undefined) => + registerProviderLimitResumeWork(db, coordinator, { + resume: (companyId, requestId) => runControl.resumeTaskRetry(companyId, requestId), + schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed, + prepareChatRetry, + }, () => canRun() && readTaskDrain(new Date()) === null), registerIssueStateRecoveryWork: (coordinator: Parameters[1], canRun: () => boolean) => registerIssueRecoveryWork(db, coordinator, { stranded: scope => reconcileStrandedAssignedIssues({ ...scope, skipExternalConversationSettlement: true, skipRelatedRecovery: true }), diff --git a/server/src/services/heartbeat/restart-interrupted-turn.ts b/server/src/services/heartbeat/restart-interrupted-turn.ts index df89505a90e..a1458a27826 100644 --- a/server/src/services/heartbeat/restart-interrupted-turn.ts +++ b/server/src/services/heartbeat/restart-interrupted-turn.ts @@ -19,8 +19,8 @@ function isReattachmentLoss(error: string | null): boolean { return error !== null && REATTACHMENT_LOST_ERRORS.some(code => error === code || error.startsWith(`${code}: `)); } -const TURN_STARTED_EVENTS = ["turn.submitted", "turn.started", "turn.accepted"]; -const TURN_SETTLED_EVENTS = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]; +export const TURN_STARTED_EVENTS = ["turn.submitted", "turn.started", "turn.accepted"]; +export const TURN_SETTLED_EVENTS = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]; const asRecord = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; @@ -29,7 +29,7 @@ const asRecord = (value: unknown): Record => * A driver that lost its event stream records `providerTerminalObserved: false` * (on the event or its stored PRP source): the real outcome is unknown, and * another turn could repeat work that already happened. */ -function isProvenTurnSettlement(event: { eventType: string; payload: unknown }) { +export function isProvenTurnSettlement(event: { eventType: string; payload: unknown }) { if (!TURN_SETTLED_EVENTS.includes(event.eventType)) return false; const payload = asRecord(event.payload); return payload.providerTerminalObserved !== false && diff --git a/server/src/services/native-runtime/native-provider-capacity.integration.test.ts b/server/src/services/native-runtime/native-provider-capacity.integration.test.ts index ee32b33e81a..d3a9a3b4167 100644 --- a/server/src/services/native-runtime/native-provider-capacity.integration.test.ts +++ b/server/src/services/native-runtime/native-provider-capacity.integration.test.ts @@ -1,8 +1,11 @@ import { randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, + agentWakeupRequests, + chatConversations, + chatEndpoints, companies, completionContracts, createDb, @@ -11,6 +14,8 @@ import { issueRecoveryActions, issues, nativeRunFinalizations, + toolApplications, + toolConnections, } from "@paperclipai/db"; import type { ControlPlanePort, @@ -31,6 +36,8 @@ import { executePaperclipNativeSession } from "./native-session-executor.js"; import { buildNativeCompletionContract } from "./completion-contracts.js"; import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js"; import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { PROVIDER_LIMIT_RESUME_KEY_PREFIX, registerProviderLimitResumeWork, requestProviderLimitResumeRetry } from "./provider-limit-resume.js"; +import { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; describe("native provider capacity failure persistence", () => { let temporary: Awaited>; @@ -62,125 +69,211 @@ describe("native provider capacity failure persistence", () => { await temporary?.cleanup(); }); + /** Runs one native session whose provider ends its turn with `payload`. */ + async function failTurn(options: { + payload: Record; + replayed?: boolean; + responsibleUserId?: string | null; + }) { + const issueId = randomUUID(); + const runId = randomUUID(); + const [issue] = await db + .insert(issues) + .values({ + id: issueId, + companyId, + title: "Reply after a capacity failure", + status: "in_progress", + workMode: "standard", + assigneeAgentId: agentId, + }) + .returning(); + const [run] = await db + .insert(heartbeatRuns) + .values({ + id: runId, + companyId, + agentId, + status: "running", + runtimeMode: "native", + nativeIssueId: issueId, + invocationSource: "assignment", + triggerDetail: "system", + contextSnapshot: { issueId }, + responsibleUserId: options.responsibleUserId ?? null, + }) + .returning(); + await db + .update(issues) + .set({ executionRunId: runId }) + .where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ + db, + run, + issue, + environmentLeaseId: randomUUID(), + }); + const [contract] = await db + .select() + .from(completionContracts) + .where(eq(completionContracts.issueId, issueId)); + const completionInput = buildNativeCompletionContract(issue, { + revision: contract.revision, + }); + expect(completionInput).toEqual(contract.contractJson); + await db.insert(nativeRunFinalizations).values({ + runId, + companyId, + issueId, + phase: "observed", + }); + // A real terminal follows provider session establishment. Keep the + // recovery evidence explicit; this must not be a bootstrap retry. + await db + .update(heartbeatRuns) + .set({ + runnerProfileJson: { + sessionCheckpoint: { + providerSessionId: "capacity-test-provider-session", + providerIdentity: { threadId: "capacity-test-thread" }, + }, + }, + }) + .where(eq(heartbeatRuns.id, runId)); + + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { + companyId, + runId, + issueId, + agentId, + executionWorkspaceId: runId, + }, + provider: { kind: "codex", model: "gpt-5.6-luna" }, + task: { + identifier: issueId, + title: issue.title, + description: null, + prompt: "Reply to the current message.", + workMode: "standard", + }, + workspace: { + cwd: "/tmp", + repoUrl: null, + repoRef: null, + branchName: null, + }, + session: { + normalizedSessionId: native.normalizedSessionId, + driverKind: "codex_app_server", + protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + }, + completionContract: { + id: contract.id, + sha256: contract.canonicalSha256, + schemaVersion: "paperclip.completion-contract.v1", + contract: completionInput, + }, + interactionResponses: [], + credentialBindings: [], + }; + const event: PrpEvent = { + schema: "paperclip.prp.event.v1", + runId, + normalizedSessionId: native.normalizedSessionId, + turnId: native.turnId, + sourceInstanceId: native.runnerInstanceId, + sourceEventId: "capacity-terminal", + sourceSeq: 1, + sourceKind: "runner", + eventType: "turn.failed", + schemaVersion: 1, + priority: 0, + emittedAt: new Date().toISOString(), + payload: options.payload, + }; + const openInput = { + identity: { + companyId, + issueId, + runId, + agentId, + sessionId: native.normalizedSessionId, + }, + backendKind: "mock" as const, + sourceInstanceId: native.runnerInstanceId, + }; + if (options.replayed) { + // Model a controller crash after the event commit but before its + // observational callback or failure coordinator could run. + const priorPort = new PaperclipControlPlanePort(db, { + companyId, + issueId, + runId, + agentId, + sessionId: native.normalizedSessionId, + sourceInstanceId: native.runnerInstanceId, + controlPlaneSourceInstanceId: "prior-controller", + completionContractId: contract.id, + completionContractSha256: contract.canonicalSha256, + }); + await priorPort.openRun(openInput); + expect((await priorPort.appendEvent(event)).disposition).toBe( + "committed", + ); + } + provider.execute + .mockReset() + .mockImplementation( + async (executeOptions: { controlPlane: ControlPlanePort }) => { + await executeOptions.controlPlane.openRun(openInput); + const appended = await executeOptions.controlPlane.appendEvent(event); + expect(appended.disposition).toBe( + options.replayed ? "duplicate" : "committed", + ); + // Production reports the provider terminal through the event, not by + // pattern-matching this exception's arbitrary message. + throw new Error("provider turn stopped"); + }, + ); + await expect( + executePaperclipNativeSession({ + db, + execution, + runnerInstanceId: native.runnerInstanceId, + backend: { + descriptor: async () => { + throw new Error( + "Unexpected provider descriptor call in capacity test", + ); + }, + openSession: async () => { + throw new Error( + "Unexpected provider session call in capacity test", + ); + }, + }, + }), + ).rejects.toThrow("provider turn stopped"); + expect(provider.execute).toHaveBeenCalledTimes(1); + return { runId, issueId, sourceEventId: event.sourceEventId }; + } + + async function holdFor(issueId: string) { + const [recovery] = await db + .select() + .from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId)); + return recovery; + } + it.each([false, true])( "stops automatic retries for a durable usage terminal (replayed=%s)", async (replayed) => { - const issueId = randomUUID(); - const runId = randomUUID(); - const [issue] = await db - .insert(issues) - .values({ - id: issueId, - companyId, - title: "Reply after a capacity failure", - status: "in_progress", - workMode: "standard", - assigneeAgentId: agentId, - }) - .returning(); - const [run] = await db - .insert(heartbeatRuns) - .values({ - id: runId, - companyId, - agentId, - status: "running", - runtimeMode: "native", - nativeIssueId: issueId, - invocationSource: "assignment", - triggerDetail: "system", - contextSnapshot: { issueId }, - }) - .returning(); - await db - .update(issues) - .set({ executionRunId: runId }) - .where(eq(issues.id, issueId)); - const native = await prepareNativeHeartbeatRun({ - db, - run, - issue, - environmentLeaseId: randomUUID(), - }); - const [contract] = await db - .select() - .from(completionContracts) - .where(eq(completionContracts.issueId, issueId)); - const completionInput = buildNativeCompletionContract(issue, { - revision: contract.revision, - }); - expect(completionInput).toEqual(contract.contractJson); - await db.insert(nativeRunFinalizations).values({ - runId, - companyId, - issueId, - phase: "observed", - }); - // A real terminal follows provider session establishment. Keep the - // recovery evidence explicit; this must not be a bootstrap retry. - await db - .update(heartbeatRuns) - .set({ - runnerProfileJson: { - sessionCheckpoint: { - providerSessionId: "capacity-test-provider-session", - providerIdentity: { threadId: "capacity-test-thread" }, - }, - }, - }) - .where(eq(heartbeatRuns.id, runId)); - - const execution: NativeExecutionInputV1 = { - schema: "paperclip.native-execution-input.v1", - binding: { - companyId, - runId, - issueId, - agentId, - executionWorkspaceId: runId, - }, - provider: { kind: "codex", model: "gpt-5.6-luna" }, - task: { - identifier: issueId, - title: issue.title, - description: null, - prompt: "Reply to the current message.", - workMode: "standard", - }, - workspace: { - cwd: "/tmp", - repoUrl: null, - repoRef: null, - branchName: null, - }, - session: { - normalizedSessionId: native.normalizedSessionId, - driverKind: "codex_app_server", - protocolVersion: 1, - lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, - }, - completionContract: { - id: contract.id, - sha256: contract.canonicalSha256, - schemaVersion: "paperclip.completion-contract.v1", - contract: completionInput, - }, - interactionResponses: [], - credentialBindings: [], - }; - const event: PrpEvent = { - schema: "paperclip.prp.event.v1", - runId, - normalizedSessionId: native.normalizedSessionId, - turnId: native.turnId, - sourceInstanceId: native.runnerInstanceId, - sourceEventId: "capacity-terminal", - sourceSeq: 1, - sourceKind: "runner", - eventType: "turn.failed", - schemaVersion: 1, - priority: 0, - emittedAt: new Date().toISOString(), + const { runId, issueId, sourceEventId } = await failTurn({ + replayed, payload: { status: "failed", error: { @@ -188,72 +281,7 @@ describe("native provider capacity failure persistence", () => { message: "Private account metadata", }, }, - }; - const openInput = { - identity: { - companyId, - issueId, - runId, - agentId, - sessionId: native.normalizedSessionId, - }, - backendKind: "mock" as const, - sourceInstanceId: native.runnerInstanceId, - }; - if (replayed) { - // Model a controller crash after the event commit but before its - // observational callback or failure coordinator could run. - const priorPort = new PaperclipControlPlanePort(db, { - companyId, - issueId, - runId, - agentId, - sessionId: native.normalizedSessionId, - sourceInstanceId: native.runnerInstanceId, - controlPlaneSourceInstanceId: "prior-controller", - completionContractId: contract.id, - completionContractSha256: contract.canonicalSha256, - }); - await priorPort.openRun(openInput); - expect((await priorPort.appendEvent(event)).disposition).toBe( - "committed", - ); - } - provider.execute - .mockReset() - .mockImplementation( - async (options: { controlPlane: ControlPlanePort }) => { - await options.controlPlane.openRun(openInput); - const appended = await options.controlPlane.appendEvent(event); - expect(appended.disposition).toBe( - replayed ? "duplicate" : "committed", - ); - // Production reports the provider terminal through the event, not by - // pattern-matching this exception's arbitrary message. - throw new Error("provider turn stopped"); - }, - ); - await expect( - executePaperclipNativeSession({ - db, - execution, - runnerInstanceId: native.runnerInstanceId, - backend: { - descriptor: async () => { - throw new Error( - "Unexpected provider descriptor call in capacity test", - ); - }, - openSession: async () => { - throw new Error( - "Unexpected provider session call in capacity test", - ); - }, - }, - }), - ).rejects.toThrow("provider turn stopped"); - - expect(provider.execute).toHaveBeenCalledTimes(1); + }); const [coordinator] = await db .select() .from(nativeRunFinalizations) @@ -271,10 +299,7 @@ describe("native provider capacity failure persistence", () => { .from(heartbeatRuns) .where(eq(heartbeatRuns.id, runId)); expect(failedRun.errorCode).toBe("native_provider_usage_limit"); - const [recovery] = await db - .select() - .from(issueRecoveryActions) - .where(eq(issueRecoveryActions.sourceIssueId, issueId)); + const recovery = await holdFor(issueId); expect(recovery).toMatchObject({ ownerType: "board", cause: "native_provider_usage_limit", @@ -294,8 +319,269 @@ describe("native provider capacity failure persistence", () => { .from(heartbeatRunEvents) .where(eq(heartbeatRunEvents.runId, runId)); expect( - events.filter((row) => row.sourceEventId === event.sourceEventId), + events.filter((row) => row.sourceEventId === sourceEventId), ).toHaveLength(1); + // No reset was reported, so nothing retries the task by itself. + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: recovery.id })) + .resolves.toEqual({ requested: false, reason: "reset_unknown" }); }, ); + + /** The ACP harness's weekly-limit terminal, as staging recorded it (PAP-1057). */ + function weeklyLimit(resetAt: Date) { + const month = resetAt.toLocaleString("en-US", { month: "short", timeZone: "UTC" }); + const hour = resetAt.getUTCHours(); + const clock = `${hour % 12 || 12}${hour < 12 ? "am" : "pm"}`; + return { + status: "failed", + error: { + code: "RUNTIME", + message: "ACP agent reported a terminal limit failure.", + providerFailure: { + schema: "paperclip.provider-failure.v1", + provider: "anthropic", + phase: "turn", + category: "quota_exhausted", + retryability: "requires_action", + message: `ACP agent reported a terminal limit failure.\nYou've hit your weekly limit · resets ${month} ${resetAt.getUTCDate()}, ${clock} (UTC)`, + }, + }, + }; + } + + it("waits for a reported usage-limit reset and then requests the task's Retry once", async () => { + const resetAt = new Date(Date.now() + 2 * 24 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const userId = `user-${randomUUID()}`; + const { runId, issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + + const hold = await holdFor(issueId); + expect(hold).toMatchObject({ cause: "native_provider_usage_limit", + evidence: expect.objectContaining({ providerLimitResetAt: resetAt.toISOString() }) }); + // The hold says when work resumes, not that its session state is ambiguous. + expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. ` + + "Paperclip will retry this task then; Retry starts it sooner if usage capacity is already restored."); + + // A hold saved by the previous release names no reset and calls the state ambiguous. + const { providerLimitResetAt: _reset, ...oldEvidence } = hold.evidence; + await db.update(issueRecoveryActions).set({ evidence: oldEvidence, nextAction: "Inspect the original provider failure " + + "and explicitly resolve the ambiguous session state; do not open a replacement provider session." }) + .where(eq(issueRecoveryActions.id, hold.id)); + + // Before the reset nothing starts; the owner keeps the reset as its deadline + // and tells the reader when work resumes. + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id })) + .resolves.toEqual({ requested: false, waitUntil: resetAt }); + expect(await holdFor(issueId)).toMatchObject({ nextAction: hold.nextAction, + evidence: expect.objectContaining({ providerLimitResetAt: resetAt.toISOString() }) }); + + // At the reset Paperclip asks for the same Retry the accountable user would. + const afterReset = new Date(resetAt.getTime() + 1000); + const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset); + expect(outcome).toMatchObject({ requested: true }); + const [receipt] = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.idempotencyKey, `task-retry:provider-limit-reset:${runId}`))); + expect(receipt).toMatchObject({ reason: "task_retry", requestedByActorType: "user", requestedByActorId: userId, + status: "deferred_issue_execution", payload: expect.objectContaining({ issueId, + taskRetry: expect.objectContaining({ sourceRunId: runId, actorId: userId }) }) }); + expect((await holdFor(issueId)).evidence.providerLimitResume).toMatchObject({ state: "requested", + requestId: receipt.id, resetAt: resetAt.toISOString() }); + + // A second pass never requests another Retry for the same hold. + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "not_waiting" }); + const receipts = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry"), + eq(agentWakeupRequests.agentId, agentId))); + expect(receipts.filter(row => (row.payload as Record).issueId === issueId)).toHaveLength(1); + }); + + it("starts the Retry from the hold's own deadline after a restart rebuilds it", async () => { + // A typed reset a few seconds out; the owner learns it only from durable rows. + const resetAt = new Date(Date.now() + 3000); + const payload = weeklyLimit(resetAt); + (payload.error.providerFailure as Record).retryAt = resetAt.toISOString(); + const userId = `user-${randomUUID()}`; + const { issueId } = await failTurn({ payload, responsibleUserId: userId }); + const hold = await holdFor(issueId); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + onError: error => { errors.push(error); } }); + const resume = vi.fn(async () => undefined); + try { + const worker = registerProviderLimitResumeWork(db, coordinator, + { resume, schedulingSuppressed: async () => false }, () => true); + await worker.ready; + // Nothing starts before the reset. + expect(resume).not.toHaveBeenCalled(); + await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1), { timeout: 20_000, interval: 200 }); + const [receipt] = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry"), + eq(agentWakeupRequests.requestedByActorId, userId))); + expect(resume).toHaveBeenCalledWith(companyId, receipt.id); + expect(Date.now()).toBeGreaterThanOrEqual(resetAt.getTime()); + expect((await holdFor(issueId)).evidence.providerLimitResume).toMatchObject({ state: "requested", requestId: receipt.id }); + expect(hold.id).toBe((await holdFor(issueId)).id); + } finally { + await coordinator.stop(); + } + expect(errors).toEqual([]); + }, 30_000); + + it("leaves a visible Retry when no user is accountable for the run", async () => { + const resetAt = new Date(Date.now() + 3 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: null }); + const hold = await holdFor(issueId); + expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. ` + + "Retry the task after that time, or sooner if usage capacity is restored."); + const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, + new Date(resetAt.getTime() + 1000)); + expect(outcome).toEqual({ requested: false, reason: "no_accountable_user" }); + expect((await holdFor(issueId)).nextAction).toBe("Paperclip did not retry this task after the provider usage limit " + + "reset because no user is accountable for the run. Retry the task when usage capacity is available."); + }); + + it("prepares a connected chat conversation's Retry through the chat service", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const userId = `user-${randomUUID()}`; + const { runId, issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + // The task belongs to a restricted external chat conversation. + const [application] = await db.insert(toolApplications).values({ companyId, name: "Slack", type: "chat" }).returning(); + const connectionId = randomUUID(); + await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId: application!.id, uid: connectionId, + name: "Slack", transport: "chat_sdk", connectionPurpose: "channel" }); + const endpointId = randomUUID(); + await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "slack", publicId: endpointId, + assignedAgentId: agentId, status: "active", externalExecutionPolicy: "restricted" }); + await db.insert(chatConversations).values({ companyId, endpointId, issueId, externalConversationId: "channel", + externalThreadId: issueId, externalLabel: "#limits", state: "waiting" }); + const hold = await holdFor(issueId); + const chatActionId = randomUUID(); + const prepareChatRetry = vi.fn(async () => ({ actionId: chatActionId })); + const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id, prepareChatRetry }, + new Date(resetAt.getTime() + 1000)); + expect(outcome).toMatchObject({ requested: true }); + expect(prepareChatRetry).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + companyId, issueId, agentId, failedRunId: runId, initiatedByUserId: userId })); + const [receipt] = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.idempotencyKey, `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${runId}`))); + expect(receipt.payload).toMatchObject({ taskRetry: expect.objectContaining({ chatActionId }) }); + }); + + it("replaces the retry promise on every give-up path", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const afterReset = new Date(resetAt.getTime() + 1000); + // The failed run's terminal can no longer be read as a provider-observed reset. + const unreadable = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` }); + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, unreadable.runId)); + const unreadableHold = await holdFor(unreadable.issueId); + expect(unreadableHold.nextAction).toContain("Paperclip will retry this task then"); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: unreadableHold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "reset_unknown" }); + expect((await holdFor(unreadable.issueId)).nextAction).toBe("Paperclip did not retry this task after the provider " + + "usage limit reset because the provider's reset could no longer be read. Retry the task when usage capacity is available."); + // The hold's run no longer failed for the usage limit. + const changed = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` }); + await db.update(heartbeatRuns).set({ errorCode: "adapter_failed" }).where(eq(heartbeatRuns.id, changed.runId)); + const changedHold = await holdFor(changed.issueId); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: changedHold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "source_run_mismatch" }); + expect((await holdFor(changed.issueId)).nextAction).toBe("Paperclip did not retry this task after the provider " + + "usage limit reset because the failed run no longer matches this hold. Retry the task when usage capacity is available."); + }); + + it("stops after three automatic Retries in a row and counts again after a successful run", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const afterReset = new Date(resetAt.getTime() + 1000); + const userId = `user-${randomUUID()}`; + const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + const hold = await holdFor(issueId); + // Earlier usage-limit Retries on this task, none followed by a success. + const earlierRetry = (task: string) => ({ companyId, agentId, source: "on_demand", triggerDetail: "manual", + reason: "task_retry", status: "completed", idempotencyKey: `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${randomUUID()}`, + requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: task }, + requestedAt: new Date(Date.now() - 60_000) }); + // Two in a row still leave this one. + await db.insert(agentWakeupRequests).values([earlierRetry(issueId), earlierRetry(issueId)]); + const [third] = await db.insert(agentWakeupRequests).values(earlierRetry(issueId)).returning(); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "automatic_retry_budget_used" }); + expect((await holdFor(issueId)).nextAction).toBe("Paperclip did not retry this task after the provider usage limit " + + "reset because three automatic Retries in a row did not restore usage. Retry the task when usage capacity is available."); + expect(third.id).toBeTruthy(); + + // A successful run on the task after earlier Retries restores the budget. + const second = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + await db.insert(agentWakeupRequests).values([earlierRetry(second.issueId), earlierRetry(second.issueId), + earlierRetry(second.issueId)]); + await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", runtimeMode: "native", + nativeIssueId: second.issueId, invocationSource: "assignment", triggerDetail: "system", + contextSnapshot: { issueId: second.issueId }, finishedAt: new Date(Date.now() - 1000), + createdAt: new Date(Date.now() - 10 * 60_000) }); + const secondHold = await holdFor(second.issueId); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: secondHold.id }, afterReset)) + .resolves.toMatchObject({ requested: true }); + }); + + it("rebuilds every waiting hold after a restart, past one page", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` }); + const hold = await holdFor(issueId); + // A hold saved before holds named their reset; it sorts after 600 others. + const { providerLimitResetAt: _reset, ...oldEvidence } = hold.evidence; + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)); + const otherCompanyId = randomUUID(); + await db.insert(companies).values({ id: otherCompanyId, name: "Other holds", issuePrefix: "OTH" }); + const otherIssues = Array.from({ length: 600 }, () => randomUUID()); + await db.insert(issues).values(otherIssues.map(id => ({ id, companyId: otherCompanyId, title: "Other", status: "in_progress" }))); + const { id: _id, companyId: _company, sourceIssueId: _issue, createdAt: _c, updatedAt: _u, ...template } = hold; + for (let page = 0; page < 6; page++) { + await db.insert(issueRecoveryActions).values(Array.from({ length: 100 }, (_, index) => ({ ...template, + companyId: otherCompanyId, sourceIssueId: otherIssues[page * 100 + index]!, + id: `00000000-0000-4000-8000-${String(page * 100 + index).padStart(12, "0")}`, + evidence: { ...oldEvidence, runId: randomUUID() } }))); + } + await db.insert(issueRecoveryActions).values({ ...hold, id: `ffffffff-ffff-4fff-bfff-${randomUUID().slice(-12)}`, + evidence: oldEvidence }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + onError: error => { errors.push(error); } }); + try { + const worker = registerProviderLimitResumeWork(db, coordinator, + { resume: vi.fn(async () => undefined), schedulingSuppressed: async () => false }, () => true); + await worker.ready; + // The hold past the first page reads its reset and records it. + await vi.waitFor(async () => expect((await holdFor(issueId)).evidence.providerLimitResetAt).toBe(resetAt.toISOString()), + { timeout: 25_000, interval: 250 }); + } finally { + await coordinator.stop(); + } + expect(errors).toEqual([]); + }, 40_000); + + it("reports a reset beyond the automatic wait without retrying by itself", async () => { + // A monthly limit, typed by the provider, three weeks out. + const resetAt = new Date(Date.now() + 21 * 24 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const payload = weeklyLimit(resetAt); + (payload.error.providerFailure as Record).retryAt = resetAt.toISOString(); + const userId = `user-${randomUUID()}`; + const { issueId } = await failTurn({ payload, responsibleUserId: userId }); + const hold = await holdFor(issueId); + expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. ` + + "Retry the task after that time, or sooner if usage capacity is restored."); + expect(hold.evidence).toMatchObject({ providerLimitResetAt: resetAt.toISOString() }); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, + new Date(resetAt.getTime() + 1000))).resolves.toEqual({ requested: false, reason: "reset_beyond_wait" }); + expect((await holdFor(issueId)).nextAction).toBe(hold.nextAction); + const receipts = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.requestedByActorId, userId))); + expect(receipts).toEqual([]); + }); }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index cc2d29953b0..7ed7a9692c6 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -12155,6 +12155,18 @@ async function executePaperclipNativeSessionAttempt( .from(heartbeatRuns).where(eq(heartbeatRuns.id, input.execution.binding.runId)) .then(rows => rows.some(row => nativeCheckpointRecordsCompletedTurn(row.runnerProfileJson, input.execution.binding.runId))) .catch(() => false); + // An exhausted provider allowance is not ambiguous session state: the + // provider ended its turn. Say when it resets and whether Paperclip will + // retry then. A failed read only loses that detail. + const providerLimit = sourceFailureCode === "native_provider_usage_limit" && phase === "terminal_failure" + ? await import("./provider-limit-resume.js").then(async ({ planProviderLimitResume, providerLimitNextAction }) => { + const plan = await planProviderLimitResume(input.db, input.execution.binding.runId); + return { plan, nextAction: providerLimitNextAction(plan) }; + }).catch((failure: unknown) => { + logger.warn({ err: failure, runId: input.execution.binding.runId }, "provider limit reset unavailable"); + return null; + }) + : null; const recoveryProjection = nativeSessionRecoveryProjection({ phase, failureCode, @@ -12222,9 +12234,12 @@ async function executePaperclipNativeSessionAttempt( providerEventsExist: recoveryEvidence.providerEventsExist, checkpointExists: recoveryEvidence.checkpointExists, ...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}), + ...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}), recoveryOwner: recoveryProjection.recoveryOwner, nextAction: - sourceFailureCode === "native_permission_declined" + providerLimit + ? providerLimit.nextAction + : sourceFailureCode === "native_permission_declined" ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." @@ -12458,6 +12473,9 @@ async function executePaperclipNativeSessionAttempt( .where(eq(issues.id, input.execution.binding.issueId)); } if (!stillOwnsTask) return; + // The hold's reset deadline belongs to the provider-limit owner. + if (providerLimit?.plan.automatic) await notifyDeliveryWork(tx, DELIVERY_QUEUES.providerLimitResume, + JSON.stringify({ companyId: input.execution.binding.companyId })); await issueRecoveryActionService( tx as unknown as Db, ).upsertSourceScoped({ @@ -12485,9 +12503,12 @@ async function executePaperclipNativeSessionAttempt( providerSessionEstablished: recoveryEvidence.providerSessionEstablished, ...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}), + ...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}), }, nextAction: - sourceFailureCode === "native_permission_declined" + providerLimit + ? providerLimit.nextAction + : sourceFailureCode === "native_permission_declined" ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." diff --git a/server/src/services/native-runtime/provider-limit-resume.ts b/server/src/services/native-runtime/provider-limit-resume.ts new file mode 100644 index 00000000000..82497b620ba --- /dev/null +++ b/server/src/services/native-runtime/provider-limit-resume.ts @@ -0,0 +1,284 @@ +import { and, asc, desc, eq, gt, inArray, isNull, like, sql } from "drizzle-orm"; +import { + agentWakeupRequests, + heartbeatRunEvents, + heartbeatRuns, + issueRecoveryActions, + issues, + type Db, +} from "@paperclipai/db"; +import { readProviderFailure } from "@paperclipai/shared"; +import { HttpError } from "../../errors.js"; +import { logger } from "../../middleware/logger.js"; +import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; +import { isProvenTurnSettlement, TURN_SETTLED_EVENTS, TURN_STARTED_EVENTS } from "../heartbeat/restart-interrupted-turn.js"; +import { parseProviderQuotaClockReset } from "../provider-quota-reset.js"; +import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; +import { requestTaskRetry } from "../task-retry.js"; + +/** The chat service's Retry callback, which a connected conversation's Retry needs. */ +export type PrepareChatRetry = NonNullable[0]["prepareChatRetry"]>; + +/** + * A native run whose provider ended its turn because the account's usage limit + * ran out. When the provider reported when the limit resets, Paperclip asks for + * the task's Retry itself at that time, as the accountable user would. Retry + * admission keeps every gate (stop proof, saved work, action reconciliation), + * so this never starts work a user's own Retry could not. + */ +export const NATIVE_PROVIDER_USAGE_LIMIT = "native_provider_usage_limit"; +/** Longer than a weekly limit's reset, so the reset is the only wait. */ +export const PROVIDER_LIMIT_RESUME_MAX_WAIT_MS = 8 * 24 * 60 * 60_000; +/** A reset older than this belongs to an incident nobody is waiting on. */ +const STALE_RESET_MS = 24 * 60 * 60_000; +/** Automatic Retries in a row without a successful run between them. */ +const MAX_AUTOMATIC_RESUMES = 3; +export const PROVIDER_LIMIT_RESUME_KEY_PREFIX = "provider-limit-reset:"; +const LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"]; + +const asRecord = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +/** The provider-reported failure on a settled turn event, raw or PRP-wrapped. */ +function providerFailureOf(payload: unknown) { + const direct = asRecord(asRecord(payload).error).providerFailure; + const wrapped = asRecord(asRecord(asRecord(asRecord(payload).prpEvent).payload).error).providerFailure; + return readProviderFailure(direct) ?? readProviderFailure(wrapped); +} + +export type ProviderLimitReset = { + resetAt: Date; observedAt: Date; + /** False for a reset further out than Paperclip waits by itself (a monthly limit). */ + withinAutomaticWait: boolean; +}; + +/** + * When the provider said the usage limit resets, from the run's own durable + * events. Null unless the last turn event is a provider-observed settlement + * reporting an exhausted allowance with a reset after it. + */ +export async function readNativeUsageLimitReset( + db: Pick, + run: { id: string; companyId: string }, +): Promise { + const [lastTurn] = await db.select({ eventType: heartbeatRunEvents.eventType, payload: heartbeatRunEvents.payload, + createdAt: heartbeatRunEvents.createdAt }) + .from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + inArray(heartbeatRunEvents.eventType, [...TURN_STARTED_EVENTS, ...TURN_SETTLED_EVENTS]), + )).orderBy(desc(heartbeatRunEvents.seq)).limit(1); + // An unsettled or unobserved turn may still be working: its outcome is unknown. + if (!lastTurn || lastTurn.eventType !== "turn.failed" || !isProvenTurnSettlement(lastTurn)) return null; + const failure = providerFailureOf(lastTurn.payload); + if (!failure || !LIMIT_CATEGORIES.includes(failure.category)) return null; + const observedAt = lastTurn.createdAt; + const typed = failure.retryAt ? new Date(failure.retryAt) : null; + const resetAt = typed && Number.isFinite(typed.getTime()) ? typed : parseProviderQuotaClockReset(failure.message, observedAt); + if (!resetAt || resetAt.getTime() <= observedAt.getTime()) return null; + return { resetAt, observedAt, + withinAutomaticWait: resetAt.getTime() - observedAt.getTime() <= PROVIDER_LIMIT_RESUME_MAX_WAIT_MS }; +} + +/** The user whose authority Retry uses: the requester, else the run's accountable user. */ +async function accountableUser(db: Pick, run: typeof heartbeatRuns.$inferSelect) { + const [wake] = run.wakeupRequestId ? await db.select({ type: agentWakeupRequests.requestedByActorType, + id: agentWakeupRequests.requestedByActorId }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.id, run.wakeupRequestId))) : []; + if (wake?.type === "user" && wake.id) return wake.id; + return run.responsibleUserId ?? null; +} + +export type ProviderLimitResumePlan = + | { automatic: true; resetAt: Date; actorId: string } + | { automatic: false; resetAt: Date | null }; + +/** Whether this failed run's task continues by itself once the limit resets. */ +export async function planProviderLimitResume(db: Pick, runId: string): Promise { + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + if (!run) return { automatic: false, resetAt: null }; + const reset = await readNativeUsageLimitReset(db, run); + if (!reset) return { automatic: false, resetAt: null }; + // A reset beyond the bounded wait is still reported; only the automatic Retry is bounded. + const actorId = reset.withinAutomaticWait ? await accountableUser(db, run) : null; + return actorId ? { automatic: true, resetAt: reset.resetAt, actorId } : { automatic: false, resetAt: reset.resetAt }; +} + +export function providerLimitNextAction(plan: ProviderLimitResumePlan) { + if (plan.automatic) { + return `The provider usage limit resets at ${plan.resetAt.toISOString()}. Paperclip will retry this task then; Retry starts it sooner if usage capacity is already restored.`; + } + return plan.resetAt + ? `The provider usage limit resets at ${plan.resetAt.toISOString()}. Retry the task after that time, or sooner if usage capacity is restored.` + : "Restore model provider usage capacity, then retry the task. The provider did not report when its usage limit resets."; +} + +type Outcome = + | { requested: true; requestId: string } + | { requested: false; waitUntil: Date } + | { requested: false; reason: string }; + +async function settle(db: Db, actionId: string, state: Record, nextAction?: string) { + await db.update(issueRecoveryActions).set({ + evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`, + ...(nextAction ? { nextAction } : {}), + updatedAt: new Date(), + }).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`)); +} + +/** Why Paperclip did not retry after a reset it announced; the Retry stays. + * Every give-up reason is listed, so no give-up leaves the promise standing. */ +const NOT_RETRIED = { + source_run_mismatch: "the failed run no longer matches this hold", + reset_unknown: "the provider's reset could no longer be read", + task_changed: "the task changed", + no_accountable_user: "no user is accountable for the run", + automatic_retry_budget_used: "three automatic Retries in a row did not restore usage", + retry_stale: "a newer run exists", + retry_refused: "Retry was not allowed for the accountable user", + reset_stale: "the reset passed more than a day ago", +} as const; +type NotRetriedReason = keyof typeof NOT_RETRIED; + +/** + * Requests the task's Retry for one usage-limit hold once its reset has + * passed. Idempotent per run: the Retry key and the recorded outcome both + * prevent a second request. + */ +export async function requestProviderLimitResumeRetry(db: Db, input: { + companyId: string; actionId: string; prepareChatRetry?: PrepareChatRetry; +}, now = new Date()): Promise { + const [action] = await db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))); + if (!action || action.status !== "active" || action.kind !== "active_run_watchdog" || action.cause !== NATIVE_PROVIDER_USAGE_LIMIT + || action.evidence?.providerLimitResume) return { requested: false, reason: "not_waiting" }; + const runId = typeof action.evidence?.runId === "string" ? action.evidence.runId : null; + const [run] = runId ? await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, action.companyId), sql`${heartbeatRuns.id}::text = ${runId}`)) : []; + const done = async (reason: NotRetriedReason, extra: Record = {}) => { + // Replace a promise to retry with what the user can do now. + const nextAction = action.evidence?.providerLimitResetAt + ? `Paperclip did not retry this task after the provider usage limit reset because ${NOT_RETRIED[reason]}. Retry the task when usage capacity is available.` + : undefined; + await settle(db, action.id, { state: "not_requested", reason, decidedAt: now.toISOString(), ...extra }, nextAction); + return { requested: false as const, reason }; + }; + // The failure that created the hold may still be settling its run. + if (run && ["queued", "running"].includes(run.status)) return { requested: false, waitUntil: new Date(now.getTime() + 60_000) }; + if (!run || run.runtimeMode !== "native" || run.status !== "failed" || run.errorCode !== NATIVE_PROVIDER_USAGE_LIMIT) + return done("source_run_mismatch"); + const reset = await readNativeUsageLimitReset(db, run); + if (!reset) return done("reset_unknown"); + if (!reset.withinAutomaticWait) { + // Too far out to wait by itself: the hold names the reset and leaves the + // Retry to the user; it never promised an automatic one. + await db.update(issueRecoveryActions).set({ + nextAction: providerLimitNextAction({ automatic: false, resetAt: reset.resetAt }), + evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`, + updatedAt: now, + }).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active"))); + await settle(db, action.id, { state: "not_requested", reason: "reset_beyond_wait", resetAt: reset.resetAt.toISOString(), + decidedAt: now.toISOString() }); + return { requested: false, reason: "reset_beyond_wait" }; + } + if (reset.resetAt.getTime() > now.getTime()) { + // A hold saved by an earlier release names no reset; tell its reader when work resumes. + if (!action.evidence?.providerLimitResetAt) { + const actorId = await accountableUser(db, run); + await db.update(issueRecoveryActions).set({ + nextAction: providerLimitNextAction(actorId + ? { automatic: true, resetAt: reset.resetAt, actorId } : { automatic: false, resetAt: reset.resetAt }), + evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`, + updatedAt: now, + }).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active"))); + } + return { requested: false, waitUntil: reset.resetAt }; + } + if (now.getTime() - reset.resetAt.getTime() > STALE_RESET_MS) return done("reset_stale", { resetAt: reset.resetAt.toISOString() }); + const issueId = action.sourceIssueId; + const [issue] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId))); + if (!issue || issue.assigneeAgentId !== run.agentId || ["done", "cancelled"].includes(issue.status)) return done("task_changed"); + const actorId = await accountableUser(db, run); + if (!actorId) return done("no_accountable_user"); + // Bound a provider that keeps reporting resets that do not restore capacity. + const [lastSuccess] = await db.select({ finishedAt: heartbeatRuns.finishedAt }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.agentId, run.agentId), eq(heartbeatRuns.status, "succeeded"), + sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`, + )).orderBy(desc(heartbeatRuns.finishedAt)).limit(1); + const earlier = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId), + like(agentWakeupRequests.idempotencyKey, `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}%`), + sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`, + lastSuccess?.finishedAt ? gt(agentWakeupRequests.requestedAt, lastSuccess.finishedAt) : undefined, + )).limit(MAX_AUTOMATIC_RESUMES); + if (earlier.length >= MAX_AUTOMATIC_RESUMES) return done("automatic_retry_budget_used"); + try { + const receipt = await requestTaskRetry({ db, companyId: run.companyId, issueId, actorId, + actorSource: actorId === "local-board" ? "local_implicit" : "session", + idempotencyKey: `${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${run.id}`, observedRunId: run.id, + initiatedBy: "provider_limit_reset", prepareChatRetry: input.prepareChatRetry }); + if (!receipt.accepted || !receipt.requestId) return done("retry_stale"); + await settle(db, action.id, { state: "requested", requestId: receipt.requestId, resetAt: reset.resetAt.toISOString(), + requestedAt: now.toISOString() }); + return { requested: true, requestId: receipt.requestId }; + } catch (error) { + // Authority or conversation checks refused it; the visible Retry remains. + if (!(error instanceof HttpError)) throw error; + logger.info({ runId: run.id, status: error.status }, "provider limit reset left for an explicit Retry"); + return done("retry_refused", { status: error.status }); + } +} + +type Scope = { companyId: string }; +const LOAD_PAGE_SIZE = 500; +type Entry = { id: string; companyId: string; dueAt: number }; + +/** + * Deadline owner for usage-limit holds: one entry per hold, due at its + * provider-reported reset. Holds are the durable truth; a new hold notifies + * this queue, and startup reconstructs every waiting hold. + */ +export function registerProviderLimitResumeWork( + db: Db, + coordinator: ReturnType, + owner: { resume(companyId: string, requestId: string): Promise; schedulingSuppressed(): Promise; + /** Read when a Retry is requested: the chat service registers it after startup. */ + prepareChatRetry?: () => PrepareChatRetry | undefined }, + canRun: () => boolean, +) { + const cursors = new Map(); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.providerLimitResume, + decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as Scope, + matches: (entry, scope) => !scope || entry.companyId === scope.companyId, + load: async scope => { + // One bounded page per pass, resumed from a stable cursor until every + // waiting hold is loaded: a hold left out would never retry. + const key = scope ? JSON.stringify(scope) : "*"; + const cursor = cursors.get(key); + const rows = await db.select({ id: issueRecoveryActions.id, companyId: issueRecoveryActions.companyId }) + .from(issueRecoveryActions).where(and( + scope ? eq(issueRecoveryActions.companyId, scope.companyId) : undefined, + eq(issueRecoveryActions.status, "active"), eq(issueRecoveryActions.kind, "active_run_watchdog"), + eq(issueRecoveryActions.cause, NATIVE_PROVIDER_USAGE_LIMIT), + sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`, + isNull(issueRecoveryActions.resolvedAt), + cursor ? gt(issueRecoveryActions.id, cursor) : undefined, + )).orderBy(asc(issueRecoveryActions.id)).limit(LOAD_PAGE_SIZE); + const complete = rows.length < LOAD_PAGE_SIZE; + if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); + // check() reads each hold's reset and returns its real deadline. + return { rows: rows.map(row => ({ ...row, dueAt: 0 })), complete }; + }, + check: async entry => { + if (await owner.schedulingSuppressed()) return { ...entry, dueAt: Date.now() + 5 * 60_000 }; + const outcome = await requestProviderLimitResumeRetry(db, { companyId: entry.companyId, actionId: entry.id, + prepareChatRetry: owner.prepareChatRetry?.() }); + if ("waitUntil" in outcome) return { ...entry, dueAt: outcome.waitUntil.getTime() }; + if (outcome.requested) await owner.resume(entry.companyId, outcome.requestId).catch((error: unknown) => + logger.warn({ err: error, actionId: entry.id }, "provider limit Retry remains queued")); + return null; + }, + }, canRun); +} diff --git a/server/src/services/provider-quota-reset.test.ts b/server/src/services/provider-quota-reset.test.ts new file mode 100644 index 00000000000..f3ba512145b --- /dev/null +++ b/server/src/services/provider-quota-reset.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { parseProviderQuotaClockReset } from "./provider-quota-reset.js"; + +describe("parseProviderQuotaClockReset", () => { + it("reads a weekly limit's calendar reset, as Claude's ACP agent reports it", () => { + // Staging run c086fa26 (PAP-1057), 2026-11-10: the reset is two days out. + const now = new Date("2026-11-10T20:06:33.000Z"); + const message = "ACP agent reported a terminal limit failure.\nYou've hit your weekly limit · resets Nov 12, 6pm (UTC)"; + expect(parseProviderQuotaClockReset(message, now)).toEqual(new Date("2026-11-12T18:00:00.000Z")); + }); + + it("reads a calendar reset in a named time zone, with minutes and an ordinal", () => { + const now = new Date("2026-07-15T20:00:00.000Z"); + expect(parseProviderQuotaClockReset("resets Jul 17th at 4:30 PM (America/Chicago)", now)) + .toEqual(new Date("2026-07-17T21:30:00.000Z")); + expect(parseProviderQuotaClockReset("Resets on August 2, 9am (UTC)", now)) + .toEqual(new Date("2026-08-02T09:00:00.000Z")); + }); + + it("rolls a calendar reset that already passed into next year, and rejects impossible dates", () => { + expect(parseProviderQuotaClockReset("resets Jan 2, 6pm (UTC)", new Date("2026-12-30T10:00:00.000Z"))) + .toEqual(new Date("2027-01-02T18:00:00.000Z")); + expect(parseProviderQuotaClockReset("resets Nov 31, 6pm (UTC)", new Date("2026-11-10T10:00:00.000Z"))).toBeNull(); + }); + + it("reads a calendar reset that already passed as expired, never as a year away", () => { + // Recovery rereads an unchanged failure days after its reset. + expect(parseProviderQuotaClockReset("resets Nov 12, 6pm (UTC)", new Date("2026-11-14T10:00:00.000Z"))) + .toEqual(new Date("2026-11-12T18:00:00.000Z")); + expect(parseProviderQuotaClockReset("resets Dec 30, 6pm (UTC)", new Date("2027-01-03T10:00:00.000Z"))) + .toEqual(new Date("2026-12-30T18:00:00.000Z")); + }); + + it("keeps reading a clock-only reset as the next matching time", () => { + const now = new Date("2026-07-15T20:00:00.000Z"); + expect(parseProviderQuotaClockReset("You've hit your session limit · resets 2am (UTC)", now)) + .toEqual(new Date("2026-07-16T02:00:00.000Z")); + expect(parseProviderQuotaClockReset("Try again at 4:30 PM (America/Chicago).", now)) + .toEqual(new Date("2026-07-15T21:30:00.000Z")); + expect(parseProviderQuotaClockReset("resets 9pm", now)).toEqual(new Date("2026-07-15T21:00:00.000Z")); + expect(parseProviderQuotaClockReset("Provider quota exceeded for this model.", now)).toBeNull(); + }); +}); diff --git a/server/src/services/provider-quota-reset.ts b/server/src/services/provider-quota-reset.ts index b2d62613b93..25e275ce9e0 100644 --- a/server/src/services/provider-quota-reset.ts +++ b/server/src/services/provider-quota-reset.ts @@ -1,17 +1,29 @@ +const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; +const RESET_PATTERN = new RegExp( + "(?:try again at|resets?(?:\\s+(?:at|on))?)\\s+" + + // Optional calendar date, as in "resets Nov 12, 6pm (UTC)" for a weekly limit. + `(?:(${MONTHS.join("|")})[a-z]*\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s+(?:at\\s+)?)?` + + "(\\d{1,2})(?::(\\d{2}))?\\s*(?:([ap])\\.?\\s*m\\.?)?(?:\\s*\\(([^)]+)\\)|\\s+([A-Z]{2,5}))?", + "i", +); + /** - * Reads a provider's "try again at 4:30 PM (America/Chicago)" or - * "resets 2am (UTC)" wording as the next matching wall-clock instant after - * `now`. A clock without a time zone is read as UTC. + * Reads a provider's "try again at 4:30 PM (America/Chicago)", "resets 2am + * (UTC)" or "resets Nov 12, 6pm (UTC)" wording. A clock alone is the next + * matching wall-clock instant after `now`; a calendar date is its occurrence + * nearest `now`, which is in the past when the reset already passed. A clock + * without a time zone is read as UTC. */ export function parseProviderQuotaClockReset(error: string, now: Date) { - const match = error.match( - /(?:try again at|resets?(?:\s+at)?)\s+(\d{1,2})(?::(\d{2}))?\s*(?:([ap])\.?\s*m\.?)?(?:\s*\(([^)]+)\)|\s+([A-Z]{2,5}))?/i, - ); + const match = error.match(RESET_PATTERN); if (!match) return null; - const hourValue = Number.parseInt(match[1] ?? "", 10); - const minute = Number.parseInt(match[2] ?? "0", 10); - const meridiem = (match[3] ?? "").toLowerCase(); + const monthIndex = match[1] ? MONTHS.indexOf(match[1].slice(0, 3).toLowerCase()) : null; + const dayOfMonth = match[2] ? Number.parseInt(match[2], 10) : null; + if (monthIndex !== null && (monthIndex < 0 || !dayOfMonth || dayOfMonth < 1 || dayOfMonth > 31)) return null; + const hourValue = Number.parseInt(match[3] ?? "", 10); + const minute = Number.parseInt(match[4] ?? "0", 10); + const meridiem = (match[5] ?? "").toLowerCase(); if (!Number.isInteger(hourValue)) return null; if ( meridiem ? hourValue < 1 || hourValue > 12 : hourValue < 0 || hourValue > 23 @@ -21,14 +33,7 @@ export function parseProviderQuotaClockReset(error: string, now: Date) { let hour = meridiem ? hourValue % 12 : hourValue; if (meridiem === "p") hour += 12; - const timeZone = (match[4] ?? match[5])?.trim(); - if (!timeZone) { - const retryAt = new Date(now); - retryAt.setUTCHours(hour, minute, 0, 0); - if (retryAt.getTime() <= now.getTime()) - retryAt.setUTCDate(retryAt.getUTCDate() + 1); - return retryAt; - } + const timeZone = (match[6] ?? match[7])?.trim() || "UTC"; try { const wallClock = (date: Date) => @@ -46,18 +51,13 @@ export function parseProviderQuotaClockReset(error: string, now: Date) { .map((part) => [part.type, part.value]), ); const nowParts = wallClock(now); - const buildRetryAt = (dayOffset: number) => { - const targetDay = new Date( - Date.UTC( - Number(nowParts.year), - Number(nowParts.month) - 1, - Number(nowParts.day) + dayOffset, - hour, - minute, - ), - ); - let candidate = targetDay; - const targetMs = targetDay.getTime(); + // The instant whose wall clock in `timeZone` reads this date and time. + const instant = (year: number, month: number, day: number) => { + const target = new Date(Date.UTC(year, month, day, hour, minute)); + // Reject dates that overflow, such as Nov 31. + if (monthIndex !== null && target.getUTCDate() !== day) return null; + let candidate = target; + const targetMs = target.getTime(); for (let attempt = 0; attempt < 4; attempt += 1) { const actual = wallClock(candidate); const actualMs = Date.UTC( @@ -73,8 +73,23 @@ export function parseProviderQuotaClockReset(error: string, now: Date) { } return candidate; }; - const sameDay = buildRetryAt(0); - return sameDay.getTime() > now.getTime() ? sameDay : buildRetryAt(1); + const year = Number(nowParts.year); + if (monthIndex !== null && dayOfMonth !== null) { + // The occurrence of that date nearest `now`: "resets Jan 2" read on + // Dec 30 is next year's. A date read after it passed stays in the past, + // so a caller reading an old message sees an expired reset rather than + // one a year away. + const candidates = [year - 1, year, year + 1] + .map((candidateYear) => instant(candidateYear, monthIndex, dayOfMonth)) + .filter((candidate): candidate is Date => candidate !== null); + if (!candidates.length) return null; + return candidates.reduce((nearest, candidate) => + Math.abs(candidate.getTime() - now.getTime()) < Math.abs(nearest.getTime() - now.getTime()) ? candidate : nearest); + } + const month = Number(nowParts.month) - 1; + const day = Number(nowParts.day); + const sameDay = instant(year, month, day)!; + return sameDay.getTime() > now.getTime() ? sameDay : instant(year, month, day + 1); } catch { return null; } diff --git a/server/src/services/recovery/provider-failure-classification.test.ts b/server/src/services/recovery/provider-failure-classification.test.ts index ce7da72da9f..d072b3d93a5 100644 --- a/server/src/services/recovery/provider-failure-classification.test.ts +++ b/server/src/services/recovery/provider-failure-classification.test.ts @@ -111,6 +111,17 @@ describe("classifyAdapterFailureForRecovery", () => { }); }); + it("releases the wait when an unchanged weekly-limit failure is reread after its calendar reset", () => { + // Read two days after "resets Nov 12": the wait is over, not a year away. + const now = new Date("2026-11-14T10:00:00.000Z"); + const classification = classifyAdapterFailureForRecovery({ + errorCode: "adapter_failed", + error: "You've hit your weekly limit · resets Nov 12, 6pm (UTC)", + resultJson: null, + }, now); + expect(classification).toEqual({ kind: "provider_quota", retryAt: now, parsedResetTime: true }); + }); + it("uses the default recovery backoff when quota reset time is absent", () => { const now = new Date("2026-07-15T20:00:00.000Z"); const classification = classifyAdapterFailureForRecovery({ diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 4cadaea1b47..4456079b96f 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -676,7 +676,8 @@ export function classifyAdapterFailureForRecovery( if (parsedClockReset) { return { kind: "provider_quota", - retryAt: parsedClockReset, + // A calendar reset read after it passed has released the wait. + retryAt: parsedClockReset > now ? parsedClockReset : now, parsedResetTime: true, }; } diff --git a/server/src/services/task-retry.ts b/server/src/services/task-retry.ts index 72050465f52..4525c5986c7 100644 --- a/server/src/services/task-retry.ts +++ b/server/src/services/task-retry.ts @@ -224,12 +224,20 @@ export async function retireSupersededTaskRetry(db: Db, input: { type TaskRetryRequest = { db: Db; companyId: string; issueId: string; actorId: string; idempotencyKey: string; observedRunId: string | null; actorSource?: string; - /** Paperclip requests the user's Retry itself after a restart lost an unstarted turn. */ - initiatedBy?: "restart_recovery"; + /** Paperclip requests the user's Retry itself: after a restart lost an + * unstarted turn, or once a provider usage limit it waited on has reset. */ + initiatedBy?: "restart_recovery" | "provider_limit_reset"; prepareChatRetry?: (tx: Db, scope: { companyId: string; issueId: string; agentId: string; failedRunId: string; initiatedByUserId: string; retryIntentId?: string }) => Promise<{ actionId: string }>; }; +/** Activity actor for a Retry: the user, or the Paperclip hook acting for them. */ +function automaticRetryActor(input: Pick) { + if (!input.initiatedBy) return { actorType: "user" as const, actorId: input.actorId }; + return { actorType: "system" as const, + actorId: input.initiatedBy === "restart_recovery" ? "restart-recovery" : "provider-limit-reset" }; +} + const TASK_RETRY_CONTENTION_ATTEMPTS = 10; const TASK_RETRY_CONTENTION_DELAY_MS = 100; @@ -324,13 +332,11 @@ function admitTaskRetry(input: TaskRetryRequest) { source: "on_demand", triggerDetail: "manual", reason: "task_retry", idempotencyKey: key, requestedByActorType: "user", requestedByActorId: input.actorId, ...settled, payload: { issueId: issue.id, taskRetry: finalizeIntent } }); - const restartRecovery = input.initiatedBy === "restart_recovery"; - await persistActivity(db, { companyId: issue.companyId, actorType: restartRecovery ? "system" : "user", - actorId: restartRecovery ? "restart-recovery" : input.actorId, + await persistActivity(db, { companyId: issue.companyId, ...automaticRetryActor(input), action: "issue.retry_requested", entityType: "issue", entityId: issue.id, runId: latest.id, details: { requestId: canonicalId ?? finalizeId, sourceRunId: latest.id, attachedToExistingWork: Boolean(canonicalId), strategy: "finalize_result", - ...(restartRecovery ? { initiatedBy: "restart_recovery", onBehalfOfUserId: input.actorId } : {}) } }); + ...(input.initiatedBy ? { initiatedBy: input.initiatedBy, onBehalfOfUserId: input.actorId } : {}) } }); const finalizing = savedResult.kind === "rearmed" || savedResult.finalizing; return { requestId: canonicalId ?? finalizeId, accepted: true, stale: false, observedRunId: latest.id, chatActionId: undefined, ...(finalizing ? { finalizeRunId: latest.id } : {}) }; @@ -371,10 +377,10 @@ function admitTaskRetry(input: TaskRetryRequest) { // A new deliberate click (new key) replaces it with a fresh attempt under the // clicker's current authority instead of joining it. Waits on shared state // (cleanup, recovery, an active run) keep coalescing: that intent starts by - // itself once the gate clears. The restart hook never replaces a user's click. + // itself once the gate clears. An automatic hook never replaces a user's click. let replacedRequestId: string | undefined; if (active && !busy && !active.runId && active.status === "deferred_issue_execution" && - input.initiatedBy !== "restart_recovery" && activeIntent && !activeIntent.chatActionId && + !input.initiatedBy && activeIntent && !activeIntent.chatActionId && !activeIntent.queuedChatRequestId && isDeclinedTaskRetry(active.payload)) { await tx.update(agentWakeupRequests).set({ status: "skipped", error: "task_retry_replaced", finishedAt: new Date(), updatedAt: new Date() }).where(and(eq(agentWakeupRequests.id, active.id), @@ -462,13 +468,11 @@ function admitTaskRetry(input: TaskRetryRequest) { actionId: action.id }, previous, next); } } - const restartRecovery = input.initiatedBy === "restart_recovery"; - await persistActivity(db, { companyId: issue.companyId, actorType: restartRecovery ? "system" : "user", - actorId: restartRecovery ? "restart-recovery" : input.actorId, + await persistActivity(db, { companyId: issue.companyId, ...automaticRetryActor(input), action: "issue.retry_requested", entityType: "issue", entityId: issue.id, runId: latest.id, details: { requestId: active?.id ?? id, sourceRunId: latest.id, attachedToExistingWork: Boolean(active || busy), ...(replacedRequestId ? { replacedRequestId } : {}), - ...(restartRecovery ? { initiatedBy: "restart_recovery", onBehalfOfUserId: input.actorId } : {}) } }); + ...(input.initiatedBy ? { initiatedBy: input.initiatedBy, onBehalfOfUserId: input.actorId } : {}) } }); return { requestId: active?.id ?? id, accepted: true, stale: false, observedRunId: latest.id, chatActionId: intent.chatActionId, ...(!active && latest.status === "scheduled_retry" ? { scheduledRetryRunId: latest.id } : {}) };