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);