From a17ac49bc849d0497f10a6a628d250802be2526b Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 03:35:24 +0000 Subject: [PATCH 1/2] GEN-2140 add trace rollout gates, provenance, reconciliation and authorized replay --- docs/execution-trace-stream.md | 19 +++ docs/trace-rollout-runbook.md | 135 ++++++++++++++++++ .../app/migrations/0011_trace_rollout.sql | 29 ++++ packages/app/src/api-contract.ts | 2 +- packages/app/src/artifact-upload.ts | 28 +++- packages/app/src/flow-service.ts | 28 +++- .../app/src/postgres/live-trace-repository.ts | 13 +- packages/app/src/postgres/run-scheduler.ts | 13 +- packages/app/src/postgres/schema.ts | 15 ++ .../postgres/trace-projection-repository.ts | 39 +++++ packages/app/src/postgres/trace-repository.ts | 7 +- packages/app/src/protected-api.ts | 2 + packages/app/src/trace-chunk-upload.ts | 5 +- packages/app/src/trace-observability.ts | 10 ++ packages/app/src/trace-replay.ts | 79 ++++++++++ packages/app/src/trace-source.ts | 8 ++ packages/app/src/types.ts | 2 + packages/app/src/ui.ts | 5 +- packages/app/test/artifact-upload.test.ts | 10 +- .../app/test/page-refresh.browser.test.ts | 34 ++++- .../postgres-live-trace-repository.test.ts | 1 + .../app/test/run-diagnostics-contract.test.ts | 19 ++- .../app/test/trace-source.postgres.test.ts | 100 ++++++++++++- packages/app/test/trace-source.test.ts | 15 ++ packages/docs/concepts.mdx | 11 ++ packages/docs/llms-full.txt | 5 + packages/docs/openapi.yaml | 89 +++++++++++- 27 files changed, 687 insertions(+), 36 deletions(-) create mode 100644 docs/trace-rollout-runbook.md create mode 100644 packages/app/migrations/0011_trace_rollout.sql create mode 100644 packages/app/src/postgres/trace-projection-repository.ts create mode 100644 packages/app/src/trace-observability.ts create mode 100644 packages/app/src/trace-replay.ts diff --git a/docs/execution-trace-stream.md b/docs/execution-trace-stream.md index 97aeef18..f85081c6 100644 --- a/docs/execution-trace-stream.md +++ b/docs/execution-trace-stream.md @@ -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. diff --git a/docs/trace-rollout-runbook.md b/docs/trace-rollout-runbook.md new file mode 100644 index 00000000..75e3b361 --- /dev/null +++ b/docs/trace-rollout-runbook.md @@ -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":"","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. diff --git a/packages/app/migrations/0011_trace_rollout.sql b/packages/app/migrations/0011_trace_rollout.sql new file mode 100644 index 00000000..98f2e110 --- /dev/null +++ b/packages/app/migrations/0011_trace_rollout.sql @@ -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); diff --git a/packages/app/src/api-contract.ts b/packages/app/src/api-contract.ts index 6c99c0ba..cb6d7fa6 100644 --- a/packages/app/src/api-contract.ts +++ b/packages/app/src/api-contract.ts @@ -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; diff --git a/packages/app/src/artifact-upload.ts b/packages/app/src/artifact-upload.ts index c5744580..8f27e87f 100644 --- a/packages/app/src/artifact-upload.ts +++ b/packages/app/src/artifact-upload.ts @@ -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; @@ -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; } @@ -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"); @@ -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 }); } diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 971c005c..b3d1d6ab 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -20,6 +20,9 @@ import { ProviderCatalog } from "./postgres/provider-catalog"; import { ArtifactRepository } from "./postgres/artifact-repository"; import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; +import { TraceProjectionRepository } from "./postgres/trace-projection-repository"; +import { replayTrace, traceReplaySchema, traceReplayRunIdSchema, TraceReplayError } from "./trace-replay"; + export class ServiceError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } } @@ -86,9 +89,30 @@ export class ApiService { async listTailIntegrations() { await this.authorize("flows:read"); return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails(); } async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query); } async search(query: string) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query); } - async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); run.execution_diagnostics ??= null; run.trace_sources ??= null; run.harness_log = (await new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId)).find(item => item.kind === "terminal_log") ?? null; return run; } + async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); run.execution_diagnostics ??= null; run.trace_sources ??= null; run.trace_projection = (await databaseFor(this.env).pool.query("SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId])).rows[0] ?? null; run.trace_generation = (await databaseFor(this.env).pool.query("SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId])).rows[0]?.generation ?? null; run.harness_log = (await new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId)).find(item => item.kind === "terminal_log") ?? null; return run; } async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); } - async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId); return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, execution: run.execution_diagnostics, traceSources: run.trace_sources, harnessLog: run.harness_log, artifact: { state: run.artifact_state, error: run.artifact_error }, activity: run.activity, createdAt: run.created_at, updatedAt: run.updated_at }; } + async getRunDiagnostics(runId: string) { + const run: any = await this.getRun(runId), database = databaseFor(this.env); + const [evidence, artifacts] = await Promise.all([ + new TraceProjectionRepository(database, this.auth.tenantId).diagnostics(runId), + new ArtifactRepository(database, this.auth.tenantId).list(runId), + ]); + const primary = run.trace_sources?.primary ?? null; + return { runId: run.id, jobId: run.job_id, state: run.state, provider: primary?.provider ?? run.agent_kind ?? null, backendKind: run.execution_backend_kind, + execution: run.execution_diagnostics, traceSources: run.trace_sources, + trace: { ...evidence, 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", + 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 }; + } + async replayRunTrace(runId: string, body: unknown) { + await this.authorizeOwnerSession("runs:write"); + const input = traceReplaySchema.parse(body); + traceReplayRunIdSchema.parse(runId); + try { return await replayTrace(this.env, this.auth.tenantId, this.auth.userId, runId, input); } + catch (error) { if (error instanceof TraceReplayError) throw new ServiceError(error.status, error.code, error.message); throw error; } + } async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } killRun(runId: string) { return this.stopRun(runId); } async listJobs() { await this.authorize("flows:read"); return Promise.all((await this.jobs().list()).map(job => this.presentJob(job))); } diff --git a/packages/app/src/postgres/live-trace-repository.ts b/packages/app/src/postgres/live-trace-repository.ts index e0099aad..50e52217 100644 --- a/packages/app/src/postgres/live-trace-repository.ts +++ b/packages/app/src/postgres/live-trace-repository.ts @@ -2,6 +2,8 @@ import type { TraceSource } from "../trace-source"; import { parseTrace, type TraceEvent } from "../trace"; import type { Database, DatabaseClient } from "./database"; +import { traceCounts, traceMetric } from "../trace-observability"; + const ZERO_HASH = "0".repeat(64); const encoder = new TextEncoder(); const hex = (bytes: ArrayBuffer) => [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, "0")).join(""); @@ -20,13 +22,16 @@ export class LiveTraceRepository { return row ? { generation: row.generation, offset: Number(row.committed_offset), rollingHash: row.rolling_hash } : { generation: null, offset: 0, rollingHash: ZERO_HASH }; } - async append(runId: string, provider: "codex" | "claude" | "pi", chunk: TraceChunk, sourceKind: TraceSource["kind"] = "native_session") { + async append(runId: string, provider: "codex" | "claude" | "pi", chunk: TraceChunk, sourceKind: TraceSource["kind"] = "native_session", sourcePath?: string) { if (!chunk.generation || chunk.generation.length > 200 || !Number.isSafeInteger(chunk.startOffset) || chunk.startOffset < 0) throw new Error("Invalid trace chunk metadata"); const actualHash = await sha256(chunk.bytes); if (actualHash !== chunk.chunkSha256) throw new Error("Trace chunk checksum mismatch"); return this.database.transaction(async client => { - await client.query("SELECT id FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, runId]); - const finalized = (await client.query("SELECT id FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 AND kind='execution_stream' AND state='stored'", [this.tenantId, runId])).rows; + const run = (await client.query("SELECT id,trace_sources FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.tenantId, runId])).rows[0]; + if (!run) throw new Error("Trace run not found"); + const primary = run.trace_sources?.primary; + if (primary && (primary.kind !== sourceKind || (primary.provider && primary.provider !== provider) || (sourcePath && primary.path && primary.path !== sourcePath))) throw new Error("Trace source mismatch"); + const finalized = (await client.query("SELECT id FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 AND kind=$3 AND state='stored'", [this.tenantId, runId, sourceKind])).rows; if (finalized.length) throw new Error("Trace stream is already finalized"); let cursor = (await client.query("SELECT generation,committed_offset,pending_bytes,next_sequence,rolling_hash FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2 FOR UPDATE", [this.tenantId, runId])).rows[0]; if (!cursor || cursor.generation !== chunk.generation) { @@ -42,6 +47,7 @@ export class LiveTraceRepository { const receipt = (await client.query<{ chunk_sha256: string; end_offset: string | number; previous_hash: string; rolling_hash: string }>("SELECT chunk_sha256,end_offset,previous_hash,rolling_hash FROM app.run_trace_chunks WHERE tenant_id=$1 AND run_id=$2 AND generation=$3 AND start_offset=$4", [this.tenantId, runId, chunk.generation, chunk.startOffset])).rows[0]; if (receipt) { if (receipt.chunk_sha256 !== chunk.chunkSha256 || Number(receipt.end_offset) !== endOffset || receipt.previous_hash !== chunk.previousHash) throw new Error("Conflicting trace chunk retry"); + traceMetric("chunk_retry", this.tenantId, runId, { generation: chunk.generation }); return { offset: Number(receipt.end_offset), rollingHash: receipt.rolling_hash, duplicate: true, events: 0 }; } if (chunk.startOffset !== committed) throw new Error(`Trace chunk offset mismatch: expected ${committed}`); @@ -66,6 +72,7 @@ export class LiveTraceRepository { for (const item of [...previous.rows].reverse()) calls.set(item.id, item.title); } const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete), sourceKind, Number(cursor.next_sequence), calls); + traceMetric("chunk_parsed", this.tenantId, runId, { ...traceCounts(parsed), generation: chunk.generation }); const nextSequence = Number(cursor.next_sequence), events = parsed.map((item, index) => ({ ...item, sequence: nextSequence + index })); for (let offset = 0; offset < events.length; offset += 250) await this.insertBatch(client, runId, events.slice(offset, offset + 250)); const rollingHash = await sha256(`${cursor.rolling_hash}:${chunk.startOffset}:${endOffset}:${chunk.chunkSha256}`); diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index fb1b6e2e..0c7bd5e6 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -13,6 +13,8 @@ import type { Database } from "./database"; import { RunRepository, type PersistedRun } from "./run-repository"; import { AutomationScheduler } from "./automation-scheduler"; import { agentDriver, driverTraceSources, type AgentKind } from "../agent-driver"; +import { traceMetric } from "../trace-observability"; +import { rolloutTraceSources } from "../trace-source"; import { LiveTraceRepository } from "./live-trace-repository"; export class RunScheduler { @@ -36,7 +38,7 @@ export class RunScheduler { private async launch(run: PersistedRun) { const backend = await this.backend(run), driver = agentDriver(run.executionTarget.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionTarget.model, effort: run.executionTarget.effort }); - const sources = driverTraceSources(driver.kind, harness); + const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); validateTraceSources(sources); const launched = await backend.launch({ runId: run.id, prompt: await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY), traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); @@ -47,7 +49,7 @@ export class RunScheduler { 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); if (["running", "blocked", "stopping"].includes(observation.state)) { - if (backend instanceof ExeVmBackend) await this.collectTraceChunk(run, backend).catch(() => undefined); + 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"); } // Persist the first terminal observation before any collection or deletion. @@ -73,8 +75,8 @@ export class RunScheduler { if (!stored.some(item => item.kind === "native_session" && item.state === "stored")) { try { const collected = await this.collectArtifact(run, backend); - if (!collected.ok) errors.push("Native session upload failed"); - } catch { errors.push("Native session collection or storage failed"); } + 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 }); } } // Retry collection, but do not keep a VM forever for an absent session/log. if (errors.length && (run.finalizationAttempt ?? 0) < 2) { @@ -121,7 +123,8 @@ export class RunScheduler { const sources = this.sources(run); source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : this.nativeSource(run)); primary ??= sources.primary.kind === "native_session"; - const token = await issueArtifactUploadGrant({ 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); + 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); return backend.collectArtifact(run.executionHandle, { source, contentType: source.mediaType, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` }); } diff --git a/packages/app/src/postgres/schema.ts b/packages/app/src/postgres/schema.ts index f7188a9f..aa0a3b60 100644 --- a/packages/app/src/postgres/schema.ts +++ b/packages/app/src/postgres/schema.ts @@ -78,6 +78,20 @@ export const wakeHints = app.table("wake_hints", { key: text("key").primaryKey() export const runTraceCursors = app.table("run_trace_cursors", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), generation: text("generation").notNull(), committedOffset: bigint("committed_offset", { mode: "number" }).notNull().default(0), pendingBytes: bytea("pending_bytes").notNull().default(sql`''::bytea`), nextSequence: bigint("next_sequence", { mode: "number" }).notNull().default(1), rollingHash: text("rolling_hash").notNull().default("0".repeat(64)), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); export const runTraceChunks = app.table("run_trace_chunks", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), generation: text("generation").notNull(), startOffset: bigint("start_offset", { mode: "number" }).notNull(), endOffset: bigint("end_offset", { mode: "number" }).notNull(), chunkSha256: text("chunk_sha256").notNull(), previousHash: text("previous_hash").notNull(), rollingHash: text("rolling_hash").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.runId, t.generation, t.startOffset] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); +export const runTraceProjections = app.table("run_trace_projections", { + tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), sourceKind: text("source_kind").notNull(), + artifactSha256: text("artifact_sha256").notNull(), parserVersion: text("parser_version").notNull(), + reconciliation: jsonb("reconciliation").notNull().default({}), updatedAt: updatedAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), check("run_trace_projections_source_kind_check", sql`${t.sourceKind} IN ('execution_stream','native_session')`)]); +export const traceReplayLimits = app.table("trace_replay_limits", { + tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), + windowStart: timestamp("window_start", { withTimezone: true }).notNull().defaultNow(), attempts: integer("attempts").notNull().default(0), +}); +export const traceReplayOperations = app.table("trace_replay_operations", { + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), requestId: uuid("request_id").notNull(), + runId: uuid("run_id").notNull(), source: text("source").notNull(), actorId: text("actor_id").notNull(), result: jsonb("result").notNull(), createdAt: createdAt(), +}, t => [primaryKey({ columns: [t.tenantId, t.requestId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("trace_replay_run").on(t.tenantId, t.runId, t.createdAt.desc()), check("trace_replay_operations_source_check", sql`${t.source} IN ('primary','native_session')`)]); + export const tenantRelations = relations(tenants, ({ many }) => ({ members: many(members), jobs: many(jobs), connections: many(connections) })); export const jobRelations = relations(jobs, ({ one, many }) => ({ tenant: one(tenants, { fields: [jobs.tenantId], references: [tenants.id] }), @@ -103,5 +117,6 @@ export const databaseSchema = { connections, linearWorkspaces, githubInstallations, githubSetupStates, jobs, triggers, invocations, jobRuns, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, + runTraceProjections, traceReplayLimits, traceReplayOperations, tenantRelations, jobRelations, triggerRelations, invocationRelations, runRelations, }; diff --git a/packages/app/src/postgres/trace-projection-repository.ts b/packages/app/src/postgres/trace-projection-repository.ts new file mode 100644 index 00000000..842d64ec --- /dev/null +++ b/packages/app/src/postgres/trace-projection-repository.ts @@ -0,0 +1,39 @@ +import type { Database, DatabaseClient } from "./database"; +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 class TraceProjectionRepository { + constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); } + + async diagnostics(runId: string) { + const [projection, cursor, counts, replay] = await Promise.all([ + this.database.pool.query("SELECT source_kind,artifact_sha256,parser_version,reconciliation,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId]), + this.database.pool.query("SELECT generation,committed_offset,octet_length(pending_bytes) pending_bytes,updated_at FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId]), + this.database.pool.query(`SELECT count(*)::int events,count(*) FILTER (WHERE event_type='warning')::int parse_warnings, + count(*) FILTER (WHERE title LIKE 'Unknown Codex%' OR title LIKE 'Unknown Claude%' OR title LIKE 'Unknown entry:%' OR title LIKE 'Unknown message role:%')::int unknown_events FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2`, [this.tenantId, runId]), + this.database.pool.query("SELECT request_id,source,result,created_at FROM app.trace_replay_operations WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at DESC LIMIT 1", [this.tenantId, runId]), + ]); + const totals = counts.rows[0] ?? { events: 0, parse_warnings: 0, unknown_events: 0 }; + return { projection: projection.rows[0] ?? null, liveCursor: cursor.rows[0] ?? null, counts: { ...totals, unknownEventRate: totals.events ? totals.unknown_events / totals.events : 0 }, lastReplay: replay.rows[0] ?? null }; + } + + /** Caller holds the tenant/run lock. Compare the live prefix before atomically replacing it. */ + async project(client: DatabaseClient, runId: string, artifact: { provider: "codex" | "claude" | "pi"; kind: TraceSource["kind"]; sha256: string; byte_size: number | string }, stream: ReadableStream, reconcile = false) { + if (reconcile) await client.query("CREATE TEMP TABLE trace_before ON COMMIT DROP AS 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", [this.tenantId, runId]); + const events = await new TraceRepository(this.database, this.tenantId).replaceStream(runId, artifact.provider, stream, artifact.kind, client); + let reconciliation: Record = { state: "reprojected", events }; + 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 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) }; + traceMetric("terminal_reconciliation", this.tenantId, runId, { mismatch, events, mismatches: comparison.mismatches }); + } + 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/postgres/trace-repository.ts b/packages/app/src/postgres/trace-repository.ts index 51e1e811..746bd2d9 100644 --- a/packages/app/src/postgres/trace-repository.ts +++ b/packages/app/src/postgres/trace-repository.ts @@ -2,6 +2,8 @@ import type { TraceSource } from "../trace-source"; import { consumeTraceStream, type TraceEvent } from "../trace"; import type { Database, DatabaseClient } from "./database"; +import { traceCounts, traceMetric } from "../trace-observability"; + export interface TracePage { items: TraceEvent[]; nextCursor: number | null; } interface TraceRow { @@ -38,7 +40,10 @@ export class TraceRepository { async replaceStream(runId: string, provider: "codex" | "claude" | "pi", stream: ReadableStream, sourceKind: TraceSource["kind"] = "native_session", client?: DatabaseClient): Promise { const project = async (client: DatabaseClient) => { await client.query("DELETE FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId]); - return consumeTraceStream(provider, stream, items => this.insertBatch(client, runId, items), 250, sourceKind); + return consumeTraceStream(provider, stream, async items => { + traceMetric("artifact_parsed", this.tenantId, runId, { ...traceCounts(items), provider, sourceKind }); + await this.insertBatch(client, runId, items); + }, 250, sourceKind); }; return client ? project(client) : this.database.transaction(project); } diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 32116941..49a824f7 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -103,6 +103,8 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1]))); const traceMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/trace$/); if (traceMatch && request.method === "GET") return Response.json(await service.getRunTrace(decodeURIComponent(traceMatch[1]), Math.max(0, Number(url.searchParams.get("after") ?? 0)), Math.max(1, Math.min(200, Number(url.searchParams.get("limit") ?? 100))))); + const replayMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/trace\/replay$/); + if (replayMatch && request.method === "POST") return Response.json(await service.replayRunTrace(decodeURIComponent(replayMatch[1]), await request.json())); const runDiagnosticMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/diagnostics$/); if (runDiagnosticMatch && request.method === "GET") return Response.json(await service.getRunDiagnostics(decodeURIComponent(runDiagnosticMatch[1]))); const stopMatch = path.match(/^\/api\/v1\/runs\/([^/]+)\/stop$/); diff --git a/packages/app/src/trace-chunk-upload.ts b/packages/app/src/trace-chunk-upload.ts index 47c3620c..278f47b5 100644 --- a/packages/app/src/trace-chunk-upload.ts +++ b/packages/app/src/trace-chunk-upload.ts @@ -3,6 +3,8 @@ import { databaseFor } from "./postgres/database"; import { LiveTraceRepository } from "./postgres/live-trace-repository"; import type { Env } from "./types"; +import { traceMetric } from "./trace-observability"; + const HASH = /^[0-9a-f]{64}$/; export async function traceChunkUpload(request: Request, env: Env, token: string): Promise { if (request.method !== "PUT") return new Response("Method not allowed", { status: 405, headers: { Allow: "PUT" } }); @@ -15,9 +17,10 @@ export async function traceChunkUpload(request: Request, env: Env, token: string const bytes = new Uint8Array(await request.arrayBuffer()); if (bytes.byteLength !== size) return new Response("Trace chunk size mismatch", { status: 400 }); try { - const result = await new LiveTraceRepository(databaseFor(env), grant.tenantId).append(grant.runId, grant.provider, { generation, expectedGeneration: expectedGeneration || null, startOffset, chunkSha256, previousHash, bytes }, grant.sourceKind); + const result = await new LiveTraceRepository(databaseFor(env), grant.tenantId).append(grant.runId, grant.provider, { generation, expectedGeneration: expectedGeneration || null, startOffset, chunkSha256, previousHash, bytes }, grant.sourceKind, grant.sourcePath); return Response.json(result, { status: result.duplicate ? 200 : 201 }); } catch (error) { + traceMetric("chunk_failure", grant.tenantId, grant.runId, { generation, offset: startOffset }); const message = error instanceof Error ? error.message : "Trace chunk ingestion failed"; return Response.json({ error: message }, { status: message.includes("mismatch") || message.includes("changed") || message.includes("Conflicting") || message.includes("Stale") || message.includes("finalized") ? 409 : 400 }); } diff --git a/packages/app/src/trace-observability.ts b/packages/app/src/trace-observability.ts new file mode 100644 index 00000000..5fc6dbbf --- /dev/null +++ b/packages/app/src/trace-observability.ts @@ -0,0 +1,10 @@ +import type { TraceEvent } from "./trace"; + +/** Structured counters only: never log artifact bytes, grants, or parser payloads. */ +export function traceMetric(name: string, tenantId: string, runId: string, values: Record = {}): void { + console.info(JSON.stringify({ component: "trace", metric: name, tenantId, runId, ...values })); +} +export function traceCounts(events: TraceEvent[]) { + return { events: events.length, parseWarnings: events.filter(event => event.type === "warning").length, + unknownEvents: events.filter(event => /^Unknown (Codex|Claude|entry:|message role:)/.test(event.title)).length }; +} diff --git a/packages/app/src/trace-replay.ts b/packages/app/src/trace-replay.ts new file mode 100644 index 00000000..ef399f8e --- /dev/null +++ b/packages/app/src/trace-replay.ts @@ -0,0 +1,79 @@ +import { z } from "zod"; +import { artifactKey } from "./artifacts"; +import type { Env } from "./types"; +import { databaseFor } from "./postgres/database"; +import { ArtifactRepository } from "./postgres/artifact-repository"; +import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./postgres/trace-projection-repository"; +import { traceMetric } from "./trace-observability"; + +export const traceReplayRunIdSchema = z.uuid(); +export const traceReplaySchema = z.object({ requestId: z.uuid(), source: z.enum(["primary", "native_session"]).default("primary") }).strict(); +export class TraceReplayError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } } + +/** One run per request bounds work; clients checkpoint request IDs while paging runs. + * Completed results and projection commit together; failed transactions can resume with the same ID. + */ +export async function replayTrace(env: Env, tenantId: string, actorId: string, runId: string, input: z.infer) { + const database = databaseFor(env); + // Reserve persistent tenant budget separately so failing replays also consume capacity. + await database.transaction(async client => { + await client.query("INSERT INTO app.trace_replay_limits(tenant_id) VALUES ($1) ON CONFLICT DO NOTHING", [tenantId]); + const allowed = await client.query(`UPDATE app.trace_replay_limits SET attempts=CASE WHEN window_start<=now()-interval '1 minute' THEN 1 ELSE attempts+1 END, + window_start=CASE WHEN window_start<=now()-interval '1 minute' THEN now() ELSE window_start END + WHERE tenant_id=$1 AND (window_start<=now()-interval '1 minute' OR attempts<10) RETURNING tenant_id`, [tenantId]); + if (!allowed.rows.length) throw new TraceReplayError(429, "rate_limited", "Trace replay is limited to 10 requests per tenant per minute."); + }); + try { + const result = await database.transaction(async client => { + // Tenant lock serializes request IDs even when clients retry against another run. + await client.query("SELECT tenant_id FROM app.trace_replay_limits WHERE tenant_id=$1 FOR UPDATE", [tenantId]); + const prior = (await client.query("SELECT run_id,source,result FROM app.trace_replay_operations WHERE tenant_id=$1 AND request_id=$2", [tenantId, input.requestId])).rows[0]; + if (prior) { + if (prior.run_id !== runId || prior.source !== input.source) throw new TraceReplayError(409, "conflict", "Replay request ID was already used for another request."); + return prior.result; + } + const run = (await client.query("SELECT state,trace_sources FROM app.runs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [tenantId, runId])).rows[0]; + if (!run) throw new TraceReplayError(404, "not_found", "Run not found"); + let result: Record; + if (!["done", "succeeded", "failed", "stopped", "ignored"].includes(run.state)) { + result = { status: "skipped", reason: "run_active" }; + } else { + 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"); + // Never silently fall back or arbitrarily pick one of multiple native sessions. + const artifact = eligible.length === 1 ? eligible[0] : null; + if (!artifact) result = { status: "unrecoverable", reason: eligible.length > 1 ? "ambiguous_artifacts" : "missing_artifact", sourceKind: kind }; + else if (!["codex", "claude", "pi"].includes(artifact.provider) || artifact.format !== "jsonl") result = { status: "skipped", reason: "unsupported_artifact" }; + else { + const prefix = artifactKey(tenantId, runId, "native/session.jsonl").slice(0, -"native/session.jsonl".length); + if (!artifact.object_key.startsWith(prefix)) throw new TraceReplayError(409, "invalid_artifact", "Artifact ownership does not match the run."); + if (!env.RUN_ARTIFACTS) throw new TraceReplayError(503, "storage_unavailable", "Artifact storage is unavailable."); + const stored = await env.RUN_ARTIFACTS.get(artifact.object_key); + if (!stored) result = { status: "unrecoverable", reason: "artifact_not_retained", sourceKind: kind }; + else { + const checksum = stored.checksums.sha256; + const hash = checksum ? [...new Uint8Array(checksum)].map(byte => byte.toString(16).padStart(2, "0")).join("") : null; + if (hash !== artifact.sha256 || stored.size !== Number(artifact.byte_size)) throw new TraceReplayError(409, "invalid_artifact", "Retained artifact checksum or size does not match its receipt."); + 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", [tenantId, runId])).rows[0]; + if (projection?.source_kind === kind && projection.artifact_sha256 === artifact.sha256 && projection.parser_version === TRACE_PARSER_VERSION) { + await stored.body.cancel(); + result = { status: "already_projected", sourceKind: kind, sha256: artifact.sha256 }; + } else { + const reconciliation = await new TraceProjectionRepository(database, tenantId).project(client, runId, { provider: artifact.provider as "codex" | "claude" | "pi", kind, sha256: artifact.sha256, byte_size: artifact.byte_size }, stored.body); + result = { status: "projected", sourceKind: kind, sha256: artifact.sha256, parserVersion: TRACE_PARSER_VERSION, reconciliation }; + } + } + } + } + result = { requestId: input.requestId, runId, ...result }; + await client.query("INSERT INTO app.trace_replay_operations(tenant_id,request_id,run_id,source,actor_id,result) VALUES ($1,$2,$3,$4,$5,$6)", [tenantId, input.requestId, runId, input.source, actorId, result]); + return result; + }); + traceMetric("replay_outcome", tenantId, runId, { requestId: input.requestId, status: String(result.status), reason: result.reason ? String(result.reason) : null }); + return result; + } catch (error) { + traceMetric("replay_failure", tenantId, runId, { requestId: input.requestId, code: error instanceof TraceReplayError ? error.code : "projection_failed" }); + throw error; + } +} diff --git a/packages/app/src/trace-source.ts b/packages/app/src/trace-source.ts index f17a07c5..6d8d1b48 100644 --- a/packages/app/src/trace-source.ts +++ b/packages/app/src/trace-source.ts @@ -31,3 +31,11 @@ export function validateTraceSources(sources: TraceSources): void { if (sources.nativeSession.kind !== "native_session" || sources.nativeSession.path === sources.primary.path && sources.primary.kind === "execution_stream") throw new Error("Native session must be separate from the execution stream"); } } + +/** 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"); + 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/types.ts b/packages/app/src/types.ts index cc8e9d31..2e3f0d41 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -28,6 +28,8 @@ export interface Env { POSTMARK_FROM_EMAIL?: string; POSTMARK_MESSAGE_STREAM?: string; RUN_ARTIFACTS?: R2Bucket; + TRACE_PRIMARY_MODE?: "execution_stream" | "native_session"; + TRACE_STREAM_TENANTS?: string; HYPERDRIVE?: Hyperdrive; /** Test-only injection point; production uses HYPERDRIVE. */ DATABASE?: import("./postgres/database").Database; diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 59558b05..4828418f 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -219,16 +219,17 @@ async function fetchTrace(reset=false){if(reset){traceCursor=0;traceDone=false;c function elapsed(r){if(!r.started_at)return ['queued','starting'].includes(r.state)?'Waiting to start':'Start time unavailable';const start=new Date(r.started_at).getTime(),end=activeStates.includes(r.state)?Date.now():new Date(r.updated_at||r.created_at).getTime(),seconds=Math.max(0,Math.floor((end-start)/1000)),hours=Math.floor(seconds/3600),minutes=Math.floor(seconds%3600/60),remainder=seconds%60;return(hours?hours+'h ':'')+(minutes||hours?minutes+'m ':'')+remainder+'s elapsed'} function queueTime(r){if(!r.started_at&&!['queued','starting'].includes(r.state))return '';const seconds=Math.max(0,Math.floor((new Date(r.started_at||Date.now()).getTime()-new Date(r.created_at).getTime())/1000));return seconds+'s '+(r.started_at?'queue time':'waiting to start')} function updateElapsed(r){const queue=$('[data-run-queue]');if(queue)queue.textContent=queueTime(r);const label=$('[data-run-elapsed]');if(label)label.textContent=elapsed(r);clearInterval(elapsedTimer);if(activeStates.includes(r.state))elapsedTimer=setInterval(()=>{const current=$('[data-run-elapsed]');if(current)current.textContent=elapsed(r);const queue=$('[data-run-queue]');if(queue)queue.textContent=queueTime(r)},1000)} +function traceSourceLabel(r){const source=r.trace_projection?.source_kind||r.trace_sources?.primary?.kind||'native_session';return (source==='execution_stream'?'Execution stream':'Native session')+' · '+(r.trace_sources?.primary?.provider||r.agent_kind||'agent')+' · '+(r.artifact_state||'pending')+(r.trace_projection?.source_kind==='native_session'&&r.trace_sources?.primary?.kind==='execution_stream'?' · Native fallback':'')} function updateRun(r){ currentRun=r; root.classList.toggle('trace-running',r.state==='running'); 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='Native '+(r.agent_kind||'agent')+' session · '+(r.artifact_state||'pending'); + const artifact=$('[data-run-artifact]');if(artifact)artifact.textContent=traceSourceLabel(r); updateElapsed(r); } -async function refreshOutput(){const r=await request('/api/v1/runs/'+encodeURIComponent(id));updateRun(r);if(traceLoading)await traceLoading;traceDone=false;await loadTrace()} +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()})} 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)+'

