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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 22 additions & 10 deletions docs/execution-trace-stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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/<sha256>.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/<sha256>.jsonl`. Codex retains exactly one `execution_stream` receipt for
`/tmp/factorize-artifacts/<run>/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)
Expand Down Expand Up @@ -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)
Expand Down
35 changes: 22 additions & 13 deletions docs/trace-rollout-runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions packages/app/migrations/0012_canonical_trace_receipts.sql
Original file line number Diff line number Diff line change
@@ -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;
6 changes: 2 additions & 4 deletions packages/app/src/agent-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
},
};
}
Expand Down
32 changes: 23 additions & 9 deletions packages/app/src/artifact-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -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.
Expand All @@ -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 });
}
Loading
Loading