From 1196a3402de2934193d7a381bf65b398addb1213 Mon Sep 17 00:00:00 2001 From: paperclipbugbot Date: Fri, 20 Nov 2026 03:57:54 -0800 Subject: [PATCH] fix(native): do not report a provider usage-limit run that a restart ended (#22385) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs report an unexpected terminal failure to Sentry through the run-failure reporter > - The reporter keeps an expected provider usage-limit failure (`native_provider_usage_limit`) out of Sentry, because the task takes its provider-limit wait and runs again after the reset > - A server restart can end such a run after its provider turn failed on the limit, but before its executor saves `native_provider_usage_limit`. Restart recovery then blocks the run as `provider_checkpoint_permanently_failed`, and the reporter sends it to Sentry > - On staging, one deploy restart sent seven such reports at once. Each task then took its provider-limit wait and finished after the reset, so no operator action was necessary > - This pull request re-derives the usage-limit fact from the run's last committed runner turn terminal and keeps that expected failure out of Sentry > - The benefit is that a deploy during a provider limit does not create false error reports, and real checkpoint failures are still reported ## Linked Issues or Issue Description **What happened?** A deploy restarted the server while several native runs were settling a provider turn that failed on a weekly allowance (`quota_exhausted`). Restart recovery blocked each run as `native_restart_recovery_blocked` / `provider_checkpoint_permanently_failed`. The run-failure reporter sent one Sentry event per run. **Expected behavior** A run that ended on a provider usage limit is an expected failure. The reporter does not send it to Sentry when the executor settles it normally. A restart during settlement must not change that. **Steps to reproduce** 1. Start a native run whose provider turn fails with a `quota_exhausted` or `rate_limit` provider failure. 2. Restart the server before the executor saves `native_provider_usage_limit`. 3. Restart recovery blocks the run as `provider_checkpoint_permanently_failed`, and the reporter sends a Sentry event. Refs #20149 ## What Changed - `native-provider-failure.ts`: move `nativeProviderUsageLimitFromEvent` here from `native-session-executor.ts` so that the evidence reader can use it. The executor re-exports it, so its callers do not change. - `native-provider-failure-evidence.ts`: add `readPersistedNativeTerminalUsageLimit`. It reads the run's last committed turn lifecycle event. It returns true only when that event is a `turn.failed` from the run's own runner instance, the PRP event validates against the stored row (run, session, source, sequence and payload hash), and the failure is a provider usage limit. - `run-failure-report.ts`: for an unexpected `native_restart_recovery_blocked` / `provider_checkpoint_permanently_failed` failure, skip the report when that reader returns true. A read error logs a warning and keeps the report. - Add a real-process restart-recovery test with four cases: usage limit and rate limit are not reported; an unknown failure and a later turn after the limit are still reported. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-runner-restart-recovery.integration.test.ts -t "provider usage limit|pending retry|unreported"`: 5 passed. - Red proof: with only `run-failure-report.ts` reverted, the `usage-limit` and `rate-limit` cases fail (`expected ... to have a length of +0 but got 1`). The two report cases still pass. - `cd server && PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm run typecheck`: passed. - `npx vitest run src/services/run-failure-report src/services/native-runtime/native-provider-failure src/services/native-runtime/native-session-executor.test.ts`: 1619 passed, 1 failed. The failure (`compares export process compatibility without changing conversation identity (changed: false)`, `db.transaction is not a function`) also fails on unchanged `master` (`ce8006de3c`), so this change does not cause it. ## Risks - Low risk. The change only removes a Sentry report. It does not change run status, task status, recovery, or the provider-limit wait. - The filter needs a validated, run-bound runner terminal. A missing, tampered, foreign or later event keeps the report. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in an agent harness. ## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../native-provider-failure-evidence.ts | 34 ++++++++++++- .../native-runtime/native-provider-failure.ts | 14 ++++++ ...unner-restart-recovery.integration.test.ts | 48 +++++++++++++++++++ .../native-runtime/native-session-executor.ts | 16 +------ server/src/services/run-failure-report.ts | 19 ++++++++ 5 files changed, 115 insertions(+), 16 deletions(-) diff --git a/server/src/services/native-runtime/native-provider-failure-evidence.ts b/server/src/services/native-runtime/native-provider-failure-evidence.ts index 02f21282af2..de5038f3280 100644 --- a/server/src/services/native-runtime/native-provider-failure-evidence.ts +++ b/server/src/services/native-runtime/native-provider-failure-evidence.ts @@ -1,8 +1,8 @@ -import { and, desc, eq, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, sql } from "drizzle-orm"; import { heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import { parseNativeExecutionInput, validatePrpEvent, type PrpTerminalState } from "../../vendor/paperclip-runner/index.js"; import { nativeSha256 } from "./canonical.js"; -import { createNativeProviderFailureObservation } from "./native-provider-failure.js"; +import { createNativeProviderFailureObservation, nativeProviderUsageLimitFromEvent } from "./native-provider-failure.js"; function record(value: unknown): Record { return value !== null && typeof value === "object" && !Array.isArray(value) @@ -66,6 +66,36 @@ export async function readPersistedNativeFailureEvidence( }; } +const TURN_LIFECYCLE_EVENT_TYPES = [ + "turn.submitted", "turn.started", "turn.accepted", "turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled", +] as const; + +/** + * True only when the run's last committed runner turn terminal is an exhausted + * provider allowance. A restart can end such a run before its executor saves + * `native_provider_usage_limit`; this re-derives that fact from the same + * immutable, run-bound event the executor classified. + */ +export async function readPersistedNativeTerminalUsageLimit( + db: Db, + run: typeof heartbeatRuns.$inferSelect, +): Promise { + if (run.runtimeMode !== "native" || !run.nativeSessionId || !run.runnerInstanceId) return false; + const [row] = await db.select().from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + sql`${heartbeatRunEvents.sourceInstanceId} is not null`, + inArray(heartbeatRunEvents.eventType, [...TURN_LIFECYCLE_EVENT_TYPES]), + )).orderBy(desc(heartbeatRunEvents.seq)).limit(1); + // A later turn, or one from another runner, means this failure did not end the run. + if (!row || row.eventType !== "turn.failed" || row.sourceInstanceId !== run.runnerInstanceId) return false; + const parsed = validatePrpEvent(record(row.payload).prpEvent); + if (!parsed.ok || parsed.event.runId !== run.id || parsed.event.normalizedSessionId !== run.nativeSessionId || + parsed.event.sourceKind !== "runner" || parsed.event.sourceInstanceId !== run.runnerInstanceId || + parsed.event.sourceEventId !== row.sourceEventId || parsed.event.sourceSeq !== row.sourceSeq || + parsed.event.eventType !== row.eventType || row.sourcePayloadSha256 !== nativeSha256(parsed.event)) return false; + return nativeProviderUsageLimitFromEvent(parsed.event); +} + export async function readPersistedNativeModelRejection( ...args: Parameters ) { diff --git a/server/src/services/native-runtime/native-provider-failure.ts b/server/src/services/native-runtime/native-provider-failure.ts index ace90fe4401..03680535dd1 100644 --- a/server/src/services/native-runtime/native-provider-failure.ts +++ b/server/src/services/native-runtime/native-provider-failure.ts @@ -27,6 +27,20 @@ function record(value: unknown): Record { : {}; } +/** Classify only a committed provider terminal, never model prose or tool output. */ +export function nativeProviderUsageLimitFromEvent( + event: Pick, +): boolean { + const payload = record(event.payload); + if (event.sourceKind !== "runner" || event.eventType !== "turn.failed" || payload.status !== "failed") return false; + const error = record(payload.error); + if (error.codexErrorInfo === "usageLimitExceeded") return true; + // ACP harnesses type the same exhausted allowance as a provider failure. + // Context, turn and configured budget limits stay ordinary terminals. + const category = readProviderFailure(error.providerFailure)?.category; + return category === "quota_exhausted" || category === "rate_limit"; +} + /** An API-key Codex turn whose configured model the Responses API answers with 404. */ export const NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC = { provider: "codex", diff --git a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts index cadd37306f1..740a6b740ac 100644 --- a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts +++ b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts @@ -62,6 +62,7 @@ import { materializeAsset } from "./runtime-context.js"; import { createRunnerTestTlsTunnel, dockerCommandRunner } from "../../__tests__/helpers/docker-command-runner.js"; import { finalizeNativeRun } from "./native-run-finalizer.js"; import { waitForPendingRunFailureReports } from "../run-failure-report.js"; +import { nativeSha256 } from "./canonical.js"; import { closeIdleWarmNativeSessionsForRestart, detachNativeSessionsForRestart, @@ -4492,6 +4493,53 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); expect(await fixture.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId))).toHaveLength(1); }); + it.each([ + { scenario: "usage-limit", category: "quota_exhausted", laterTurn: false, reported: false }, + { scenario: "rate-limit", category: "rate_limit", laterTurn: false, reported: false }, + { scenario: "other-failure", category: "unknown", laterTurn: false, reported: true }, + { scenario: "later-turn", category: "quota_exhausted", laterTurn: true, reported: true }, + ])("reports a failed checkpoint a restart ended only when its last turn was not a provider usage limit ($scenario)", + async ({ scenario, category, laterTurn, reported }) => { + // Staging run 3f4a9403: the ACP turn failed on a weekly allowance, and a + // deploy restarted the server while the run settled. Normal settlement + // keeps that expected failure out of Sentry; restart recovery must too. + const fixture = await seedRun(`FAILED-CHECKPOINT-LIMIT-${scenario}`); + await fixture.db.update(heartbeatRuns).set({ runnerProfileJson: { sessionCheckpoint: { + terminal: { runTerminalState: "failed", turnTerminalState: "failed" }, + providerSessionId: "limited-provider-session", + } } }).where(eq(heartbeatRuns.id, fixture.runId)); + await fixture.db.update(nativeRunFinalizations).set({ attempt: 1 }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const runnerEvent = (sourceSeq: number, eventType: string, turnId: string, payload: Record) => ({ + schema: "paperclip.prp.event.v1", runId: fixture.runId, normalizedSessionId: fixture.native.normalizedSessionId, + turnId, sourceInstanceId: fixture.native.runnerInstanceId, + sourceEventId: `${fixture.native.runnerInstanceId}:${fixture.runId}:${sourceSeq}`, sourceSeq, + sourceKind: "runner", eventType, schemaVersion: 1, priority: 1, emittedAt: new Date().toISOString(), payload, + }); + const events = [runnerEvent(12, "turn.failed", "limited-turn", { status: "failed", error: { + code: "RUNTIME", message: "ACP agent reported a terminal limit failure.", + providerFailure: { schema: "paperclip.provider-failure.v1", phase: "turn", provider: "anthropic", category, + retryability: "requires_action", message: "ACP agent reported a terminal limit failure." }, + } })]; + if (laterTurn) events.push(runnerEvent(13, "turn.started", "later-turn", { status: "inProgress" })); + for (const [index, event] of events.entries()) { + await fixture.db.insert(heartbeatRunEvents).values({ companyId, runId: fixture.runId, agentId, seq: 900 + index, + stream: "system", level: "info", eventType: event.eventType, payload: { prpEvent: event }, + sourceInstanceId: event.sourceInstanceId, sourceEventId: event.sourceEventId, sourceSeq: event.sourceSeq, + sourcePayloadSha256: nativeSha256(event) }); + } + const captureCallsBefore = mockCaptureRunFailure.mock.calls.length; + + expect(await claimNativeRestartRecoveries({ + db: fixture.db, controller: successor, restartKind: "hard", runIds: [fixture.runId], + })).toEqual([{ kind: "blocked", runId: fixture.runId, reason: "provider_checkpoint_permanently_failed" }]); + await waitForPendingRunFailureReports(); + + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run).toMatchObject({ status: "failed", errorCode: "native_restart_recovery_blocked", + error: "provider_checkpoint_permanently_failed" }); + expect(mockCaptureRunFailure.mock.calls.slice(captureCallsBefore)).toHaveLength(reported ? 1 : 0); + }); + it("reports one event when it blocks a failed run that was an unreported pending retry", async () => { const fixture = await seedRun("PENDING-RETRY-BLOCKED"); // The executor stores a scheduled same-run retry as failed + retryable_failure, diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 68857191dc4..bdf7d3ae00c 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -119,7 +119,7 @@ import { createAgentIdentityRedactor } from "../agent-identity-redaction.js"; import { redactNativeFailureError } from "./native-failure-redaction.js"; import { parseCodexCliVersion } from "./codex-runtime-compatibility.js"; import { createNativeToolTrace, type NativeToolTrace } from "./native-tool-trace.js"; -import { createNativeProviderFailureObservation } from "./native-provider-failure.js"; +import { createNativeProviderFailureObservation, nativeProviderUsageLimitFromEvent } from "./native-provider-failure.js"; import { explainNativeTurnFailure } from "./native-run-failure-explanation.js"; import { nativeStartupRetryExhaustedAction, nativeStartupRetryWait, planNativeStartupRetry } from "./native-startup-retry.js"; import { admitUnclaimedNativeBootstrapRetry } from "./native-bootstrap-retry.js"; @@ -9024,19 +9024,7 @@ function armWarmNativeSessionIdleTimer( entry.idleTimer.unref(); } -/** Classify only a committed provider terminal, never model prose or tool output. */ -export function nativeProviderUsageLimitFromEvent( - event: Pick, -): boolean { - const payload = record(event.payload); - if (event.sourceKind !== "runner" || event.eventType !== "turn.failed" || payload.status !== "failed") return false; - const error = record(payload.error); - if (error.codexErrorInfo === "usageLimitExceeded") return true; - // ACP harnesses type the same exhausted allowance as a provider failure. - // Context, turn and configured budget limits stay ordinary terminals. - const category = readProviderFailure(error.providerFailure)?.category; - return category === "quota_exhausted" || category === "rate_limit"; -} +export { nativeProviderUsageLimitFromEvent }; export function nativeSessionFailureDisposition( attempt: number, diff --git a/server/src/services/run-failure-report.ts b/server/src/services/run-failure-report.ts index 79b8b2805aa..e4592e70901 100644 --- a/server/src/services/run-failure-report.ts +++ b/server/src/services/run-failure-report.ts @@ -268,6 +268,20 @@ function isNativeProviderUsageLimitFailure(run: HeartbeatRun, options: RunFailur return category === "quota_exhausted" || category === "rate_limit"; } +/** + * A server restart can interrupt a run whose provider turn already ended on an + * exhausted allowance, before its executor saves `native_provider_usage_limit`. + * Restart recovery then ends the run as `provider_checkpoint_permanently_failed`. + * The task still takes its provider-limit wait, so the same expected failure + * stays unreported. The run's persisted runner terminal is the proof. + */ +async function isRestartEndedNativeUsageLimit(db: Db, run: HeartbeatRun, options: RunFailureReportOptions): Promise { + if (run.status !== "failed" || run.runtimeMode !== "native" || run.errorCode !== "native_restart_recovery_blocked" || + run.error !== "provider_checkpoint_permanently_failed" || options.phase === "setup" || run.signal != null) return false; + const { readPersistedNativeTerminalUsageLimit } = await import("./native-runtime/native-provider-failure-evidence.js"); + return readPersistedNativeTerminalUsageLimit(db, run); +} + function isCodexAcpModelCapacityFailure(run: HeartbeatRun, options: RunFailureReportOptions): boolean { const result = asRecord(run.resultJson); return run.status === "failed" && run.errorCode === "codex_transient_upstream" && @@ -424,6 +438,11 @@ async function captureTerminalRunFailure( return false; }); if (capacityRetry) return; + const restartEndedUsageLimit = await isRestartEndedNativeUsageLimit(db, run, options).catch((err) => { + logger.warn({ err, runId: run.id }, "failed to read native usage-limit terminal for run failure report"); + return false; + }); + if (restartEndedUsageLimit) return; } const taskId = readTaskId(run);