'}});`); diff --git a/packages/app/test/artifact-upload.test.ts b/packages/app/test/artifact-upload.test.ts index 584165c0..b415c805 100644 --- a/packages/app/test/artifact-upload.test.ts +++ b/packages/app/test/artifact-upload.test.ts @@ -15,10 +15,10 @@ describe("artifact upload grants", () => { it("streams the request into its deterministic object key", async () => { const put = vi.fn(async (_key, body) => ({ httpEtag: "etag", size: 7, body })); const token = await issueArtifactUploadGrant(grant, secret); - const query = vi.fn(async () => ({ rows: [], rowCount: 1 })), get = vi.fn(async () => ({ body: new Response(JSON.stringify({ type: "session_meta", payload: { id: "s1" } })).body })); + const query = vi.fn(async (sql: string) => ({ rows: sql.startsWith("SELECT id,trace_sources") ? [{ id: "run-1" }] : [], rowCount: 1 })), get = vi.fn(async () => ({ body: new Response(JSON.stringify({ type: "session_meta", payload: { id: "s1" } })).body })); const response = await artifactUpload(new Request(`https://app/internal/run-artifacts/${encodeURIComponent(token)}`, { method: "PUT", headers: { "Content-Type": grant.contentType, "X-Artifact-SHA256": "a".repeat(64) }, body: "session" }), { SESSION_SIGNING_SECRET: secret, RUN_ARTIFACTS: { put, get }, DATABASE: { pool: { query }, transaction: (work: any) => work({ query }) } } as any, token); expect(response.status).toBe(201); - expect(put).toHaveBeenCalledWith("tenants/tenant-1/runs/run-1/native/session.jsonl", expect.any(ReadableStream), expect.objectContaining({ customMetadata: { tenantId: "tenant-1", runId: "run-1" } })); + expect(put).toHaveBeenCalledWith(`tenants/tenant-1/runs/run-1/native/${"a".repeat(64)}.jsonl`, expect.any(ReadableStream), expect.objectContaining({ customMetadata: { tenantId: "tenant-1", runId: "run-1" } })); }); it("rejects mismatched content types before storage", async () => { @@ -32,7 +32,7 @@ describe("artifact upload grants", () => { const jsonl = JSON.stringify({ version: 1, id: "a", type: "assistant_message", title: "Assistant", preview: "hello" }) + "\n{partial"; const put = vi.fn(async (_key: string, _body: any, _options: any) => ({ httpEtag: "etag" })), get = vi.fn(async () => ({ body: new Response(jsonl).body })); const env = { SESSION_SIGNING_SECRET: secret, RUN_ARTIFACTS: { put, get }, DATABASE: { pool: { query }, transaction: (work: any) => work({ query }) } } as any; - const primary = { ...grant, sourceKind: "execution_stream" as const, sourcePath: "/tmp/events.jsonl", formatVersion: "1", harnessVersion: "h1", cliVersion: "p1", primary: true }; + const primary = { ...grant, sourceKind: "execution_stream" as const, traceGeneration: null, sourcePath: "/tmp/events.jsonl", formatVersion: "1", harnessVersion: "h1", cliVersion: "p1", primary: true }; const upload = async (value: typeof grant) => { const token = await issueArtifactUploadGrant(value, secret); return artifactUpload(new Request("https://app/upload", { method: "PUT", headers: { "Content-Type": grant.contentType, "Content-Length": String(new TextEncoder().encode(jsonl).length), "X-Artifact-SHA256": "b".repeat(64) }, body: jsonl }), env, token); @@ -46,11 +46,11 @@ describe("artifact upload grants", () => { query.mockClear(); expect((await upload({ ...grant, primary: false } as any)).status).toBe(201); expect(query.mock.calls.some(([sql]) => sql.startsWith("DELETE FROM app.run_trace_events"))).toBe(false); - expect(put.mock.calls[1][0]).toBe("tenants/tenant-1/runs/run-1/native/session.jsonl"); + expect(put.mock.calls[1][0]).toBe(`tenants/tenant-1/runs/run-1/native/${"b".repeat(64)}.jsonl`); }); it("rejects replacement of a terminal stream with different bytes", async () => { const query = vi.fn(async () => ({ rows: [{ kind: "execution_stream", state: "stored", sha256: "a".repeat(64) }], rowCount: 1 })); - const put = vi.fn(), token = await issueArtifactUploadGrant({ ...grant, sourceKind: "execution_stream" }, secret); + const put = vi.fn(), token = await issueArtifactUploadGrant({ ...grant, sourceKind: "execution_stream", traceGeneration: null }, secret); const response = await artifactUpload(new Request("https://app/upload", { method: "PUT", headers: { "Content-Type": grant.contentType, "X-Artifact-SHA256": "b".repeat(64), "Content-Length": "2" }, body: "{}" }), { SESSION_SIGNING_SECRET: secret, RUN_ARTIFACTS: { put }, DATABASE: { pool: { query } } } as any, token); expect(response.status).toBe(409); expect(put).not.toHaveBeenCalled(); diff --git a/packages/app/test/page-refresh.browser.test.ts b/packages/app/test/page-refresh.browser.test.ts index 232d1509..231ef9d5 100644 --- a/packages/app/test/page-refresh.browser.test.ts +++ b/packages/app/test/page-refresh.browser.test.ts @@ -162,8 +162,8 @@ describe("lifecycle page refresh", () => { expect(document.querySelector('#run-detail h1').textContent).toBe(current.name); expect(document.title).toBe(current.name + ' — Factorize'); } - expect(trace.firstElementChild).toBe(first); - expect(trace.children).toHaveLength(6); + expect(trace.firstElementChild).not.toBe(first); + expect(trace.children).toHaveLength(1); expect(document.querySelector('[data-run-prompt-details]').open).toBe(true); expect(document.querySelector('#kill-run')).toBeNull(); expect(document.querySelector('[data-run-live]').hidden).toBe(true); @@ -172,7 +172,7 @@ describe("lifecycle page refresh", () => { await vi.advanceTimersByTimeAsync(30000); expect(fetcher).toHaveBeenCalledTimes(calls); const traceUrls = fetcher.mock.calls.map(([url]) => url).filter(url => url.includes('/trace?')); - expect(traceUrls).toEqual([0, 1, 2, 3, 4, 5].map(after => '/api/v1/runs/run-1/trace?after=' + after + '&limit=100')); + expect(traceUrls).toEqual([0, 1, 2, 3, 4, 0].map(after => '/api/v1/runs/run-1/trace?after=' + after + '&limit=100')); }); it("waits for terminal artifacts and serializes Load more with automatic trace refresh", async () => { @@ -200,4 +200,32 @@ describe("lifecycle page refresh", () => { await vi.advanceTimersByTimeAsync(30000); expect(traces).toBe(3); }); + it.each(['codex', 'claude', 'pi'])("shows %s live tools and replaces a reconciled or rolled-back projection without duplicates", async provider => { + let current: any = { ...run, state: 'running', agent_kind: provider, trace_sources: { primary: { provider, kind: provider === 'pi' ? 'native_session' : 'execution_stream' } }, trace_generation: 'file-1', trace_projection: null }; + let items = [{ sequence: 1, id: 'call', type: 'tool_call', title: 'shell', preview: 'live command', display: {} }]; + const fetcher = vi.fn(async (input: string) => { + if (input.includes('/trace?')) { const after = Number(new URL(input, 'https://app').searchParams.get('after')); return json({ items: items.filter(item => item.sequence > after), nextCursor: null }); } + return json(input.startsWith('/api/v1/jobs/') ? job : current); + }); + render(jobRunPage(viewer, run.id), fetcher); await flush(); + expect(document.querySelector('[data-run-state]').textContent).toBe('running'); + expect(document.querySelector('[data-run-trace]').textContent).toContain('live command'); + expect(document.querySelector('[data-run-artifact]').textContent).toContain(provider === 'pi' ? 'Native session' : 'Execution stream'); + await vi.advanceTimersByTimeAsync(3000); + expect(document.querySelector('[data-run-trace]').children).toHaveLength(1); + items = [{ sequence: 1, id: 'reconciled', type: 'tool_call', title: 'shell', preview: 'terminal command', display: {} }]; + current = { ...current, state: 'succeeded', artifact_state: 'collecting', trace_projection: { source_kind: current.trace_sources.primary.kind, artifact_sha256: 'stream', updated_at: 'one' } }; + await vi.advanceTimersByTimeAsync(3000); + expect(document.querySelector('[data-run-trace]').children).toHaveLength(1); + expect(document.querySelector('[data-run-trace]').textContent).toContain('terminal command'); + expect(document.querySelector('[data-run-trace]').textContent).not.toContain('live command'); + items = [{ sequence: 1, id: 'native', type: 'tool_call', title: 'apply_patch', preview: 'recovered native command', display: {} }]; + current = { ...current, artifact_state: 'stored', trace_projection: { source_kind: 'native_session', artifact_sha256: 'native', updated_at: 'two' } }; + await vi.advanceTimersByTimeAsync(10000); + expect(document.querySelector('[data-run-trace]').children).toHaveLength(1); + expect(document.querySelector('[data-run-trace]').textContent).toContain('recovered native command'); + expect(document.querySelector('[data-run-artifact]').textContent).toContain('Native session'); + if (provider !== 'pi') expect(document.querySelector('[data-run-artifact]').textContent).toContain('Native fallback'); + }); + }); diff --git a/packages/app/test/postgres-live-trace-repository.test.ts b/packages/app/test/postgres-live-trace-repository.test.ts index ca7be055..cde644e7 100644 --- a/packages/app/test/postgres-live-trace-repository.test.ts +++ b/packages/app/test/postgres-live-trace-repository.test.ts @@ -11,6 +11,7 @@ function fakeDatabase() { const chunks = new Map(), events: any[] = []; const query = async (sql: string, values: any[] = []) => { if (sql.startsWith("SELECT id,title FROM app.run_trace_events")) return { rows: events.filter(item => item.event_type === "tool_call").reverse().map(item => ({ id: item.id, title: item.title })), rowCount: 0 }; + if (sql.startsWith("SELECT id,trace_sources FROM app.runs")) return { rows: [{ id: "run-1" }], rowCount: 1 }; if (sql.startsWith("SELECT id FROM app.")) return { rows: [], rowCount: 0 }; if (sql.startsWith("SELECT generation,committed_offset") && sql.includes("FOR UPDATE")) return { rows: cursor ? [cursor] : [], rowCount: cursor ? 1 : 0 }; if (sql.startsWith("DELETE FROM app.run_trace_events")) { events.length = 0; return { rows: [], rowCount: 0 }; } diff --git a/packages/app/test/run-diagnostics-contract.test.ts b/packages/app/test/run-diagnostics-contract.test.ts index dc528a9a..4a59e92c 100644 --- a/packages/app/test/run-diagnostics-contract.test.ts +++ b/packages/app/test/run-diagnostics-contract.test.ts @@ -10,7 +10,7 @@ const execution = { state: "failed", detail: "Process exited with status 42", sy const traceSources = { primary: { kind: "execution_stream", path: "/tmp/events.jsonl", mediaType: "application/x-ndjson", provider: "codex", formatVersion: "1", cliVersion: "test-cli", harnessVersion: "test-harness" } }; const artifact = { id: "artifact", kind: "terminal_log", object_key: "tenants/tenant/runs/run/harness/stderr.txt", format: "text", state: "stored", byte_size: "27", sha256: "a".repeat(64) }; -async function fixture(tenantId = "tenant", scopes = ["runs:read"]) { +async function fixture(tenantId = "tenant", scopes = ["runs:read"], authMethod?: "session") { const key = btoa("a".repeat(32)), encryptedPrompt = await encrypt("private prompt", key); vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue({ role: "owner", sessionVersion: 1 } as any); const query = vi.fn(async (sql: string, values: any[]) => { @@ -19,7 +19,7 @@ async function fixture(tenantId = "tenant", scopes = ["runs:read"]) { if (sql.includes("app.run_artifacts")) return { rows: [artifact] }; return { rows: [] }; }); - return new ApiService({ DATABASE: { pool: { query } }, CREDENTIAL_ENCRYPTION_KEY: key } as any, { tenantId, userId: "user", sessionVersion: 1, scopes } as any); + return new ApiService({ DATABASE: { pool: { query } }, CREDENTIAL_ENCRYPTION_KEY: key } as any, { tenantId, userId: "user", sessionVersion: 1, scopes, authMethod } as any); } describe("run diagnostics API boundary", () => { @@ -46,9 +46,22 @@ describe("run diagnostics API boundary", () => { vi.spyOn(ArtifactRepository.prototype, "list").mockResolvedValue([]); expect(await service.getRunDiagnostics("old")).toMatchObject({ execution: null, harnessLog: null, traceSources: null }); }); + it("requires write scope and an interactive owner session for replay before reading storage", async () => { + const body = { requestId: crypto.randomUUID(), source: "native_session" }; + expect(isDeclaredApiOperation("POST", "/api/v1/runs/run/trace/replay")).toBe(true); + await expect((await fixture("tenant", ["runs:read"])).replayRunTrace(crypto.randomUUID(), body)).rejects.toMatchObject({ status: 403, code: "insufficient_scope" }); + await expect((await fixture("tenant", ["runs:write"])).replayRunTrace(crypto.randomUUID(), body)).rejects.toMatchObject({ status: 403, code: "session_required" }); + }); + it("validates replay input after owner-session authorization", async () => { + const service = await fixture("tenant", ["runs:write"], "session"); + await expect(service.replayRunTrace(crypto.randomUUID(), { requestId: "invalid", tenantId: "other" })).rejects.toMatchObject({ name: "ZodError" }); + await expect(service.replayRunTrace("not-a-run", { requestId: crypto.randomUUID() })).rejects.toMatchObject({ name: "ZodError" }); + vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue({ role: "owner", sessionVersion: 2 } as any); + await expect(service.replayRunTrace(crypto.randomUUID(), { requestId: crypto.randomUUID() })).rejects.toMatchObject({ status: 401 }); + }); it("documents the externally visible fields and schema references", () => { const spec = readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"); - for (const field of ["traceSources:", "trace_sources:", "harnessVersion:", "cliVersion:", "execution_diagnostics", "harness_log", "execution:", "harnessLog:", "execMainCode", "execMainStatus", "activeState", "subState", "object_key"]) + for (const field of ["TraceReplayRequest:", "TraceReplayResult:", "TraceDiagnostics:", "trace_generation:", "trace_projection:", "traceSources:", "trace_sources:", "harnessVersion:", "cliVersion:", "execution_diagnostics", "harness_log", "execution:", "harnessLog:", "execMainCode", "execMainStatus", "activeState", "subState", "object_key"]) expect(spec).toContain(field); expect(spec).toContain("$ref: '#/components/schemas/RunDetail'"); expect(spec).toContain("$ref: '#/components/schemas/RunDiagnostics'"); diff --git a/packages/app/test/trace-source.postgres.test.ts b/packages/app/test/trace-source.postgres.test.ts index 899e0b5c..d8b2d9c1 100644 --- a/packages/app/test/trace-source.postgres.test.ts +++ b/packages/app/test/trace-source.postgres.test.ts @@ -4,6 +4,8 @@ import { Database } from "../src/postgres/database"; import { LiveTraceRepository } from "../src/postgres/live-trace-repository"; import { TraceRepository } from "../src/postgres/trace-repository"; import { ArtifactRepository } from "../src/postgres/artifact-repository"; +import { replayTrace } from "../src/trace-replay"; +import { TraceProjectionRepository } from "../src/postgres/trace-projection-repository"; import { artifactUpload, issueArtifactUploadGrant } from "../src/artifact-upload"; const url = process.env.TRACE_TEST_DATABASE_URL ?? process.env.AUTH_TEST_DATABASE_URL; @@ -34,14 +36,15 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { const blobs = new Map(); const env = { DATABASE: database, SESSION_SIGNING_SECRET: secret, RUN_ARTIFACTS: { put: async (key: string, stream: ReadableStream, options: any) => { const bytes = new Uint8Array(await new Response(stream).arrayBuffer()); expect(await hash(bytes)).toBe(options.sha256); blobs.set(key, bytes); return { httpEtag: "test" }; }, - get: async (key: string) => blobs.has(key) ? { body: new Response(new Uint8Array(blobs.get(key)!)).body } : null, + get: async (key: string) => blobs.has(key) ? { body: new Response(new Uint8Array(blobs.get(key)!)).body, size: blobs.get(key)!.length, checksums: { sha256: await crypto.subtle.digest("SHA-256", new Uint8Array(blobs.get(key)!).buffer) } } : null, } } as any; const upload = async (text: string, kind: "execution_stream" | "native_session" = "execution_stream") => { const bytes = new TextEncoder().encode(text), sha256 = await hash(bytes); - const token = await issueArtifactUploadGrant({ tenantId, runId, path: kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: "application/x-ndjson", provider, format: "jsonl", sourceKind: kind, sourcePath: "/tmp/trace.jsonl", formatVersion: "1", cliVersion: "p1", harnessVersion: "h1", primary: kind === "execution_stream", expiresAt: Date.now() + 60_000 }, secret); + const traceGeneration = kind === "execution_stream" ? (await new LiveTraceRepository(database, tenantId).cursor(runId)).generation : undefined; + const token = await issueArtifactUploadGrant({ traceGeneration, tenantId, runId, path: kind === "execution_stream" ? "trace/stream.jsonl" : "native/session.jsonl", contentType: "application/x-ndjson", provider, format: "jsonl", sourceKind: kind, sourcePath: "/tmp/trace.jsonl", formatVersion: "1", cliVersion: "p1", harnessVersion: "h1", primary: kind === "execution_stream", expiresAt: Date.now() + 60_000 }, secret); return artifactUpload(new Request("https://app/upload", { method: "PUT", headers: { "Content-Type": "application/x-ndjson", "Content-Length": String(bytes.length), "X-Artifact-SHA256": sha256 }, body: bytes }), env, token); }; - return { runId, upload, blobs, live: new LiveTraceRepository(database, tenantId), trace: new TraceRepository(database, tenantId), artifacts: new ArtifactRepository(database, tenantId) }; + return { tenantId, env, runId, upload, blobs, live: new LiveTraceRepository(database, tenantId), trace: new TraceRepository(database, tenantId), artifacts: new ArtifactRepository(database, tenantId) }; } it.each(["codex", "claude"] as const)("reconciles %s durable bytes, preserves native audit data, and rejects late chunks", async provider => { @@ -53,6 +56,7 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { expect(live.items).toHaveLength(1); expect((await f.upload(text)).status).toBe(201); expect(await f.trace.page(f.runId)).toEqual(live); + expect((await new TraceProjectionRepository(database, f.tenantId).diagnostics(f.runId)).projection?.reconciliation.state).toBe("matched"); expect((await f.upload('{"type":"session_meta","payload":{"id":"native"}}\n', "native_session")).status).toBe(201); expect(await f.trace.page(f.runId)).toEqual(live); const artifacts = await f.artifacts.list(f.runId); @@ -82,4 +86,94 @@ describe.skipIf(!url)("trace sources with PostgreSQL", () => { expect(await f.artifacts.list(f.runId)).toHaveLength(0); expect((await f.upload(record("live"))).status).toBe(201); }); + it("replays corrected historical Codex calls, resumes, rate limits, and preserves artifacts across rollback", async () => { + const f = await fixture(); + const native = JSON.stringify({ type: "response_item", payload: { type: "custom_tool_call", call_id: "apply-1", name: "apply_patch", input: "patch" } }) + "\n"; + await f.upload(record("stream")); + await f.upload(native, "native_session"); + await database.pool.query("UPDATE app.runs SET state='succeeded' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + const requestId = crypto.randomUUID(), input = { requestId, source: "native_session" as const }; + const result = await replayTrace(f.env, f.tenantId, "owner", f.runId, input); + expect(result).toMatchObject({ status: "projected", sourceKind: "native_session" }); + expect((await f.trace.page(f.runId)).items).toMatchObject([{ type: "tool_call", title: "apply_patch", id: "apply-1" }]); + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, input)).toEqual(result); + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, { ...input, requestId: crypto.randomUUID() })).toMatchObject({ status: "already_projected" }); + expect((await f.upload(record("stream"))).status).toBe(201); + expect((await f.trace.page(f.runId)).items[0].type).toBe("tool_call"); + expect(await f.artifacts.list(f.runId)).toHaveLength(2); + await expect(replayTrace(f.env, f.tenantId, "owner", crypto.randomUUID(), input)).rejects.toMatchObject({ status: 409 }); + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, { requestId: crypto.randomUUID(), source: "primary" })).toMatchObject({ status: "projected", sourceKind: "execution_stream" }); + expect((await f.trace.page(f.runId)).items[0].id).toBe("stream"); + for (let i = 0; i < 5; i++) await replayTrace(f.env, f.tenantId, "owner", f.runId, { requestId: crypto.randomUUID(), source: "primary" }); + await expect(replayTrace(f.env, f.tenantId, "owner", f.runId, input)).rejects.toMatchObject({ status: 429 }); + }); + + it("reports active and unavailable runs without inventing recovery; isolates requests and retained bytes", async () => { + const f = await fixture(), other = await fixture(); + const input = { requestId: crypto.randomUUID(), source: "primary" as const }; + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, input)).toMatchObject({ status: "skipped", reason: "run_active" }); + await expect(replayTrace(f.env, other.tenantId, "owner", f.runId, { ...input, requestId: crypto.randomUUID() })).rejects.toMatchObject({ status: 404 }); + await database.pool.query("UPDATE app.runs SET state='succeeded' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, { ...input, requestId: crypto.randomUUID() })).toMatchObject({ status: "unrecoverable", reason: "missing_artifact" }); + await f.upload(record("saved")); + f.blobs.clear(); + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, { ...input, requestId: crypto.randomUUID() })).toMatchObject({ status: "unrecoverable", reason: "artifact_not_retained" }); + expect((await f.trace.page(f.runId)).items[0].id).toBe("saved"); + }); + + it("persists mismatch evidence, rejects stale terminal generations, and makes failed replay resumable", async () => { + const f = await fixture(), liveText = record("old"), bytes = new TextEncoder().encode(liveText); + await f.live.append(f.runId, "codex", { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await hash(bytes), previousHash: zero, bytes }, "execution_stream"); + const stale = await issueArtifactUploadGrant({ tenantId: f.tenantId, runId: f.runId, path: "trace/stream.jsonl", contentType: "application/x-ndjson", provider: "codex", format: "jsonl", sourceKind: "execution_stream", traceGeneration: null, expiresAt: Date.now() + 60_000 }, secret); + expect((await artifactUpload(new Request("https://app/upload", { method: "PUT", headers: { "Content-Type": "application/x-ndjson", "Content-Length": String(bytes.length), "X-Artifact-SHA256": await hash(bytes) }, body: bytes }), f.env, stale)).status).toBe(409); + expect((await f.upload(record("new"))).status).toBe(201); + expect((await new TraceProjectionRepository(database, f.tenantId).diagnostics(f.runId)).projection?.reconciliation).toMatchObject({ state: "mismatch", mismatches: 1 }); + await f.upload(JSON.stringify({ type: "response_item", payload: { type: "custom_tool_call", call_id: "call", name: "apply_patch", input: "reject" } }) + "\n", "native_session"); + await database.pool.query("UPDATE app.runs SET state='succeeded' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + const input = { requestId: crypto.randomUUID(), source: "native_session" as const }; + await database.pool.query("ALTER TABLE app.run_trace_events ADD CONSTRAINT reject_replay CHECK (preview_text <> 'reject')"); + try { await expect(replayTrace(f.env, f.tenantId, "owner", f.runId, input)).rejects.toThrow("reject_replay"); } + finally { await database.pool.query("ALTER TABLE app.run_trace_events DROP CONSTRAINT reject_replay"); } + expect((await f.trace.page(f.runId)).items[0].id).toBe("new"); + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, input)).toMatchObject({ status: "projected" }); + }); + + it("backfills an undeclared historical session and rejects missing checksums or cross-tenant keys", async () => { + const f = await fixture(); + await database.pool.query("UPDATE app.runs SET state='succeeded',trace_sources=NULL WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + const text = JSON.stringify({ type: "response_item", payload: { type: "custom_tool_call", call_id: "historical", name: "apply_patch", input: "retained patch" } }) + "\n" + JSON.stringify({ type: "response_item", payload: { type: "custom_tool_call_output", call_id: "historical", output: "success" } }) + "\n"; + const bytes = new TextEncoder().encode(text), sha256 = await hash(bytes); + const key = `tenants/${f.tenantId}/runs/${f.runId}/native/session.jsonl`; + f.blobs.set(key, bytes); + await f.artifacts.record({ runId: f.runId, kind: "native_session", provider: "codex", format: "jsonl", objectKey: key, byteSize: bytes.length, sha256 }); + const input = { requestId: crypto.randomUUID(), source: "primary" as const }; + const originalGet = f.env.RUN_ARTIFACTS.get; + f.env.RUN_ARTIFACTS.get = async (key: string) => ({ ...await originalGet(key), checksums: {} }); + await expect(replayTrace(f.env, f.tenantId, "owner", f.runId, input)).rejects.toMatchObject({ status: 409, code: "invalid_artifact" }); + expect((await f.trace.page(f.runId)).items).toHaveLength(0); + f.env.RUN_ARTIFACTS.get = originalGet; + expect(await replayTrace(f.env, f.tenantId, "owner", f.runId, input)).toMatchObject({ status: "projected" }); + expect((await f.trace.page(f.runId)).items).toMatchObject([{ type: "tool_call", id: "historical", title: "apply_patch" }, { type: "tool_result", parentId: "historical", title: "apply_patch" }]); + await database.pool.query("UPDATE app.run_artifacts SET object_key='tenants/another/runs/other/native/session.jsonl' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + await expect(replayTrace(f.env, f.tenantId, "owner", f.runId, { ...input, requestId: crypto.randomUUID() })).rejects.toMatchObject({ status: 409, code: "invalid_artifact" }); + expect((await f.trace.page(f.runId)).items).toHaveLength(2); + }); + + it("finalizes Pi native projection, rejects late chunks, and preserves immutable native snapshots", async () => { + const f = await fixture(); + await database.pool.query("UPDATE app.runs SET trace_sources=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, { primary: { kind: "native_session", provider: "pi" } }]); + const text = JSON.stringify({ type: "message", id: "tool", message: { role: "assistant", content: [{ type: "toolCall", id: "pi-call", name: "bash", arguments: { command: "pwd" } }] } }) + "\n"; + const bytes = new TextEncoder().encode(text), chunk = { generation: "pi-session", expectedGeneration: null, startOffset: 0, chunkSha256: await hash(bytes), previousHash: zero, bytes }; + await f.live.append(f.runId, "pi", chunk, "native_session"); + const token = await issueArtifactUploadGrant({ tenantId: f.tenantId, runId: f.runId, provider: "pi", format: "jsonl", path: "native/session.jsonl", contentType: "application/x-ndjson", sourceKind: "native_session", primary: true, traceGeneration: "pi-session", expiresAt: Date.now() + 60_000 }, secret); + const upload = async (bytes: Uint8Array) => artifactUpload(new Request("https://app/upload", { method: "PUT", headers: { "Content-Type": "application/x-ndjson", "Content-Length": String(bytes.length), "X-Artifact-SHA256": await hash(bytes) }, body: new Uint8Array(bytes) }), f.env, token); + expect((await upload(bytes)).status).toBe(201); + expect((await f.trace.page(f.runId)).items).toMatchObject([{ id: "tool", type: "tool_call", title: "bash", display: { toolCallId: "pi-call" } }]); + await expect(f.live.append(f.runId, "pi", chunk, "native_session")).rejects.toThrow("already finalized"); + expect((await upload(new TextEncoder().encode(text + '{}\n'))).status).toBe(409); + expect(await f.artifacts.list(f.runId)).toHaveLength(1); + const retained = (await f.artifacts.list(f.runId))[0]; + expect(new TextDecoder().decode(f.blobs.get(retained.object_key))).toBe(text); + }); + }); diff --git a/packages/app/test/trace-source.test.ts b/packages/app/test/trace-source.test.ts index 60005672..f879bdac 100644 --- a/packages/app/test/trace-source.test.ts +++ b/packages/app/test/trace-source.test.ts @@ -36,3 +36,18 @@ describe("execution stream contract", () => { expect(() => parseTrace("claude", "invalid", "execution_stream")).toThrow("Invalid execution stream JSON"); }); }); + + +describe("deployment source gates", () => { + it("canaries only selected tenants and restores native for new launches while retaining Pi", async () => { + const { rolloutTraceSources } = await import("../src/trace-source"); + const { agentDriver } = await import("../src/agent-driver"); + for (const provider of ["codex", "claude", "pi"] as const) { + const sources = agentDriver(provider).launch("run", {}).traceSources!; + expect(rolloutTraceSources(sources, "canary", { TRACE_STREAM_TENANTS: "canary" }).primary.kind).toBe(provider === "pi" ? "native_session" : "execution_stream"); + expect(rolloutTraceSources(sources, "other", { TRACE_STREAM_TENANTS: "canary" }).primary.kind).toBe("native_session"); + expect(rolloutTraceSources(sources, "canary", { TRACE_PRIMARY_MODE: "native_session" }).primary.kind).toBe("native_session"); + expect(sources.primary.kind).toBe(provider === "pi" ? "native_session" : "execution_stream"); + } + }); +}); diff --git a/packages/docs/concepts.mdx b/packages/docs/concepts.mdx index 99086649..16c4046b 100644 --- a/packages/docs/concepts.mdx +++ b/packages/docs/concepts.mdx @@ -12,3 +12,14 @@ Trigger kinds are `manual`, `schedule`, `webhook`, and `jobLifecycle`. Webhooks See the repository's [trigger context contract](https://github.com/GenerationSoftware/factorize/blob/main/docs/job-trigger-context.md) for the reflection paths exposed with every trigger. Prompt and run-name templates render plain text: double-brace substitutions preserve URLs, quotes, Markdown, and code without HTML entity escaping. Triple-brace substitutions remain supported. Literal entity text in job context is preserved, not decoded. The web UI escapes rendered values when displaying them. This applies to new runs; existing persisted prompts are unchanged. + + +## Run traces and recovery + +Codex and Claude can show tool calls live from an execution stream; Pi uses its native session. The run page identifies the source and artifact state, and labels native fallback after rollback. A trace may be partial when collection fails. + +`GET /api/v1/runs/{runId}/diagnostics` reports the declared source and versions, actual projection source and artifact checksum, live generation and byte cursor, terminal reconciliation state, parse warnings, unknown-event rate, retained artifacts, and fallback use. `matched` verifies the projected live prefix against the terminal artifact. Missing reconciliation evidence does not establish completeness. + +An interactive tenant owner with `runs:write` can use `POST /api/v1/runs/{runId}/trace/replay` to reproject retained primary bytes or restore a retained native session. Supply a UUID `requestId` and `source` (`primary` or `native_session`). Preserve the request ID when retrying an interrupted operation. Replay is limited to 10 requests per tenant per minute. Results distinguish projected, already projected, skipped, and unrecoverable runs. Historical Codex tool calls can be recovered only if the native session artifact still exists. Replay preserves stored artifacts; expired or deleted bytes cannot be recovered. + +See the [trace rollout and debugging runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for canary gates, retention, resumption, and rollback. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 11e869e8..bad64d3c 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -17,3 +17,8 @@ Connect to `APP_ORIGIN/mcp` using Streamable HTTP. Tools mirror the REST surface ## Triggers Webhooks support Linear, ClickUp, GitHub, and Cloudflare Tail. Schedule config is `{cron,timezone}`. Lifecycle config is `{sourceJobIds,states}` with succeeded, failed, or stopped. Templates address the firing trigger by slug, for example `{{trigger-1.issue.title}}`. Manual idempotency keys are client values and must not begin with `manual:`. + + +## Trace provenance and recovery + +Codex and Claude use execution-stream primary sources when admitted by rollout gates; Pi uses its version-pinned native session. Run diagnostics expose source/CLI/harness versions, retained artifact receipts, projection checksum/parser version, live generation/offset, reconciliation, warning and unknown counts, and native fallback use. Owner sessions with runs:write may POST /api/v1/runs/{runId}/trace/replay with {requestId: UUID, source: primary|native_session}. One terminal run per request, 10 attempts per tenant/minute. Checkpoint request IDs for retries; completed outcomes are durable and idempotent, failed transactions resume, and missing/expired artifacts are explicitly unrecoverable. Native replay can recover retained historical Codex custom tool calls. Neither replay nor rollback deletes artifacts. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 07579fbc..f49c4e60 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -3,7 +3,7 @@ info: title: Factorize API version: 1.0.0 description: Versioned Factorize REST API. See the hosted docs for examples and OAuth discovery. - x-dashboard-auth: Access-token and authorized-client management operations require an interactive owner session; all other operations accept a suitably scoped bearer token or owner session. + x-dashboard-auth: Access-token and authorized-client management and trace replay operations require an interactive owner session; all other operations accept a suitably scoped bearer token or owner session. servers: - url: https://app.factorize.sh security: [{ bearerAuth: [] }] @@ -83,6 +83,70 @@ components: properties: primary: { $ref: '#/components/schemas/TraceSource' } nativeSession: { $ref: '#/components/schemas/TraceSource' } + TraceProjection: + type: [object, 'null'] + description: Committed projection receipt. Null means no durable reconciliation evidence; it does not mean complete. + properties: + source_kind: { type: string, enum: [execution_stream, native_session] } + artifact_sha256: { type: string } + parser_version: { type: string } + updated_at: { type: string, format: date-time } + reconciliation: + type: object + properties: + state: { type: string, enum: [matched, mismatch, no_live_cursor, reprojected] } + events: { type: integer } + liveEvents: { type: integer } + mismatches: { type: integer } + liveOffset: { type: [integer, 'null'] } + artifactBytes: { type: integer } + TraceDiagnostics: + type: object + required: [primarySource, sourceVersion, projection, liveCursor, counts, artifacts, nativeArtifactState, fallbackUsed, lastReplay] + properties: + primarySource: { type: string, enum: [execution_stream, native_session] } + sourceVersion: { type: [string, 'null'] } + projection: { $ref: '#/components/schemas/TraceProjection' } + liveCursor: + type: [object, 'null'] + properties: + generation: { type: string } + committed_offset: { type: [integer, string] } + pending_bytes: { type: integer } + updated_at: { type: string, format: date-time } + counts: + type: object + properties: + events: { type: integer } + parse_warnings: { type: integer } + unknown_events: { type: integer } + unknownEventRate: { type: number, minimum: 0, maximum: 1 } + artifacts: + type: array + description: Tenant/run-scoped receipts; storage keys are locators, never public download URLs. Includes kind, provider, format and source/CLI/harness versions, byte size, checksum and storage state. + items: { type: object } + nativeArtifactState: { type: string, enum: [stored, missing], description: Missing means no retained native artifact receipt; recovery is not promised. } + fallbackUsed: { type: boolean, description: Native projection selected for a run originally declared with an execution stream primary. } + lastReplay: { type: [object, 'null'], description: Latest completed replay request ID, source, result, and timestamp; failed requests are retryable and logged. } + TraceReplayRequest: + type: object + additionalProperties: false + required: [requestId] + properties: + requestId: { type: string, format: uuid, description: Tenant-scoped idempotency key; preserve it when retrying. Use a new key to reconsider a previously skipped or unrecoverable run. } + source: { type: string, enum: [primary, native_session], default: primary, description: Primary replays the persisted source declaration (native for historical runs); native_session explicitly rolls back to retained native bytes. } + TraceReplayResult: + type: object + required: [requestId, runId, status] + properties: + requestId: { type: string, format: uuid } + runId: { type: string, format: uuid } + status: { type: string, enum: [projected, already_projected, skipped, unrecoverable] } + reason: { type: string, enum: [run_active, ambiguous_artifacts, missing_artifact, unsupported_artifact, artifact_not_retained] } + sourceKind: { type: string, enum: [execution_stream, native_session] } + sha256: { type: string } + parserVersion: { type: string } + reconciliation: { type: object } RunDetail: allOf: - $ref: '#/components/schemas/Run' @@ -91,6 +155,8 @@ components: properties: id: { type: string } state: { type: string } + trace_generation: { type: [string, 'null'], description: Live file generation; clients reset trace pagination when it changes. } + trace_projection: { $ref: '#/components/schemas/TraceProjection' } trace_sources: { $ref: '#/components/schemas/TraceSources' } execution_diagnostics: { $ref: '#/components/schemas/ExecutionDiagnostics' } harness_log: { $ref: '#/components/schemas/HarnessLog' } @@ -104,6 +170,7 @@ components: state: { type: string } provider: { type: string } backendKind: { type: string } + trace: { $ref: '#/components/schemas/TraceDiagnostics' } traceSources: { $ref: '#/components/schemas/TraceSources' } execution: { $ref: '#/components/schemas/ExecutionDiagnostics' } harnessLog: { $ref: '#/components/schemas/HarnessLog' } @@ -173,6 +240,26 @@ paths: get: { summary: List runs, parameters: [{ name: jobId, in: query, schema: { type: string } }, { name: state, in: query, schema: { type: string } }, { name: contextQuery, in: query, schema: { type: string } }, { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }, { name: cursor, in: query, schema: { type: string } }], responses: { '200': { description: Paginated runs, content: { application/json: { schema: { $ref: '#/components/schemas/RunPage' } } } } } } /api/v1/runs/{runId}: { get: { summary: Get run, responses: { '200': { description: Run including durable execution diagnostics and harness artifact location, content: { application/json: { schema: { $ref: '#/components/schemas/RunDetail' } } } } } } } /api/v1/runs/{runId}/trace: { get: { summary: Get paginated run trace events, responses: { '200': { description: Trace page } } } } + /api/v1/runs/{runId}/trace/replay: + post: + summary: Replay a retained trace artifact or restore a native-session projection + description: Requires runs:write and an interactive tenant owner session. One terminal run per request, limited to 10 attempts per tenant per minute including retries and failures. Projection and result commit atomically; no artifacts are deleted. Retry failed requests with the same requestId. Conflicting reuse is rejected. Missing bytes cannot be recovered. Does not change the source declaration of an active or future run. + x-required-scope: runs:write + x-owner-session-required: true + parameters: + - { name: runId, in: path, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: { application/json: { schema: { $ref: '#/components/schemas/TraceReplayRequest' } } } + responses: + '200': { description: Durable replay result, content: { application/json: { schema: { $ref: '#/components/schemas/TraceReplayResult' } } } } + '400': { description: Invalid request } + '401': { description: Invalid owner session } + '403': { description: Missing runs:write scope or interactive owner session } + '404': { description: Run not found within the tenant } + '409': { description: Request ID conflict or artifact ownership/checksum mismatch } + '429': { description: Tenant rate limit reached; wait one minute before retrying } + '503': { description: Artifact storage unavailable } /api/v1/runs/{runId}/diagnostics: { get: { summary: Get credential-safe run lifecycle diagnostics, responses: { '200': { description: Credential-safe execution metadata and durable harness artifact location, content: { application/json: { schema: { $ref: '#/components/schemas/RunDiagnostics' } } } } } } } /api/v1/runs/{runId}/stop: { post: { summary: Stop run, responses: { '200': { description: Stopped } } } } /api/v1/runs/{runId}/kill: { post: { summary: Kill run and immediately release its concurrency slot, responses: { '200': { description: Killed } } } } From 50ef2f645ff4b1acf84f59b84a0ff6c3e04bd077 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Fri, 9 Oct 2026 03:38:42 +0000 Subject: [PATCH 2/2] Preserve trigger provider compatibility in trace diagnostics --- packages/app/src/flow-service.ts | 4 ++-- packages/app/test/run-diagnostics-contract.test.ts | 2 +- packages/docs/openapi.yaml | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index b3d1d6ab..35318bb3 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -98,9 +98,9 @@ export class ApiService { new ArtifactRepository(database, this.auth.tenantId).list(runId), ]); const primary = run.trace_sources?.primary ?? null; - return { runId: run.id, jobId: run.job_id, state: run.state, provider: primary?.provider ?? run.agent_kind ?? null, backendKind: run.execution_backend_kind, + return { runId: run.id, jobId: run.job_id, state: run.state, provider: run.provider, backendKind: run.execution_backend_kind, execution: run.execution_diagnostics, traceSources: run.trace_sources, - trace: { ...evidence, primarySource: primary?.kind ?? "native_session", sourceVersion: primary?.formatVersion ?? null, + 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", fallbackUsed: evidence.projection?.source_kind === "native_session" && primary?.kind === "execution_stream" }, diff --git a/packages/app/test/run-diagnostics-contract.test.ts b/packages/app/test/run-diagnostics-contract.test.ts index 4a59e92c..12073c30 100644 --- a/packages/app/test/run-diagnostics-contract.test.ts +++ b/packages/app/test/run-diagnostics-contract.test.ts @@ -29,7 +29,7 @@ describe("run diagnostics API boundary", () => { expect(isDeclaredApiOperation("GET", "/api/v1/runs/run/diagnostics")).toBe(true); expect(await service.getRun("run")).toMatchObject({ execution_diagnostics: execution, harness_log: artifact, trace_sources: traceSources }); const diagnostics = await service.getRunDiagnostics("run"); - expect(diagnostics).toMatchObject({ execution, traceSources, harnessLog: artifact, artifact: { state: "partial", error: "Native session upload failed" } }); + expect(diagnostics).toMatchObject({ trace: { provider: "codex", primarySource: "execution_stream" }, execution, traceSources, harnessLog: artifact, artifact: { state: "partial", error: "Native session upload failed" } }); expect(JSON.stringify(diagnostics)).not.toContain("private prompt"); expect(JSON.stringify(diagnostics)).not.toContain("encrypted_prompt"); }); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index f49c4e60..f5122f8d 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -102,8 +102,9 @@ components: artifactBytes: { type: integer } TraceDiagnostics: type: object - required: [primarySource, sourceVersion, projection, liveCursor, counts, artifacts, nativeArtifactState, fallbackUsed, lastReplay] + required: [provider, primarySource, sourceVersion, projection, liveCursor, counts, artifacts, nativeArtifactState, fallbackUsed, lastReplay] properties: + provider: { type: [string, 'null'], description: Agent trace provider; the outer diagnostics provider remains the trigger provider. } primarySource: { type: string, enum: [execution_stream, native_session] } sourceVersion: { type: [string, 'null'] } projection: { $ref: '#/components/schemas/TraceProjection' }