From 7e962cca06d09f2cd48a5c8878feb8c383b77167 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 18 Sep 2026 22:08:26 +0000 Subject: [PATCH] Persist harness stderr and terminal execution diagnostics --- .../migrations/0007_harness_diagnostics.sql | 2 + packages/app/src/exe-vm-backend.ts | 46 ++++++--- packages/app/src/execution.ts | 1 + packages/app/src/flow-service.ts | 4 +- packages/app/src/harness-diagnostics.ts | 27 +++++ .../app/src/postgres/artifact-repository.ts | 2 +- packages/app/src/postgres/run-repository.ts | 26 +++-- packages/app/src/postgres/run-scheduler.ts | 66 +++++++++++-- packages/app/src/postgres/schema.ts | 2 +- packages/app/test/execution-backend.test.ts | 11 ++- packages/app/test/harness-diagnostics.test.ts | 60 +++++++++++ .../app/test/postgres-run-repository.test.ts | 27 +++++ .../app/test/run-diagnostics-contract.test.ts | 55 +++++++++++ packages/app/test/run-finalization.test.ts | 99 +++++++++++++++++++ packages/docs/openapi.yaml | 66 ++++++++++++- 15 files changed, 454 insertions(+), 40 deletions(-) create mode 100644 packages/app/migrations/0007_harness_diagnostics.sql create mode 100644 packages/app/src/harness-diagnostics.ts create mode 100644 packages/app/test/harness-diagnostics.test.ts create mode 100644 packages/app/test/run-diagnostics-contract.test.ts create mode 100644 packages/app/test/run-finalization.test.ts diff --git a/packages/app/migrations/0007_harness_diagnostics.sql b/packages/app/migrations/0007_harness_diagnostics.sql new file mode 100644 index 00000000..dd7d2fd9 --- /dev/null +++ b/packages/app/migrations/0007_harness_diagnostics.sql @@ -0,0 +1,2 @@ +-- Terminal execution evidence is independent of artifact and cleanup errors. +ALTER TABLE app.runs ADD COLUMN execution_diagnostics jsonb; diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index dae1eb24..aa8915ee 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -2,6 +2,8 @@ import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, Laun import { base64 } from "./crypto"; import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; +import { HARNESS_LOG_LIMIT, safeDiagnosticText } from "./harness-diagnostics"; + const API = "https://exe.dev/exec"; const capabilities = ["output", "recovery", "stop"] as const; @@ -101,15 +103,14 @@ export class ExeVmBackend implements ExecutionBackend { "mkdir -p /home/exedev/workspace", "cd /home/exedev/workspace", `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, - `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:${output} ${harnessCommand(request.harness)}; fi`, + `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`, "echo started", ].join("; "); let started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); const accepted = (result: BackendCommandResult) => result.ok && result.body.trim() === "started"; for (let attempt = 1; !accepted(started) && attempt < 5; attempt++) started = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(work)}`); if (!accepted(started)) { - const cleanup = await this.deleteVm(vm); - const detail = `VM provisioning failed (${started.status}): ${started.body.slice(0, 500)}${cleanup.ok ? "" : `; cleanup also failed: ${cleanup.body.slice(0, 200)}`}`; + const detail = `VM provisioning failed (${started.status}): ${safeDiagnosticText(started.body, 500)}`; return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "failed", detail, command: started }, command: started }; } return { handle: { backendKind: this.kind, id: vm }, destinationUrl: `https://${vm}.exe.xyz/`, capabilities, observation: { state: "running", command: started }, command: started }; @@ -117,15 +118,36 @@ export class ExeVmBackend implements ExecutionBackend { async inspect(handle: RunHandle): Promise { const vm = this.vm(handle); - const inspect = `unit=${shellAtom(vm)}; load=$(sudo systemctl show "$unit" --property=LoadState --value 2>/dev/null || true); active=$(sudo systemctl show "$unit" --property=ActiveState --value 2>/dev/null || true); sub=$(sudo systemctl show "$unit" --property=SubState --value 2>/dev/null || true); result=$(sudo systemctl show "$unit" --property=Result --value 2>/dev/null || true); code=$(sudo systemctl show "$unit" --property=ExecMainStatus --value 2>/dev/null || true); if [ "$load" != loaded ]; then printf missing; elif [ "$sub" = running ] || [ "$sub" = start ] || [ "$active" = activating ] || [ "$active" = deactivating ]; then printf running; elif [ "$result" = success ] && [ "$code" = 0 ]; then printf succeeded; else printf failed; fi`; - const result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`); - if (!result.ok) return result.status >= 500 - ? { state: "running", detail: `VM inspection is temporarily unavailable (${result.status})`, command: result } - : { state: "failed", detail: `The run-owned VM is unavailable (${result.status}): ${result.body.slice(0, 300)}`, command: result }; - const state = result.body.trim(); - if (state === "succeeded") return { state: "succeeded", command: result }; - if (state === "running") return { state: "running", command: result }; - return { state: "failed", detail: state === "missing" ? "The run supervisor disappeared before recording a result." : "The supervised agent process exited unsuccessfully.", command: result }; + const inspect = `sudo systemctl show ${shellAtom(vm)} --property=LoadState,ActiveState,SubState,Result,ExecMainCode,ExecMainStatus`; + let response: BackendCommandResult; + try { response = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(inspect)}`); } + catch { return { state: "running", detail: "VM inspection is temporarily unavailable" }; } + // 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})` }; + 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 (["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}).` }; + } + + async readHarnessLog(handle: RunHandle): Promise { + // Read the first bounded bytes: starting in the middle of a credential could evade redaction. + // Old VMs have only the combined log. + const remote = `if [ -f /tmp/factorize.stderr ]; then head -c ${HARNESS_LOG_LIMIT} /tmp/factorize.stderr; else head -c ${HARNESS_LOG_LIMIT} /tmp/factorize.log; fi`; + const response = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); + if (!response.ok) throw new Error(`Harness log collection failed (${response.status})`); + // Drop a possibly cut final line before redaction. Never retain a partial credential. + const text = new TextEncoder().encode(response.body).length >= HARNESS_LOG_LIMIT + ? response.body.slice(0, response.body.lastIndexOf("\n") + 1) + "\n[Harness log truncated]\n" : response.body; + return safeDiagnosticText(text, HARNESS_LOG_LIMIT); } async readOutput(handle: RunHandle): Promise { diff --git a/packages/app/src/execution.ts b/packages/app/src/execution.ts index 736d4184..2339973f 100644 --- a/packages/app/src/execution.ts +++ b/packages/app/src/execution.ts @@ -20,6 +20,7 @@ export interface LaunchRequest { export interface RunHandle { backendKind: string; id: string; } export interface ExecutionObservation { + systemd?: import("./harness-diagnostics").ExecutionDiagnostics["systemd"]; state: ExecutionState; detail?: string; command?: BackendCommandResult; diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 6d5aee3d..8283e0fc 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -86,9 +86,9 @@ export class ApiService { async listTailIntegrations() { await this.authorize("flows:read"); return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails(); } async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query); } async search(query: string) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query); } - async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); return run; } + async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); run.execution_diagnostics ??= null; run.harness_log = (await new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId)).find(item => item.kind === "terminal_log") ?? null; return run; } async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); } - async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; } + async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, execution: run.execution_diagnostics, harnessLog: run.harness_log, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; } async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } killRun(runId: string) { return this.stopRun(runId); } async listJobs() { await this.authorize("flows:read"); return Promise.all((await this.jobs().list()).map(job => this.presentJob(job))); } diff --git a/packages/app/src/harness-diagnostics.ts b/packages/app/src/harness-diagnostics.ts new file mode 100644 index 00000000..7a09edad --- /dev/null +++ b/packages/app/src/harness-diagnostics.ts @@ -0,0 +1,27 @@ +import type { ExecutionObservation } from "./execution"; +import { scrubSession } from "./session-scrubber"; + +export const HARNESS_LOG_LIMIT = 64 * 1024; +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; +} + +/** Redact before truncation so a cut cannot expose part of a recognized credential. */ +export function safeDiagnosticText(value: string, limit = 2048): string { + const withoutAssignments = value.replace(/^.*["']?(?:[\w-]*(?:token|secret|password|passwd|api[_-]?key|authorization|cookie))["']?\s*[:=].*$/gim, "[REDACTED]"); + const safe = scrubSession(withoutAssignments) + .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*/gi, "[REDACTED]") + .replace(/\b[A-Z][A-Z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD)\s*=\s*[^\r\n]+/g, "[REDACTED]") + .replace(/([?&](?:token|key|signature|credential|password|secret|x-amz-[\w-]+)=)[^&#\s]+/gi, "$1[REDACTED]"); + return new TextDecoder().decode(new TextEncoder().encode(safe).slice(0, limit)).replace(/\uFFFD$/, ""); +} + +export function terminalDiagnostics(observation: ExecutionObservation): ExecutionDiagnostics { + return { + state: observation.state === "succeeded" ? "succeeded" : observation.state === "stopped" ? "stopped" : "failed", + detail: observation.detail ? safeDiagnosticText(observation.detail) : null, + systemd: observation.systemd ?? null, + }; +} diff --git a/packages/app/src/postgres/artifact-repository.ts b/packages/app/src/postgres/artifact-repository.ts index 48f2ae51..29207f6d 100644 --- a/packages/app/src/postgres/artifact-repository.ts +++ b/packages/app/src/postgres/artifact-repository.ts @@ -11,7 +11,7 @@ export class ArtifactRepository { await client.query(`INSERT INTO app.run_artifacts(tenant_id,run_id,id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) ON CONFLICT (tenant_id,object_key) DO UPDATE SET byte_size=excluded.byte_size,sha256=excluded.sha256,state=excluded.state`, [this.tenantId, input.runId, id, input.kind, input.objectKey, input.provider, input.format, input.formatVersion ?? null, input.cliVersion ?? null, input.nativeSessionId ?? null, input.byteSize, input.sha256, input.state ?? "stored"]); - await client.query("UPDATE app.runs SET artifact_state='stored',artifact_error=NULL,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]); + await client.query("UPDATE app.runs SET artifact_state='stored',updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]); }); } async list(runId: string) { return (await this.database.pool.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } diff --git a/packages/app/src/postgres/run-repository.ts b/packages/app/src/postgres/run-repository.ts index 5a04a2b7..15f9ee59 100644 --- a/packages/app/src/postgres/run-repository.ts +++ b/packages/app/src/postgres/run-repository.ts @@ -1,18 +1,22 @@ +import { terminalDiagnostics, safeDiagnosticText, type ExecutionDiagnostics } from "../harness-diagnostics"; +import type { ExecutionObservation } from "../execution"; import type { ExecutionState, RunHandle } from "../execution"; import type { Database, DatabaseClient } from "./database"; export interface PersistedRun { tenantId: string; id: string; jobId: string; invocationId: string; state: ExecutionState; encryptedPrompt: string; executionTarget: Record; executionHandle: RunHandle | null; + executionDiagnostics?: ExecutionDiagnostics | null; finalizationAttempt?: number; backendKind: string; capabilities: string[]; artifactState: string; createdAt: string; updatedAt: string; } interface RunRow { tenant_id: string; id: string; job_id: string; invocation_id: string; state: ExecutionState; encrypted_prompt: string; execution_target: Record; execution_handle: RunHandle | null; execution_backend_kind: string; + execution_diagnostics: ExecutionDiagnostics | null; vm_cleanup_attempt: number; execution_capabilities: string[]; artifact_state: string; 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, executionTarget: row.execution_target, executionHandle: row.execution_handle, backendKind: row.execution_backend_kind, capabilities: row.execution_capabilities, artifactState: row.artifact_state, 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, executionTarget: row.execution_target, 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, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); export class RunRepository { constructor(private database: Database) {} @@ -27,7 +31,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,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.artifact_state,c.created_at,c.updated_at + ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,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; @@ -37,7 +41,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,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.artifact_state,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,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,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); @@ -57,20 +61,28 @@ export class RunRepository { }); } - async terminal(run: PersistedRun, state: "succeeded" | "failed" | "stopped", artifactState: "stored" | "partial" | "failed", error?: string): Promise { + async recordObservation(run: PersistedRun, observation: ExecutionObservation): Promise { + const diagnostics = terminalDiagnostics(observation); + const result = await this.database.pool.query<{ execution_diagnostics: ExecutionDiagnostics }>( + "UPDATE app.runs SET execution_diagnostics=COALESCE(execution_diagnostics,$3::jsonb),updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING execution_diagnostics", + [run.tenantId, run.id, JSON.stringify(diagnostics)]); + return result.rows[0].execution_diagnostics; + } + + async terminal(run: PersistedRun, state: "succeeded" | "failed" | "stopped", artifactState: "stored" | "partial" | "failed", error?: string, cleanupComplete = false): Promise { await this.database.transaction(async client => { 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, state]); - await client.query("UPDATE app.runs SET state=$3,artifact_state=$4,artifact_error=$5,claim_released=true,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, state, artifactState, error ?? null]); + await client.query("UPDATE app.runs SET state=$3,artifact_state=$4,artifact_error=$5,claim_released=true,vm_cleanup_complete=$6,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, state, 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]); }); } async retryFinalization(run: PersistedRun, artifactState: "pending" | "collecting" | "stored" | "partial" | "failed", error: string): Promise { await this.database.transaction(async client => { - const attempt = (await client.query<{ vm_cleanup_attempt: number }>("UPDATE app.runs SET artifact_state=$3,artifact_error=$4,vm_cleanup_attempt=vm_cleanup_attempt+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING vm_cleanup_attempt", [run.tenantId, run.id, artifactState, error])).rows[0]?.vm_cleanup_attempt ?? 1; + const attempt = (await client.query<{ vm_cleanup_attempt: number }>("UPDATE app.runs SET artifact_state=$3,artifact_error=$4,vm_cleanup_attempt=vm_cleanup_attempt+1,updated_at=now() WHERE tenant_id=$1 AND id=$2 RETURNING vm_cleanup_attempt", [run.tenantId, run.id, artifactState, safeDiagnosticText(error)])).rows[0]?.vm_cleanup_attempt ?? 1; const seconds = Math.min(60, 2 ** Math.min(attempt, 6)); await client.query("UPDATE app.job_runs SET state='running',next_poll_at=now()+make_interval(secs=>$3),updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, seconds]); - await client.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) VALUES ($1,$2,$3,'finalization_retry',$4)", [run.tenantId, crypto.randomUUID(), run.id, `Attempt ${attempt}: ${error}`]); + await client.query("INSERT INTO app.run_activity(tenant_id,id,run_id,action,detail) VALUES ($1,$2,$3,'finalization_retry',$4)", [run.tenantId, crypto.randomUUID(), run.id, `Attempt ${attempt}: ${safeDiagnosticText(error)}`]); }); } diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index 25d17aa0..3317adf1 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -1,5 +1,8 @@ import { AmpBackend, type AmpConnection } from "../amp-backend"; import { issueArtifactUploadGrant } from "../artifact-upload"; +import { artifactKey } from "../artifacts"; +import { ArtifactRepository } from "./artifact-repository"; +import { safeDiagnosticText } from "../harness-diagnostics"; import { decrypt } from "../crypto"; import { ExeVmBackend } from "../exe-vm-backend"; import type { ExeRunConnection } from "../exe"; @@ -34,26 +37,61 @@ export class RunScheduler { private async launch(run: PersistedRun) { const backend = await this.backend(run), driver = agentDriver(run.executionTarget.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionTarget.model, effort: run.executionTarget.effort }); const launched = await backend.launch({ runId: run.id, prompt: await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY), harness: { executable: harness.executable, args: harness.args, env: harness.env } }); - if (launched.observation.state === "failed") throw new Error(launched.observation.detail ?? "Agent launch failed"); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities); + if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } private async poll(run: PersistedRun) { const backend = await this.backend(run); if (!run.executionHandle) throw new Error("Execution handle is missing"); - const observation = await backend.inspect(run.executionHandle); + const observation = run.executionDiagnostics ?? await backend.inspect(run.executionHandle); if (["running", "blocked", "stopping"].includes(observation.state)) { if (backend instanceof ExeVmBackend) await this.collectTraceChunk(run, backend).catch(() => undefined); return this.runs.schedulePoll(run, observation.state as "running" | "blocked" | "stopping"); } - let artifactState: "stored" | "partial" | "failed" = "stored", artifactError: string | undefined; + // Persist the first terminal observation before any collection or deletion. + // Retries use this snapshot even if the VM has subsequently disappeared. + const diagnostics = await this.runs.recordObservation(run, { ...observation, detail: observation.detail ?? undefined }); + run.executionDiagnostics = diagnostics; + let artifactState: "stored" | "partial" | "failed" = "stored"; + const errors: string[] = []; if (backend instanceof ExeVmBackend) { - const collected = await this.collectArtifact(run, backend); - if (!collected.ok) { await this.runs.retryFinalization(run, "failed", collected.detail ?? "Native session upload failed"); return; } - const stopped = await backend.stop(run.executionHandle); - if (stopped.state !== "stopped") { await this.runs.retryFinalization(run, "stored", stopped.detail ?? "VM deletion failed after artifact upload"); return; } + const artifacts = new ArtifactRepository(this.database, run.tenantId); + const stored = await artifacts.list(run.id); + if (!stored.some(item => item.kind === "terminal_log" && item.state === "stored")) { + try { await this.collectHarnessLog(run, backend, artifacts); } + catch { errors.push("Harness log collection or storage failed"); } + } + if (!stored.some(item => item.kind === "native_session" && item.state === "stored")) { + try { + const collected = await this.collectArtifact(run, backend); + if (!collected.ok) errors.push("Native session upload failed"); + } catch { errors.push("Native session collection or storage failed"); } + } + // Retry collection, but do not keep a VM forever for an absent session/log. + if (errors.length && (run.finalizationAttempt ?? 0) < 2) { + await this.runs.retryFinalization(run, "partial", errors.join("; ")); + return; + } + if (errors.length) artifactState = "partial"; + try { + const stopped = await backend.stop(run.executionHandle); + if (stopped.state !== "stopped") throw new Error("VM cleanup failed"); + } catch { + await this.runs.retryFinalization(run, artifactState, [...errors, "VM cleanup failed"].join("; ")); + return; + } } - const state = observation.state === "succeeded" ? "succeeded" : observation.state === "stopped" ? "stopped" : "failed"; - await this.runs.terminal(run, state, artifactState, artifactError); + await this.runs.terminal(run, diagnostics.state, artifactState, errors.join("; ") || undefined, true); + } + + private async collectHarnessLog(run: PersistedRun, backend: ExeVmBackend, artifacts: ArtifactRepository) { + if (!this.env.RUN_ARTIFACTS || !run.executionHandle) throw new Error("Harness artifact storage is unavailable"); + const text = await backend.readHarnessLog(run.executionHandle); + const bytes = new TextEncoder().encode(text); + const sha256 = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), byte => byte.toString(16).padStart(2, "0")).join(""); + const key = artifactKey(run.tenantId, run.id, "harness/stderr.txt"); + await this.env.RUN_ARTIFACTS.put(key, bytes, { httpMetadata: { contentType: "text/plain; charset=utf-8" }, sha256 }); + await artifacts.record({ runId: run.id, kind: "terminal_log", objectKey: key, provider: String(run.executionTarget.agentKind), format: "text", byteSize: bytes.length, sha256 }); } private async collectArtifact(run: PersistedRun, backend: ExeVmBackend) { @@ -71,5 +109,13 @@ export class RunScheduler { return backend.collectTraceChunk(run.executionHandle, { discoverCommand: locator.discoverCommand, 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) { await this.runs.terminal(run, "failed", "failed", error instanceof Error ? error.message : "Run processing failed"); } + private async fail(run: PersistedRun, error: unknown) { + // 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") }); + await this.runs.terminal(run, "failed", "failed"); + } } diff --git a/packages/app/src/postgres/schema.ts b/packages/app/src/postgres/schema.ts index 09f1b8ac..a0bddd39 100644 --- a/packages/app/src/postgres/schema.ts +++ b/packages/app/src/postgres/schema.ts @@ -51,7 +51,7 @@ export const jobRuns = app.table("job_runs", { }, 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("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`)]); export const runs = app.table("runs", { - 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"), 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"), 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"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type().notNull(), createdAt: createdAt(), diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index 16241ae1..415a674f 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -61,6 +61,7 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("--property=RemainAfterExit=yes"); expect(requests[1]).toContain("--property=StandardInput=file:/tmp/factorize-prompt.md"); expect(requests[1]).toContain("--property=StandardOutput=append:/tmp/factorize.log"); + expect(requests[1]).toContain("--property=StandardError=append:/tmp/factorize.stderr"); expect(requests[1]).not.toContain("nohup"); expect(requests[1]).toContain("; echo started"); expect(requests[1]).toContain("systemctl show"); @@ -68,10 +69,10 @@ describe("ExeVmBackend", () => { it("uses the systemd unit as the authoritative run state", async () => { const states = [ - "running", - "succeeded", - "failed", - "missing", + "LoadState=loaded\nActiveState=active\nSubState=running\nResult=success\nExecMainCode=0\nExecMainStatus=0", + "LoadState=loaded\nActiveState=active\nSubState=exited\nResult=success\nExecMainCode=1\nExecMainStatus=0", + "LoadState=loaded\nActiveState=failed\nSubState=failed\nResult=exit-code\nExecMainCode=1\nExecMainStatus=42", + "LoadState=not-found\nActiveState=inactive\nSubState=dead", ]; const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { @@ -81,7 +82,7 @@ describe("ExeVmBackend", () => { const backend = new ExeVmBackend(connection), handle = { backendKind: "exe-vm", id: "factorize-run-1" }; await expect(backend.inspect(handle)).resolves.toMatchObject({ state: "running" }); await expect(backend.inspect(handle)).resolves.toMatchObject({ state: "succeeded" }); - await expect(backend.inspect(handle)).resolves.toMatchObject({ state: "failed", detail: expect.stringContaining("unsuccessfully") }); + await expect(backend.inspect(handle)).resolves.toMatchObject({ state: "failed", systemd: { result: "exit-code", execMainCode: 1, execMainStatus: 42, activeState: "failed", subState: "failed" }, detail: expect.stringContaining("unsuccessfully") }); await expect(backend.inspect(handle)).resolves.toMatchObject({ state: "failed", detail: expect.stringContaining("supervisor disappeared") }); expect(requests.every(request => request.includes("systemctl show"))).toBe(true); expect(requests.every(request => !request.includes("factorize.status"))).toBe(true); diff --git a/packages/app/test/harness-diagnostics.test.ts b/packages/app/test/harness-diagnostics.test.ts new file mode 100644 index 00000000..297524bf --- /dev/null +++ b/packages/app/test/harness-diagnostics.test.ts @@ -0,0 +1,60 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ExeVmBackend } from "../src/exe-vm-backend"; +import { HARNESS_LOG_LIMIT, safeDiagnosticText, terminalDiagnostics } from "../src/harness-diagnostics"; +import { agentDriver } from "../src/agent-driver"; + +afterEach(() => vi.unstubAllGlobals()); +const handle = { backendKind: "exe-vm", id: "factorize-test" }; +const backend = () => new ExeVmBackend({ apiToken: "secret", tags: [] }); + +describe("harness diagnostics", () => { + it.each(["codex", "claude", "pi"] as const)("separates %s stderr from stdout", async agentKind => { + const requests: string[] = []; + vi.stubGlobal("fetch", vi.fn(async (_url, init) => { + requests.push(String(init.body)); + return new Response(requests.length === 1 ? "created" : "started"); + })); + await new ExeVmBackend({ apiToken: "secret", tags: [], agentKind, model: "", effort: "" }).launch({ runId: "test", prompt: "work", harness: agentDriver(agentKind).launch("test", {}) }); + expect(requests[1]).toContain("StandardError=append:/tmp/factorize.stderr"); + expect(requests[1]).toContain("StandardOutput=append:/tmp/factorize.log"); + }); + + it.each([503, 429, 408, 422])("keeps an inspection failure (%s) nonterminal", async status => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("password=do-not-store", { status }))); + expect(await backend().inspect(handle)).toEqual({ state: "running", detail: `VM inspection is temporarily unavailable (${status})` }); + }); + it("keeps transport and incomplete metadata failures nonterminal", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValueOnce(new Error("connection reset")).mockResolvedValueOnce(new Response("LoadState=loaded"))); + expect((await backend().inspect(handle)).state).toBe("running"); + expect((await backend().inspect(handle)).state).toBe("running"); + }); + it("records missing supervisor metadata even when systemctl exits nonzero", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("LoadState=not-found\nActiveState=inactive\nSubState=dead", { headers: { "X-Exe-Exit": "1" } }))); + expect(await backend().inspect(handle)).toMatchObject({ state: "failed", systemd: { loadState: "not-found", activeState: "inactive", subState: "dead", execMainCode: null }, detail: expect.stringContaining("supervisor disappeared") }); + }); + it("retains stderr while redacting credentials and bounding bytes", async () => { + vi.stubGlobal("fetch", vi.fn(async (_url, init) => { + expect(String(init.body)).toContain(`head -c ${HARNESS_LOG_LIMIT}`); + return new Response('recognizable harness failure\nAuthorization: Bearer secret-value\n{"password": "long secret value"}\nhttps://example.test/?token=hidden\n'); + })); + const log = await backend().readHarnessLog(handle); + expect(log).toContain("recognizable harness failure"); + for (const secret of ["secret-value", "long secret value", "hidden"]) expect(log).not.toContain(secret); + expect(new TextEncoder().encode(safeDiagnosticText("漢".repeat(HARNESS_LOG_LIMIT), HARNESS_LOG_LIMIT)).length).toBeLessThanOrEqual(HARNESS_LOG_LIMIT); + }); + it("redacts quoted assignments before a generic scrubber can remove their key", () => { + expect(safeDiagnosticText("password='a longer secret'\nAPI_KEY=secret with spaces\n-----BEGIN PRIVATE KEY-----\nprivate material")).not.toMatch(/longer|with spaces|private material/); + }); + it("retains signal termination metadata", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("LoadState=loaded\nActiveState=failed\nSubState=failed\nResult=signal\nExecMainCode=2\nExecMainStatus=9"))); + expect(await backend().inspect(handle)).toMatchObject({ state: "failed", systemd: { result: "signal", execMainCode: 2, execMainStatus: 9 } }); + }); + it("drops a truncated last line that might contain a partial secret", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("first line\n" + "x".repeat(HARNESS_LOG_LIMIT)))); + expect(await backend().readHarnessLog(handle)).toBe("first line\n\n[Harness log truncated]\n"); + }); + it("does not persist backend commands or raw responses", () => { + const value = terminalDiagnostics({ state: "failed", detail: "Bearer secret", command: { ok: false, status: 500, exitCode: 42, requestBody: "private command", body: "private response" } }); + expect(value).toEqual({ state: "failed", detail: "[REDACTED]", systemd: null }); + }); +}); diff --git a/packages/app/test/postgres-run-repository.test.ts b/packages/app/test/postgres-run-repository.test.ts index ceceb386..7319205c 100644 --- a/packages/app/test/postgres-run-repository.test.ts +++ b/packages/app/test/postgres-run-repository.test.ts @@ -10,3 +10,30 @@ describe("RunRepository", () => { expect(query.mock.calls[0][0]).toContain("concurrency_limit"); }); }); + +describe("execution evidence persistence", () => { + it("uses a tenant-qualified first-write-wins snapshot without persisting raw commands", async () => { + const first = { state: "failed", detail: "exit 42", systemd: null }; + const query = vi.fn(async (_sql: string, _values: unknown[]) => ({ rows: [{ execution_diagnostics: first }] })); + const repository = new RunRepository({ pool: { query } } as any); + const result = await repository.recordObservation({ tenantId: "tenant", id: "run" } as any, { + state: "failed", detail: "Bearer secret", command: { ok: false, status: 500, exitCode: 1, body: "raw response", requestBody: "raw command" }, + }); + expect(result).toEqual(first); + expect(query.mock.calls[0]).toEqual([ + expect.stringContaining("execution_diagnostics=COALESCE(execution_diagnostics,$3::jsonb)"), + ["tenant", "run", JSON.stringify({ state: "failed", detail: "[REDACTED]", systemd: null })], + ]); + expect(query.mock.calls[0][0]).toContain("WHERE tenant_id=$1 AND id=$2"); + }); +}); + +it("recording an independent artifact cannot clear execution or collection errors", async () => { + const { ArtifactRepository } = await import("../src/postgres/artifact-repository"); + const query = vi.fn(async (_sql: string, _values: unknown[]) => ({ rows: [] })); + const repository = new ArtifactRepository({ transaction: (work: any) => work({ query }) } as any, "tenant"); + await repository.record({ runId: "run", kind: "terminal_log", objectKey: "log", provider: "codex", format: "text", byteSize: 1, sha256: "a".repeat(64) }); + const update = query.mock.calls.find(([sql]) => sql.startsWith("UPDATE app.runs"))![0]; + expect(update).not.toContain("artifact_error"); + expect(update).not.toContain("execution_diagnostics"); +}); diff --git a/packages/app/test/run-diagnostics-contract.test.ts b/packages/app/test/run-diagnostics-contract.test.ts new file mode 100644 index 00000000..31079eea --- /dev/null +++ b/packages/app/test/run-diagnostics-contract.test.ts @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { ApiService } from "../src/flow-service"; +import { IdentityRepository } from "../src/postgres/identity-repository"; +import { encrypt } from "../src/crypto"; +import { isDeclaredApiOperation } from "../src/api-contract"; + +afterEach(() => vi.restoreAllMocks()); +const execution = { state: "failed", detail: "Process exited with status 42", systemd: { loadState: "loaded", activeState: "failed", subState: "failed", result: "exit-code", execMainCode: 1, execMainStatus: 42 } }; +const artifact = { id: "artifact", kind: "terminal_log", object_key: "tenants/tenant/runs/run/harness/stderr.txt", format: "text", state: "stored", byte_size: "27", sha256: "a".repeat(64) }; + +async function fixture(tenantId = "tenant", scopes = ["runs:read"]) { + const key = btoa("a".repeat(32)), encryptedPrompt = await encrypt("private prompt", key); + vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue({ role: "owner", sessionVersion: 1 } as any); + const query = vi.fn(async (sql: string, values: any[]) => { + if (values[0] !== "tenant") return { rows: [] }; + if (sql.includes("SELECT r.*")) return { rows: [{ id: "run", job_id: "job", state: "failed", encrypted_prompt: encryptedPrompt, execution_diagnostics: execution, execution_backend_kind: "exe-vm", artifact_state: "partial", artifact_error: "Native session upload failed" }] }; + if (sql.includes("app.run_artifacts")) return { rows: [artifact] }; + return { rows: [] }; + }); + return new ApiService({ DATABASE: { pool: { query } }, CREDENTIAL_ENCRYPTION_KEY: key } as any, { tenantId, userId: "user", sessionVersion: 1, scopes } as any); +} + +describe("run diagnostics API boundary", () => { + it("exposes durable evidence and artifact location through both declared versioned operations", async () => { + const service = await fixture(); + expect(isDeclaredApiOperation("GET", "/api/v1/runs/run")).toBe(true); + expect(isDeclaredApiOperation("GET", "/api/v1/runs/run/diagnostics")).toBe(true); + expect(await service.getRun("run")).toMatchObject({ execution_diagnostics: execution, harness_log: artifact }); + const diagnostics = await service.getRunDiagnostics("run"); + expect(diagnostics).toMatchObject({ execution, harnessLog: artifact, artifact: { state: "partial", error: "Native session upload failed" } }); + expect(JSON.stringify(diagnostics)).not.toContain("private prompt"); + expect(JSON.stringify(diagnostics)).not.toContain("encrypted_prompt"); + }); + it("requires runs:read and isolates artifact lookup by tenant", async () => { + await expect((await fixture("tenant", [])).getRunDiagnostics("run")).rejects.toMatchObject({ status: 403 }); + await expect((await fixture("other-tenant")).getRunDiagnostics("run")).rejects.toMatchObject({ status: 404 }); + }); + it("returns null evidence and log for older runs", async () => { + const service = await fixture(); + const { RunQueryRepository } = await import("../src/postgres/run-query-repository"); + const { ArtifactRepository } = await import("../src/postgres/artifact-repository"); + const key = btoa("a".repeat(32)); + vi.spyOn(RunQueryRepository.prototype, "get").mockResolvedValue({ id: "old", encrypted_prompt: await encrypt("", key) }); + vi.spyOn(ArtifactRepository.prototype, "list").mockResolvedValue([]); + expect(await service.getRunDiagnostics("old")).toMatchObject({ execution: null, harnessLog: null }); + }); + it("documents the externally visible fields and schema references", () => { + const spec = readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"); + for (const field of ["execution_diagnostics", "harness_log", "execution:", "harnessLog:", "execMainCode", "execMainStatus", "activeState", "subState", "object_key"]) + expect(spec).toContain(field); + expect(spec).toContain("$ref: '#/components/schemas/RunDetail'"); + expect(spec).toContain("$ref: '#/components/schemas/RunDiagnostics'"); + }); +}); diff --git a/packages/app/test/run-finalization.test.ts b/packages/app/test/run-finalization.test.ts new file mode 100644 index 00000000..58e65c6a --- /dev/null +++ b/packages/app/test/run-finalization.test.ts @@ -0,0 +1,99 @@ +import { spawnSync } from "node:child_process"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { RunScheduler } from "../src/postgres/run-scheduler"; +import { RunRepository } from "../src/postgres/run-repository"; +import { ArtifactRepository } from "../src/postgres/artifact-repository"; +import { ExeVmBackend } from "../src/exe-vm-backend"; +import { terminalDiagnostics, type ExecutionDiagnostics } from "../src/harness-diagnostics"; + +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + +function fixture(exit = 42) { + const harness = spawnSync("bash", ["-c", `printf 'recognizable harness error\\n' >&2; exit ${exit}`], { encoding: "utf8" }); + const events: string[] = [], artifacts: any[] = [], blobs = new Map(); + let saved: ExecutionDiagnostics | null = null; + const backend = new ExeVmBackend({ apiToken: "secret", tags: [] }); + const run: any = { tenantId: "tenant", id: "run", jobId: "job", executionTarget: { agentKind: "codex" }, executionHandle: { backendKind: "exe-vm", id: "factorize-run" }, finalizationAttempt: 0 }; + vi.stubGlobal("fetch", vi.fn(async (_url, init) => new Response(String(init.body).includes("systemctl") + ? `LoadState=loaded\nActiveState=${exit ? "failed" : "active"}\nSubState=${exit ? "failed" : "exited"}\nResult=${exit ? "exit-code" : "success"}\nExecMainCode=1\nExecMainStatus=${harness.status}` + : harness.stderr))); + const recordObservation = vi.spyOn(RunRepository.prototype, "recordObservation").mockImplementation(async (_run, observation) => { + events.push("observation"); saved ??= terminalDiagnostics(observation); return saved; + }); + const terminal = vi.spyOn(RunRepository.prototype, "terminal").mockResolvedValue(); + 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); + const put = vi.fn(async (key, bytes) => { events.push("log"); blobs.set(key, new TextDecoder().decode(bytes)); }); + const scheduler: any = new RunScheduler({} as any, { RUN_ARTIFACTS: { put } } as any); + vi.spyOn(scheduler, "backend").mockResolvedValue(backend); + const native = vi.spyOn(scheduler, "collectArtifact").mockImplementation(async () => { events.push("native"); artifacts.push({ kind: "native_session", state: "stored" }); return { ok: true }; }); + // Match the state returned by PostgreSQL for a recorded harness artifact. + vi.spyOn(ArtifactRepository.prototype, "record").mockImplementation(async item => { artifacts.push({ ...item, state: "stored" }); }); + const stop = vi.spyOn(backend, "stop").mockImplementation(async () => { events.push("cleanup"); return { state: "stopped" }; }); + return { scheduler, run, backend, terminal, retry, schedule, stop, native, put, blobs, artifacts, events, recordObservation, saved: () => saved }; +} + +describe("durable run finalization", () => { + it("stores real nonzero harness stderr and exit metadata before deleting the VM", async () => { + const f = fixture(); + await f.scheduler.poll(f.run); + expect(f.saved()).toMatchObject({ state: "failed", detail: expect.stringContaining("ExecMainStatus=42"), systemd: { result: "exit-code", execMainCode: 1, execMainStatus: 42, activeState: "failed", subState: "failed" } }); + 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); + }); + 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); + }); + it.each(["native", "put"] as const)("bounds %s upload retries without replacing the primary failure", async target => { + const f = fixture(); + f[target].mockRejectedValue(new Error("Authorization: Bearer sensitive")); + await f.scheduler.poll(f.run); + const first = f.saved(); + expect(f.stop).not.toHaveBeenCalled(); + await f.scheduler.poll(f.run); + await f.scheduler.poll(f.run); + 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(JSON.stringify(f.terminal.mock.calls)).not.toContain("sensitive"); + }); + it("retries cleanup using the original observation even if inspection later reports missing", async () => { + const f = fixture(); + f.stop.mockResolvedValueOnce({ state: "failed", detail: "cleanup error" }); + await f.scheduler.poll(f.run); + const first = f.saved(); + const inspect = vi.spyOn(f.backend, "inspect").mockResolvedValue({ state: "failed", detail: "supervisor missing" }); + await f.scheduler.poll(f.run); + expect(inspect).not.toHaveBeenCalled(); + expect(f.saved()).toEqual(first); + expect(f.put).toHaveBeenCalledOnce(); + expect(f.native).toHaveBeenCalledOnce(); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true); + }); + 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." }); + 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); + }); + it("does not finalize or delete on a temporary inspection failure", async () => { + const f = fixture(); + vi.spyOn(f.backend, "inspect").mockResolvedValue({ state: "running", detail: "temporarily unavailable" }); + vi.spyOn(f.scheduler, "collectTraceChunk").mockResolvedValue({ ok: true }); + await f.scheduler.poll(f.run); + expect(f.schedule).toHaveBeenCalled(); + expect(f.recordObservation).not.toHaveBeenCalled(); + expect(f.stop).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 78cd4270..0475f6a6 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -25,6 +25,68 @@ components: model: { type: string, maxLength: 120 } effort: { type: string, maxLength: 40 } triggers: { type: array, maxItems: 50, items: { type: object } } + ExecutionDiagnostics: + type: [object, 'null'] + description: First terminal backend observation, retained independently of collection and cleanup errors. Null for older or nonterminal runs. Commands and raw backend responses are never included. + required: [state, detail, systemd] + properties: + state: { type: string, enum: [succeeded, failed, stopped] } + detail: { type: [string, 'null'], maxLength: 2048, description: Bounded credential-redacted backend observation detail } + systemd: + type: [object, 'null'] + required: [loadState, activeState, subState, result, execMainCode, execMainStatus] + properties: + loadState: { type: string, maxLength: 64 } + activeState: { type: string, maxLength: 64 } + subState: { type: string, maxLength: 64 } + result: { type: string, maxLength: 64 } + execMainCode: { type: [integer, 'null'], description: systemd ExecMainCode (for example 1 for exit and 2 for signal) } + execMainStatus: { type: [integer, 'null'], description: systemd exit status or signal number; null if unavailable } + HarnessLog: + type: [object, 'null'] + description: Stored redacted harness stderr artifact, or null if unavailable. Uses the combined log for older VMs. Retains at most the first 64 KiB, drops a truncated final line, and redacts recognizable credentials before storage. The object key is a storage locator, not a public or signed URL. This artifact remains available after VM deletion. + required: [id, kind, object_key, provider, format, byte_size, sha256, state, created_at] + properties: + id: { type: string } + kind: { type: string, const: terminal_log } + object_key: { type: string } + provider: { type: string } + format: { type: string, const: text } + format_version: { type: [string, 'null'] } + cli_version: { type: [string, 'null'] } + native_session_id: { type: [string, 'null'] } + byte_size: { type: [integer, string], description: Byte count (PostgreSQL bigint may serialize as a decimal string), maximum: 65536 } + sha256: { type: string, pattern: '^[a-f0-9]{64}$' } + state: { type: string, enum: [stored] } + created_at: { type: string, format: date-time } + RunDetail: + type: object + required: [id, state, execution_diagnostics, harness_log] + properties: + id: { type: string } + state: { type: string } + execution_diagnostics: { $ref: '#/components/schemas/ExecutionDiagnostics' } + harness_log: { $ref: '#/components/schemas/HarnessLog' } + artifact_error: { type: [string, 'null'], description: Secondary artifact or cleanup error; does not replace execution_diagnostics } + RunDiagnostics: + type: object + required: [runId, jobId, state, execution, harnessLog, artifact, activity] + properties: + runId: { type: string } + jobId: { type: string } + state: { type: string } + provider: { type: string } + backendKind: { type: string } + execution: { $ref: '#/components/schemas/ExecutionDiagnostics' } + harnessLog: { $ref: '#/components/schemas/HarnessLog' } + artifact: + type: object + properties: + state: { type: string } + error: { type: [string, 'null'], description: Secondary collection or cleanup error. Collection is retried up to three times before cleanup proceeds with partial artifacts. Cleanup failures remain retryable. } + activity: { type: array, items: { type: object } } + createdAt: { type: string, format: date-time } + updatedAt: { type: string, format: date-time } RunPage: { type: object, required: [items], properties: { items: { type: array, items: { type: object } }, nextCursor: { type: string, nullable: true } } } ManualInvocation: type: object @@ -82,9 +144,9 @@ paths: /api/v1/job-handlers/test: { post: { summary: Test webhook handler, responses: { '200': { description: Decision } } } } /api/v1/runs: get: { summary: List runs, parameters: [{ name: jobId, in: query, schema: { type: string } }, { name: state, in: query, schema: { type: string } }, { name: contextQuery, in: query, schema: { type: string } }, { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }, { name: cursor, in: query, schema: { type: string } }], responses: { '200': { description: Paginated runs, content: { application/json: { schema: { $ref: '#/components/schemas/RunPage' } } } } } } - /api/v1/runs/{runId}: { get: { summary: Get run, responses: { '200': { description: Run } } } } + /api/v1/runs/{runId}: { get: { summary: Get run, responses: { '200': { description: Run including durable execution diagnostics and harness artifact location, content: { application/json: { schema: { $ref: '#/components/schemas/RunDetail' } } } } } } } /api/v1/runs/{runId}/trace: { get: { summary: Get paginated run trace events, responses: { '200': { description: Trace page } } } } - /api/v1/runs/{runId}/diagnostics: { get: { summary: Get credential-safe run lifecycle diagnostics, responses: { '200': { description: Launch, prompt, output, claim, cleanup, and activity diagnostics } } } } + /api/v1/runs/{runId}/diagnostics: { get: { summary: Get credential-safe run lifecycle diagnostics, responses: { '200': { description: Credential-safe execution metadata and durable harness artifact location, content: { application/json: { schema: { $ref: '#/components/schemas/RunDiagnostics' } } } } } } } /api/v1/runs/{runId}/stop: { post: { summary: Stop run, responses: { '200': { description: Stopped } } } } /api/v1/runs/{runId}/kill: { post: { summary: Kill run and immediately release its concurrency slot, responses: { '200': { description: Killed } } } } /api/v1/schedules/preview: { post: { summary: Preview schedule, responses: { '200': { description: Next occurrence } } } }