From 5c777808e580358250b02eaea503bd377a5266e3 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 18:04:34 +0000 Subject: [PATCH] GEN-2150 retain and finalize canonical Codex execution streams --- docs/execution-trace-stream.md | 32 +++-- docs/trace-rollout-runbook.md | 35 +++-- .../0012_canonical_trace_receipts.sql | 3 + packages/app/src/agent-driver.ts | 6 +- packages/app/src/artifact-upload.ts | 32 +++-- packages/app/src/exe-vm-backend.ts | 7 + packages/app/src/flow-service.ts | 2 +- .../app/src/postgres/artifact-repository.ts | 10 +- packages/app/src/postgres/run-repository.ts | 11 +- packages/app/src/postgres/run-scheduler.ts | 48 ++++++- packages/app/src/postgres/schema.ts | 2 +- .../postgres/trace-projection-repository.ts | 9 +- packages/app/src/trace-replay.ts | 1 + packages/app/src/trace-source.ts | 1 + packages/app/src/ui.ts | 4 +- packages/app/test/artifact-upload.test.ts | 10 +- packages/app/test/codex-trace.test.ts | 5 +- packages/app/test/execution-backend.test.ts | 14 ++ .../app/test/postgres-run-repository.test.ts | 2 +- .../app/test/run-diagnostics-contract.test.ts | 4 +- packages/app/test/run-finalization.test.ts | 70 +++++++++- .../app/test/trace-source.postgres.test.ts | 124 ++++++++++++++++-- packages/app/test/trace-source.test.ts | 4 +- packages/app/test/ui.test.ts | 4 +- packages/docs/openapi.yaml | 9 +- 25 files changed, 356 insertions(+), 93 deletions(-) create mode 100644 packages/app/migrations/0012_canonical_trace_receipts.sql diff --git a/docs/execution-trace-stream.md b/docs/execution-trace-stream.md index f85081c6..5202fb14 100644 --- a/docs/execution-trace-stream.md +++ b/docs/execution-trace-stream.md @@ -3,8 +3,8 @@ An agent launch may declare `traceSources.primary` with `kind: execution_stream`, an absolute guest `path`, `mediaType: application/x-ndjson`, and its `provider`. `formatVersion`, `cliVersion`, and `harnessVersion` identify the producing harness -when known. Declare the native audit session separately as `nativeSession`; -native discovery commands remain supported. Codex declares raw `codex exec --json` stdout as its primary stream with +when known. Claude may declare a separate native audit session as `nativeSession`. +Codex declares only the canonical stream and never discovers or captures a native session. Codex declares raw `codex exec --json` stdout as its primary stream with `formatVersion: codex-exec-jsonl`; Claude declares the stream producer described below. Pi keeps its published native session as primary; see [Pi session contract](pi-session-contract.md). @@ -42,17 +42,25 @@ must use rename rotation, never truncate and regrow between polls: an unobserved rewrite violates the append-only contract. File descriptors pin the file identity during each read, avoiding rename/read races. -At termination (including process failure), the exact stream snapshot is uploaded -to `trace/.jsonl`, separately from `native/session.jsonl`. Reprojection -reads that durable snapshot. Its stored artifact receipt and final projection -commit together under the same run lock as live ingestion. Later chunks are +At termination (success, failure, or stop), the exact stream snapshot is uploaded +to `trace/.jsonl`. Codex retains exactly one `execution_stream` receipt for +`/tmp/factorize-artifacts//codex-exec.jsonl`; stderr remains a separate +`terminal_log`. Stopping terminates the writer before collecting and deleting the VM. +Reprojection reads the durable snapshot under the same run lock as live ingestion. +The receipt survives projection failure, allowing finalization to retry from retained +bytes without recapturing a mutable guest file. Later chunks are rejected, terminal retries cannot replace the snapshot with different bytes, and native audit uploads cannot overwrite its projection. Failed collection is retried and ultimately reported as partial using the existing finalization policy. Launch source declarations are persisted on the run (`trace_sources`), exposed by run detail and diagnostics. Artifact rows retain source kind, guest path, -media type, provider, format/CLI/harness versions where supplied. Historical +media type, provider, source generation, and format/CLI/harness versions where supplied. +Missing `turn.completed` in Codex stdout is recorded as +`reconciliation.codexCompletion=missing_turn_completed`, and finalization reports +`artifact_state=partial` with a specific reason, even when the process exited zero. +Reconciliation mismatches and collection/projection failures also report partial. +The UI displays that failure reason. Cleanup occurs only after bounded retries. Historical native-only runs still use their existing provider parser and artifact semantics. ## Claude Code stdout producer (GEN-2138) @@ -101,15 +109,19 @@ https://code.claude.com/docs/en/cli-reference . Run diagnostics expose the declared provider/source/version, retained artifact receipts, actual projection source/checksum/parser revision, live generation and byte cursor, reconciliation state, warning and unknown-event counts, and explicit -native fallback use. A null projection or missing native artifact is not proof -of completeness or recoverability. Terminal reconciliation compares the live +native fallback use. A null projection or missing primary artifact is not proof +of completeness or recoverability. Codex native artifact state is `not_applicable`. Terminal reconciliation compares the live projection prefix to the durable snapshot. The browser resets pagination when its source generation or durable projection changes, including rollback. Tenant owners can replay one terminal run's retained primary or native artifact through `POST /api/v1/runs/{runId}/trace/replay`, using an interactive owner session with `runs:write` and a UUID `requestId`. Native replay recovers historical Codex -custom tool calls only when native JSONL exists. Completed requests are idempotent; +custom tool calls only for historical native-only runs when native JSONL exists. +Canonical Codex runs reject `source=native_session`; they replay only their primary +stream. No migration of historical native bytes is required, and no new native +Codex artifacts are accepted. Deployment gates cannot switch new Codex launches +to native primary. Claude rollout gates and Pi native primary remain supported. Completed requests are idempotent; failed transactions can resume; missing artifacts are reported unrecoverable. Replay is limited to 10 requests per tenant per minute. Artifact keys are storage locators, not download URLs. See the [rollout and incident runbook](trace-rollout-runbook.md) diff --git a/docs/trace-rollout-runbook.md b/docs/trace-rollout-runbook.md index 75e3b361..0b3e4af7 100644 --- a/docs/trace-rollout-runbook.md +++ b/docs/trace-rollout-runbook.md @@ -7,15 +7,16 @@ release ticket before widening the rollout. Never paste grants or artifact paylo ## Deployment gates -1. Apply `0011_trace_rollout.sql` before deploying the application. Keep all earlier +1. Apply `0012_canonical_trace_receipts.sql` before deploying the application. Keep all earlier migrations. This additive migration does not delete events, artifacts, or cursors. -2. Begin with `TRACE_PRIMARY_MODE=native_session`. This affects **new launches**; +2. Claude can begin with `TRACE_PRIMARY_MODE=native_session`. This affects **new launches**; existing runs retain their declared primary through finalization. Pi remains on its version-pinned native session in every mode. Historical undeclared runs - remain native. Preserve native artifacts for all stream canaries. + remain readable from retained native artifacts. Codex always launches its canonical + stream; both deployment gates apply only to Claude. Codex native capture is disabled. 3. Set `TRACE_PRIMARY_MODE=execution_stream` and `TRACE_STREAM_TENANTS` to a comma-separated allowlist of approved canary tenant UUIDs. An empty allowlist - admits no tenants. Tenants outside the list use native primary. Unset the + admits no tenants. Claude tenants outside the list use native primary. Unset the allowlist only after the canary gates pass. With both variables absent the prerequisite implementation's stream primary behavior is preserved. 4. Run at least 10 Codex and 10 Claude canaries over 24 hours, including successful @@ -27,18 +28,23 @@ release ticket before widening the rollout. Never paste grants or artifact paylo `trace.projection.reconciliation.state=matched` for every streamed canary with a live cursor; `no_live_cursor` is not evidence of live completeness. Require zero mismatches, zero chunk conflicts beyond deliberately injected tests, no - unexplained parse warnings, unknown-event rate below 1%, and stored native and - primary artifacts. Verify the stream provider and CLI/harness/source version. + unexplained parse warnings, unknown-event rate below 1%, and a stored primary + artifact (plus a native artifact for Claude). Codex must have exactly one trace + artifact, `execution_stream`, and `codexCompletion=turn.completed`. Verify the stream provider and CLI/harness/source version. For Pi require native primary, retained artifact, and visible calls/results. 6. Expand the allowlist gradually (10%, 50%, then all approved tenants), observing each stage for 24 hours under the same gates. Stop on a single reconciliation - mismatch, missing native artifact, lost call/result, or cross-source conflict. + mismatch, missing primary artifact, missing Claude native artifact, lost call/result, or cross-source conflict. ## Diagnostics and alerts The declared source lives in `traceSources`; `trace.projection` identifies the **actual** source, artifact checksum, parser revision, and reconciliation receipt. -`fallbackUsed` means an explicit native replay replaced a declared stream projection. +`fallbackUsed` means an explicit native replay replaced a declared Claude stream projection. +Codex `nativeArtifactState=not_applicable`. Receipts include `source_path`, +`source_generation`, byte length and checksum. Missing `turn.completed`, collection +failure, projection failure, or reconciliation mismatch produces `artifact.state=partial` +and a specific `artifact.error`; process success alone does not imply a complete trace. `liveCursor` shows file generation, committed byte offset, and pending byte count. A missing receipt is not a complete trace. An unterminated final line is retained in the artifact but is intentionally not projected. Warnings are visible events; @@ -90,10 +96,13 @@ in diagnostics; failed attempts appear in structured logs. ## Rollback -Set `TRACE_PRIMARY_MODE=native_session` for new launches and retain the canary +Set `TRACE_PRIMARY_MODE=native_session` for new Claude launches and retain the canary allowlist configuration for later review. Do not alter active run declarations or -reuse their generation IDs. Let active runs finalize and retain both snapshots. -For a terminal stream run, replay with a **new** request UUID and +reuse their generation IDs. Let active runs finalize and retain their declared snapshots. +Codex has no native rollback: replay the canonical primary for terminal runs. +Historical native-only Codex runs remain eligible for native reads/replay; no +migration is required and no new Codex native upload is accepted. +For a terminal Claude stream run, replay with a **new** request UUID and `source=native_session`. Check the result is `projected` or `already_projected`, `trace.projection.source_kind=native_session`, and `fallbackUsed=true`. Both artifacts, live cursor, and chunk receipts remain intact. A late terminal @@ -104,7 +113,7 @@ the current projection. Never promise recovery or delete the stream to force it. ## Retention and incident debugging -Retain both exact primary and native snapshots for at least the rollout window +Retain the exact Codex primary snapshot and both Claude primary/native snapshots for at least the rollout window and 30 days after the final stage (or longer under the tenant's retention policy). Do not enable an object lifecycle expiration shorter than this window. Deployment and rollback do not remove objects. Job deletion intentionally deletes job artifacts @@ -122,7 +131,7 @@ same generation/offset/hash or perform the normal generation transition. Termina grants are bound to the observed generation and reject stale collectors. A terminal reconciliation mismatch compares projected live events to their durable prefix and checks that committed bytes do not exceed the snapshot size. Preserve -the immutable snapshots and receipts; use an authorized native replay if available. +the immutable snapshots and receipts; use authorized primary replay for Codex or native replay for Claude if available. If collection failed, let finalization retry before cleanup. After cleanup, absent bytes are unrecoverable. Attach safe diagnostics and ledger outcomes to the incident. diff --git a/packages/app/migrations/0012_canonical_trace_receipts.sql b/packages/app/migrations/0012_canonical_trace_receipts.sql new file mode 100644 index 00000000..cfe0466a --- /dev/null +++ b/packages/app/migrations/0012_canonical_trace_receipts.sql @@ -0,0 +1,3 @@ +-- Historical receipts remain readable with an unknown generation. +ALTER TABLE app.run_artifacts ADD COLUMN source_generation text; +INSERT INTO app.schema_migrations(version) VALUES ('0012_canonical_trace_receipts') ON CONFLICT DO NOTHING; diff --git a/packages/app/src/agent-driver.ts b/packages/app/src/agent-driver.ts index 22658420..241584c6 100644 --- a/packages/app/src/agent-driver.ts +++ b/packages/app/src/agent-driver.ts @@ -9,7 +9,7 @@ export interface ArtifactLocator { roots: string[]; fileNameIncludes: string; sessionId?: string; - /** Prints one canonical native session path from inside the guest. */ + /** Prints the declared trace file path from inside the guest. */ discoverCommand: string; } export interface AgentLaunchSpec { @@ -31,13 +31,11 @@ class CodexDriver implements AgentDriver { const args = ["exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--color", "never", "-c", "model_provider=exe-llm", "-c", 'model_providers.exe-llm.name="exe-llm"', "-c", 'model_providers.exe-llm.base_url="https://llm.int.exe.xyz/v1"']; if (config.model?.trim()) args.push("--model", config.model.trim()); if (config.effort?.trim()) args.push("-c", `model_reasoning_effort=${config.effort.trim()}`); - const nativeSession = { kind: "native_session" as const, path: "${CODEX_HOME:-$HOME/.codex}/sessions", mediaType: "application/x-ndjson" as const, provider: this.kind, discoverCommand: `find "\${CODEX_HOME:-$HOME/.codex}/sessions" -type f -name 'rollout-*.jsonl' -printf '%T@ %p\\n' | sort -nr | head -1 | cut -d' ' -f2-` }; return { executable: "codex", args, env: {}, stdin: "prompt", - artifacts: { roots: [nativeSession.path], fileNameIncludes: "rollout-", discoverCommand: nativeSession.discoverCommand }, + artifacts: { roots: [`/tmp/factorize-artifacts/${runId}`], fileNameIncludes: "codex-exec.jsonl", discoverCommand: `printf '%s' '/tmp/factorize-artifacts/${runId}/codex-exec.jsonl'` }, traceSources: { primary: { kind: "execution_stream", path: `/tmp/factorize-artifacts/${runId}/codex-exec.jsonl`, mediaType: "application/x-ndjson", provider: this.kind, formatVersion: "codex-exec-jsonl" }, - nativeSession, }, }; } diff --git a/packages/app/src/artifact-upload.ts b/packages/app/src/artifact-upload.ts index 8f27e87f..50749f8f 100644 --- a/packages/app/src/artifact-upload.ts +++ b/packages/app/src/artifact-upload.ts @@ -58,9 +58,10 @@ export async function artifactUpload(request: Request, env: Env, token: string): if (!env.RUN_ARTIFACTS) return new Response("Artifact storage is unavailable", { status: 503 }); const grant = await readArtifactUploadGrant(token, env.SESSION_SIGNING_SECRET); if (!grant || grant.purpose === "trace_chunk") return new Response("Invalid or expired artifact upload grant", { status: 401 }); - if (!request.body) return new Response("Artifact body is required", { status: 400 }); - const sha256 = request.headers.get("X-Artifact-SHA256")?.toLowerCase() ?? "", size = Number(request.headers.get("Content-Length")); + if (grant.provider === "codex" && grant.sourceKind !== "execution_stream") return new Response("Codex native artifact capture is disabled; historical receipts remain readable", { status: 409 }); + const sha256 = request.headers.get("X-Artifact-SHA256")?.toLowerCase() ?? "", size = Number(request.headers.get("Content-Length") ?? NaN); if (!/^[0-9a-f]{64}$/.test(sha256) || !Number.isSafeInteger(size) || size < 0) return new Response("Artifact checksum and size are required", { status: 400 }); + if (!request.body && size !== 0) return new Response("Artifact body is required", { status: 400 }); if (size > 256 * 1024 * 1024) return new Response("Artifact exceeds the 256 MiB limit", { status: 413 }); const suppliedType = request.headers.get("Content-Type")?.split(";", 1)[0]?.trim().toLowerCase(); if (suppliedType !== grant.contentType.toLowerCase()) return new Response("Artifact content type does not match the grant", { status: 400 }); @@ -71,10 +72,13 @@ export async function artifactUpload(request: Request, env: Env, token: string): const existing = await repository.list(grant.runId); const terminal = existing.find(item => item.kind === "execution_stream" && item.state === "stored"); if (grant.sourceKind === "execution_stream" && terminal && terminal.sha256 !== sha256) return new Response("Terminal trace stream is immutable", { status: 409 }); - const object = await env.RUN_ARTIFACTS.put(key, request.body, { httpMetadata: { contentType: grant.contentType }, customMetadata: { tenantId: grant.tenantId, runId: grant.runId }, sha256 }); - const record = (client: DatabaseClient) => repository.record({ runId: grant.runId, kind: grant.sourceKind ?? "native_session", sourcePath: grant.sourcePath, mediaType: grant.contentType, harnessVersion: grant.harnessVersion, formatVersion: grant.formatVersion, cliVersion: grant.cliVersion, objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }, client); + const retainedStream = grant.sourceKind === "execution_stream" && terminal; + if (retainedStream) await request.body?.cancel(); + const object = retainedStream ? null : await env.RUN_ARTIFACTS.put(key, request.body ?? new Uint8Array(), { httpMetadata: { contentType: grant.contentType }, customMetadata: { tenantId: grant.tenantId, runId: grant.runId, generation: grant.traceGeneration ?? "", sourcePath: grant.sourcePath ?? "" }, sha256 }); + const record = (client: DatabaseClient) => repository.record({ runId: grant.runId, kind: grant.sourceKind ?? "native_session", sourceGeneration: grant.traceGeneration, sourcePath: grant.sourcePath, mediaType: grant.contentType, harnessVersion: grant.harnessVersion, formatVersion: grant.formatVersion, cliVersion: grant.cliVersion, objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }, client); const stored = await env.RUN_ARTIFACTS.get(key); if (!stored) return new Response("Artifact disappeared after upload", { status: 502 }); + if (stored.size !== size) { await stored.body.cancel(); return new Response("Retained artifact size does not match upload receipt", { status: 422 }); } const database = databaseFor(env); const conflict = await database.transaction(async client => { // Shares the lock with incremental ingestion: terminal projection wins atomically. @@ -93,13 +97,23 @@ export async function artifactUpload(request: Request, env: Env, token: string): if (grant.sourceKind !== "execution_stream" && native && native.sha256 !== sha256) return "Terminal native session is immutable"; const primary = grant.sourceKind === "execution_stream" || (grant.primary !== false && !terminal && run?.trace_sources?.primary?.kind !== "execution_stream"); const projection = (await client.query("SELECT source_kind,artifact_sha256,parser_version FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [grant.tenantId, grant.runId])).rows[0]; - // A terminal retry after an explicit rollback must never restore the stream projection. - const alreadyProjected = projection?.source_kind === (grant.sourceKind ?? "native_session") && projection?.artifact_sha256 === sha256 && projection?.parser_version === TRACE_PARSER_VERSION; - if (primary && !alreadyProjected && !(terminal && projection?.source_kind === "native_session")) await new TraceProjectionRepository(database, grant.tenantId).project(client, grant.runId, { provider: grant.provider, kind: grant.sourceKind ?? "native_session", sha256, byte_size: size }, stored.body, grant.sourceKind === "execution_stream"); - if (!primary || alreadyProjected || (terminal && projection?.source_kind === "native_session")) await stored.body.cancel(); await record(client); + // Keep the immutable receipt even when projection fails. A retry projects + // these retained bytes, rather than replacing them with another guest snapshot. + await client.query("SAVEPOINT terminal_projection"); + try { + const alreadyProjected = projection?.source_kind === (grant.sourceKind ?? "native_session") && projection?.artifact_sha256 === sha256 && projection?.parser_version === TRACE_PARSER_VERSION; + const historicalRollback = grant.provider !== "codex" && terminal && projection?.source_kind === "native_session"; + if (primary && !alreadyProjected && !historicalRollback) await new TraceProjectionRepository(database, grant.tenantId).project(client, grant.runId, { provider: grant.provider, kind: grant.sourceKind ?? "native_session", sha256, byte_size: size }, stored.body, grant.sourceKind === "execution_stream"); + else await stored.body.cancel(); + await client.query("RELEASE SAVEPOINT terminal_projection"); + } catch { + await client.query("ROLLBACK TO SAVEPOINT terminal_projection"); + await client.query("UPDATE app.runs SET artifact_state='partial',artifact_error='Retained primary trace projection failed',updated_at=now() WHERE tenant_id=$1 AND id=$2", [grant.tenantId, grant.runId]); + return "Retained primary trace projection failed"; + } return null; }); if (conflict) return new Response(conflict, { status: 409 }); - return Response.json({ key, etag: object.httpEtag }, { status: 201 }); + return Response.json({ key, etag: object?.httpEtag ?? stored.httpEtag }, { status: 201 }); } diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index 4241335e..d9c50c31 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -146,6 +146,13 @@ export class ExeVmBackend implements ExecutionBackend { return { state: "failed", systemd, detail: `The supervised agent process exited unsuccessfully (Result=${systemd.result}, ExecMainCode=${systemd.execMainCode}, ExecMainStatus=${systemd.execMainStatus}).` }; } + /** Stop the writer but preserve the guest until terminal artifacts are retained. */ + async terminate(handle: RunHandle): Promise { + const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(`sudo systemctl stop ${shellAtom(this.vm(handle))}`)}`); + if (!result.ok) return { state: "stopping", detail: "Agent process termination is temporarily unavailable" }; + return { ...await this.inspect(handle), state: "stopped" }; + } + 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. diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 35318bb3..db96193e 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -102,7 +102,7 @@ export class ApiService { 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)), - nativeArtifactState: artifacts.some(item => item.kind === "native_session" && item.state === "stored") ? "stored" : "missing", + nativeArtifactState: primary?.provider === "codex" && primary.kind === "execution_stream" ? "not_applicable" : artifacts.some(item => item.kind === "native_session" && item.state === "stored") ? "stored" : "missing", fallbackUsed: evidence.projection?.source_kind === "native_session" && primary?.kind === "execution_stream" }, harnessLog: run.harness_log, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; } diff --git a/packages/app/src/postgres/artifact-repository.ts b/packages/app/src/postgres/artifact-repository.ts index b84f807d..95836a6d 100644 --- a/packages/app/src/postgres/artifact-repository.ts +++ b/packages/app/src/postgres/artifact-repository.ts @@ -5,17 +5,17 @@ import { runArtifacts, runs } from "./schema"; export class ArtifactRepository { constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); } - async record(input: { runId: string; kind: ArtifactKind; objectKey: string; provider: string; format: string; formatVersion?: string; cliVersion?: string; nativeSessionId?: string; sourcePath?: string; mediaType?: string; harnessVersion?: string; byteSize: number; sha256: string; state?: ArtifactState }, client?: DatabaseClient) { + async record(input: { runId: string; kind: ArtifactKind; objectKey: string; provider: string; format: string; formatVersion?: string; cliVersion?: string; nativeSessionId?: string; sourceGeneration?: string | null; sourcePath?: string; mediaType?: string; harnessVersion?: string; byteSize: number; sha256: string; state?: ArtifactState }, client?: DatabaseClient) { const id = crypto.randomUUID(); const write = async (client: DatabaseClient) => { - 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,source_path,media_type,harness_version) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16) - 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", input.sourcePath ?? null, input.mediaType ?? null, input.harnessVersion ?? null]); + 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,source_path,media_type,harness_version,source_generation) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17) + 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", input.sourcePath ?? null, input.mediaType ?? null, input.harnessVersion ?? null, input.sourceGeneration ?? null]); await client.query("UPDATE app.runs SET artifact_state='stored',updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]); }; if (client) await write(client); else await this.database.transaction(write); } - async list(runId: string, client: DatabaseClient = this.database.pool) { return (await client.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,source_path,media_type,harness_version,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } + async list(runId: string, client: DatabaseClient = this.database.pool) { return (await client.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,source_path,media_type,harness_version,source_generation,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } async keysForJob(jobId: string): Promise { const rows = await this.database.orm.select({ key: runArtifacts.objectKey }).from(runArtifacts).innerJoin(runs, and(eq(runs.tenantId, runArtifacts.tenantId), eq(runs.id, runArtifacts.runId))).where(and(eq(runArtifacts.tenantId, this.tenantId), eq(runs.jobId, jobId))); return rows.map(row => row.key); diff --git a/packages/app/src/postgres/run-repository.ts b/packages/app/src/postgres/run-repository.ts index 213f2574..c45fd02f 100644 --- a/packages/app/src/postgres/run-repository.ts +++ b/packages/app/src/postgres/run-repository.ts @@ -7,17 +7,17 @@ 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; + traceSources?: TraceSources | 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; + trace_sources: TraceSources | null; 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, 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() }); +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, 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, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }); export class RunRepository { constructor(private database: Database) {} @@ -34,7 +34,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,'traceSources',x.trace_sources) 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 + ) 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.trace_sources,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; @@ -44,7 +44,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,'traceSources',x.trace_sources) 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 + 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.trace_sources,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); @@ -55,6 +55,7 @@ export class RunRepository { await client.query("UPDATE app.job_runs SET state='running',started_at=COALESCE(started_at,now()),launch_lease_expires_at=NULL,next_poll_at=now()+interval '3 seconds',updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id]); await client.query("UPDATE app.runs SET state='running',execution_handle=$3,execution_backend_kind=$4,execution_capabilities=$5,destination_url=$6,trace_sources=$7,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, handle, handle.backendKind, JSON.stringify(capabilities), destinationUrl, traceSources ? JSON.stringify(traceSources) : null]); }); + run.traceSources = traceSources ?? null; } async schedulePoll(run: PersistedRun, state: Extract, seconds = 3): Promise { diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index 0c7bd5e6..c633a8c7 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -15,6 +15,7 @@ import { AutomationScheduler } from "./automation-scheduler"; import { agentDriver, driverTraceSources, type AgentKind } from "../agent-driver"; import { traceMetric } from "../trace-observability"; import { rolloutTraceSources } from "../trace-source"; +import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./trace-projection-repository"; import { LiveTraceRepository } from "./live-trace-repository"; export class RunScheduler { @@ -47,7 +48,7 @@ export class RunScheduler { private async poll(run: PersistedRun) { const backend = await this.backend(run); if (!run.executionHandle) throw new Error("Execution handle is missing"); - const observation = run.executionDiagnostics ?? await backend.inspect(run.executionHandle); + const observation = run.executionDiagnostics ?? (run.state === "stopping" && backend instanceof ExeVmBackend ? await backend.terminate(run.executionHandle) : await backend.inspect(run.executionHandle)); if (["running", "blocked", "stopping"].includes(observation.state)) { if (backend instanceof ExeVmBackend) await this.collectTraceChunk(run, backend).catch(() => { traceMetric("chunk_collection_failure", run.tenantId, run.id); }); return this.runs.schedulePoll(run, observation.state as "running" | "blocked" | "stopping"); @@ -66,18 +67,23 @@ export class RunScheduler { catch { errors.push("Harness log collection or storage failed"); } } const sources = this.sources(run); + if (sources.primary.provider === "codex" && sources.primary.kind !== "execution_stream") errors.push("Historical Codex native source is read-only; canonical execution stream was not declared"); if (sources.primary.kind === "execution_stream" && !stored.some(item => item.kind === "execution_stream" && item.state === "stored")) { try { const collected = await this.collectArtifact(run, backend, sources.primary, true); - if (!collected.ok) errors.push("Primary trace stream upload failed"); - } catch { errors.push("Primary trace stream collection or reconciliation failed"); } + if (!collected.ok) errors.push(`Canonical execution stream upload failed: ${sources.primary.path}`); + } catch { errors.push(`Canonical execution stream collection failed: ${sources.primary.path}`); } } - if (!stored.some(item => item.kind === "native_session" && item.state === "stored")) { + if (sources.primary.provider !== "codex" && !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"); traceMetric("missing_native_artifact", run.tenantId, run.id, { attempt: run.finalizationAttempt ?? 0 }); } } catch { errors.push("Native session collection or storage failed"); traceMetric("missing_native_artifact", run.tenantId, run.id, { attempt: run.finalizationAttempt ?? 0 }); } } + if (sources.primary.kind === "execution_stream") { + try { errors.push(...await this.finalizePrimary(run, sources.primary)); } + catch { errors.push("Retained primary trace projection 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("; ")); @@ -95,6 +101,34 @@ export class RunScheduler { await this.runs.terminal(run, diagnostics.state, artifactState, errors.join("; ") || undefined, true); } + /** Retry projection from retained bytes, without relying on a surviving VM. */ + private async finalizePrimary(run: PersistedRun, source: TraceSource): Promise { + return this.database.transaction(async client => { + await client.query("SELECT id FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [run.tenantId, run.id]); + const artifacts = await new ArtifactRepository(this.database, run.tenantId).list(run.id, client); + const retained = artifacts.filter(item => item.kind === "execution_stream" && item.state === "stored"); + if (retained.length !== 1) return ["Canonical execution stream receipt missing or ambiguous"]; + const artifact = retained[0]; + if (artifact.source_path !== source.path || artifact.provider !== source.provider) return ["Canonical execution stream receipt source mismatch"]; + let projection = (await client.query("SELECT source_kind,artifact_sha256,parser_version,reconciliation FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [run.tenantId, run.id])).rows[0]; + if (projection?.source_kind !== source.kind || projection?.artifact_sha256 !== artifact.sha256 || projection?.parser_version !== TRACE_PARSER_VERSION) { + const stored = await this.env.RUN_ARTIFACTS?.get(artifact.object_key); + if (!stored) return ["Retained canonical execution stream object missing"]; + const hash = stored.checksums.sha256 ? [...new Uint8Array(stored.checksums.sha256)].map(byte => byte.toString(16).padStart(2, "0")).join("") : null; + if (hash !== artifact.sha256 || stored.size !== Number(artifact.byte_size)) { await stored.body.cancel(); return ["Retained canonical execution stream checksum or size mismatch"]; } + const reconciliation = await new TraceProjectionRepository(this.database, run.tenantId).project(client, run.id, { provider: source.provider, kind: source.kind, sha256: artifact.sha256, byte_size: artifact.byte_size }, stored.body, true); + projection = { reconciliation }; + } + const errors: string[] = []; + if (!["matched", "no_live_cursor"].includes(projection?.reconciliation?.state)) errors.push("Canonical execution stream terminal reconciliation mismatch"); + if (source.provider === "codex") { + const completed = (await client.query("SELECT count(*)::int completed FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2 AND display_data->>'eventType'='turn.completed'", [run.tenantId, run.id])).rows[0]?.completed ?? 0; + if (!completed) errors.push("Canonical Codex execution stream is incomplete: missing turn.completed"); + } + return errors; + }); + } + 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); @@ -106,7 +140,9 @@ export class RunScheduler { } private sources(run: PersistedRun): TraceSources { - if (run.executionTarget.traceSources) return run.executionTarget.traceSources; + if (run.traceSources) return run.traceSources; + // Undeclared Codex runs must never discover or create a native artifact. + if (run.executionTarget.agentKind === "codex") return driverTraceSources("codex", agentDriver("codex").launch(run.id, {})); // Runs launched before a source declaration existed must keep their native // trace even when the current driver now produces an execution stream. return { primary: this.nativeSource(run) }; @@ -121,7 +157,7 @@ export class RunScheduler { private async collectArtifact(run: PersistedRun, backend: ExeVmBackend, source?: TraceSource, primary?: boolean) { if (!run.executionHandle) throw new Error("Execution handle is missing"); const sources = this.sources(run); - source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : this.nativeSource(run)); + source ??= sources.nativeSession ?? sources.primary; primary ??= sources.primary.kind === "native_session"; const traceGeneration = primary ? (await new LiveTraceRepository(this.database, run.tenantId).cursor(run.id)).generation : undefined; const token = await issueArtifactUploadGrant({ traceGeneration, tenantId: run.tenantId, runId: run.id, path: source.kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: source.mediaType, provider: source.provider, format: "jsonl", sourceKind: source.kind, sourcePath: source.path, formatVersion: source.formatVersion, cliVersion: source.cliVersion, harnessVersion: source.harnessVersion, primary, expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); diff --git a/packages/app/src/postgres/schema.ts b/packages/app/src/postgres/schema.ts index aa0a3b60..7e1734c0 100644 --- a/packages/app/src/postgres/schema.ts +++ b/packages/app/src/postgres/schema.ts @@ -55,7 +55,7 @@ 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"), 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"), 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(), + 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(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.objectKey), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("run_artifacts_by_run").on(t.tenantId, t.runId, t.createdAt, t.id)]); export const runTraceEvents = app.table("run_trace_events", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), sequence: bigint("sequence", { mode: "number" }).notNull(), id: text("id").notNull(), parentId: text("parent_id"), eventType: text("event_type").notNull(), role: text("role"), title: text("title").notNull(), previewText: text("preview_text").notNull(), displayData: jsonb("display_data").$type>().notNull().default({}), occurredAt: timestamp("occurred_at", { withTimezone: true }), createdAt: createdAt(), searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', title || ' ' || preview_text)`), diff --git a/packages/app/src/postgres/trace-projection-repository.ts b/packages/app/src/postgres/trace-projection-repository.ts index 842d64ec..19970b20 100644 --- a/packages/app/src/postgres/trace-projection-repository.ts +++ b/packages/app/src/postgres/trace-projection-repository.ts @@ -3,7 +3,7 @@ import type { TraceSource } from "../trace-source"; import { TraceRepository } from "./trace-repository"; import { traceMetric } from "../trace-observability"; -export const TRACE_PARSER_VERSION = "trace-v2-custom-tool-call"; +export const TRACE_PARSER_VERSION = "trace-v3-canonical-codex"; export class TraceProjectionRepository { constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); } @@ -27,11 +27,16 @@ export class TraceProjectionRepository { if (reconcile) { const comparison = (await client.query(`SELECT (SELECT count(*) FROM trace_before)::int live_events, (SELECT count(*) FROM (SELECT * FROM trace_before EXCEPT SELECT sequence,id,parent_id,event_type,role,title,preview_text,display_data,occurred_at FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2) missing)::int mismatches, + (SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2) generation, (SELECT committed_offset FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2) live_offset`, [this.tenantId, runId])).rows[0] ?? { live_events: 0, mismatches: 0, live_offset: null }; const mismatch = comparison.mismatches > 0 || Number(comparison.live_offset ?? 0) > Number(artifact.byte_size); - reconciliation = { state: comparison.live_offset == null ? "no_live_cursor" : mismatch ? "mismatch" : "matched", events, liveEvents: comparison.live_events, mismatches: comparison.mismatches, liveOffset: comparison.live_offset == null ? null : Number(comparison.live_offset), artifactBytes: Number(artifact.byte_size) }; + reconciliation = { state: comparison.live_offset == null ? "no_live_cursor" : mismatch ? "mismatch" : "matched", events, liveEvents: comparison.live_events, mismatches: comparison.mismatches, liveOffset: comparison.live_offset == null ? null : Number(comparison.live_offset), artifactBytes: Number(artifact.byte_size), generation: comparison.generation ?? null }; traceMetric("terminal_reconciliation", this.tenantId, runId, { mismatch, events, mismatches: comparison.mismatches }); } + if (artifact.provider === "codex" && artifact.kind === "execution_stream") { + const completed = (await client.query("SELECT count(*)::int completed FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2 AND display_data->>'eventType'='turn.completed'", [this.tenantId, runId])).rows[0]?.completed ?? 0; + reconciliation.codexCompletion = completed ? "turn.completed" : "missing_turn_completed"; + } await client.query(`INSERT INTO app.run_trace_projections(tenant_id,run_id,source_kind,artifact_sha256,parser_version,reconciliation) VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (tenant_id,run_id) DO UPDATE SET source_kind=excluded.source_kind,artifact_sha256=excluded.artifact_sha256,parser_version=excluded.parser_version,reconciliation=excluded.reconciliation,updated_at=now()`, [this.tenantId, runId, artifact.kind, artifact.sha256, TRACE_PARSER_VERSION, reconciliation]); return reconciliation; diff --git a/packages/app/src/trace-replay.ts b/packages/app/src/trace-replay.ts index ef399f8e..a252439b 100644 --- a/packages/app/src/trace-replay.ts +++ b/packages/app/src/trace-replay.ts @@ -38,6 +38,7 @@ export async function replayTrace(env: Env, tenantId: string, actorId: string, r if (!["done", "succeeded", "failed", "stopped", "ignored"].includes(run.state)) { result = { status: "skipped", reason: "run_active" }; } else { + if (input.source === "native_session" && run.trace_sources?.primary?.provider === "codex" && run.trace_sources.primary.kind === "execution_stream") throw new TraceReplayError(400, "invalid_source", "Codex runs replay only their canonical execution stream."); const artifacts = await new ArtifactRepository(database, tenantId).list(runId, client); const kind = input.source === "native_session" ? "native_session" : run.trace_sources?.primary?.kind ?? "native_session"; const eligible = artifacts.filter(item => item.kind === kind && item.state === "stored"); diff --git a/packages/app/src/trace-source.ts b/packages/app/src/trace-source.ts index 6d8d1b48..9d28e42d 100644 --- a/packages/app/src/trace-source.ts +++ b/packages/app/src/trace-source.ts @@ -35,6 +35,7 @@ export function validateTraceSources(sources: TraceSources): void { /** Deployment controls affect new launches only; never change an active run's source. */ export function rolloutTraceSources(sources: TraceSources, tenantId: string, config: { TRACE_PRIMARY_MODE?: string; TRACE_STREAM_TENANTS?: string }): TraceSources { if (config.TRACE_PRIMARY_MODE && !["execution_stream", "native_session"].includes(config.TRACE_PRIMARY_MODE)) throw new Error("Invalid TRACE_PRIMARY_MODE"); + if (sources.primary.provider === "codex") return { primary: sources.primary }; const canaries = config.TRACE_STREAM_TENANTS?.split(",").map(value => value.trim()).filter(Boolean); const native = config.TRACE_PRIMARY_MODE === "native_session" || (canaries !== undefined && !canaries.includes(tenantId)); return native && sources.nativeSession ? { primary: sources.nativeSession } : sources; diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 4828418f..71d3c3a3 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -226,11 +226,11 @@ function updateRun(r){ const state=$('[data-run-state]');if(state)state.innerHTML=stateBadge(r.state); if(!activeStates.includes(r.state))$('#kill-run')?.remove(); const live=$('[data-run-live]');if(live)live.hidden=!activeStates.includes(r.state); - const artifact=$('[data-run-artifact]');if(artifact)artifact.textContent=traceSourceLabel(r); + const artifact=$('[data-run-artifact]');if(artifact)artifact.textContent=traceSourceLabel(r)+(r.artifact_error?' · '+r.artifact_error:''); updateElapsed(r); } async function refreshOutput(){const r=await request('/api/v1/runs/'+encodeURIComponent(id));const reset=currentRun&&(r.trace_generation!==currentRun.trace_generation||JSON.stringify(r.trace_projection)!==JSON.stringify(currentRun.trace_projection)||(activeStates.includes(currentRun.state)&&!activeStates.includes(r.state)));updateRun(r);if(traceLoading)await traceLoading;traceDone=false;await loadTrace(Boolean(reset))} -async function loadRun(){return request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(async({r,j})=>{const canKill=activeStates.includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='

