Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions packages/api/migrations/0032_run_failure_outcomes.sql
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion packages/api/scripts/static-slice.config.ts
Original file line number Diff line number Diff line change
@@ -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"] } });
8 changes: 5 additions & 3 deletions packages/api/src/amp-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ExecutionObservation> {
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<ExecutionObservation> {
const result = await this.call(`/runs/${encodeURIComponent(handle.id)}/stop`, { method: "POST", body: "{}" });
Expand Down
9 changes: 5 additions & 4 deletions packages/api/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
}
Expand All @@ -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. */
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)),
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/harness-diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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) } } : {}),
};
}
9 changes: 5 additions & 4 deletions packages/api/src/postgres/run-query-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any>(`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
Expand All @@ -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))))
Expand All @@ -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,
Expand All @@ -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 => {
Expand Down
Loading
Loading