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
19 changes: 19 additions & 0 deletions docs/execution-trace-stream.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,22 @@ child text. Boundary tests execute the exact guest supervisor with a fake CLI,
including live pre-exit visibility, malformed/partial lines, UTF-8 fragmentation,
terminal reprojection, failure exits and native recovery. CLI flags follow
https://code.claude.com/docs/en/cli-reference .

## Provenance, replay, and rollout

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
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;
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)
for deployment gates, canary evidence, checkpointing, retention, and rollback.
135 changes: 135 additions & 0 deletions docs/trace-rollout-runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Trace-source rollout and recovery

GEN-2140 adds deployment gates, projection receipts, diagnostics, and authorized
retained-artifact replay. A merged implementation is not production canary evidence.
Record deployment revision, tenant IDs, run IDs, timestamps, and diagnostics in the
release ticket before widening the rollout. Never paste grants or artifact payloads.

## Deployment gates

1. Apply `0011_trace_rollout.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**;
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.
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
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
tool execution, a failed tool, interrupted/nonzero CLI exit, multiple polls,
partial-line arrival, and a forced upload retry. Include at least 3 Pi runs.
Confirm a tool call appears in the browser **before process exit**, its result
refers to the call, and browser refresh does not duplicate events.
5. Fetch `/api/v1/runs/{runId}/diagnostics` and retain the safe response. Require
`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.
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.

## 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.
`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;
`counts` reports parse warnings and unknown events with their projected-event rate.

Structured logs have `component=trace`, tenant/run IDs, and a `metric`:
`chunk_parsed`, `chunk_retry`, `chunk_failure`, `chunk_collection_failure`,
`artifact_parsed`, `terminal_reconciliation`, `missing_native_artifact`, and
`replay_failure`, and `replay_outcome`. Aggregate warning/unknown counts divided by parsed event counts
per provider; alert at 1% unknown rate, any mismatch, or exhausted artifact retries.
Retry/failure counters measure attempts; logs emitted inside a transaction are
not commit evidence. Use persisted diagnostics to establish the final outcome.
No trace payloads, upload grants, or credentials are logged by these counters.
Collection has the existing bounded finalization retry policy; partial artifacts
remain a secondary diagnostic and do not replace the process exit status.

## Authorized backfill and resumption

Only an interactive tenant owner session with `runs:write` may POST
`/api/v1/runs/{runId}/trace/replay`:

```json
{"requestId":"<new UUID>","source":"primary"}
```

Page the tenant's `/api/v1/runs` API and checkpoint its pagination cursor, the run
ID and request UUID **before** each call. Process one run per request with one
in-flight request and at least 6 seconds between requests (10 attempts/minute per
tenant, including failures/retries). Do not use a global cross-tenant list.
Request IDs are scoped to the authenticated tenant. Keep a ledger of each returned
status/reason. Completed projection and operation receipts commit atomically.
Resume a failed/interrupted request using its original UUID; repeat successes
return the original result. Reusing that UUID for another run/source returns 409.
Retry 429 after one minute; retry 503/500 with bounded exponential backoff. Stop
and investigate 409 checksum/ownership conflicts; never bypass integrity checks.

`primary` uses the run's persisted source declaration; undeclared historical runs
use retained native sessions. This reprojects historical Codex `custom_tool_call`
and matching outputs with the corrected parser. Native sessions are never derived
from human logs. `already_projected` avoids unnecessary replacement at the same
checksum/source/parser revision. `skipped/run_active` leaves the run untouched.
`unrecoverable/missing_artifact` and `artifact_not_retained` explicitly mean no
recovery is possible from retained storage. Multiple candidate artifacts report
`ambiguous_artifacts`; unsupported providers/formats are skipped. A new request
UUID is necessary to reconsider a previously skipped/unrecoverable result after
conditions change. Parser/storage failures roll back projection and operation;
the original request UUID remains resumable. The last completed replay appears
in diagnostics; failed attempts appear in structured logs.

## Rollback

Set `TRACE_PRIMARY_MODE=native_session` for new 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
`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
stream retry cannot undo this explicit rollback. Re-enable an individual run by
issuing a new replay request with `source=primary`; no new VM is needed.
If no native artifact is retained, rollback reports unrecoverable and preserves
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
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
under the existing policy; deleted/expired bytes cannot be backfilled. Native
snapshots uploaded by this implementation use checksum-addressed keys; older
`native/session.jsonl` locators remain eligible. Object size and checksum must match
the tenant/run's stored receipt before replay. Never list the bucket to discover
another tenant's artifacts or change receipt metadata to bypass checks.

For an incident, freeze rollout; collect run diagnostics, deployment revision,
source/CLI/harness/parser versions, safe metric counts, and request IDs. Distinguish
process failure from collection failure. For a stale generation/offset conflict,
compare cursor generation and offset to the collector request; retry only the
same generation/offset/hash or perform the normal generation transition. Terminal
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.
If collection failed, let finalization retry before cleanup. After cleanup, absent
bytes are unrecoverable. Attach safe diagnostics and ledger outcomes to the incident.

## Evidence status

