From 92cf446fb63185a1ab6b8768a9d74ee7227a6350 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:31:58 -0600 Subject: [PATCH] fix(native): keep an accepted finish as the outcome after a transient provider refusal (#22676) 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 harness runs end with a result from the agent's finish tool and a provider terminal > - A provider can refuse a later request in the same turn after the finish was accepted (Antigravity 1.5.2 streams its final reply after the finish) > - Paperclip counted that run as failed and retried it, so the agent did the work again and posted the same reply again > - The product rule is that recovery is automatic and that finished work is never repeated visibly > - This pull request makes an accepted done report the run's outcome when the only later failure is a transient provider refusal (capacity or rate limit), for every native harness > - The benefit is one reply per task and no retry for work that is already done ## Linked Issues or Issue Description **What happened?** In a local run of Google Antigravity 1.5.2 (Google sign-in, `gemini-3.8-flash-low`), Google refused 10 of 17 runs with 503 "No capacity available". In two runs the agent's finish was already accepted when the refusal came. Paperclip failed those runs and scheduled the capacity retry. One task got the same answer three times. **Expected behavior** When the agent's done report was accepted and the only later failure is a transient provider refusal, the run succeeds, the task closes as for any done report, and no retry starts. A real failure (model not available, exhausted allowance, rejected sign-in, untyped failure, cancelled run, no accepted finish) stays a failure. **Steps to reproduce** 1. Run a native task whose finish tool is accepted. 2. Make the provider fail the same turn afterwards with a typed `overloaded` or `rate_limit` failure (or Codex `serverOverloaded`). 3. See that the run fails and a capacity retry is scheduled. **Agent adapter(s) involved** Not adapter-specific (core bug). Observed with Google Antigravity; the same path applies to Codex and other native harnesses. ## What Changed - `native-provider-failure.ts`: the rule `nativeAcceptedResultOutlivesProviderFailure`. It reads only the committed terminal and its typed failure. It is true only for a failed turn with an accepted `done` report and a transient `overloaded` or `rate_limit` failure (or the classified Codex overload). Other accepted dispositions keep the bounded capacity retry. - `native-accepted-outcome.ts` (new): the decision is made once, when `PaperclipControlPlanePort.completeRun` accepts the result, and saved as `acceptedOutcome` beside the raw terminal in `native_run_results.result_json`. The raw terminal does not change, because it is part of the accepted result's integrity digest. No migration: the field is optional JSON, and a row saved by an older release keeps its raw terminal as before. - Every reader of the run outcome uses that saved value: the executor's adapter result, the finalizer, the projection repair pass (`native-run-projection.ts`, also in SQL), accepted-result settlement, and the run's saved `prpRunTerminalState` (read by the exhausted and superseded finalization paths). - The run records a closed diagnostic `providerFailureAfterAcceptedResult: { provider, category }` and no provider text. Its warm provider session stays open (`nativeRetainsWarmSession`): the refusal came from the remote model service and the turn ended cleanly, so closing it would only cold-start the next message. - `doc/plans/2026-11-22-antigravity-qualification.md`: records the first completed prompts on 1.5.2 and the open decisions below. ## Verification - `server/src/services/native-runtime/native-provider-overload.integration.test.ts` (embedded Postgres, executor and finalizer, replayed twice): - New: accepted finish, then a typed capacity refusal, a typed rate limit, or Codex `serverOverloaded`: the run succeeds, the task is done, no successor run, no failure report. Red before the fix (3 failed), green after. - New: after the finalizer commits, a restart that leaves the run `running` is settled by the projection repair pass as succeeded, with no failure report; the saved `prpRunTerminalState` is `succeeded`. Red before the stored outcome (projection flipped the run to failed). - New: a row saved without the accepted outcome (older release) stays failed through finalizer and projection. - New guards: accepted finish, then model unavailable, exhausted allowance, rejected sign-in or an untyped failure: the run still fails and the task is not done. - Existing capacity-retry cases (accepted `needs_review` result) still retry after one and two minutes, then block. - `server/src/services/native-runtime/native-provider-failure.test.ts`: new unit cases with the real Antigravity observation (503 and 429 outlive the finish; model, quota, sign-in, unknown retryability, timeout, `needs_review` and cancelled do not). 70/70 pass. - `tsc --noEmit` for `server`: clean. - 40 neighbouring test files that import the port, projection, settlement or finalizer: 4,193 passed, 10 failed. The same 10 fail with the base source (missing local bundled skill file and a runnerd fixture directory), so they are local-environment failures. - `pnpm verify` selected 2,980 of 3,857 test files (core native-runtime modules changed), which is a full-suite run. I stopped it after its first group (4 files, 85 tests) passed and left the broad suite to required CI, as AGENTS.md section 7 says. - Not run live: the fixed behavior has not been re-run against Google. The evidence came from a local instance before this change. Daytona and the API-key route were not run. ## Risks - Behavior change for every native harness: a failed turn with an accepted done report and a transient refusal now ends as success. A done report still goes through the same completion policy, deliverable evidence check and review stages as any done report. - A run whose result was saved by the previous release and finalized by this one keeps its raw failed terminal (old behavior), consistently in the finalizer and the projection (tested). - Not fixed here, open for an owner decision: - A capacity refusal before any accepted result takes the saved-work replacement path (about 30 s, task shown as blocked meanwhile). One after an accepted result takes the bounded capacity retry. The Antigravity classifier already types both as `overloaded`/`transient`; the split is by path. Moving the first kind to the capacity retry skips the replacement's stop proof and unconfirmed-action check. - Antigravity 1.5.2 streams the provider's error text as agent text before it ends the turn, so the live transcript shows it like a reply. A fix belongs in the runner driver. - Follow-ups seen in the same evidence, not fixed here: the finish tool once refused a reply that cited a workspace-only file before the agent registered a deliverable. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, local test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [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 --- .../2026-11-22-antigravity-qualification.md | 66 ++++++- .../native-terminal-state-readers.test.ts | 104 +++++++++++ .../chat-channels/failed-run-retry.ts | 3 +- .../chat-channels/task-retry-authority.ts | 3 +- .../services/explicit-native-continuation.ts | 9 +- server/src/services/idle-sleep-safety.ts | 73 ++++---- .../native-accepted-outcome.test.ts | 27 +++ .../native-runtime/native-accepted-outcome.ts | 87 +++++++++ .../native-accepted-result-settlement.ts | 3 +- .../native-provider-failure.test.ts | 29 ++- .../native-runtime/native-provider-failure.ts | 15 ++ ...tive-provider-overload.integration.test.ts | 171 +++++++++++++++++- .../native-response-presentation-query.ts | 5 +- .../native-runtime/native-run-finalizer.ts | 14 +- .../native-runtime/native-run-projection.ts | 5 +- .../native-runtime/native-session-executor.ts | 39 ++-- .../paperclip-control-plane-port.ts | 12 +- .../preserved-native-result-finalization.ts | 3 +- .../status-decision-committer.ts | 3 +- .../services/preserved-result-finalization.ts | 3 +- .../src/services/workspace-recovery-source.ts | 3 +- 21 files changed, 593 insertions(+), 84 deletions(-) create mode 100644 server/src/__tests__/native-terminal-state-readers.test.ts create mode 100644 server/src/services/native-runtime/native-accepted-outcome.test.ts create mode 100644 server/src/services/native-runtime/native-accepted-outcome.ts diff --git a/doc/plans/2026-11-22-antigravity-qualification.md b/doc/plans/2026-11-22-antigravity-qualification.md index 14315e1c0de..6535c4ed128 100644 --- a/doc/plans/2026-11-22-antigravity-qualification.md +++ b/doc/plans/2026-11-22-antigravity-qualification.md @@ -76,10 +76,12 @@ Order: 1 and 2 in parallel; then 3, 4 and 5; then 6. Profile state: **pending**. The qualification flip has not happened and must not happen until every row marked NOT RUN below has passed live. -**No prompt has completed on 1.5.2 on any platform.** The only Gemini key -available is free tier; Google answered every prompt attempt on two days with -503 (overloaded) or 429 (`RESOURCE_EXHAUSTED`). Everything below that needs a -model to answer is therefore NOT RUN, not failed and not passed. +**First prompts completed on 1.5.2 on 2026-11-23, local darwin-arm64 only, +Google sign-in route, model `gemini-3.8-flash-low`** (see "First live tasks" +below). The API-key route has still not completed a prompt: the only Gemini +key available is free tier, and Google answered every attempt with 503 +(overloaded) or 429 (`RESOURCE_EXHAUSTED`). Rows that need another model, the +API-key route or Daytona remain NOT RUN, not failed and not passed. | Gate | Required observation | Verdict (2026-11-22) | | --- | --- | --- | @@ -88,19 +90,54 @@ model to answer is therefore NOT RUN, not failed and not passed. | Remote provider pack | Pack carries the Linux closure; server's remote path verifies it | Passed for linux-x64 through the server's remote path in Daytona. Re-verification on a reused sandbox lease 4.3 s → ~0.25 s | | API-key auth | Native `gemini-api-key` session reaches an exact-model receipt | Passed live on macOS and Linux x64 (receipt only; no prompt) | | Model admission | Every model ID admitted by exact-model admission, prompt-free | Passed: all 28 IDs (14 Gemini 3, 14 Gemini 4 including Neon at four levels) get exact receipts under an API key on both platforms, without `AGY_ACP_DEFAULT_MODEL` | -| Kill and resume | Native process killed between turns; a new process resumes the session | Passed prompt-free on macOS and Linux x64 with exact receipts. Not yet shown with a completed prompt, and no live `session/load` was observed | +| Kill and resume | Native process killed between turns; a new process resumes the session | Passed prompt-free on macOS and Linux x64 with exact receipts. With completed prompts (2026-11-23, local, sign-in): native process kill recovered and the task finished. No live `session/load` call was observed in the logs | | Launch cost | Run start to native initialize | Sealed verified store: 1.46 s (macOS) / 1.74 s (Linux x64), from 3.45 / 3.65 s. Measured before the launcher regained its streamed executable hash (below); that hash measured ~60 ms for the 179 MB macOS server and is not yet re-measured for the ~722 MB Linux launcher | -| Model lineup inference | Per model/level: one accepted prompt | NOT RUN (no prompt completes on the free key) | -| Neon inference | Real task on `gemini-4-neon-*`, each level acknowledged | NOT RUN (free-tier Neon quota is 0) | -| Ordinary task | File bytes, artifact, accepted result, Done after reload, local and Daytona | NOT RUN on 1.5.2 (local macOS passed on 1.4.3 in October) | +| Model lineup inference | Per model/level: one accepted prompt | Partial: `gemini-3.8-flash-low` accepted prompts over Google sign-in (local). The signed-in catalog listed only three Gemini 3.8 Flash levels, so the rest of the lineup is NOT RUN; the free API key still completes no prompt | +| Neon inference | Real task on `gemini-4-neon-*`, each level acknowledged | NOT RUN (free-tier Neon quota is 0; the signed-in catalog does not list Neon) | +| Ordinary task | File bytes, artifact, accepted result, Done after reload, local and Daytona | Local darwin-arm64 passed on 1.5.2 (sign-in, 2026-11-23), including a follow-up on the same task. Daytona NOT RUN | | Scoped tools | Semantic and MCP round trip; wrong-company and stale authority denied | NOT RUN | -| Questions and permissions | Native identity, one continuation, denial holds | NOT RUN | -| Stop and lifecycle | Stop during a tool call, pending-input Stop, provider death mid-turn, no late revival | NOT RUN | +| Questions and permissions | Native identity, one continuation, denial holds | Question passed locally (asked, answered, task finished). Permissions NOT RUN | +| Stop and lifecycle | Stop during a tool call, pending-input Stop, provider death mid-turn, no late revival | Partial: Stop of a running task passed locally (run cancelled, task kept its status, as for every native harness). Pending-input Stop and provider death mid-turn NOT RUN | | Continuity and recovery | Loaded session keeps model and instructions; interrupted run resumes or Retry works | Partial: prompt-free resume only (see Kill and resume) | | Qualification suite | All 24 `antigravity-qualification` cells, local and Daytona | NOT RUN | | Evals under the native Runner | Applicable Product E2E and chat cases run with Antigravity; numbers recorded | NOT RUN | | Image pull and startup time | Daytona image with the Linux closure, measured cold | NOT RUN | +### First live tasks (2026-11-23, local, Google sign-in) + +Setup: ACP server 1.5.2 (`1.5.2-paperclip.2`), darwin-arm64, a local source +checkout of Paperclip, Google sign-in connection, model +`gemini-3.8-flash-low`. A source checkout needed the dev-only "Run tasks in +this worktree" setting before tasks would start; installed builds do not. + +| Case | Result | +| --- | --- | +| Ordinary task (create a file, reply with its content, mark Done) | Passed | +| Follow-up on the same task (recall the earlier file, append a line) | Passed | +| Question (agent asks, user answers, agent finishes) | Passed | +| Stop of a running task | Passed: run cancelled, task keeps its status | +| Native process killed during a task | Passed: recovered automatically and finished | + +Provider capacity: 10 of 17 runs were refused by Google with 503 +`No capacity available for model ...`; every task still finished through +automatic retries, with no user action. This exposed three product issues: + +- Two refusals arrived after the agent's finish had already been accepted; + the run was counted as failed and retried, so one task got the same reply + three times. Fixed: an accepted done report followed only by a transient + provider refusal (capacity or rate limit) is now the run's outcome, for + every native harness. +- A refusal before any accepted result takes the saved-work replacement + path (about 30 s, task shown as blocked meanwhile), while one after an + accepted result takes the bounded capacity retry. Both carry the same typed + `overloaded`/`transient` failure; the split is by path, not by classifier. + Open decision below. +- Antigravity 1.5.2 streams the provider's error text as agent text before it + ends the turn, so the live transcript shows it like a reply. Open below. + +No live `session/load` call was observed in the logs, so the profile still +must not claim `recovery: "session-load"`. + ### Must pass live before the qualification flip 1. All 24 `antigravity-qualification` cells, local (darwin-arm64) and Daytona @@ -176,6 +213,15 @@ provider-death fixtures now target the store and per-launch directory layout. ## Open decisions +- Capacity refusals before an accepted result: route them to the bounded + capacity retry (one-, then two-minute waits, then blocked) instead of the + saved-work replacement, and keep the task out of "blocked" while that retry + is pending. The replacement path proves the previous session stopped and + reconciles unconfirmed actions before a fresh session; the capacity retry + does not, so moving these failures changes a recovery safeguard. +- Hide provider error text that Antigravity streams as agent text when the + turn then ends with a typed provider failure (runner driver change). + - A paid Gemini key for the prompt-dependent gates (the API-key route to Neon is admitted; inference is unproven). - Orchestrator mode: excluded for this release (not exposed over ACP in 1.5.2). diff --git a/server/src/__tests__/native-terminal-state-readers.test.ts b/server/src/__tests__/native-terminal-state-readers.test.ts new file mode 100644 index 00000000000..3eb30b14314 --- /dev/null +++ b/server/src/__tests__/native-terminal-state-readers.test.ts @@ -0,0 +1,104 @@ +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +// A native run whose done report outlived a transient provider refusal keeps +// its raw failed terminal in native_run_results (the integrity digest covers +// it) and settles from the saved accepted outcome. Every source line that +// reads a terminal state must be listed here with why it may read it; a new +// reader of the stored result must use native-accepted-outcome instead. +const here = path.dirname(fileURLToPath(import.meta.url)); +const sourceRoot = path.resolve(here, ".."); +const TERMINAL_STATE_READ = /runTerminalState|turnTerminalState|prp(Run|Turn)TerminalState|\{terminal,|->'terminal'/; + +const ALLOWED: ReadonlyArray = [ + ["services/task-interruption-presentation.ts", "and ${heartbeatRuns.runnerProfileJson}#>>'{sessionCheckpoint,terminal,turnTerminalState}' = 'completed'", "runner session checkpoint, not a stored result"], + ["services/chat-channels/failed-run-retry.ts", "terminal.turnTerminalState !== \"completed\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/chat-channels/failed-run-retry.ts", "terminal.runTerminalState !== \"succeeded\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/chat-channels/failed-run-retry.ts", "nativeEffectiveTerminal(accepted?.resultJson, { ...(accepted?.resultJson.terminal as Record | undefined) }).runTerminalState === \"failed\";", "reads the effective outcome (accepted outcome applied)"], + ["services/recovery/service.ts", "terminal.runTerminalState !== \"succeeded\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/recovery/service.ts", "terminal.turnTerminalState !== \"completed\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/native-runtime/native-task-session-publication.ts", "return snapshot.goal == null && snapshot.semanticResult != null && snapshot.terminal?.runTerminalState === \"succeeded\"", "runner session snapshot; a turn that failed is not published for resume, so the next turn starts from saved context"], + ["services/native-runtime/status-decision-committer.ts", "terminal.schema !== \"paperclip.prp.terminal.v1\" || terminal.runTerminalState !== \"succeeded\" || terminal.turnTerminalState !== \"completed\" || terminal.reportedWorkDisposition !== \"yielded\") throw new NativeStatusRaceError();", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/native-runtime/status-decision-committer.ts", "terminal.runTerminalState !== \"succeeded\" || terminal.turnTerminalState !== \"completed\" ||", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-board-response-wait.ts", "terminal.runTerminalState !== \"succeeded\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/native-runtime/native-board-response-wait.ts", "terminal.turnTerminalState !== \"completed\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/native-runtime/native-session-executor.ts", "terminal.turnTerminalState !== \"completed\" ||", "retained-cleanup proof recomputes the result digest over the raw terminal; an accepted-outcome run takes the conservative cleanup path"], + ["services/native-runtime/native-session-executor.ts", "terminal.runTerminalState !== \"succeeded\" ||", "retained-cleanup proof recomputes the result digest over the raw terminal; an accepted-outcome run takes the conservative cleanup path"], + ["services/native-runtime/native-session-executor.ts", "record(checkpointRecord.terminal).runTerminalState !== \"failed\"", "runner session checkpoint, not a stored result"], + ["services/native-runtime/native-session-executor.ts", "result.terminal.runTerminalState === \"succeeded\" ? \"ok\" : \"failed\",", "runner's own terminal in memory before acceptance"], + ["services/native-runtime/native-session-executor.ts", "if (native.terminal.runTerminalState === \"succeeded\" || acceptedOutcome) {", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-session-executor.ts", "exitCode: terminal.runTerminalState === \"succeeded\" ? 0 : 1,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-session-executor.ts", "terminal.runTerminalState === \"succeeded\"", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-session-executor.ts", "?? `Native session ${terminal.runTerminalState}`,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-session-executor.ts", "terminal.runTerminalState === \"succeeded\" ? \"ok\" : \"failed\",", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-codex-runner.ts", "const succeeded = completed === null || completed.terminal.runTerminalState === \"succeeded\";", "runner's own terminal in memory, before or at acceptance; the accepted outcome does not exist yet"], + ["services/native-runtime/native-run-coordinator-store.ts", "typeof terminal.turnTerminalState !== \"string\" ||", "checks the stored terminal is well formed, not which outcome it settles"], + ["services/native-runtime/native-run-coordinator-store.ts", "terminal.turnTerminalState,", "checks the stored terminal is well formed, not which outcome it settles"], + ["services/native-runtime/native-run-coordinator-store.ts", "typeof terminal.runTerminalState !== \"string\" ||", "checks the stored terminal is well formed, not which outcome it settles"], + ["services/native-runtime/native-run-coordinator-store.ts", "![\"succeeded\", \"failed\", \"cancelled\"].includes(terminal.runTerminalState) ||", "checks the stored terminal is well formed, not which outcome it settles"], + ["services/native-runtime/native-plan-wait.ts", "terminal.schema !== \"paperclip.prp.terminal.v1\" || terminal.runTerminalState !== \"succeeded\" || terminal.turnTerminalState !== \"completed\" || terminal.reportedWorkDisposition !== \"yielded\") return false;", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/native-runtime/native-provider-failure.ts", "terminal: Pick;", "runner's own terminal in memory, before or at acceptance; the accepted outcome does not exist yet"], + ["services/native-runtime/native-provider-failure.ts", "if (input.terminal.runTerminalState !== \"failed\" || input.terminal.turnTerminalState !== \"failed\" ||", "runner's own terminal in memory, before or at acceptance; the accepted outcome does not exist yet"], + ["services/native-runtime/native-provider-failure.ts", "if (!turnId || terminal.turnTerminalState !== \"failed\" || terminal.runTerminalState !== \"failed\") return null;", "runner's own terminal in memory, before or at acceptance; the accepted outcome does not exist yet"], + ["services/native-runtime/native-provider-failure.ts", "if (!turnId || terminal.turnTerminalState !== \"failed\" || terminal.runTerminalState !== \"failed\" ||", "runner's own terminal in memory, before or at acceptance; the accepted outcome does not exist yet"], + ["services/native-runtime/native-accepted-result-settlement.ts", "if (terminal.schema !== \"paperclip.prp.terminal.v1\" || !RUN_TERMINAL_STATES.has(String(terminal.runTerminalState))) return null;", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-accepted-result-settlement.ts", "const succeeded = nativeTerminal.runTerminalState === \"succeeded\";", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-accepted-result-settlement.ts", "errorMessage: succeeded ? null : `Native session ${nativeTerminal.runTerminalState}`,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/completed-turn-cleanup-hold-settlement.ts", "and run.runner_profile_json->'sessionCheckpoint'->'terminal'->>'turnTerminalState' = 'completed'`;", "runner session checkpoint, not a stored result"], + ["services/native-runtime/native-chat-review-presentation.ts", "record(canonical.terminal).runTerminalState !== \"succeeded\" ||", "only yielded/blocked results reach here; an accepted outcome only exists for done"], + ["services/native-runtime/native-response-presentation-query.ts", "sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson, \"turnTerminalState\")} = 'completed'`,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-response-presentation-query.ts", "sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'done'`),", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-response-presentation-query.ts", "sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'needs_review'`),", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-response-presentation-query.ts", "sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'blocked'`,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-response-presentation-query.ts", "sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'yielded'`),", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-response-presentation-query.ts", "sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'yielded'`,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-finalization-upgrade-readiness.ts", "terminalState: sql`${nativeRunResults.resultJson}->'terminal'->>'runTerminalState'` }).from(nativeRunResults).where(and(eq(nativeRunResults.id, coordinator.resultId),", "checks the stored terminal is well formed, not which outcome it settles"], + ["services/native-runtime/preserved-native-result-finalization.ts", "terminalDisposition: sql`${nativeRunResults.resultJson}#>>'{terminal,reportedWorkDisposition}'`,", "reported disposition is the same in the raw and effective terminal"], + ["services/native-runtime/completed-turn-cleanup.ts", "&& terminal.turnTerminalState === \"completed\";", "runner session checkpoint, not a stored result"], + ["services/native-runtime/native-restart-recovery.ts", "?.runTerminalState === \"failed\" &&", "runner session checkpoint, not a stored result"], + ["services/native-runtime/paperclip-control-plane-port.ts", "|| ![\"completed\", \"failed\", \"interrupted\", \"cancelled\"].includes(String(terminal.turnTerminalState))", "checks the terminal is well formed, not which outcome it settles"], + ["services/native-runtime/paperclip-control-plane-port.ts", "|| ![\"succeeded\", \"failed\", \"cancelled\"].includes(String(terminal.runTerminalState))", "checks the terminal is well formed, not which outcome it settles"], + ["services/native-runtime/paperclip-control-plane-port.ts", "const acceptedOutcome = value.terminal.runTerminalState === \"failed\" && value.terminal.reportedWorkDisposition === \"done\"", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/paperclip-control-plane-port.ts", "prpTurnTerminalState: effectiveTerminal.turnTerminalState,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/paperclip-control-plane-port.ts", "prpRunTerminalState: effectiveTerminal.runTerminalState,", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-run-finalizer.ts", "const accepted = record(run.resultJson).prpRunTerminalState;", "saved prpRunTerminalState is written effective at acceptance"], + ["services/native-runtime/native-run-finalizer.ts", ").prpRunTerminalState;", "saved prpRunTerminalState is written effective at acceptance"], + ["services/native-runtime/native-run-finalizer.ts", "terminal.runTerminalState === \"succeeded\" && terminal.turnTerminalState === \"completed\" &&", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-run-finalizer.ts", "terminal.runTerminalState === \"succeeded\" &&", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-run-finalizer.ts", "terminal.turnTerminalState === \"completed\" &&", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-run-finalizer.ts", "terminal.runTerminalState !== \"succeeded\" ||", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-run-finalizer.ts", "terminal.turnTerminalState !== \"completed\" ||", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-run-finalizer.ts", "if (![\"succeeded\", \"failed\", \"cancelled\"].includes(String(terminal.runTerminalState))) {", "checks the terminal is well formed, not which outcome it settles"], + ["services/native-runtime/native-run-finalizer.ts", "const terminalState = applyNativeAcceptedOutcome(acceptedOutcome, terminal).runTerminalState;", "reads the effective outcome (accepted outcome applied)"], + ["services/native-runtime/native-provider-failure-evidence.ts", "terminal.turnTerminalState !== \"failed\" || terminal.runTerminalState !== \"failed\") return null;", "reads the committed turn failure itself, which decides the accepted outcome"], + ["services/heartbeat/run-completion.ts", "adapterResult.nativeFinalization.terminal.runTerminalState;", "adapter result terminal, already effective (the executor applies the accepted outcome)"], +]; + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return entry.name === "__tests__" || entry.name === "vendor" ? [] : sourceFiles(full); + return entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts") ? [full] : []; + }); +} + +function terminalStateReads() { + return sourceFiles(sourceRoot).flatMap(file => { + const relative = path.relative(sourceRoot, file).split(path.sep).join("/"); + if (relative === "services/native-runtime/native-accepted-outcome.ts") return []; + return readFileSync(file, "utf8").split("\n").map(line => line.trim()) + .filter(line => TERMINAL_STATE_READ.test(line)).map(line => `${relative} | ${line}`); + }); +} + +describe("readers of a stored native terminal state", () => { + it("lists every terminal-state read with a reason, and nothing stale", () => { + const allowed = new Set(ALLOWED.map(([file, line]) => `${file} | ${line}`)); + const found = new Set(terminalStateReads()); + expect([...found].filter(read => !allowed.has(read)), "unlisted reads: settle them through native-accepted-outcome or list them with a reason").toEqual([]); + expect([...allowed].filter(entry => !found.has(entry)), "stale allowlist entries").toEqual([]); + expect(ALLOWED.every(([, , reason]) => reason.trim().length > 0)).toBe(true); + }); +}); diff --git a/server/src/services/chat-channels/failed-run-retry.ts b/server/src/services/chat-channels/failed-run-retry.ts index da6f970200f..56bf3b622f5 100644 --- a/server/src/services/chat-channels/failed-run-retry.ts +++ b/server/src/services/chat-channels/failed-run-retry.ts @@ -1,4 +1,5 @@ import { hasCommittedNativeControllerContainment } from "../native-runtime/native-failed-run-owner-release.js"; +import { nativeEffectiveTerminal } from "../native-runtime/native-accepted-outcome.js"; import { notifyStrandedAgentStatus } from "../live-run-recovery-notifications.js"; import { notifyDeferredExecutionWork, notifyTaskRetrySettlement } from "../deferred-execution-notifications.js"; import { notifyNativeResponsePresentation } from "../native-response-presentation-notifications.js"; @@ -996,7 +997,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti const independentFailedInput = input.taskRetryIntentId && pendingSources?.length && pendingSources.every(action => action.payload.requestedByActorType === "user") && commentIds.every(id => !previousComments.has(id)) && failedRun.status === "failed" && - (accepted?.resultJson.terminal as Record | undefined)?.runTerminalState === "failed"; + nativeEffectiveTerminal(accepted?.resultJson, { ...(accepted?.resultJson.terminal as Record | undefined) }).runTerminalState === "failed"; const [resultPublication] = await tx .select({ id: chatPublications.id }) .from(chatPublications) diff --git a/server/src/services/chat-channels/task-retry-authority.ts b/server/src/services/chat-channels/task-retry-authority.ts index 65ef377bc7b..d70b0149645 100644 --- a/server/src/services/chat-channels/task-retry-authority.ts +++ b/server/src/services/chat-channels/task-retry-authority.ts @@ -1,4 +1,5 @@ import { hasCommittedNativeControllerContainment } from "../native-runtime/native-failed-run-owner-release.js"; +import { nativeEffectiveRunTerminalStateSql } from "../native-runtime/native-accepted-outcome.js"; import { and, eq, sql } from "drizzle-orm"; import { agentWakeupRequests, environmentLeases, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, nativeRunResults, issues, type Db } from "@paperclipai/db"; import { buildExecutionContinuation } from "../execution-continuation.js"; @@ -68,7 +69,7 @@ async function taskChatRetryExecutionContained(db: Db, run: typeof heartbeatRuns eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id), eq(nativeRunResults.issueId, run.nativeIssueId!), eq(nativeRunResults.id, coordinator.resultId), eq(nativeRunResults.schemaStatus, "accepted"), eq(nativeRunResults.completionContractId, run.completionContractId), - sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'failed'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'failed'`, )).limit(1); if (!failedResult) return false; } diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.ts index e5be7ec17a1..8032d09f863 100644 --- a/server/src/services/explicit-native-continuation.ts +++ b/server/src/services/explicit-native-continuation.ts @@ -1,4 +1,5 @@ import { notifyUnsafeWorkspaceExportRecovery } from "./unsafe-workspace-export-notifications.js"; +import { nativeEffectiveRunTerminalStateSql, nativeEffectiveRunTerminalStateSqlText } from "./native-runtime/native-accepted-outcome.js"; import { agentDirectoryPreparationWaitPredicate, isAgentDirectoryPreparationWait } from "./pre-dispatch-execution-evidence.js"; import { assertDurableChatWakeupRequest, assertDurableChatWakeupReceipt, type DurableChatWakeupRequest } from "./durable-chat-wakeup.js"; import { notifyExecutionRunWork } from "./execution-control-notifications.js"; @@ -305,7 +306,7 @@ export async function admitExplicitNativeContinuation(input: { where completed.company_id = ${companyId} and result.issue_id = ${issueId} and completed.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') and completed.runtime_mode = 'native' and completed.status = 'succeeded' and finalized.phase = 'committed' - and result.schema_status = 'accepted' and result.result_json#>>'{terminal,runTerminalState}' = 'succeeded')`, + and result.schema_status = 'accepted' and ${sql.raw(nativeEffectiveRunTerminalStateSqlText("result.result_json"))} = 'succeeded')`, )), )).for("update"); const sourceChecks: Array<{ id?: string; cause: string; evidence: Record }> = @@ -334,7 +335,7 @@ export async function admitExplicitNativeContinuation(input: { eq(nativeRunResults.companyId, companyId), eq(nativeRunResults.issueId, issueId), eq(nativeRunResults.runId, latest.id), eq(nativeRunResults.id, coordinator.resultId), eq(nativeRunResults.schemaStatus, "accepted"), - sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'succeeded'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'succeeded'`, )).limit(1) : []; if (!result || await hasPendingRunCleanup(db, companyId, latest.id)) return blocked("cleanup_pending", "Waiting for the previous run to finish cleanup. Your message is saved."); @@ -453,7 +454,7 @@ export async function admitExplicitNativeContinuation(input: { eq(nativeRunResults.companyId, companyId), eq(nativeRunResults.issueId, issueId), eq(nativeRunResults.runId, run.id), eq(nativeRunResults.id, coordinator.resultId), eq(nativeRunResults.schemaStatus, "accepted"), - sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'succeeded'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'succeeded'`, )).limit(1); const recovery = readSystemRecovery(action.evidence); const snapshotSettled = completedResult && freshIntent && action.id && recovery?.state === "complete" @@ -535,7 +536,7 @@ export async function admitExplicitNativeContinuation(input: { eq(nativeRunResults.companyId, companyId), eq(nativeRunResults.issueId, issueId), eq(nativeRunResults.runId, run.id), eq(nativeRunResults.id, coordinator.resultId), eq(nativeRunResults.schemaStatus, "accepted"), - sql`${nativeRunResults.resultJson}->'terminal'->>'runTerminalState' = 'failed'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'failed'`, )).limit(1) : []; // A terminal failure may retain a result accepted before checkpoint or diff --git a/server/src/services/idle-sleep-safety.ts b/server/src/services/idle-sleep-safety.ts index bb6a344fe0a..9ff2a5e009f 100644 --- a/server/src/services/idle-sleep-safety.ts +++ b/server/src/services/idle-sleep-safety.ts @@ -1,4 +1,5 @@ import { instanceSettingsService } from "./instance-settings.js"; +import { nativeEffectiveRunTerminalStateSqlText } from "./native-runtime/native-accepted-outcome.js"; import { idleMcpWorkQuery } from "./public-mcp/idle-work-query.js"; import type { McpWakeAdmission } from "./public-mcp/wake-admission.js"; import { pendingBudgetEvaluationWorkQuery } from "./budget-evaluation-work.js"; @@ -77,6 +78,42 @@ export type InspectIdlePlugins = (hold: { ownerId: string; expiresAt: number }) // evidence that a restarted process has no persisted work to recover. const workCheck = (reason: string, query: string | SQLWrapper) => ({ reason, query: typeof query === "string" ? sql.raw(query) : query }); +export const NATIVE_RUN_FINALIZATION_WORK_QUERY = `SELECT 1 FROM native_run_finalizations f WHERE ( + f.phase = 'committed' AND f.lease_owner IS NULL AND f.lease_expires_at IS NULL + AND f.next_attempt_at IS NULL AND f.control_deadline_at IS NULL + AND f.recovery_state IS NULL AND f.recovery_request_id IS NULL + AND f.failure_code IS NULL AND f.failure_detail IS NULL + AND EXISTS ( + SELECT 1 FROM heartbeat_runs r + JOIN native_run_results result_row ON result_row.id = f.result_id + AND result_row.company_id = r.company_id AND result_row.issue_id = r.native_issue_id + AND result_row.run_id = r.id AND result_row.completion_contract_id = r.completion_contract_id + JOIN work_assessments assessment ON assessment.id = f.assessment_id + AND assessment.company_id = r.company_id AND assessment.issue_id = r.native_issue_id + AND assessment.run_id = r.id AND assessment.result_id = result_row.id + JOIN status_decisions decision ON decision.id = f.decision_id + AND decision.company_id = r.company_id AND decision.issue_id = r.native_issue_id + AND decision.run_id = r.id AND decision.assessment_id = assessment.id + WHERE r.id = f.run_id AND r.company_id = f.company_id AND r.native_issue_id = f.issue_id + AND r.runtime_mode = 'native' AND r.native_phase = 'committed' + AND ${finishedRun("r")} + AND r.result_json->>'finalizationPhase' = 'committed' + AND r.result_json->>'nextAttemptAt' IS NULL AND r.result_json->>'failureCode' IS NULL + AND r.result_json->>'originalFailureCode' IS NULL + AND result_row.schema_status = 'accepted' + AND ${nativeEffectiveRunTerminalStateSqlText("result_row.result_json")} = r.status + AND decision.application_state = 'applied' AND decision.applied_at IS NOT NULL) + AND EXISTS (SELECT 1 FROM workspace_operations operation + WHERE operation.company_id = f.company_id AND operation.issue_id = f.issue_id + AND operation.heartbeat_run_id = f.run_id + AND operation.phase = 'workspace_finalize' AND operation.status = 'succeeded') + AND NOT EXISTS ( + SELECT 1 FROM status_decision_effects effect WHERE effect.decision_id = f.decision_id + AND (effect.company_id <> f.company_id OR effect.issue_id <> f.issue_id + OR effect.delivery_state <> 'delivered' OR effect.delivered_at IS NULL + OR effect.next_attempt_at IS NOT NULL)) + ) IS NOT TRUE`; + const WORK_CHECKS = [ workCheck("agents.execution_or_timer", `SELECT 1 FROM agents WHERE status = 'running' OR (status NOT IN ('terminated', 'paused', 'pending_approval') AND @@ -247,41 +284,7 @@ const WORK_CHECKS = [ WHERE c.status = 'active' AND s.enabled AND s.automatic_updates AND (s.access_scope = 'company' OR EXISTS ( SELECT 1 FROM project_skill_sources b WHERE b.source_id = s.id AND b.company_id = s.company_id AND b.active))`), - workCheck("native_run_finalizations", `SELECT 1 FROM native_run_finalizations f WHERE ( - f.phase = 'committed' AND f.lease_owner IS NULL AND f.lease_expires_at IS NULL - AND f.next_attempt_at IS NULL AND f.control_deadline_at IS NULL - AND f.recovery_state IS NULL AND f.recovery_request_id IS NULL - AND f.failure_code IS NULL AND f.failure_detail IS NULL - AND EXISTS ( - SELECT 1 FROM heartbeat_runs r - JOIN native_run_results result_row ON result_row.id = f.result_id - AND result_row.company_id = r.company_id AND result_row.issue_id = r.native_issue_id - AND result_row.run_id = r.id AND result_row.completion_contract_id = r.completion_contract_id - JOIN work_assessments assessment ON assessment.id = f.assessment_id - AND assessment.company_id = r.company_id AND assessment.issue_id = r.native_issue_id - AND assessment.run_id = r.id AND assessment.result_id = result_row.id - JOIN status_decisions decision ON decision.id = f.decision_id - AND decision.company_id = r.company_id AND decision.issue_id = r.native_issue_id - AND decision.run_id = r.id AND decision.assessment_id = assessment.id - WHERE r.id = f.run_id AND r.company_id = f.company_id AND r.native_issue_id = f.issue_id - AND r.runtime_mode = 'native' AND r.native_phase = 'committed' - AND ${finishedRun("r")} - AND r.result_json->>'finalizationPhase' = 'committed' - AND r.result_json->>'nextAttemptAt' IS NULL AND r.result_json->>'failureCode' IS NULL - AND r.result_json->>'originalFailureCode' IS NULL - AND result_row.schema_status = 'accepted' - AND result_row.result_json->'terminal'->>'runTerminalState' = r.status - AND decision.application_state = 'applied' AND decision.applied_at IS NOT NULL) - AND EXISTS (SELECT 1 FROM workspace_operations operation - WHERE operation.company_id = f.company_id AND operation.issue_id = f.issue_id - AND operation.heartbeat_run_id = f.run_id - AND operation.phase = 'workspace_finalize' AND operation.status = 'succeeded') - AND NOT EXISTS ( - SELECT 1 FROM status_decision_effects effect WHERE effect.decision_id = f.decision_id - AND (effect.company_id <> f.company_id OR effect.issue_id <> f.issue_id - OR effect.delivery_state <> 'delivered' OR effect.delivered_at IS NULL - OR effect.next_attempt_at IS NOT NULL)) - ) IS NOT TRUE`), + workCheck("native_run_finalizations", NATIVE_RUN_FINALIZATION_WORK_QUERY), ...completedHistoryChecks.map(check => workCheck(check.reason, check.query)), ] as const; diff --git a/server/src/services/native-runtime/native-accepted-outcome.test.ts b/server/src/services/native-runtime/native-accepted-outcome.test.ts new file mode 100644 index 00000000000..b75fba86795 --- /dev/null +++ b/server/src/services/native-runtime/native-accepted-outcome.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import type { PrpTerminalState } from "../../vendor/paperclip-runner/index.js"; +import { deriveNativeAcceptedOutcome, nativeEffectiveRunTerminalStateSqlText, nativeEffectiveTerminal, nativeRetainsWarmSession } from "./native-accepted-outcome.js"; + +const failedDone: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "failed", runTerminalState: "failed", reportedWorkDisposition: "done" }; +const outcome = deriveNativeAcceptedOutcome({ terminal: failedDone, providerFailure: null, providerExplanation: { + schema: "paperclip.provider-failure.v1", provider: "codex", phase: "turn", category: "overloaded", message: "busy", retryability: "transient" } }); + +describe("native accepted outcome", () => { + it("keeps the warm session open so the next message does not cold-start", () => { + expect(outcome).not.toBeNull(); + expect(nativeRetainsWarmSession({ terminal: failedDone, acceptedOutcome: outcome })).toBe(true); + expect(nativeRetainsWarmSession({ terminal: failedDone, acceptedOutcome: null })).toBe(false); + expect(nativeRetainsWarmSession({ terminal: failedDone, acceptedOutcome: outcome, continuationKind: "case_handoff" })).toBe(false); + }); + + it("settles a saved row from its outcome and leaves older rows on their raw terminal", () => { + expect(nativeEffectiveTerminal({ terminal: failedDone, acceptedOutcome: outcome }, failedDone)).toMatchObject({ runTerminalState: "succeeded", turnTerminalState: "completed" }); + expect(nativeEffectiveTerminal({ terminal: failedDone }, failedDone)).toBe(failedDone); + expect(nativeEffectiveTerminal({ terminal: failedDone, acceptedOutcome: { ...outcome, schema: "other" } }, failedDone)).toBe(failedDone); + }); + + it("refuses a column reference that is not a plain alias", () => { + expect(nativeEffectiveRunTerminalStateSqlText("result_row.result_json")).toContain("result_row.result_json->'terminal'"); + expect(() => nativeEffectiveRunTerminalStateSqlText("x; drop table y")).toThrow(); + }); +}); diff --git a/server/src/services/native-runtime/native-accepted-outcome.ts b/server/src/services/native-runtime/native-accepted-outcome.ts new file mode 100644 index 00000000000..7e150184776 --- /dev/null +++ b/server/src/services/native-runtime/native-accepted-outcome.ts @@ -0,0 +1,87 @@ +import { sql, type SQL, type AnyColumn } from "drizzle-orm"; +import type { PrpTerminalState } from "../../vendor/paperclip-runner/index.js"; +import type { ProviderFailure } from "@paperclipai/shared"; +import { nativeAcceptedResultOutlivesProviderFailure } from "./native-provider-failure.js"; + +/** Saved beside the raw terminal, which stays unchanged because the result's integrity digest covers it. */ +export const NATIVE_ACCEPTED_OUTCOME_KEY = "acceptedOutcome"; +const SCHEMA = "paperclip.native-accepted-outcome.v1"; +const CAUSE = "transient_provider_refusal_after_finish"; + +export interface NativeAcceptedOutcome { + schema: typeof SCHEMA; + cause: typeof CAUSE; + runTerminalState: "succeeded"; + turnTerminalState: "completed"; + providerFailure: { provider: string; category: string }; +} + +const CLOSED_VALUE = /^[a-z0-9_.-]{1,64}$/; + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +export function deriveNativeAcceptedOutcome(input: { + terminal: PrpTerminalState; + providerFailure: { errorCode: string; diagnostic?: unknown } | null; + providerExplanation: ProviderFailure | null; +}): NativeAcceptedOutcome | null { + if (!nativeAcceptedResultOutlivesProviderFailure(input)) return null; + const source = input.providerExplanation + ? { provider: input.providerExplanation.provider, category: input.providerExplanation.category } + : record(input.providerFailure?.diagnostic); + const provider = typeof source.provider === "string" && CLOSED_VALUE.test(source.provider) ? source.provider : "unknown"; + const category = typeof source.category === "string" && CLOSED_VALUE.test(source.category) ? source.category : "unknown"; + return { schema: SCHEMA, cause: CAUSE, runTerminalState: "succeeded", turnTerminalState: "completed", + providerFailure: { provider, category } }; +} + +export function readNativeAcceptedOutcome(resultJson: unknown): NativeAcceptedOutcome | null { + const value = record(record(resultJson)[NATIVE_ACCEPTED_OUTCOME_KEY]); + if (value.schema !== SCHEMA || value.cause !== CAUSE || value.runTerminalState !== "succeeded" || + value.turnTerminalState !== "completed") return null; + const failure = record(value.providerFailure); + const closed = (field: unknown) => typeof field === "string" && CLOSED_VALUE.test(field) ? field : "unknown"; + return { schema: SCHEMA, cause: CAUSE, runTerminalState: "succeeded", turnTerminalState: "completed", + providerFailure: { provider: closed(failure.provider), category: closed(failure.category) } }; +} + +export function applyNativeAcceptedOutcome | PrpTerminalState>( + outcome: NativeAcceptedOutcome | null, terminal: T, +): T { + return outcome ? { ...terminal, runTerminalState: outcome.runTerminalState, turnTerminalState: outcome.turnTerminalState } : terminal; +} + +export function nativeEffectiveTerminal | PrpTerminalState>(resultJson: unknown, terminal: T): T { + return applyNativeAcceptedOutcome(readNativeAcceptedOutcome(resultJson), terminal); +} + +const ALIAS = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/; +type TerminalField = "runTerminalState" | "turnTerminalState"; +const SETTLED: Record = { runTerminalState: "succeeded", turnTerminalState: "completed" }; + +export function nativeEffectiveRunTerminalStateSqlText(resultJson: string, field: TerminalField = "runTerminalState"): string { + if (!ALIAS.test(resultJson)) throw new Error("native_accepted_outcome_column_invalid"); + const outcome = `${resultJson}->'${NATIVE_ACCEPTED_OUTCOME_KEY}'`; + return `(case when ${outcome}->>'schema' = '${SCHEMA}' and ${outcome}->>'cause' = '${CAUSE}' + and ${outcome}->>'runTerminalState' = 'succeeded' and ${outcome}->>'turnTerminalState' = 'completed' + then '${SETTLED[field]}' else ${resultJson}->'terminal'->>'${field}' end)`; +} + +export function nativeEffectiveRunTerminalStateSql(resultJson: AnyColumn | SQL, field: TerminalField = "runTerminalState"): SQL { + const outcome = sql`${resultJson}->${NATIVE_ACCEPTED_OUTCOME_KEY}`; + return sql`(case when ${outcome}->>'schema' = ${SCHEMA} and ${outcome}->>'cause' = ${CAUSE} + and ${outcome}->>'runTerminalState' = 'succeeded' and ${outcome}->>'turnTerminalState' = 'completed' + then ${SETTLED[field]} else ${resultJson}->'terminal'->>${field} end)`; +} + +/** A transient refusal came from the remote model service and the turn ended cleanly, so the warm process stays usable. */ +export function nativeRetainsWarmSession(input: { + terminal: { runTerminalState: string }; + acceptedOutcome: NativeAcceptedOutcome | null; + continuationKind?: string; +}) { + return (input.terminal.runTerminalState === "succeeded" || input.acceptedOutcome !== null) + && input.continuationKind !== "case_handoff"; +} diff --git a/server/src/services/native-runtime/native-accepted-result-settlement.ts b/server/src/services/native-runtime/native-accepted-result-settlement.ts index 423a63f6887..edf64d70e53 100644 --- a/server/src/services/native-runtime/native-accepted-result-settlement.ts +++ b/server/src/services/native-runtime/native-accepted-result-settlement.ts @@ -4,6 +4,7 @@ import { NATIVE_FINALIZATION_SCHEMA, type NativeFinalizationResult } from "@pape import type { AdapterExecutionResult } from "../../adapters/index.js"; import { readAcceptedRunUsageCheckpoint } from "../usage-receipts.js"; import type { NativePostResultFailureDiagnostic } from "./native-post-result-failure.js"; +import { nativeEffectiveTerminal } from "./native-accepted-outcome.js"; function record(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; @@ -42,7 +43,7 @@ export async function acceptedNativeAdapterResult(db: Db, input: { )).limit(1); if (!row) return null; const result = record(row.resultJson.result); - const terminal = record(row.resultJson.terminal); + const terminal = nativeEffectiveTerminal(row.resultJson, record(row.resultJson.terminal)); if (terminal.schema !== "paperclip.prp.terminal.v1" || !RUN_TERMINAL_STATES.has(String(terminal.runTerminalState))) return null; const nativeTerminal = terminal as unknown as NativeFinalizationResult["terminal"]; const succeeded = nativeTerminal.runTerminalState === "succeeded"; diff --git a/server/src/services/native-runtime/native-provider-failure.test.ts b/server/src/services/native-runtime/native-provider-failure.test.ts index 002ec6363be..1e8a446646e 100644 --- a/server/src/services/native-runtime/native-provider-failure.test.ts +++ b/server/src/services/native-runtime/native-provider-failure.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js"; import { antigravityModelRefusalMessage } from "@paperclipai/shared"; -import { createNativeProviderFailureObservation, nativeProviderUsageLimitFromEvent, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js"; +import { createNativeProviderFailureObservation, nativeAcceptedResultOutlivesProviderFailure, nativeProviderUsageLimitFromEvent, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js"; const model = "test-model"; const response = { @@ -354,3 +354,30 @@ describe("Google Antigravity provider failures", () => { expect(observed.forTerminal("turn", terminal)).toBeNull(); }); }); + +describe("an accepted finish followed by a provider refusal", () => { + const done: PrpTerminalState = { ...terminal, reportedWorkDisposition: "done" }; + const outlives = (providerFailure: Record, end: PrpTerminalState = done) => { + const observed = createNativeProviderFailureObservation({ kind: "acpx", agent: "antigravity", model: "gemini-3.8-flash-low" }, { antigravityRoute: "subscription" }); + observed.observe({ ...event, payload: { status: "failed", error: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", message: "No capacity available for model gemini-3.8-flash-low on the server", ...providerFailure } } } }); + return nativeAcceptedResultOutlivesProviderFailure({ terminal: end, + providerFailure: observed.forTerminal("turn", end), providerExplanation: observed.providerFailureForTerminal("turn", end) }); + }; + + it("keeps the finish after a transient capacity refusal or rate limit", () => { + expect(outlives({ category: "overloaded", httpStatus: 503, providerCode: "UNAVAILABLE", retryability: "transient" })).toBe(true); + expect(outlives({ category: "rate_limit", httpStatus: 429, retryability: "transient" })).toBe(true); + }); + + it("keeps real failures and unfinished work as failures", () => { + expect(outlives({ category: "model_unavailable", providerCode: "antigravity_model_unavailable", retryability: "requires_action" })).toBe(false); + expect(outlives({ category: "quota_exhausted", retryability: "requires_action" })).toBe(false); + expect(outlives({ category: "authentication", retryability: "requires_action" })).toBe(false); + expect(outlives({ category: "overloaded", retryability: "unknown" })).toBe(false); + expect(outlives({ category: "timeout", retryability: "transient" })).toBe(false); + // Only an accepted done report outlives the refusal; other reports keep the capacity retry. + expect(outlives({ category: "overloaded", retryability: "transient" }, { ...done, reportedWorkDisposition: "needs_review" })).toBe(false); + expect(outlives({ category: "overloaded", retryability: "transient" }, { ...done, runTerminalState: "cancelled", turnTerminalState: "cancelled" })).toBe(false); + }); +}); diff --git a/server/src/services/native-runtime/native-provider-failure.ts b/server/src/services/native-runtime/native-provider-failure.ts index b38f2acf472..c0e8a976772 100644 --- a/server/src/services/native-runtime/native-provider-failure.ts +++ b/server/src/services/native-runtime/native-provider-failure.ts @@ -236,6 +236,21 @@ export function readNativeTurnFailureDiagnostic(value: unknown): NativeTurnFailu } catch { return null; } } +const TRANSIENT_PROVIDER_REFUSALS: ReadonlySet = new Set(["overloaded", "rate_limit"]); + +/** An accepted done report outlives a later transient provider refusal in the same turn. */ +export function nativeAcceptedResultOutlivesProviderFailure(input: { + terminal: Pick; + providerFailure: { errorCode: string } | null; + providerExplanation: ProviderFailure | null; +}): boolean { + if (input.terminal.runTerminalState !== "failed" || input.terminal.turnTerminalState !== "failed" || + input.terminal.reportedWorkDisposition !== "done") return false; + if (input.providerFailure) return input.providerFailure.errorCode === NATIVE_PROVIDER_OVERLOADED_CODE; + const failure = input.providerExplanation; + return failure !== null && failure.retryability === "transient" && TRANSIENT_PROVIDER_REFUSALS.has(failure.category); +} + /** Observe only events accepted by the bound control-plane persistence port. */ export function createNativeProviderFailureObservation( provider: { kind: string; model?: string | null; agent?: string }, diff --git a/server/src/services/native-runtime/native-provider-overload.integration.test.ts b/server/src/services/native-runtime/native-provider-overload.integration.test.ts index 08c328fc9ea..86619a304bb 100644 --- a/server/src/services/native-runtime/native-provider-overload.integration.test.ts +++ b/server/src/services/native-runtime/native-provider-overload.integration.test.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { agents, agentWakeupRequests, companies, completionContracts, createDb, environmentLeases, heartbeatRuns, issueComments, issueRecoveryActions, issues, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db"; +import { agents, agentWakeupRequests, companies, completionContracts, nativeRunResults, workspaceOperations, createDb, environmentLeases, heartbeatRuns, issueComments, issueRecoveryActions, issues, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db"; import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent, PrpTerminalState } from "@paperclipai/paperclip-runner"; import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js"; @@ -17,7 +17,11 @@ vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ import { executePaperclipNativeSession } from "./native-session-executor.js"; import { buildNativeCompletionContract } from "./completion-contracts.js"; import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; -import { finalizeNativeRun } from "./native-run-finalizer.js"; +import { endSupersededNativeFinalizationRuns, finalizeNativeRun, NATIVE_FINALIZATION_SUPERSEDED } from "./native-run-finalizer.js"; +import { projectCommittedRun } from "./native-run-projection.js"; +import { NATIVE_RUN_FINALIZATION_WORK_QUERY } from "../idle-sleep-safety.js"; +import { nativeResponsePresentationCandidates } from "./native-response-presentation-query.js"; +import { admitExplicitNativeContinuation } from "../explicit-native-continuation.js"; import { readPersistedNativeProviderFailure } from "./native-provider-failure-evidence.js"; import { NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; import { heartbeatService } from "../heartbeat.js"; @@ -188,6 +192,167 @@ describe("durable native provider capacity retry", () => { await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry.id)); }); + /** + * The agent's finish was accepted, then the provider refused a later request + * in the same turn (Antigravity streams its final reply after the finish). + */ + async function acceptResultThenProviderFailure(runId: string, issueId: string, failure: { + provider: NativeExecutionInputV1["provider"]; error: Record; savedByOlderRelease?: boolean; + }) { + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [run] = await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: issueId }).where(eq(heartbeatRuns.id, runId)).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 contractInput = buildNativeCompletionContract(issue, { revision: contract.revision }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: failure.provider, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Continue the task using its history.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: failure.provider.kind === "opencode" ? "opencode_server" : "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: contractInput }, + interactionResponses: [], credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + const event: PrpEvent = { + schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId, turnId: native.turnId, + sourceInstanceId: native.runnerInstanceId, sourceEventId: "after-finish", sourceSeq: 1, sourceKind: "runner", eventType: "turn.failed", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), + payload: { status: "failed", error: failure.error }, + }; + const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "failed", runTerminalState: "failed", reportedWorkDisposition: "done" }; + const result = { ...CONTROL_PLANE_CONFORMANCE_RESULT, summary: "The file is written and verified.", + completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: contractInput.revision } }; + provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => { + await options.controlPlane.openRun({ identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock", sourceInstanceId: native.runnerInstanceId }); + await options.controlPlane.appendEvent(event); + await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId }); + if (failure.savedByOlderRelease) { + // A result row saved before this release has no accepted outcome. + const [saved] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId)); + const { acceptedOutcome: _dropped, ...older } = saved.resultJson as Record; + await db.update(nativeRunResults).set({ resultJson: older }).where(eq(nativeRunResults.id, saved.id)); + const [accepting] = await db.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + await db.update(heartbeatRuns).set({ resultJson: { ...accepting.resultJson, + prpRunTerminalState: terminal.runTerminalState, prpTurnTerminalState: terminal.turnTerminalState } }).where(eq(heartbeatRuns.id, runId)); + } + return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-session", driverKind: "codex_app_server", driverVersion: "fixture", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + const unexpected = async () => { throw new Error("Unexpected provider call"); }; + const adapter = await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { descriptor: unexpected, openSession: unexpected } }); + for (let replay = 0; replay < 2; replay++) await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + // The durable projection pass re-derives the run status from the saved + // result after a restart or deploy; it must reach the same outcome. + const [projectedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + await projectCommittedRun({ db, run: projectedRun, coordinator }); + return adapter; + } + + /** A later finalization attempt was superseded: the run ends from its saved terminal state. */ + async function endAsSuperseded(runId: string) { + await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", failureCode: NATIVE_FINALIZATION_SUPERSEDED, failureDetail: {} }) + .where(eq(nativeRunFinalizations.runId, runId)); + await db.update(heartbeatRuns).set({ status: "running", finishedAt: null, errorCode: null, error: null }).where(eq(heartbeatRuns.id, runId)); + expect(await endSupersededNativeFinalizationRuns(db, [runId])).toEqual([runId]); + return (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]; + } + + const capacityRefusal = { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", category: "overloaded", + message: "No capacity available for model gemini-3.8-flash-low on the server", providerCode: "UNAVAILABLE", httpStatus: 503, retryability: "transient" }; + // The finalizer re-reads the pinned execution input, and a v1 input cannot + // carry an ACPX provider. The rule reads only the typed failure, so a v1 + // provider carries Antigravity's exact refusal here. + const typedProvider = { kind: "opencode", model: "google/gemini-3.8-flash-low" } as NativeExecutionInputV1["provider"]; + + it.each([ + ["typed capacity refusal (Antigravity 503)", typedProvider, { code: "provider_turn_failed", message: capacityRefusal.message, providerFailure: capacityRefusal }], + ["typed rate limit (Antigravity 429)", typedProvider, { code: "provider_turn_failed", message: "Slow down", providerFailure: { ...capacityRefusal, category: "rate_limit", httpStatus: 429, providerCode: "RESOURCE_EXHAUSTED" } }], + ["Codex serverOverloaded", { kind: "codex", model: "test-model" } as NativeExecutionInputV1["provider"], { codexErrorInfo: "serverOverloaded", message: NATIVE_PROVIDER_OVERLOADED_MESSAGE }], + ])("keeps an accepted finish as the outcome after a later %s, without a retry", async (_name, runProvider, error) => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Finished before capacity refusal", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: { issueId } }); + sentry.captureRunFailure.mockClear(); + const adapter = await acceptResultThenProviderFailure(runId, issueId, { provider: runProvider, error }); + await waitForPendingRunFailureReports(); + expect(adapter).toMatchObject({ exitCode: 0, errorMessage: null, nativeFinalization: { terminal: { runTerminalState: "succeeded" } } }); + expect(adapter.errorCode).toBeUndefined(); + expect(adapter.resultJson).not.toHaveProperty("providerFailure"); + expect(Object.keys(adapter.resultJson?.providerFailureAfterAcceptedResult as object).sort()).toEqual(["category", "provider"]); + expect(adapter.resultJson?.providerFailureAfterAcceptedResult).toMatchObject({ category: expect.stringMatching(/^(overloaded|rate_limit|server_overloaded)$/) }); + const [finished] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(finished).toMatchObject({ status: "succeeded", error: null, errorCode: null }); + // Recovery paths that settle from the saved run read this state. + expect(finished.resultJson).toMatchObject({ prpRunTerminalState: "succeeded" }); + // A restart after the live finalizer committed but before heartbeat saved + // the run status leaves it running; the projection pass settles it. + await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, runId)); + const [restarted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + await projectCommittedRun({ db, run: restarted, coordinator }); + await waitForPendingRunFailureReports(); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toMatchObject({ status: "succeeded", errorCode: null }); + // A reply not yet published (restart, failed publication) is recovered for this succeeded run. + const replies = nativeResponsePresentationCandidates(undefined, undefined, runId).as("pending_native_response"); + expect((await db.select().from(replies)).map(row => row.id)).toEqual([runId]); + // A message the user queued and then sent proceeds once cleanup has finished. + const commentId = randomUUID(), queueId = randomUUID(), blocked: string[] = []; + await db.insert(issueComments).values({ id: commentId, companyId, issueId, authorType: "user", authorUserId: "capacity-owner", body: "One more thing." }); + await db.insert(agentWakeupRequests).values({ id: queueId, companyId, agentId, source: "on_demand", reason: "issue_commented", + status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "capacity-owner", + payload: { issueId, _paperclipWakeContext: { wakeCommentIds: [commentId] }, + queuedCommentInterrupt: { actorId: "capacity-owner", requestedAt: new Date().toISOString() } } }); + await db.transaction(tx => admitExplicitNativeContinuation({ db: tx as unknown as typeof db, companyId, issueId, agentId, + actorType: "user", actorId: "capacity-owner", reason: "issue_commented", commentId, successorRunId: randomUUID(), + queuedCommentInterruptId: queueId, dryRun: true, onBlocked: reason => blocked.push(reason) })); + expect(blocked).not.toContain("cleanup_pending"); + await db.update(agentWakeupRequests).set({ status: "cancelled" }).where(eq(agentWakeupRequests.id, queueId)); + // Idle sleep treats this settled finalization as history, not pending work. + await db.insert(workspaceOperations).values({ companyId, issueId, heartbeatRunId: runId, phase: "workspace_finalize", status: "succeeded" }); + await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, runId)); + const pending = await db.execute(sql.raw(NATIVE_RUN_FINALIZATION_WORK_QUERY.replace("WHERE (", `WHERE f.run_id = '${runId}' AND (`))); + expect(Array.from(pending)).toHaveLength(0); + expect(await endAsSuperseded(runId)).toMatchObject({ status: "succeeded" }); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "done" }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + expect(sentry.captureRunFailure).not.toHaveBeenCalled(); + expect(provider.execute).toHaveBeenCalledTimes(1); + }); + + it.each([ + ["a model the connection cannot use", { code: "antigravity_model_unavailable", message: "Not available", providerFailure: { ...capacityRefusal, category: "model_unavailable", retryability: "requires_action" } }], + ["an exhausted allowance", { code: "provider_turn_failed", message: "Quota", providerFailure: { ...capacityRefusal, category: "quota_exhausted", retryability: "requires_action" } }], + ["a rejected sign-in", { code: "provider_turn_failed", message: "Denied", providerFailure: { ...capacityRefusal, category: "authentication", retryability: "requires_action" } }], + ["an untyped failure", { code: "provider_turn_failed", message: "Something broke" }], + ])("still fails the run after an accepted finish followed by %s", async (_name, error) => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Finished before a real failure", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: { issueId } }); + const adapter = await acceptResultThenProviderFailure(runId, issueId, { provider: typedProvider, error }); + await waitForPendingRunFailureReports(); + expect(adapter).toMatchObject({ exitCode: 1, nativeFinalization: { terminal: { runTerminalState: "failed" } } }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0].status).toBe("failed"); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).not.toBe("done"); + for (const retry of await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))) + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry.id)); + }); + + it("keeps a result saved by an older release on its recorded outcome through projection", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Saved before the accepted outcome", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: { issueId } }); + await acceptResultThenProviderFailure(runId, issueId, { provider: typedProvider, savedByOlderRelease: true, + error: { code: "provider_turn_failed", message: capacityRefusal.message, providerFailure: capacityRefusal } }); + // The finalizer, the projection and the superseded path all keep the saved failed terminal. + const [settled] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(settled).toMatchObject({ status: "failed", resultJson: { prpRunTerminalState: "failed" } }); + expect(await endAsSuperseded(runId)).toMatchObject({ status: "failed" }); + for (const retry of await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))) + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry.id)); + }); + it("does not retry or change the task after reassignment", async () => { const issueId = randomUUID(), runId = randomUUID(); await db.insert(issues).values({ id: issueId, companyId, title: "Reassigned capacity task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" }); diff --git a/server/src/services/native-runtime/native-response-presentation-query.ts b/server/src/services/native-runtime/native-response-presentation-query.ts index a86931c1c35..2a2157855d9 100644 --- a/server/src/services/native-runtime/native-response-presentation-query.ts +++ b/server/src/services/native-runtime/native-response-presentation-query.ts @@ -1,4 +1,5 @@ import { alias, QueryBuilder } from "drizzle-orm/pg-core"; +import { nativeEffectiveRunTerminalStateSql } from "./native-accepted-outcome.js"; import { and, asc, eq, exists, gt, inArray, isNotNull, isNull, ne, notExists, or, sql } from "drizzle-orm"; import { chatActions, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, statusDecisions, statusDecisionEffects } from "@paperclipai/db"; import type { NativeResponsePresentationScope } from "../native-response-presentation-notifications.js"; @@ -39,8 +40,8 @@ export function nativeResponsePresentationCandidates(scope?: NativeResponsePrese sql`${heartbeatRuns.contextSnapshot}->'skipIssueComment' is distinct from 'true'::jsonb`, sql`coalesce(${statusDecisions.decisionJson}->'externalChatReviewPresentation', 'null'::jsonb) in ('null'::jsonb, 'false'::jsonb, '0'::jsonb, '""'::jsonb)`, sql`${nativeRunResults.resultJson} #>> '{result,schema}' = 'paperclip.run_result.v1'`, - sql`${nativeRunResults.resultJson} #>> '{terminal,runTerminalState}' = 'succeeded'`, - sql`${nativeRunResults.resultJson} #>> '{terminal,turnTerminalState}' = 'completed'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'succeeded'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson, "turnTerminalState")} = 'completed'`, or( and(eq(heartbeatRuns.status, "succeeded"), or(sql`(coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = '')`, diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index fac6d0a6d76..6ff84b17b54 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -32,6 +32,7 @@ import { settleExternalConversation } from "../slack-conversation-lifecycle.js"; import { executionFailureRetryCount } from "../execution-recovery-attempt.js"; import { isFailedTurnContinuationRun } from "./native-failed-turn-continuation.js"; import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js"; +import { applyNativeAcceptedOutcome, nativeEffectiveTerminal, readNativeAcceptedOutcome } from "./native-accepted-outcome.js"; import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, cancelStoppedRunContinuation, nativeRunHasStopRequest, readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js"; import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE, isNativeEnvironmentBlocker } from "./native-environment-blocker.js"; import { hasQueuedChatRequest } from "./first-turn-queued-input.js"; @@ -1159,7 +1160,7 @@ async function recoverCommittedNativeChatResponseInScope( .for("share"); const envelope = record(accepted?.resultJson); const result = record(envelope.result); - const terminal = record(envelope.terminal); + const terminal = nativeEffectiveTerminal(envelope, record(envelope.terminal)); if ( !accepted || !decision || @@ -1571,10 +1572,11 @@ export async function finalizeNativeRun(input: { const envelope = record(resultRow.resultJson); const result = record(envelope.result); const terminal = record(envelope.terminal); - const terminalState = terminal.runTerminalState; - if (!["succeeded", "failed", "cancelled"].includes(String(terminalState))) { + if (!["succeeded", "failed", "cancelled"].includes(String(terminal.runTerminalState))) { throw new Error("native_finalization_invalid"); } + const acceptedOutcome = readNativeAcceptedOutcome(envelope); + const terminalState = applyNativeAcceptedOutcome(acceptedOutcome, terminal).runTerminalState; await input.db .update(nativeRunFinalizations) @@ -1735,9 +1737,9 @@ export async function finalizeNativeRun(input: { (!planWait || nativeSha256(planWait.result) !== nativeSha256(result))) { throw new Error("native_plan_wait_authority_lost"); } - const { providerFailure, turnFailure, providerExplanation } = await readPersistedNativeFailureEvidence( - input.db, run, resultRow.turnId, envelope.terminal as PrpTerminalState, - ); + const { providerFailure, turnFailure, providerExplanation } = acceptedOutcome + ? { providerFailure: null, turnFailure: null, providerExplanation: null } + : await readPersistedNativeFailureEvidence(input.db, run, resultRow.turnId, envelope.terminal as PrpTerminalState); const ownsProviderFailureDecision = (!authoritativeIssue.executionRunId || authoritativeIssue.executionRunId === run.id) && (reviewContext ? nativeReview?.interaction.status === "pending" diff --git a/server/src/services/native-runtime/native-run-projection.ts b/server/src/services/native-runtime/native-run-projection.ts index b480977eb23..1e0bf6875a7 100644 --- a/server/src/services/native-runtime/native-run-projection.ts +++ b/server/src/services/native-runtime/native-run-projection.ts @@ -1,4 +1,5 @@ import { notifyExternalConversationSettlement } from "../external-conversation-settlement-notifications.js"; +import { nativeEffectiveRunTerminalStateSql } from "./native-accepted-outcome.js"; import { promoteDeferredWorkIntents } from "../work-intent-outbox.js"; import { notifyStrandedAgentStatus } from "../live-run-recovery-notifications.js"; import { notifyNativeEnvironmentSettlement } from "../native-environment-settlement-notifications.js"; @@ -102,7 +103,7 @@ export function nativeRunProjectionNeedsRepair(projectedStatus: "succeeded" | "f export function pendingNativeRunProjectionCondition(db: Db) { - const status = sql`${nativeRunResults.resultJson}->'terminal'->>'runTerminalState'`; + const status = nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson); return exists(db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and( eq(nativeRunResults.id, nativeRunFinalizations.resultId), eq(nativeRunResults.runId, nativeRunFinalizations.runId), @@ -132,7 +133,7 @@ export async function projectCommittedRun(input: { }) { if (!input.coordinator.resultId) return; const resultRow = await input.db - .select({ terminalState: sql`${nativeRunResults.resultJson}->'terminal'->>'runTerminalState'` }) + .select({ terminalState: nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson) }) .from(nativeRunResults) .where( and( diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 93a313418b8..77f211b3507 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -1,4 +1,5 @@ import { currentControllerProcess } from "../controller-process-identity.js"; +import { applyNativeAcceptedOutcome, nativeRetainsWarmSession, readNativeAcceptedOutcome, type NativeAcceptedOutcome } from "./native-accepted-outcome.js"; import { settleReattachRun } from "../heartbeat/run-admission.js"; import { remoteRecoveryLeaseMismatch } from "./remote-recovery-lease-mismatch.js"; import { isGovernancePauseStop } from "../governance-pause-stop.js"; @@ -9268,6 +9269,15 @@ function runnerClosedTurnStartSession(error: unknown, depth = 0): boolean { return runnerClosedTurnStartSession(value.cause, depth + 1); } +async function readSavedNativeAcceptedOutcome(db: Db, binding: { runId: string; companyId: string; issueId: string }, turnId: string | null) { + const [row] = await db.select({ resultJson: nativeRunResults.resultJson }).from(nativeRunResults).where(and( + eq(nativeRunResults.runId, binding.runId), eq(nativeRunResults.companyId, binding.companyId), + eq(nativeRunResults.issueId, binding.issueId), eq(nativeRunResults.schemaStatus, "accepted"), + turnId ? eq(nativeRunResults.turnId, turnId) : isNull(nativeRunResults.turnId), + )).limit(1); + return readNativeAcceptedOutcome(row?.resultJson); +} + export function nativeSessionFailureSourceCode(error: unknown, runnerSandboxDiskFull = false) { return nativeSandboxDiskFullSourceCode(classifyNativeSessionFailure(error), error, runnerSandboxDiskFull); } @@ -12229,6 +12239,7 @@ async function executePaperclipNativeSessionAttempt( }, ); let native: Awaited>; + let acceptedOutcome: NativeAcceptedOutcome | null = null; let releaseGoalController: (() => void) | null = null; const releaseRegisteredGoalController = () => { // The controller is assigned from the asynchronous onSession callback. @@ -13193,7 +13204,8 @@ async function executePaperclipNativeSessionAttempt( } await input.onLog?.("stderr", "[paperclip-runner] managed credential refresh failed; provider session retired.\n"); } - if (native.terminal.runTerminalState === "succeeded") { + acceptedOutcome = await readSavedNativeAcceptedOutcome(input.db, input.execution.binding, native.turnId); + if (native.terminal.runTerminalState === "succeeded" || acceptedOutcome) { // A truncated, verified external-chat wake cannot settle from the // provider's partial inline prompt. The run-scoped reader records a // durable complete-page receipt; this fence revalidates that exact @@ -14027,7 +14039,7 @@ async function executePaperclipNativeSessionAttempt( let postExecutionCleanupFailed = false; try { if (warmSessionId !== null && lifecyclePolicy.mode === "warm") { - const retainSession = native.terminal.runTerminalState === "succeeded" && native.result.continuation?.kind !== "case_handoff"; + const retainSession = nativeRetainsWarmSession({ terminal: native.terminal, acceptedOutcome, continuationKind: native.result.continuation?.kind }); const instructionCopy = input.instructionWorkingCopy; const ownedSession = warmNativeSessions.get(warmSessionId); let collectInstructions: boolean; @@ -14227,6 +14239,7 @@ async function executePaperclipNativeSessionAttempt( logger.warn({ runId: input.execution.binding.runId }, "Native finalization claim release failed after an earlier error"); } } + const terminal = applyNativeAcceptedOutcome(acceptedOutcome, native.terminal); const finalization: NativeFinalizationResult = { schema: "paperclip.native-finalization.v1", runtimeMode: "native", @@ -14234,7 +14247,7 @@ async function executePaperclipNativeSessionAttempt( issueId: input.execution.binding.issueId, companyId: input.execution.binding.companyId, result: native.result as unknown as Record, - terminal: native.terminal, + terminal, turnId: native.turnId, sourceInstanceId: effectiveRunnerInstanceId, normalizedSessionId: native.normalizedSessionId, @@ -14245,28 +14258,30 @@ async function executePaperclipNativeSessionAttempt( highestContiguousSourceSeq: native.highestContiguousSourceSeq, workspaceFinalizeStatus: "pending", }; - const providerFailure = providerFailureObservation.forTerminal(native.turnId, native.terminal); - const providerExplanation = providerFailureObservation.providerFailureForTerminal(native.turnId, native.terminal); + const providerFailure = acceptedOutcome ? null : providerFailureObservation.forTerminal(native.turnId, native.terminal); + const providerExplanation = acceptedOutcome ? null : providerFailureObservation.providerFailureForTerminal(native.turnId, native.terminal); // Keep the generic failure behavior, but record why the turn failed. - const unclassifiedTurnFailure = providerFailureObservation.unclassifiedTurnFailure(native.turnId, native.terminal); + const unclassifiedTurnFailure = providerFailureObservation.unclassifiedTurnFailure(native.turnId, terminal); const adapterResult: AdapterExecutionResult = { - exitCode: native.terminal.runTerminalState === "succeeded" ? 0 : 1, + exitCode: terminal.runTerminalState === "succeeded" ? 0 : 1, signal: null, timedOut: false, errorMessage: - native.terminal.runTerminalState === "succeeded" + terminal.runTerminalState === "succeeded" ? null : providerFailure?.errorMessage ?? explainNativeTurnFailure(unclassifiedTurnFailure)?.error - ?? `Native session ${native.terminal.runTerminalState}`, + ?? `Native session ${terminal.runTerminalState}`, ...(providerFailure ? { errorCode: providerFailure.errorCode } : {}), resultJson: { nativeResult: native.result as unknown as Record, - nativeTerminal: native.terminal as unknown as Record, + nativeTerminal: terminal as unknown as Record, ...((input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8") ? { providerAccounting: { usage: null, cost: null, externallyBilled: true }, externalStopConfirmed: false } : {}), ...(input.execution.provider.kind === "cursor_cloud" ? { providerAccounting: { usage: null, cost: null, externallyBilled: true } } : {}), ...(providerFailure ? { nativeProviderFailure: providerFailure.diagnostic } : {}), ...(unclassifiedTurnFailure ? { nativeTurnFailure: unclassifiedTurnFailure } : {}), ...(providerExplanation ? { providerFailure: providerExplanation } : {}), + ...(acceptedOutcome ? { providerFailureAfterAcceptedResult: { + provider: acceptedOutcome.providerFailure.provider, category: acceptedOutcome.providerFailure.category } } : {}), ...(native.goalRolloverRequired ? { goalRolloverRequired: true } : {}), planSynchronizations, }, @@ -14291,11 +14306,11 @@ async function executePaperclipNativeSessionAttempt( if (taskSettleScope) { await trace.end(taskSettleScope, { outcome: - native.terminal.runTerminalState === "succeeded" ? "ok" : "failed", + terminal.runTerminalState === "succeeded" ? "ok" : "failed", }); } await trace.finish( - native.terminal.runTerminalState === "succeeded" ? "ok" : "failed", + terminal.runTerminalState === "succeeded" ? "ok" : "failed", ); return adapterResult; } diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.ts b/server/src/services/native-runtime/paperclip-control-plane-port.ts index d495d94668a..495de4852ec 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.ts @@ -1,4 +1,6 @@ import { notifyNativeResultCommit } from "../native-result-commit-notifications.js"; +import { applyNativeAcceptedOutcome, deriveNativeAcceptedOutcome, NATIVE_ACCEPTED_OUTCOME_KEY } from "./native-accepted-outcome.js"; +import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js"; import { notifyNativeWorkspaceFinalization } from "../native-workspace-finalization-notifications.js"; import { createAgentIdentityRedactor } from "../agent-identity-redaction.js"; import { and, asc, eq, gt, or, sql } from "drizzle-orm"; @@ -742,9 +744,15 @@ export class PaperclipControlPlanePort implements ControlPlanePort { return false; } if (owner?.resultId) throw new Error("structured_result_replay_conflict"); + const acceptedOutcome = value.terminal.runTerminalState === "failed" && value.terminal.reportedWorkDisposition === "done" + ? deriveNativeAcceptedOutcome({ terminal: value.terminal, + ...await readPersistedNativeFailureEvidence(tx as unknown as Db, run, value.turnId ?? null, value.terminal) }) + : null; + const effectiveTerminal = applyNativeAcceptedOutcome(acceptedOutcome, value.terminal); const resultJson = { result: validated.result, terminal: value.terminal, + ...(acceptedOutcome ? { [NATIVE_ACCEPTED_OUTCOME_KEY]: acceptedOutcome } : {}), normalizationDiagnostics: { ignoredAttentionRequests: normalizationDiagnostics.ignoredAttentionRequests, }, @@ -792,8 +800,8 @@ export class PaperclipControlPlanePort implements ControlPlanePort { // Publish the accepted contract with its durable receipt. Recovery // may settle this run without the original adapter ever returning. nativeTerminal: value.terminal, - prpTurnTerminalState: value.terminal.turnTerminalState, - prpRunTerminalState: value.terminal.runTerminalState, + prpTurnTerminalState: effectiveTerminal.turnTerminalState, + prpRunTerminalState: effectiveTerminal.runTerminalState, prpReportedWorkDisposition: value.terminal.reportedWorkDisposition, }, updatedAt: new Date(), diff --git a/server/src/services/native-runtime/preserved-native-result-finalization.ts b/server/src/services/native-runtime/preserved-native-result-finalization.ts index d39c00459ca..0631dafd861 100644 --- a/server/src/services/native-runtime/preserved-native-result-finalization.ts +++ b/server/src/services/native-runtime/preserved-native-result-finalization.ts @@ -1,4 +1,5 @@ import { and, eq, gte, inArray, ne, or, sql } from "drizzle-orm"; +import { nativeEffectiveRunTerminalStateSql } from "./native-accepted-outcome.js"; import { completionContracts, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; import { z } from "zod"; @@ -63,7 +64,7 @@ export async function readPreservedNativeResultFinalization(db: Db, binding: { disposition: sql`${nativeRunResults.resultJson}#>>'{result,reportedWorkDisposition}'`, continuation: sql`${nativeRunResults.resultJson}#>>'{result,continuation,kind}'`, terminalDisposition: sql`${nativeRunResults.resultJson}#>>'{terminal,reportedWorkDisposition}'`, - terminalState: sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}'` }, + terminalState: nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson) }, contract: { id: completionContracts.id, sha256: completionContracts.canonicalSha256 }, actionId: issueRecoveryActions.id, evidence: sql>`jsonb_build_object('runId', ${issueRecoveryActions.evidence}->'runId', diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 5f0cc7516fb..8fcd60bd528 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -1,4 +1,5 @@ import { NativePullRequestCompletionError, verifyNativePullRequestCompletion } from "./native-pull-request-completion.js"; +import { nativeEffectiveTerminal } from "./native-accepted-outcome.js"; import { notifyNativeStatusWakeWork } from "../deferred-execution-notifications.js"; import { toolCallLoopContinuationKey } from "./repeated-tool-failure-guard.js"; import { assertAgentInteraction } from "../agent-interaction-policy.js"; @@ -2373,7 +2374,7 @@ export async function commitNativeStatusDecision(input: { eq(nativeRunResults.id, coordinator.resultId!), eq(nativeRunResults.companyId, input.companyId), eq(nativeRunResults.issueId, input.issueId), eq(nativeRunResults.runId, input.runId), eq(nativeRunResults.schemaStatus, "accepted"), )); - const result = record(accepted?.resultJson.result), terminal = record(accepted?.resultJson.terminal); + const result = record(accepted?.resultJson.result), terminal = nativeEffectiveTerminal(accepted?.resultJson, record(accepted?.resultJson.terminal)); if (ids.length !== expected.interactionIds.length || expected.interactionIds.some(id => !ids.includes(id)) || terminal.runTerminalState !== "succeeded" || terminal.turnTerminalState !== "completed" || !["done", "yielded"].includes(String(result.reportedWorkDisposition)) || diff --git a/server/src/services/preserved-result-finalization.ts b/server/src/services/preserved-result-finalization.ts index 95f7e31476b..99c847b43d7 100644 --- a/server/src/services/preserved-result-finalization.ts +++ b/server/src/services/preserved-result-finalization.ts @@ -1,4 +1,5 @@ import { notifyNativeFinalizationWork } from "./native-finalization-notifications.js"; +import { nativeEffectiveRunTerminalStateSql } from "./native-runtime/native-accepted-outcome.js"; import { and, desc, eq, gte, ne, or, sql } from "drizzle-orm"; import { agentWakeupRequests, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; import { readSystemRecovery } from "./system-recovery-state.js"; @@ -83,7 +84,7 @@ async function readApplicableResult(db: Db, companyId: string, runId: string, lo eq(nativeRunResults.companyId, companyId), eq(nativeRunResults.issueId, issue.id), eq(nativeRunResults.runId, runId), eq(nativeRunResults.id, coordinator.resultId), eq(nativeRunResults.schemaStatus, "accepted"), - sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'succeeded'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'succeeded'`, )); return result ? { coordinator, issue, run, result } : null; } diff --git a/server/src/services/workspace-recovery-source.ts b/server/src/services/workspace-recovery-source.ts index 19dc219c2a1..44b5e74a68a 100644 --- a/server/src/services/workspace-recovery-source.ts +++ b/server/src/services/workspace-recovery-source.ts @@ -1,4 +1,5 @@ import { hasMigratedLegacyWorkspaceSource } from "./legacy-workspace-recovery-migration.js"; +import { nativeEffectiveRunTerminalStateSql } from "./native-runtime/native-accepted-outcome.js"; import { retiredReusableLeasePredecessors } from "./environment-lease-handoff.js"; import { and, eq, inArray, ne, or, sql } from "drizzle-orm"; import { environmentLeases, environments, executionWorkspaces, executionWorkspaceSnapshots, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; @@ -151,7 +152,7 @@ export async function inspectWorkspaceRecoverySource(db: Db, input: WorkspaceRec eq(nativeRunResults.runId, run.id), eq(nativeRunResults.id, coordinator.resultId), eq(nativeRunResults.completionContractId, run.completionContractId), eq(nativeRunResults.schemaStatus, "accepted"), - sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'succeeded'`, + sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'succeeded'`, )).limit(1))[0] : null; const sources = []; for (const leaseId of leaseIds as string[]) {