From 957de6579639a030cc50bf2cc8bbf32238ed48d7 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 01:02:01 +0000 Subject: [PATCH 1/2] Distinguish run failures from system failures --- packages/api-client/src/schema.d.ts | 24 ++++++ .../migrations/0032_run_failure_outcomes.sql | 21 +++++ packages/api/scripts/static-slice.config.ts | 2 +- packages/api/src/amp-backend.ts | 8 +- packages/api/src/exe-vm-backend.ts | 9 ++- packages/api/src/execution.ts | 2 + packages/api/src/flow-service.ts | 4 +- packages/api/src/harness-diagnostics.ts | 2 + .../api/src/postgres/run-query-repository.ts | 9 ++- packages/api/src/postgres/run-repository.ts | 29 +++++-- packages/api/src/postgres/run-scheduler.ts | 39 ++++++---- packages/api/src/postgres/schema.ts | 2 +- packages/api/src/run-read-contracts.ts | 5 +- .../test/report-run-error-boundary.test.ts | 6 +- .../test/report-run-error.postgres.test.ts | 2 +- packages/api/test/run-finalization.test.ts | 31 ++++---- packages/app/src/features/runs/detail.tsx | 2 +- packages/app/src/features/runs/history.tsx | 4 +- packages/app/src/features/runs/list.tsx | 2 +- packages/app/src/shared/ui.tsx | 17 +++-- packages/app/test/runs.browser.test.mjs | 23 +++++- packages/docs/llms-full.txt | 28 ++++++- packages/docs/openapi.yaml | 76 +++++++++++++++++++ packages/docs/troubleshooting/runs.mdx | 5 +- packages/docs/work/results.mdx | 23 +++++- 25 files changed, 301 insertions(+), 74 deletions(-) create mode 100644 packages/api/migrations/0032_run_failure_outcomes.sql diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 8e15beb9..eca44928 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1822,6 +1822,12 @@ export interface components { updated_at: string; started_at: string | null; failure_source: ("system" | "agent") | null; + failure?: { + /** @enum {string} */ + source: "run" | "system"; + code: string; + reason: string; + } | null; agent_error: { reason: string; reported_at: string; @@ -1870,6 +1876,12 @@ export interface components { updated_at: string; started_at: string | null; failure_source: ("system" | "agent") | null; + failure?: { + /** @enum {string} */ + source: "run" | "system"; + code: string; + reason: string; + } | null; agent_error: { reason: string; reported_at: string; @@ -2049,6 +2061,12 @@ export interface components { updated_at: string; started_at: string | null; failure_source: ("system" | "agent") | null; + failure?: { + /** @enum {string} */ + source: "run" | "system"; + code: string; + reason: string; + } | null; agent_error: { reason: string; reported_at: string; @@ -6674,6 +6692,12 @@ export interface operations { finalizing: boolean; trace_revision: string; failure_source: ("system" | "agent") | null; + failure?: { + /** @enum {string} */ + source: "run" | "system"; + code: string; + reason: string; + } | null; agent_error: { reason: string; reported_at: string; diff --git a/packages/api/migrations/0032_run_failure_outcomes.sql b/packages/api/migrations/0032_run_failure_outcomes.sql new file mode 100644 index 00000000..6c1063af --- /dev/null +++ b/packages/api/migrations/0032_run_failure_outcomes.sql @@ -0,0 +1,21 @@ +ALTER TABLE app.runs ADD COLUMN IF NOT EXISTS failure_code text; +ALTER TABLE app.runs ADD COLUMN IF NOT EXISTS failure_reason text; +ALTER TABLE app.runs DROP CONSTRAINT IF EXISTS runs_failure_outcome_check; +ALTER TABLE app.runs ADD CONSTRAINT runs_failure_outcome_check CHECK ( + (failure_code IS NULL AND failure_reason IS NULL) OR + (failure_code IS NOT NULL AND failure_reason IS NOT NULL) +); + +-- Only direct retained evidence proves a task failure here. +UPDATE app.runs +SET failure_source='agent', failure_code='task_reported_failure', + failure_reason=job_result->>'reason', + artifact_error=CASE WHEN artifact_error=job_result->>'reason' THEN NULL ELSE artifact_error END +WHERE state='failed' AND failure_source='system' + AND job_result->>'status'='failed' + AND execution_diagnostics->>'state'='succeeded' + AND execution_diagnostics->'systemd'->>'result'='success' + AND execution_diagnostics->'systemd'->>'execMainStatus'='0' + AND coalesce(job_result->>'reason','') <> ''; + +INSERT INTO app.schema_migrations(version) VALUES ('0032_run_failure_outcomes') ON CONFLICT DO NOTHING; diff --git a/packages/api/scripts/static-slice.config.ts b/packages/api/scripts/static-slice.config.ts index 2f1e6b66..f410738d 100644 --- a/packages/api/scripts/static-slice.config.ts +++ b/packages/api/scripts/static-slice.config.ts @@ -1,2 +1,2 @@ import { defineConfig } from "vitest/config"; -export default defineConfig({ test: { include: ["test/static-slice.e2e.test.ts"] } }); +export default defineConfig({ test: { testTimeout: 60_000, hookTimeout: 30_000, include: ["test/static-slice.e2e.test.ts"] } }); diff --git a/packages/api/src/amp-backend.ts b/packages/api/src/amp-backend.ts index 27f1c018..3470b424 100644 --- a/packages/api/src/amp-backend.ts +++ b/packages/api/src/amp-backend.ts @@ -34,12 +34,14 @@ export class AmpBackend implements ExecutionBackend { if (!result.command.ok) throw new Error(`Amp launch failed (${result.command.status}): ${result.command.body.slice(0, 500)}`); const threadId = String(result.data.threadId ?? result.data.threadID ?? result.data.id ?? ""); if (!threadId) throw new Error("Amp launch response did not include a thread ID."); - return { handle: { backendKind: this.kind, id: threadId }, destinationUrl: String(result.data.url ?? `https://ampcode.com/threads/${encodeURIComponent(threadId)}`), capabilities: this.capabilities, observation: { state: mapAmpState(result.data.status ?? "starting") }, command: result.command }; + const state = mapAmpState(result.data.status ?? "starting"); + return { handle: { backendKind: this.kind, id: threadId }, destinationUrl: String(result.data.url ?? `https://ampcode.com/threads/${encodeURIComponent(threadId)}`), capabilities: this.capabilities, observation: { state, ...(state === "failed" ? { failure: { source: "run" as const, code: "process_exit", reason: String(result.data.detail ?? "Amp reported an unsuccessful execution") } } : {}) }, command: result.command }; } async inspect(handle: RunHandle): Promise { const result = await this.call(`/runs/${encodeURIComponent(handle.id)}`); - if (!result.command.ok) return { state: result.command.status === 404 ? "failed" : "running", detail: result.command.body, command: result.command }; - return { state: mapAmpState(result.data.status ?? result.data.state), detail: result.data.detail, command: result.command }; + if (!result.command.ok) return result.command.status === 404 ? { state: "failed", detail: result.command.body, command: result.command, failure: { source: "system", code: "execution_unavailable", reason: "Amp execution could not be found" } } : { state: "running", detail: result.command.body, command: result.command }; + const state = mapAmpState(result.data.status ?? result.data.state); + return { state, detail: result.data.detail, command: result.command, ...(state === "failed" ? { failure: { source: "run" as const, code: "process_exit", reason: String(result.data.detail ?? "Amp reported an unsuccessful execution") } } : {}) }; } async stop(handle: RunHandle): Promise { const result = await this.call(`/runs/${encodeURIComponent(handle.id)}/stop`, { method: "POST", body: "{}" }); diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index 1f9f32cb..aec73009 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -208,7 +208,7 @@ export class ExeVmBackend implements ExecutionBackend { for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); if (!accepted(started)) { const detail = `VM provisioning failed (${started.status}): ${safeDiagnosticText(started.body, 500)}`; - return { handle, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail, command: started }, command: started }; + return { handle, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail, failure: { source: "system", code: "launch_failed", reason: detail }, command: started }, command: started }; } return { handle, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "running", command: started }, command: started }; } @@ -222,17 +222,18 @@ export class ExeVmBackend implements ExecutionBackend { // systemctl can return nonzero for a missing unit, but still emits LoadState. if (!response.ok && !response.body.includes("LoadState=not-found")) return ![404, 410].includes(response.status) ? { state: "running", detail: `VM inspection is temporarily unavailable (${response.status})` } - : { state: "failed", detail: `The run-owned VM is unavailable (${response.status})` }; + : { state: "failed", detail: `The run-owned VM is unavailable (${response.status})`, failure: { source: "system", code: "vm_unavailable", reason: `The run-owned VM is unavailable (${response.status})` } }; const properties = Object.fromEntries(response.body.split("\n").filter(line => /^[A-Za-z]+=/.test(line)).map(line => { const index = line.indexOf("="); return [line.slice(0, index), line.slice(index + 1).trim()]; })); const label = (name: string) => /^[a-z-]{1,64}$/.test(properties[name] ?? "") ? properties[name] : ""; const number = (name: string) => /^\d{1,10}$/.test(properties[name] ?? "") ? Number(properties[name]) : null; const systemd = { loadState: label("LoadState"), activeState: label("ActiveState"), subState: label("SubState"), result: label("Result"), execMainCode: number("ExecMainCode"), execMainStatus: number("ExecMainStatus") }; if (!systemd.loadState) return { state: "running", detail: "VM inspection returned incomplete supervisor metadata" }; - if (systemd.loadState !== "loaded") return { state: "failed", systemd, detail: "The run supervisor disappeared before recording a result." }; + if (systemd.loadState !== "loaded") return { state: "failed", systemd, detail: "The run supervisor disappeared before recording a result.", failure: { source: "system", code: "supervisor_disappeared", reason: "The run supervisor disappeared before recording a result." } }; if (["running", "start"].includes(systemd.subState) || ["activating", "deactivating"].includes(systemd.activeState)) return { state: "running", systemd }; if (!systemd.activeState || !systemd.subState || !systemd.result || systemd.execMainStatus === null || systemd.execMainCode === null) return { state: "running", detail: "VM inspection returned incomplete supervisor metadata" }; if (systemd.result === "success" && systemd.execMainStatus === 0) return { state: "succeeded", systemd }; - return { state: "failed", systemd, detail: `The supervised agent process exited unsuccessfully (Result=${systemd.result}, ExecMainCode=${systemd.execMainCode}, ExecMainStatus=${systemd.execMainStatus}).` }; + const reason = `The supervised agent process exited unsuccessfully (Result=${systemd.result}, ExecMainCode=${systemd.execMainCode}, ExecMainStatus=${systemd.execMainStatus}).`; + return { state: "failed", systemd, detail: reason, failure: { source: "run", code: "process_exit", reason } }; } /** Stop the writer but preserve the guest until terminal artifacts are retained. */ diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 5b220870..22caae78 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -29,6 +29,8 @@ export interface ExecutionObservation { state: ExecutionState; detail?: string; command?: BackendCommandResult; + /** Backend evidence only; guest supplied result documents cannot set this. */ + failure?: { source: "run" | "system"; code: string; reason: string }; } export interface LaunchReceipt { diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 130fada1..9402a3a6 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -217,7 +217,7 @@ export class ApiService { execution_handle: run.execution_handle ? { backendKind: run.execution_handle.backendKind, id: run.execution_handle.id } : null, provider: run.provider, issue_id: run.issue_id, issue_url: run.issue_url, issue_title: run.issue_title, run_name: run.run_name, agent_name: run.agent_name, workspace_name: run.workspace_name, agent_kind: run.agent_kind, execution_type: run.execution_type ?? run.execution_config?.executionType ?? "agent", - state: run.state, failure_source: run.failure_source ?? null, agent_error: agentError, execution_backend_kind: run.execution_backend_kind, backend_kind: run.backend_kind, + state: run.state, failure_source: run.failure_source ?? null, failure: run.failure_code && run.failure_reason ? { source: run.failure_source === "agent" ? "run" : "system", code: run.failure_code, reason: run.failure_reason } : null, agent_error: agentError, execution_backend_kind: run.execution_backend_kind, backend_kind: run.backend_kind, execution_capabilities: run.execution_capabilities, capabilities: run.capabilities, destination_url: run.destination_url, artifact_state: run.artifact_state, artifact_error: run.artifact_error, claim_released: run.claim_released, vm_cleanup_attempt: run.vm_cleanup_attempt, cleanup_next_at: run.cleanup_next_at, vm_cleanup_complete: run.vm_cleanup_complete, execution_script: typeof run.execution_config?.script === "string" ? run.execution_config.script : null, execution_configuration: run.execution_config, @@ -245,7 +245,7 @@ export class ApiService { new ArtifactRepository(database, this.auth.tenantId).list(runId), ]); const primary = run.trace_sources?.primary ?? null; - return { runId: run.id, jobId: run.job_id, state: run.state, failureSource: run.failure_source, agentError: run.agent_error, provider: run.provider, backendKind: run.execution_backend_kind, + return { runId: run.id, jobId: run.job_id, state: run.state, failureSource: run.failure_source, failure: run.failure, agentError: run.agent_error, provider: run.provider, backendKind: run.execution_backend_kind, execution: run.execution_diagnostics, traceSources: run.trace_sources, trace: { ...evidence, provider: primary?.provider ?? artifacts.find(item => item.kind === "native_session")?.provider ?? run.agent_kind ?? null, primarySource: primary?.kind ?? "native_session", sourceVersion: primary?.formatVersion ?? null, artifacts: artifacts.filter(item => ["execution_stream", "native_session"].includes(item.kind)), diff --git a/packages/api/src/harness-diagnostics.ts b/packages/api/src/harness-diagnostics.ts index c5b52ecf..e6a7e3df 100644 --- a/packages/api/src/harness-diagnostics.ts +++ b/packages/api/src/harness-diagnostics.ts @@ -6,6 +6,7 @@ export interface ExecutionDiagnostics { state: "succeeded" | "failed" | "stopped"; detail: string | null; systemd: { loadState: string; activeState: string; subState: string; result: string; execMainCode: number | null; execMainStatus: number | null } | null; + failure?: { source: "run" | "system"; code: string; reason: string }; } /** Redact before truncation so a cut cannot expose part of a recognized credential. */ @@ -30,5 +31,6 @@ export function terminalDiagnostics(observation: ExecutionObservation): Executio state: observation.state === "succeeded" ? "succeeded" : observation.state === "stopped" ? "stopped" : "failed", detail: observation.detail ? safeDiagnosticText(observation.detail) : null, systemd: observation.systemd ?? null, + ...(observation.failure ? { failure: { ...observation.failure, reason: safeDiagnosticText(observation.failure.reason) } } : {}), }; } diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index b8a8eca6..0c49613a 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -36,7 +36,8 @@ export class RunQueryRepository { const order = sort ? `CASE WHEN ${sortExpressions[sort]} IS NULL THEN 1 ELSE 0 END ASC, ${sortExpressions[sort]} ${direction} NULLS LAST, r.id ${direction}` : "r.created_at DESC,r.id DESC"; const selectedOrder = order.replaceAll("r.", "selected.").replaceAll("j.name", "selected.job_name"); const result = await this.database.pool.query(`WITH selected AS MATERIALIZED ( - SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,coalesce(r.execution_config->>'executionType','agent') execution_type,r.state,r.failure_source, + SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,coalesce(r.execution_config->>'executionType','agent') execution_type,r.state,r.failure_source,r.failure_code,r.failure_reason, + CASE WHEN r.failure_code IS NULL OR r.failure_reason IS NULL THEN NULL ELSE jsonb_build_object('source',CASE WHEN r.failure_source='agent' THEN 'run' ELSE 'system' END,'code',r.failure_code,'reason',r.failure_reason) END failure, CASE WHEN r.agent_error_reason IS NULL THEN NULL ELSE jsonb_build_object('reason',r.agent_error_reason,'reported_at',r.agent_error_reported_at,'reporter',jsonb_build_object('user_id',r.agent_error_reporter_user_id,'kind',r.agent_error_reporter_kind,'id',r.agent_error_reporter_id)) END agent_error, r.provider,r.execution_backend_kind backend_kind,r.execution_capabilities capabilities,r.destination_url,r.artifact_state,r.artifact_error,r.created_at,r.updated_at,jr.started_at,jr.updated_at job_run_updated_at FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.projects p ON p.tenant_id=j.tenant_id AND p.id=j.project_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id @@ -53,7 +54,7 @@ export class RunQueryRepository { AND completed.started_at IS NOT NULL AND completed.updated_at>=completed.started_at GROUP BY completed.job_id ) - SELECT selected.id,selected.job_id,selected.project_id,selected.job_name,selected.project_name,selected.issue_id,selected.issue_url,selected.issue_title,selected.run_name,selected.agent_name,selected.workspace_name,selected.agent_kind,selected.execution_type,selected.state,selected.failure_source,selected.agent_error, + SELECT selected.id,selected.job_id,selected.project_id,selected.job_name,selected.project_name,selected.issue_id,selected.issue_url,selected.issue_title,selected.run_name,selected.agent_name,selected.workspace_name,selected.agent_kind,selected.execution_type,selected.state,selected.failure_source,selected.failure_code,selected.failure_reason,selected.failure,selected.agent_error, selected.provider,selected.backend_kind,selected.capabilities,selected.destination_url,selected.artifact_state,selected.artifact_error,selected.created_at,selected.updated_at,selected.started_at, CASE WHEN selected.state IN ('succeeded','failed','stopped') AND selected.started_at IS NOT NULL AND selected.job_run_updated_at>=selected.started_at THEN json_build_object('duration',round(EXTRACT(EPOCH FROM (selected.job_run_updated_at-selected.started_at)))) @@ -74,7 +75,7 @@ export class RunQueryRepository { FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id WHERE r.tenant_id=$1 AND r.id=$2`, [this.tenantId, runId])).rows[0] ?? null; } async status(runId: string) { - const row = (await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,pr.name project_name,jr.state,r.run_name,j.name job_name,r.destination_url,r.failure_source,coalesce(r.execution_config->>'executionType','agent') execution_type, + const row = (await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,pr.name project_name,jr.state,r.run_name,j.name job_name,r.destination_url,r.failure_source,r.failure_code,r.failure_reason,CASE WHEN r.failure_code IS NULL OR r.failure_reason IS NULL THEN NULL ELSE jsonb_build_object('source',CASE WHEN r.failure_source='agent' THEN 'run' ELSE 'system' END,'code',r.failure_code,'reason',r.failure_reason) END failure,coalesce(r.execution_config->>'executionType','agent') execution_type, CASE WHEN r.agent_error_reason IS NULL THEN NULL ELSE jsonb_build_object('reason',r.agent_error_reason,'reported_at',r.agent_error_reported_at,'reporter',jsonb_build_object('user_id',r.agent_error_reporter_user_id,'kind',r.agent_error_reporter_kind,'id',r.agent_error_reporter_id)) END agent_error, r.created_at,greatest(r.updated_at,jr.updated_at) updated_at,jr.started_at,r.artifact_state, (jr.state IN ('succeeded','failed','stopped') AND (r.artifact_state IN ('pending','collecting') OR NOT r.vm_cleanup_complete)) finalizing, @@ -86,7 +87,7 @@ export class RunQueryRepository { LEFT JOIN app.run_trace_projections p ON p.tenant_id=r.tenant_id AND p.run_id=r.id WHERE r.tenant_id=$1 AND r.id=$2`, [this.tenantId, runId])).rows[0]; if (!row) return null; - return { ...row, created_at: row.created_at.toISOString(), updated_at: row.updated_at.toISOString(), started_at: row.started_at?.toISOString() ?? null }; + return { ...row, failure: row.failure_code && row.failure_reason ? { source: row.failure_source === "agent" ? "run" : "system", code: row.failure_code, reason: row.failure_reason } : null, created_at: row.created_at.toISOString(), updated_at: row.updated_at.toISOString(), started_at: row.started_at?.toISOString() ?? null }; } async rename(runId: string, name: string, expectedName?: string): Promise<"missing" | "stale" | { run_name: string }> { return this.database.transaction(async client => { diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index 5c3b180b..e881a0f1 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -9,16 +9,19 @@ export interface PersistedRun { tenantId: string; id: string; jobId: string; invocationId: string; state: ExecutionState; encryptedPrompt: string; executionConfig: Record; executionHandle: RunHandle | null; traceSources?: TraceSources | null; executionDiagnostics?: ExecutionDiagnostics | null; finalizationAttempt?: number; + failureCode?: string | null; failureReason?: string | null; backendKind: string; capabilities: string[]; artifactState: string; resultProtocolVersion: number; createdAt: string; updatedAt: string; } +export interface RunFailure { source: "run" | "system"; code: string; reason: string } interface RunRow { tenant_id: string; id: string; job_id: string; invocation_id: string; state: ExecutionState; encrypted_prompt: string; execution_config: Record; execution_handle: RunHandle | null; execution_backend_kind: string; + failure_code?: string | null; failure_reason?: string | null; trace_sources: TraceSources | null; execution_diagnostics: ExecutionDiagnostics | null; vm_cleanup_attempt: number; execution_capabilities: string[]; artifact_state: string; result_protocol_version: number; created_at: Date; updated_at: Date; } -const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: row.id, jobId: row.job_id, invocationId: row.invocation_id, state: row.state, encryptedPrompt: row.encrypted_prompt, executionConfig: row.execution_config, traceSources: row.trace_sources, executionHandle: row.execution_handle, executionDiagnostics: row.execution_diagnostics, finalizationAttempt: row.vm_cleanup_attempt, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, resultProtocolVersion: row.result_protocol_version, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); +const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: row.id, jobId: row.job_id, invocationId: row.invocation_id, state: row.state, encryptedPrompt: row.encrypted_prompt, executionConfig: row.execution_config, traceSources: row.trace_sources, executionHandle: row.execution_handle, executionDiagnostics: row.execution_diagnostics, finalizationAttempt: row.vm_cleanup_attempt, failureCode: row.failure_code, failureReason: row.failure_reason, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, resultProtocolVersion: row.result_protocol_version, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); export class RunRepository { constructor(private database: Database) {} @@ -36,7 +39,7 @@ export class RunRepository { ), claimed AS ( UPDATE app.job_runs r SET state='starting',launch_lease_expires_at=now()+interval '5 minutes',updated_at=now() FROM candidate c WHERE r.tenant_id=c.tenant_id AND r.id=c.id RETURNING r.* - ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,c.created_at,c.updated_at + ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.failure_code,x.failure_reason,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,c.created_at,c.updated_at FROM claimed c JOIN app.jobs j ON j.tenant_id=c.tenant_id AND j.id=c.job_id JOIN app.runs x ON x.tenant_id=c.tenant_id AND x.id=c.id`, []); const row = result.rows[0]; if (!row) return null; @@ -46,7 +49,7 @@ export class RunRepository { } async dueForPoll(limit = 40): Promise { - const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,r.created_at,r.updated_at + const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,x.execution_config,x.trace_sources,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.failure_code,x.failure_reason,x.vm_cleanup_attempt,x.artifact_state,x.result_protocol_version,r.created_at,r.updated_at FROM app.job_runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.runs x ON x.tenant_id=r.tenant_id AND x.id=r.id WHERE r.state IN ('running','blocked','stopping') AND (r.next_poll_at IS NULL OR r.next_poll_at<=now()) ORDER BY r.next_poll_at NULLS FIRST,r.updated_at LIMIT $1`, [limit]); return result.rows.map(mapped); @@ -91,6 +94,13 @@ export class RunRepository { await this.database.pool.query("UPDATE app.runs SET job_result=COALESCE(job_result,$3::jsonb),updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, JSON.stringify(result)]); } + async recordFailureOutcome(run: PersistedRun, failure: RunFailure): Promise { + const result = await this.database.pool.query<{ failure_code: string; failure_reason: string }>( + "UPDATE app.runs SET failure_code=COALESCE(failure_code,$3),failure_reason=COALESCE(failure_reason,$4),updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING failure_code,failure_reason", + [run.tenantId, run.id, failure.code, safeDiagnosticText(failure.reason)]); + run.failureCode = result.rows[0]?.failure_code ?? failure.code; run.failureReason = result.rows[0]?.failure_reason ?? failure.reason; + } + async recordStopAttempt(run: PersistedRun): Promise { await this.database.pool.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) VALUES ($1,$2,$3,'stop_attempt','Scheduler attempted agent termination')", [run.tenantId, crypto.randomUUID(), run.id]); } @@ -112,16 +122,23 @@ export class RunRepository { }); } - async terminal(run: PersistedRun, state: "succeeded" | "failed" | "stopped", artifactState: "stored" | "partial" | "failed", error?: string, cleanupComplete = false): Promise { + async terminal(run: PersistedRun, state: "succeeded" | "failed" | "stopped", artifactState: "stored" | "partial" | "failed", error?: string, cleanupComplete = false, failure?: RunFailure): Promise { await this.database.transaction(async client => { await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))", [run.tenantId]); const current = (await client.query<{ state: ExecutionState }>("SELECT state FROM app.job_runs WHERE tenant_id=$1 AND id=$2 AND state IN ('starting','running','blocked','stopping') FOR UPDATE", [run.tenantId, run.id])).rows[0]; if (!current) return; const saved = (await client.query<{ agent_error_reason: string | null }>("SELECT agent_error_reason FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [run.tenantId, run.id])).rows[0]; const terminalState = current.state === "stopping" ? "stopped" : state === "succeeded" && saved?.agent_error_reason ? "failed" : state; - const failureSource = terminalState === "failed" ? state === "failed" ? "system" : "agent" : null; + const savedResult = (await client.query<{ job_result: { status?: string; reason?: string } | null; agent_error_reason: string | null; failure_source: string | null; failure_code: string | null; failure_reason: string | null }>("SELECT job_result,agent_error_reason,failure_source,failure_code,failure_reason FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [run.tenantId, run.id])).rows[0]; + const explicitReport = savedResult?.agent_error_reason; + const outcome = terminalState !== "failed" ? null : savedResult?.failure_code && savedResult.failure_reason ? { source: failure?.source ?? (savedResult.failure_source === "agent" ? "run" as const : "system" as const), code: savedResult.failure_code, reason: savedResult.failure_reason } : failure ?? (state === "succeeded" && explicitReport + ? { source: "run" as const, code: "task_reported_failure", reason: explicitReport } + : state === "failed" && savedResult?.job_result?.status === "failed" + ? { source: "run" as const, code: "task_reported_failure", reason: savedResult.job_result.reason ?? "The task reported failure" } + : state === "failed" && explicitReport ? { source: "run" as const, code: "task_reported_failure", reason: explicitReport } : null); + const failureSource = outcome ? outcome.source === "run" ? "agent" : "system" : null; await client.query("UPDATE app.job_runs SET state=$3,next_poll_at=NULL,launch_lease_expires_at=NULL,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, terminalState]); - await client.query("UPDATE app.runs SET state=$3,failure_source=$4,artifact_state=$5,artifact_error=$6,claim_released=true,vm_cleanup_complete=$7,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, terminalState, failureSource, artifactState, error ? safeDiagnosticText(error) : null, cleanupComplete]); + await client.query("UPDATE app.runs SET state=$3,failure_source=$4,failure_code=$5,failure_reason=$6,artifact_state=$7,artifact_error=$8,claim_released=true,vm_cleanup_complete=$9,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, terminalState, failureSource, outcome?.code ?? null, outcome ? safeDiagnosticText(outcome.reason) : null, artifactState, error ? safeDiagnosticText(error) : null, cleanupComplete]); await client.query("DELETE FROM app.active_claims WHERE tenant_id=$1 AND run_id=$2", [run.tenantId, run.id]); // Automation runs before polling, so terminal events need another pass. await client.query("INSERT INTO app.wake_hints(key,not_before) VALUES ('global',now()) ON CONFLICT (key) DO UPDATE SET not_before=least(app.wake_hints.not_before,excluded.not_before),updated_at=now()"); diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index e807fe0f..1200f6a8 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -27,8 +27,8 @@ export class RunScheduler { async process(): Promise { await this.runs.consumeWakeHint(); await new AutomationScheduler(this.database, this.env).process(); - for (const run of await this.runs.dueForPoll()) await this.poll(run).catch(error => this.fail(run, error)); - for (let count = 0; count < 20; count++) { const run = await this.runs.claimNext(); if (!run) break; await this.launch(run).catch(error => this.fail(run, error)); } + for (const run of await this.runs.dueForPoll()) await this.poll(run).catch(error => this.fail(run, error, "poll")); + for (let count = 0; count < 20; count++) { const run = await this.runs.claimNext(); if (!run) break; await this.launch(run).catch(error => this.fail(run, error, "launch")); } } private connections(run: PersistedRun) { return new ConnectionRepository(this.database, run.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } @@ -82,21 +82,26 @@ export class RunScheduler { let artifactState: "stored" | "partial" | "failed" = "stored"; const errors: string[] = []; let finalState = diagnostics.state; - let resultFailure: string | undefined; - if (run.resultProtocolVersion === 1 && diagnostics.state !== "failed" && diagnostics.state !== "stopped") { + let taskFailure: { source: "run" | "system"; code: string; reason: string } | undefined = run.failureCode && run.failureReason + ? { source: diagnostics.failure?.source ?? "run", code: run.failureCode, reason: run.failureReason } : diagnostics.failure; + if (taskFailure) await this.runs.recordFailureOutcome(run, taskFailure); + if (!run.failureCode && run.resultProtocolVersion === 1 && diagnostics.state !== "failed" && diagnostics.state !== "stopped") { if (!(backend instanceof ExeVmBackend)) throw new Error("This execution backend cannot collect structured job results"); let raw: string | null; try { raw = await backend.readJobResult(run.executionHandle!); } catch (error) { throw error; } // Collection errors are transient and retried by finalization. - if (raw === null) { finalState = "failed"; resultFailure = "Required structured job result is missing"; } + if (raw === null) { finalState = "failed"; taskFailure = { source: "run", code: "result_missing", reason: "Required structured job result is missing" }; } else { - try { - const result = parseJobResult(raw); + let result; + try { result = parseJobResult(raw); } + catch (error) { finalState = "failed"; taskFailure = { source: "run", code: "result_invalid", reason: `Invalid structured job result: ${error instanceof Error ? error.message : "validation failed"}` }; } + if (result) { await this.runs.recordJobResult(run, result); - if (result.status === "failed") { finalState = "failed"; resultFailure = result.reason; } - } catch (error) { finalState = "failed"; resultFailure = `Invalid structured job result: ${error instanceof Error ? error.message : "validation failed"}`; } + if (result.status === "failed") { finalState = "failed"; taskFailure ??= { source: "run", code: "task_reported_failure", reason: result.reason! }; } + } } } + if (taskFailure) await this.runs.recordFailureOutcome(run, taskFailure); if (backend instanceof ExeVmBackend) { const artifacts = new ArtifactRepository(this.database, run.tenantId); const stored = await artifacts.list(run.id); @@ -152,7 +157,8 @@ export class RunScheduler { return; } } - await this.runs.terminal(run, finalState, artifactState, [resultFailure, ...errors].filter(Boolean).join("; ") || undefined, true); + if (finalState === "failed" && diagnostics.state === "succeeded" && !taskFailure) taskFailure = { source: "run", code: "task_reported_failure", reason: "The run reported an error" }; + await this.runs.terminal(run, finalState, artifactState, errors.filter(Boolean).join("; ") || undefined, true, taskFailure); } /** Retry projection from retained bytes, without relying on a surviving VM. */ @@ -226,18 +232,25 @@ export class RunScheduler { return backend.collectTraceChunk(run.executionHandle, { source, generation: cursor.generation, offset: cursor.offset, previousHash: cursor.rollingHash, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-trace-chunks/${encodeURIComponent(token)}` }); } - private async fail(run: PersistedRun, error: unknown) { + private async fail(run: PersistedRun, error: unknown, phase: "poll" | "launch" = "launch") { // Infrastructure errors while finalizing must not change the execution result. if (run.executionDiagnostics) { await this.runs.retryFinalization(run, "partial", "Run finalization temporarily failed"); return; } - await this.runs.recordObservation(run, { state: "failed", detail: safeDiagnosticText(error instanceof Error ? error.message : "Run processing failed") }); + // An unconfirmed inspection transport error must retry under the normal + // polling lifecycle; it is not evidence that the guest task or system ended. + if (phase === "poll" && run.executionHandle) { + await this.runs.schedulePoll(run, run.state === "stopping" ? "stopping" : "running"); + return; + } + const reason = safeDiagnosticText(error instanceof Error ? error.message : "Run processing failed"); + await this.runs.recordObservation(run, { state: "failed", detail: reason, failure: { source: "system", code: "execution_unavailable", reason } }); if (run.executionHandle) { if (run.state === "starting" || run.state === "stopping") await this.runs.markLaunched(run, run.executionHandle, `https://${run.executionHandle.id}.exe.xyz/`, run.capabilities ?? [], run.traceSources ?? undefined); await this.runs.schedulePoll(run, run.state === "stopping" ? "stopping" : "running"); return; } - await this.runs.terminal(run, "failed", "failed"); + await this.runs.terminal(run, "failed", "failed", undefined, false, { source: "system", code: "launch_failed", reason }); } } diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index bc1a37f8..bf7fdf6f 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -73,7 +73,7 @@ export const jobRuns = app.table("job_runs", { export const runs = app.table("runs", { executionConfig: jsonb("execution_config").$type().notNull(), - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), failureCode: text("failure_code"), failureReason: text("failure_reason"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]); export const runArtifacts = app.table("run_artifacts", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), id: uuid("id").notNull(), kind: text("kind").$type().notNull(), objectKey: text("object_key").notNull(), provider: text("provider").notNull(), format: text("format").notNull(), formatVersion: text("format_version"), cliVersion: text("cli_version"), nativeSessionId: text("native_session_id"), sourceGeneration: text("source_generation"), sourcePath: text("source_path"), mediaType: text("media_type"), harnessVersion: text("harness_version"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type().notNull(), createdAt: createdAt(), diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index ff35e99b..62e19940 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -5,13 +5,14 @@ export const runtimeContextResponse = z.object({ }); export const executionState = z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped"]); export const agentErrorResponse = z.object({ reason: z.string(), reported_at: z.string(), reporter: z.object({ user_id: z.string(), kind: z.enum(["api_key", "oauth", "session", "run_token"]), id: z.string() }) }); +export const runFailureResponse = z.object({ source: z.enum(["run", "system"]), code: z.string(), reason: z.string() }); export const runStatusResponse = z.object({ id: z.string(), job_id: z.string(), project_id: z.string().optional(), project_name: z.string().optional(), state: executionState, execution_type: z.enum(["agent", "code"]).default("agent"), run_name: z.string(), job_name: z.string(), destination_url: z.string().nullable(), created_at: z.string(), updated_at: z.string(), started_at: z.string().nullable(), artifact_state: z.enum(["pending", "collecting", "stored", "partial", "failed"]), - finalizing: z.boolean(), trace_revision: z.string(), failure_source: z.enum(["system", "agent"]).nullable(), agent_error: agentErrorResponse.nullable(), + finalizing: z.boolean(), trace_revision: z.string(), failure_source: z.enum(["system", "agent"]).nullable(), failure: runFailureResponse.nullable().optional(), agent_error: agentErrorResponse.nullable(), }); export const traceEventResponse = z.object({ sequence: z.number().int(), id: z.string(), parentId: z.string().optional(), @@ -24,7 +25,7 @@ export const revisionTracePage = z.object({ items: z.array(traceEventResponse), export const traceRevisionSql = "jsonb_build_array(c.generation,p.source_kind,p.artifact_sha256,p.parser_version,p.updated_at)::text"; export const runSummaryResponse = z.object({ id: z.string(), job_id: z.string(), project_id: z.string().optional(), project_name: z.string().optional(), job_name: z.string(), issue_id: z.string(), issue_url: z.string().nullable(), issue_title: z.string(), run_name: z.string(), agent_name: z.string(), workspace_name: z.string(), agent_kind: z.string(), execution_type: z.enum(["agent", "code"]), state: z.enum([...executionState.options, "done", "ignored"]), provider: z.string(), backend_kind: z.string(), capabilities: z.array(z.string()), destination_url: z.string().nullable(), artifact_state: z.enum(["pending", "collecting", "stored", "partial", "failed"]), artifact_error: z.string().nullable(), created_at: z.string(), updated_at: z.string(), started_at: z.string().nullable(), - failure_source: z.enum(["system", "agent"]).nullable(), agent_error: agentErrorResponse.nullable(), + failure_source: z.enum(["system", "agent"]).nullable(), failure: runFailureResponse.nullable().optional(), agent_error: agentErrorResponse.nullable(), elapsed_time: z.union([ z.object({ duration: z.number() }), z.object({ low: z.number(), high: z.number() }), diff --git a/packages/api/test/report-run-error-boundary.test.ts b/packages/api/test/report-run-error-boundary.test.ts index 31fbe588..b3f41418 100644 --- a/packages/api/test/report-run-error-boundary.test.ts +++ b/packages/api/test/report-run-error-boundary.test.ts @@ -67,21 +67,21 @@ describe("report persistence lock and retry behavior", () => { it.each([ ["succeeded", "running", "reported problem", "failed", "agent"], - ["failed", "running", "reported problem", "failed", "system"], + ["failed", "running", "reported problem", "failed", "agent"], ["succeeded", "stopping", "reported problem", "stopped", null], ] as const)("finalizes observer %s from %s with report precedence", async (observation, existingState, reason, expectedState, expectedSource) => { const calls: Array<[string, unknown[]]> = []; const query = vi.fn(async (sql: string, values: unknown[] = []) => { calls.push([sql, values]); if (sql.includes("FROM app.job_runs") && sql.includes("FOR UPDATE")) return { rows: [{ state: existingState }] }; - if (sql.includes("SELECT agent_error_reason")) return { rows: [{ agent_error_reason: reason }] }; + if (sql.includes("agent_error_reason")) return { rows: [{ agent_error_reason: reason, job_result: null, failure_source: null, failure_code: null, failure_reason: null }] }; return { rows: [] }; }); const repo = new RunRepository({ transaction: (work: any) => work({ query }) } as any); await repo.terminal({ tenantId: "tenant", id: runId } as any, observation, "partial", "artifact failed", true); const runUpdate = calls.find(([sql]) => sql.startsWith("UPDATE app.runs SET state="))!; expect(runUpdate[0]).toContain("failure_source=$4"); - expect(runUpdate[1].slice(2, 7)).toEqual([expectedState, expectedSource, "partial", "artifact failed", true]); + expect(runUpdate[1].slice(2)).toEqual([expectedState, expectedSource, expectedState === "failed" ? "task_reported_failure" : null, expectedState === "failed" ? "reported problem" : null, "partial", "artifact failed", true]); }); }); diff --git a/packages/api/test/report-run-error.postgres.test.ts b/packages/api/test/report-run-error.postgres.test.ts index eecd39af..add6c2b8 100644 --- a/packages/api/test/report-run-error.postgres.test.ts +++ b/packages/api/test/report-run-error.postgres.test.ts @@ -39,7 +39,7 @@ describe.skipIf(!url)("agent run error persistence (PostgreSQL)", () => { const runs = new RunRepository(f.db), provenance = { userId: f.auth.userId, reporterKind: "api_key", reporterId: "stable-token" }; await activate(); expect(await runs.reportAgentError({ tenantId: f.tenantId, runId: f.runId, reason: "agent finding", ...provenance })).toBe("reported"); - await runs.terminal({ tenantId: f.tenantId, id: f.runId } as any, "failed", "partial", "artifact upload failed", true); + await runs.terminal({ tenantId: f.tenantId, id: f.runId } as any, "failed", "partial", "artifact upload failed", true, { source: "system", code: "vm_unavailable", reason: "The run-owned VM became unavailable during supervision" }); let final = (await f.db.pool.query("SELECT jr.state job_state,r.state,r.failure_source,r.agent_error_reason,r.agent_error_reporter_id,r.artifact_error FROM app.job_runs jr JOIN app.runs r USING (tenant_id,id) WHERE r.tenant_id=$1 AND r.id=$2", [f.tenantId, f.runId])).rows[0]; expect(final).toMatchObject({ job_state: "failed", state: "failed", failure_source: "system", agent_error_reason: "agent finding", agent_error_reporter_id: "stable-token", artifact_error: "artifact upload failed" }); diff --git a/packages/api/test/run-finalization.test.ts b/packages/api/test/run-finalization.test.ts index 75d87d4f..d3952ae0 100644 --- a/packages/api/test/run-finalization.test.ts +++ b/packages/api/test/run-finalization.test.ts @@ -21,6 +21,7 @@ function fixture(exit = 42) { events.push("observation"); saved ??= terminalDiagnostics(observation); return saved; }); const terminal = vi.spyOn(RunRepository.prototype, "terminal").mockResolvedValue(); + vi.spyOn(RunRepository.prototype, "recordFailureOutcome").mockImplementation(async (_run, failure) => { run.failureCode = failure.code; run.failureReason = failure.reason; }); const retry = vi.spyOn(RunRepository.prototype, "retryFinalization").mockImplementation(async () => { run.finalizationAttempt++; }); const schedule = vi.spyOn(RunRepository.prototype, "schedulePoll").mockResolvedValue(); vi.spyOn(ArtifactRepository.prototype, "list").mockImplementation(async () => artifacts); @@ -41,7 +42,7 @@ describe("durable run finalization", () => { expect(f.scheduler.sources(f.run).primary).toMatchObject({ kind: "native_session", provider: "claude", discoverCommand: expect.stringContaining(".claude/projects") }); await f.scheduler.poll(f.run); expect(f.native).toHaveBeenCalledOnce(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true, undefined); }); it("stores real nonzero harness stderr and exit metadata before deleting the VM", async () => { const f = fixture(); @@ -50,14 +51,14 @@ describe("durable run finalization", () => { expect([...f.blobs.values()]).toEqual(["recognizable harness error\n"]); expect(f.artifacts.find(a => a.kind === "terminal_log")).toMatchObject({ objectKey: "tenants/tenant/runs/run/harness/stderr.txt", format: "text", byteSize: 27, sha256: expect.stringMatching(/^[a-f0-9]{64}$/) }); expect(f.events).toEqual(["observation", "log", "native", "cleanup"]); - expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true, expect.objectContaining({ source: "run", code: "process_exit" })); }); it("keeps successful native sessions and normal cleanup", async () => { const f = fixture(0); await f.scheduler.poll(f.run); expect(f.native).toHaveBeenCalledOnce(); expect(f.stop).toHaveBeenCalledOnce(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true, undefined); }); it("requires and persists a valid structured result before marking a new run succeeded", async () => { const f = fixture(0); f.run.resultProtocolVersion = 1; @@ -67,7 +68,7 @@ describe("durable run finalization", () => { f.terminal.mockImplementation(async () => { expect(f.events.indexOf("result")).toBeLessThan(f.events.indexOf("cleanup")); }); await f.scheduler.poll(f.run); expect(saved).toHaveBeenCalledWith(f.run, { status: "succeeded", summary: "ready", outputs: { count: 3 } }); - expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "stored", undefined, true, undefined); }); it("retains regular job files before VM cleanup", async () => { const f = fixture(0); f.run.resultProtocolVersion = 1; @@ -90,7 +91,7 @@ describe("durable run finalization", () => { vi.spyOn(f.backend, "listJobFiles").mockResolvedValue([]); vi.spyOn(RunRepository.prototype, "recordJobResult").mockResolvedValue(); await f.scheduler.poll(f.run); - expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", expect.stringContaining(reason), true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true, expect.objectContaining({ source: "run", reason: expect.stringContaining(reason) })); }); it.each(["native", "put"] as const)("bounds %s upload retries without replacing the primary failure", async target => { const f = fixture(); @@ -103,7 +104,7 @@ describe("durable run finalization", () => { expect(f.saved()).toEqual(first); expect(f.retry).toHaveBeenCalledTimes(2); expect(f.stop).toHaveBeenCalledOnce(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "partial", expect.stringContaining(target === "put" ? "Harness" : "Native"), true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "partial", expect.stringContaining(target === "put" ? "Harness" : "Native"), true, expect.objectContaining({ source: "run", code: "process_exit" })); expect(JSON.stringify(f.terminal.mock.calls)).not.toContain("sensitive"); }); it("retries cleanup using the original observation even if inspection later reports missing", async () => { @@ -117,16 +118,16 @@ describe("durable run finalization", () => { expect(f.saved()).toEqual(first); expect(f.put).toHaveBeenCalledOnce(); expect(f.native).toHaveBeenCalledOnce(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true, expect.objectContaining({ source: "run", code: "process_exit" })); }); it("persists missing supervisor as the original cause even if artifact collection also fails", async () => { const f = fixture(); - vi.spyOn(f.backend, "inspect").mockResolvedValue({ state: "failed", detail: "The run supervisor disappeared before recording a result." }); + vi.spyOn(f.backend, "inspect").mockResolvedValue({ state: "failed", detail: "The run supervisor disappeared before recording a result.", failure: { source: "system", code: "supervisor_disappeared", reason: "The run supervisor disappeared before recording a result." } }); f.native.mockRejectedValue(new Error("missing session")); f.run.finalizationAttempt = 2; await f.scheduler.poll(f.run); expect(f.saved()?.detail).toContain("supervisor disappeared"); - expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "partial", expect.any(String), true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "partial", expect.any(String), true, expect.objectContaining({ source: "system", code: "supervisor_disappeared" })); }); it("does not finalize or delete on a temporary inspection failure", async () => { const f = fixture(); @@ -147,7 +148,7 @@ describe("durable run finalization", () => { await f.scheduler.poll(f.run); expect(f.events).toEqual(["observation", "log", "stream", "cleanup"]); expect((f.native.mock.calls as any)[0].slice(2)).toEqual([source, true]); - expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true, expect.objectContaining({ source: "run", code: "process_exit" })); }); it.each(["succeeded", "failed", "stopped"])("retains the canonical source for %s before cleanup", async state => { @@ -160,7 +161,7 @@ describe("durable run finalization", () => { await f.scheduler.poll(f.run); expect(f.native).toHaveBeenCalledOnce(); expect(f.native.mock.calls[0].slice(2)).toEqual([source, true]); - expect(f.terminal).toHaveBeenCalledWith(f.run, state, "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, state, "stored", undefined, true, undefined); }); it("shows incomplete Codex traces as partial and retries without recapturing stored bytes", async () => { const f = fixture(0); @@ -171,7 +172,7 @@ describe("durable run finalization", () => { await f.scheduler.poll(f.run); await f.scheduler.poll(f.run); await f.scheduler.poll(f.run); expect(f.native).not.toHaveBeenCalled(); expect(f.stop).toHaveBeenCalledOnce(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "partial", expect.stringContaining("missing turn.completed"), true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "partial", expect.stringContaining("missing turn.completed"), true, undefined); }); it("stops the Codex writer before collecting a cancelled run", async () => { const f = fixture(0); @@ -184,7 +185,7 @@ describe("durable run finalization", () => { await f.scheduler.poll(f.run); expect(terminate).toHaveBeenCalledOnce(); expect(f.events[0]).toBe("terminate"); - expect(f.terminal).toHaveBeenCalledWith(f.run, "stopped", "stored", undefined, true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "stopped", "stored", undefined, true, undefined); }); it("bounds canonical collection failures, exposes the exact path, and never collects native", async () => { @@ -198,7 +199,7 @@ describe("durable run finalization", () => { expect(f.native).toHaveBeenCalledTimes(3); expect(f.native.mock.calls.every(call => call[2] === source)).toBe(true); expect(f.stop).toHaveBeenCalledOnce(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "partial", expect.stringContaining(source.path), true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "partial", expect.stringContaining(source.path), true, undefined); }); it("does not create artifacts for an in-flight historical native-only Codex run", async () => { @@ -208,7 +209,7 @@ describe("durable run finalization", () => { f.run.finalizationAttempt = 2; await f.scheduler.poll(f.run); expect(f.native).not.toHaveBeenCalled(); - expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "partial", expect.stringContaining("read-only"), true); + expect(f.terminal).toHaveBeenCalledWith(f.run, "succeeded", "partial", expect.stringContaining("read-only"), true, undefined); }); }); diff --git a/packages/app/src/features/runs/detail.tsx b/packages/app/src/features/runs/detail.tsx index c2fc6bb5..08131e46 100644 --- a/packages/app/src/features/runs/detail.tsx +++ b/packages/app/src/features/runs/detail.tsx @@ -62,7 +62,7 @@ export function RunDetail() { {status.isPending &&

Loading run…

}{status.error &&

{status.error.message}

} {status.data ? {status.data.job_name} : Projects} {status.data && <> - { event.preventDefault(); setNameError(""); rename.mutate(); }}> { setNameDraft(event.target.value); setNameError(""); }} onKeyDown={event => { if (event.key === "Escape") { event.preventDefault(); cancelRename(); } }} />{nameError && {nameError}} : } description={

{status.data.finalizing ? " · Finalizing trace and artifacts" : ""}{(status.data.agent_error as any)?.reason && {(status.data.agent_error as any).reason}}

}>{["starting", "running", "blocked", "stopping"].includes(status.data.state) && }
+ { event.preventDefault(); setNameError(""); rename.mutate(); }}> { setNameDraft(event.target.value); setNameError(""); }} onKeyDown={event => { if (event.key === "Escape") { event.preventDefault(); cancelRename(); } }} />{nameError && {nameError}} : } description={

{status.data.finalizing ? " · Finalizing trace and artifacts" : ""}{(status.data.failure?.reason || (status.data.agent_error as any)?.reason) && {status.data.failure?.reason || (status.data.agent_error as any).reason}}

}>{["starting", "running", "blocked", "stopping"].includes(status.data.state) && }
} {!status.data && } {stop.error &&

{stop.error.message}

} diff --git a/packages/app/src/features/runs/history.tsx b/packages/app/src/features/runs/history.tsx index 17859184..2ce13f6f 100644 --- a/packages/app/src/features/runs/history.tsx +++ b/packages/app/src/features/runs/history.tsx @@ -25,8 +25,8 @@ export function RunHistory({ jobId }: { jobId: string }) { {runs.data && <>{columns.slice(1, 2).map(([column, label]) => sortColumn(column)} />)}{columns.slice(2).map(([column, label]) => sortColumn(column)} />)}{runs.data.items.map(run => - - + + )}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
Elapsed
{run.run_name || run.issue_title || "Run"}{(run.agent_error as any)?.reason &&

{(run.agent_error as any).reason}

}
{run.run_name || run.issue_title || "Run"}{(run.failure?.reason || (run.agent_error as any)?.reason) &&

{(run.failure?.reason || (run.agent_error as any).reason)}

}
{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}{run.execution_type === "code" ? "Code script" : run.agent_kind}
{search.states?.length ? <>

No runs match the selected statuses.

: "No runs found."}
} diff --git a/packages/app/src/features/runs/list.tsx b/packages/app/src/features/runs/list.tsx index 1b320a46..0c77edd0 100644 --- a/packages/app/src/features/runs/list.tsx +++ b/packages/app/src/features/runs/list.tsx @@ -29,5 +29,5 @@ export function RunList({ jobId, projectId, limit = 30 }: { jobId?: string; proj const pagination = jobId ? : projectId ? : ; const projectOptions = (projects.data ?? []).map(project => ({ id: project.id, label: project.name })), jobOptions = (jobs.data?.items ?? []).map(job => ({ id: job.id, label: job.name })); const emptyMessage = search.states?.length && !search.projects?.length && !search.jobs?.length ? "No runs match the selected statuses." : "No runs match the selected filters."; - return
{runs.isPending &&

Loading runs…

}{runs.error &&

{runs.error.message}

}{runs.data && <>{statusHeader}{!scoped ? changeSelection("projects", id, checked)} onClear={() => clearFilters("projects")} /> : }{!jobId ? changeSelection("jobs", id, checked)} onClear={() => clearFilters("jobs")} /> : }{sortableHeader("run", "Run")}{sortableHeader("created", "Created")}{runs.data.items.map(run => )}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
ProjectJobElapsed
{run.project_id && run.project_name ?
{!scoped&& changeSelection("projects", run.project_id!, !(search.projects ?? []).includes(run.project_id!))}/>}{run.project_name}
: —}
{!scoped&& changeSelection("jobs", run.job_id, !(search.jobs ?? []).includes(run.job_id))}/>}{run.job_name}
{run.run_name || "Run"}{(run.agent_error as any)?.reason &&

{(run.agent_error as any).reason}

}
{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}
{search.states?.length || search.projects?.length || search.jobs?.length ? <>

{emptyMessage}

: jobId || projectId ? "No runs found." : "No runs yet"}
}{pagination}
; + return
{runs.isPending &&

Loading runs…

}{runs.error &&

{runs.error.message}

}{runs.data && <>{statusHeader}{!scoped ? changeSelection("projects", id, checked)} onClear={() => clearFilters("projects")} /> : }{!jobId ? changeSelection("jobs", id, checked)} onClear={() => clearFilters("jobs")} /> : }{sortableHeader("run", "Run")}{sortableHeader("created", "Created")}{runs.data.items.map(run => )}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
ProjectJobElapsed
{run.project_id && run.project_name ?
{!scoped&& changeSelection("projects", run.project_id!, !(search.projects ?? []).includes(run.project_id!))}/>}{run.project_name}
: —}
{!scoped&& changeSelection("jobs", run.job_id, !(search.jobs ?? []).includes(run.job_id))}/>}{run.job_name}
{run.run_name || "Run"}{(run.failure?.reason || (run.agent_error as any)?.reason) &&

{run.failure?.reason || (run.agent_error as any).reason}

}
{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}
{search.states?.length || search.projects?.length || search.jobs?.length ? <>

{emptyMessage}

: jobId || projectId ? "No runs found." : "No runs yet"}
}{pagination}
; } diff --git a/packages/app/src/shared/ui.tsx b/packages/app/src/shared/ui.tsx index 7a44a737..3c244a3f 100644 --- a/packages/app/src/shared/ui.tsx +++ b/packages/app/src/shared/ui.tsx @@ -60,18 +60,19 @@ const runStatusStyles: Record; } -export function RunStatusLabel({ state, failureSource, className = "" }: { state: string; failureSource?: string | null; className?: string }) { - const status = runStatusDetails(state, failureSource); - const text = state === "failed" && failureSource ? status.label : state || "Unknown"; - return {text}; +export function RunStatusLabel({ state, failureSource, failure, className = "" }: { state: string; failureSource?: string | null; failure?: { source?: string } | null; className?: string }) { + const status = runStatusDetails(state, failureSource, failure); + const text = state === "failed" && status.label !== "Failed" ? status.label : state || "Unknown"; + return {text}; } export function Button({ variant = "secondary", className = "", ...props }: ComponentProps<"button"> & { variant?: keyof typeof buttonClasses }) { return