Repository tests exercise Codex/Claude live/terminal paths, retries, generation
conflicts, rollback, historical tool recovery, authorization, tenant isolation,
rate limiting, missing bytes, failed transaction resumption, and browser refresh.
Production canary evidence must be collected by the release operator after this
revision is deployed; repository tests must not be represented as that evidence.
29 changes: 29 additions & 0 deletions packages/app/migrations/0011_trace_rollout.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
-- Projection provenance is separate from immutable artifact receipts.
CREATE TABLE app.run_trace_projections (
tenant_id uuid NOT NULL,
run_id uuid NOT NULL,
source_kind text NOT NULL CHECK (source_kind IN ('execution_stream','native_session')),
artifact_sha256 text NOT NULL,
parser_version text NOT NULL,
reconciliation jsonb NOT NULL DEFAULT '{}',
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id,run_id),
FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE
);
CREATE TABLE app.trace_replay_limits (
tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE,
window_start timestamptz NOT NULL DEFAULT now(),
attempts integer NOT NULL DEFAULT 0
);
CREATE TABLE app.trace_replay_operations (
tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE,
request_id uuid NOT NULL,
run_id uuid NOT NULL,
source text NOT NULL CHECK (source IN ('primary','native_session')),
actor_id text NOT NULL,
result jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id,request_id),
FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE
);
CREATE INDEX trace_replay_run ON app.trace_replay_operations(tenant_id,run_id,created_at DESC);
2 changes: 1 addition & 1 deletion packages/app/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const API_OPERATIONS = [
["GET", "/api/v1/jobs"], ["POST", "/api/v1/jobs"], ["GET", "/api/v1/jobs/{jobId}"], ["PUT", "/api/v1/jobs/{jobId}"], ["DELETE", "/api/v1/jobs/{jobId}"],
["POST", "/api/v1/jobs/{jobId}/enable"], ["POST", "/api/v1/jobs/{jobId}/disable"], ["POST", "/api/v1/jobs/{jobId}/invocations"], ["GET", "/api/v1/jobs/{jobId}/events"],
["POST", "/api/v1/job-handlers/test"], ["GET", "/api/v1/runs"], ["GET", "/api/v1/runs/{runId}"], ["GET", "/api/v1/runs/{runId}/trace"],
["GET", "/api/v1/runs/{runId}/diagnostics"], ["POST", "/api/v1/runs/{runId}/stop"], ["POST", "/api/v1/runs/{runId}/kill"], ["GET", "/api/v1/search"],
["POST", "/api/v1/runs/{runId}/trace/replay"], ["GET", "/api/v1/runs/{runId}/diagnostics"], ["POST", "/api/v1/runs/{runId}/stop"], ["POST", "/api/v1/runs/{runId}/kill"], ["GET", "/api/v1/search"],
["GET", "/api/v1/webhooks/deliveries"], ["GET", "/api/v1/webhooks/deliveries/{deliveryId}"],
] as const;

Expand Down
28 changes: 22 additions & 6 deletions packages/app/src/artifact-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { hmac } from "./crypto";
import type { Env } from "./types";
import { databaseFor } from "./postgres/database";
import { ArtifactRepository } from "./postgres/artifact-repository";
import { TraceRepository } from "./postgres/trace-repository";
import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./postgres/trace-projection-repository";

export interface ArtifactUploadGrant {
tenantId: string;
Expand All @@ -20,6 +20,8 @@ export interface ArtifactUploadGrant {
cliVersion?: string;
harnessVersion?: string;
primary?: boolean;
/** Execution terminal uploads are bound to the live source generation. */
traceGeneration?: string | null;
purpose?: "artifact" | "trace_chunk";
expiresAt: number;
}
Expand Down Expand Up @@ -62,8 +64,9 @@ export async function artifactUpload(request: Request, env: Env, token: string):
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 });
if ((grant.sourceKind === "execution_stream" || grant.primary === true) && grant.traceGeneration === undefined) return new Response("Terminal trace generation is required", { status: 400 });
// Content-addressed stream keys preserve the exact terminal snapshot across retries.
const key = artifactKey(grant.tenantId, grant.runId, grant.sourceKind === "execution_stream" ? `trace/${sha256}.jsonl` : grant.path);
const key = artifactKey(grant.tenantId, grant.runId, grant.sourceKind === "execution_stream" ? `trace/${sha256}.jsonl` : `native/${sha256}.jsonl`);
const repository = new ArtifactRepository(databaseFor(env), grant.tenantId);
const existing = await repository.list(grant.runId);
const terminal = existing.find(item => item.kind === "execution_stream" && item.state === "stored");
Expand All @@ -76,14 +79,27 @@ export async function artifactUpload(request: Request, env: Env, token: string):
const conflict = await database.transaction(async client => {
// Shares the lock with incremental ingestion: terminal projection wins atomically.
const run = (await client.query("SELECT id,trace_sources FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [grant.tenantId, grant.runId])).rows[0];
if (!run) return "Run not found";
if (grant.sourceKind === "execution_stream" || grant.primary === true) {
const primary = run.trace_sources?.primary;
if (primary && (primary.kind !== (grant.sourceKind ?? "native_session") || (primary.provider && primary.provider !== grant.provider) || (primary.path && primary.path !== grant.sourcePath))) return "Terminal trace source mismatch";
const cursor = (await client.query("SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [grant.tenantId, grant.runId])).rows[0];
if ((cursor?.generation ?? null) !== grant.traceGeneration) return "Stale terminal trace generation";
}
const artifacts = await repository.list(grant.runId, client);
const terminal = artifacts.find(item => item.kind === "execution_stream" && item.state === "stored");
if (grant.sourceKind === "execution_stream" && terminal && terminal.sha256 !== sha256) return true;
if (grant.sourceKind === "execution_stream" && terminal && terminal.sha256 !== sha256) return "Terminal trace stream is immutable";
const native = artifacts.find(item => item.kind === "native_session" && item.state === "stored");
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");
if (primary) await new TraceRepository(database, grant.tenantId).replaceStream(grant.runId, grant.provider, stored.body, grant.sourceKind, client);
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);
return false;
return null;
});
if (conflict) return new Response("Terminal trace stream is immutable", { status: 409 });
if (conflict) return new Response(conflict, { status: 409 });
return Response.json({ key, etag: object.httpEtag }, { status: 201 });
}
Loading
Loading