'+esc(runLabel)+'

'+elapsed(r)+'

'+queueTime(r)+'

'+stateBadge(r.state)+''+(canKill?'':'')+'
'+triggerProvenance(r)+'
Prompt
'+esc(r.prompt||'Prompt is not available for this run.')+'

Trace

Native '+esc(r.agent_kind||'agent')+' session · '+esc(r.artifact_state||'pending')+'

'+(activeStates.includes(r.state)?'Live · refreshes automatically':'')+'

Trace events are not available yet.

';if(canKill)$('#kill-run').onclick=async()=>{if(!confirm('Kill this run and release its concurrency slot?'))return;await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});await runRefresh.refresh()};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace().catch(()=>{})};updateRun(r);await loadTrace()})} +async function loadRun(){return request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(async({r,j})=>{const canKill=activeStates.includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='

'+esc(runLabel)+'

'+elapsed(r)+'

'+queueTime(r)+'

'+stateBadge(r.state)+''+(canKill?'':'')+'
'+triggerProvenance(r)+'
Prompt
'+esc(r.prompt||'Prompt is not available for this run.')+'

Trace

'+esc(traceSourceLabel(r))+'

'+(activeStates.includes(r.state)?'Live · refreshes automatically':'')+'

Trace events are not available yet.

';if(canKill)$('#kill-run').onclick=async()=>{if(!confirm('Kill this run and release its concurrency slot?'))return;await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});await runRefresh.refresh()};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace().catch(()=>{})};updateRun(r);await loadTrace()})} const runRefresh=pageRefresh(async()=>{if(!currentRun)await loadRun();else await refreshOutput()},{delay:()=>activeStates.includes(currentRun.state)?3000:['pending','collecting'].includes(currentRun.artifact_state)?10000:null,onError:e=>{if(!currentRun)root.innerHTML='

'+esc(e.message)+'

'}});`); const settingsLayout = (active: "integrations" | "api-keys", content: string) => `