From dd4d2827092f204936600acd3ba7784d63a1d333 Mon Sep 17 00:00:00 2001 From: Brendan Date: Fri, 18 Sep 2026 19:08:29 +0000 Subject: [PATCH] Stream live traces incrementally --- .../0003_incremental_trace_ingestion.sql | 28 ++++++++ packages/app/src/artifact-upload.ts | 3 +- packages/app/src/exe-vm-backend.ts | 9 ++- .../app/src/postgres/live-trace-repository.ts | 68 +++++++++++++++++++ packages/app/src/postgres/run-scheduler.ts | 25 +++++-- packages/app/src/trace-chunk-upload.ts | 24 +++++++ packages/app/src/worker.ts | 3 + packages/app/test/execution-backend.test.ts | 30 ++++++++ .../postgres-live-trace-repository.test.ts | 47 +++++++++++++ 9 files changed, 231 insertions(+), 6 deletions(-) create mode 100644 packages/app/migrations/0003_incremental_trace_ingestion.sql create mode 100644 packages/app/src/postgres/live-trace-repository.ts create mode 100644 packages/app/src/trace-chunk-upload.ts create mode 100644 packages/app/test/postgres-live-trace-repository.test.ts diff --git a/packages/app/migrations/0003_incremental_trace_ingestion.sql b/packages/app/migrations/0003_incremental_trace_ingestion.sql new file mode 100644 index 00000000..68a1ef42 --- /dev/null +++ b/packages/app/migrations/0003_incremental_trace_ingestion.sql @@ -0,0 +1,28 @@ +CREATE TABLE IF NOT EXISTS app.run_trace_cursors ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + generation text NOT NULL, + committed_offset bigint NOT NULL DEFAULT 0 CHECK (committed_offset >= 0), + pending_bytes bytea NOT NULL DEFAULT ''::bytea, + next_sequence bigint NOT NULL DEFAULT 1 CHECK (next_sequence > 0), + rolling_hash text NOT NULL DEFAULT repeat('0',64) CHECK (rolling_hash ~ '^[0-9a-f]{64}$'), + 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 IF NOT EXISTS app.run_trace_chunks ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + generation text NOT NULL, + start_offset bigint NOT NULL CHECK (start_offset >= 0), + end_offset bigint NOT NULL CHECK (end_offset > start_offset), + chunk_sha256 text NOT NULL CHECK (chunk_sha256 ~ '^[0-9a-f]{64}$'), + previous_hash text NOT NULL CHECK (previous_hash ~ '^[0-9a-f]{64}$'), + rolling_hash text NOT NULL CHECK (rolling_hash ~ '^[0-9a-f]{64}$'), + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id,run_id,generation,start_offset), + FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE +); + +INSERT INTO app.schema_migrations(version) VALUES ('0003_incremental_trace_ingestion') ON CONFLICT DO NOTHING; diff --git a/packages/app/src/artifact-upload.ts b/packages/app/src/artifact-upload.ts index 4bfb47c0..b775a479 100644 --- a/packages/app/src/artifact-upload.ts +++ b/packages/app/src/artifact-upload.ts @@ -13,6 +13,7 @@ export interface ArtifactUploadGrant { provider: "codex" | "claude" | "pi"; format: "jsonl"; nativeSessionId?: string; + purpose?: "artifact" | "trace_chunk"; expiresAt: number; } @@ -46,7 +47,7 @@ export async function artifactUpload(request: Request, env: Env, token: string): if (request.method !== "PUT") return new Response("Method not allowed", { status: 405, headers: { Allow: "PUT" } }); if (!env.RUN_ARTIFACTS) return new Response("Artifact storage is unavailable", { status: 503 }); const grant = await readArtifactUploadGrant(token, env.SESSION_SIGNING_SECRET); - if (!grant) return new Response("Invalid or expired artifact upload grant", { status: 401 }); + if (!grant || grant.purpose === "trace_chunk") return new Response("Invalid or expired artifact upload grant", { status: 401 }); if (!request.body) return new Response("Artifact body is required", { status: 400 }); const sha256 = request.headers.get("X-Artifact-SHA256")?.toLowerCase() ?? "", size = Number(request.headers.get("Content-Length")); if (!/^[0-9a-f]{64}$/.test(sha256) || !Number.isSafeInteger(size) || size < 0) return new Response("Artifact checksum and size are required", { status: 400 }); diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index 84520e8a..8953b4de 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -134,11 +134,18 @@ export class ExeVmBackend implements ExecutionBackend { } async collectArtifact(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; contentType: string }) { - const remote = `file=$(${request.discoverCommand}); test -n "$file"; test -f "$file"; size=$(wc -c < "$file" | tr -d ' '); sha=$(sha256sum "$file" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$file" ${shellAtom(request.uploadUrl)}`; + const remote = `file=$(${request.discoverCommand}); test -n "$file"; test -f "$file"; snapshot=$(mktemp); trap 'rm -f "$snapshot"' EXIT; cp "$file" "$snapshot"; size=$(wc -c < "$snapshot" | tr -d ' '); sha=$(sha256sum "$snapshot" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H ${shellAtom(`Content-Type: ${request.contentType}`)} -H "Content-Length: $size" -H "X-Artifact-SHA256: $sha" --data-binary @"$snapshot" ${shellAtom(request.uploadUrl)}`; const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); return { ok: result.ok, detail: result.ok ? undefined : `Native session upload failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; } + async collectTraceChunk(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; generation: string | null; offset: number; previousHash: string }) { + const expectedGeneration = request.generation ?? "", zeroHash = "0".repeat(64); + const remote = `file=$(${request.discoverCommand}); test -n "$file"; test -f "$file"; generation=$(stat -c '%d:%i:%W' "$file"); start=${request.offset}; previous=${shellAtom(request.previousHash)}; if [ -n ${shellAtom(expectedGeneration)} ] && [ "$generation" != ${shellAtom(expectedGeneration)} ]; then start=0; previous=${shellAtom(zeroHash)}; fi; total=$(wc -c < "$file" | tr -d ' '); if [ "$total" -le "$start" ]; then printf 'no-change'; exit 0; fi; count=$((total-start)); if [ "$count" -gt 4194304 ]; then count=4194304; fi; chunk=$(mktemp); trap 'rm -f "$chunk"' EXIT; dd if="$file" of="$chunk" iflag=skip_bytes,count_bytes skip="$start" count="$count" status=none; size=$(wc -c < "$chunk" | tr -d ' '); sha=$(sha256sum "$chunk" | cut -d' ' -f1); curl --fail --silent --show-error -X PUT -H "Content-Length: $size" -H "X-Trace-Generation: $generation" -H ${shellAtom(`X-Trace-Expected-Generation: ${expectedGeneration}`)} -H "X-Trace-Start: $start" -H "X-Trace-SHA256: $sha" -H "X-Trace-Previous-Hash: $previous" --data-binary @"$chunk" ${shellAtom(request.uploadUrl)}`; + const result = await this.api(`ssh ${shellAtom(this.vm(handle))} ${shellAtom(remote)}`); + return { ok: result.ok, detail: result.ok ? undefined : `Live trace upload failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; + } + async stop(handle: RunHandle): Promise { const result = await this.deleteVm(this.vm(handle)); return { state: result.ok ? "stopped" : "failed", detail: result.ok ? undefined : `VM deletion failed (${result.status}): ${result.body.slice(0, 300)}`, command: result }; diff --git a/packages/app/src/postgres/live-trace-repository.ts b/packages/app/src/postgres/live-trace-repository.ts new file mode 100644 index 00000000..53084b44 --- /dev/null +++ b/packages/app/src/postgres/live-trace-repository.ts @@ -0,0 +1,68 @@ +import { parseTrace, type TraceEvent } from "../trace"; +import type { Database, DatabaseClient } from "./database"; + +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(""); +const sha256 = async (bytes: Uint8Array | string) => { const value = typeof bytes === "string" ? encoder.encode(bytes) : new Uint8Array(bytes); return hex(await crypto.subtle.digest("SHA-256", value.buffer)); }; + +export interface LiveTraceCursor { generation: string | null; offset: number; rollingHash: string; } +export interface TraceChunk { generation: string; expectedGeneration: string | null; startOffset: number; chunkSha256: string; previousHash: string; bytes: Uint8Array; } + +interface CursorRow { generation: string; committed_offset: string | number; pending_bytes: Uint8Array; next_sequence: string | number; rolling_hash: string; } + +export class LiveTraceRepository { + constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); } + + async cursor(runId: string): Promise { + const row = (await this.database.pool.query("SELECT generation,committed_offset,pending_bytes,next_sequence,rolling_hash FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId])).rows[0]; + 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) { + 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 => { + 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) { + if (chunk.startOffset !== 0) throw new Error("Trace generation changed; restart at offset zero"); + if ((cursor?.generation ?? null) !== chunk.expectedGeneration) throw new Error("Stale trace generation transition"); + await client.query("DELETE FROM app.run_trace_events WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId]); + await client.query("DELETE FROM app.run_trace_chunks WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId]); + await client.query(`INSERT INTO app.run_trace_cursors(tenant_id,run_id,generation,committed_offset,pending_bytes,next_sequence,rolling_hash) + VALUES ($1,$2,$3,0,''::bytea,1,$4) ON CONFLICT (tenant_id,run_id) DO UPDATE SET generation=excluded.generation,committed_offset=0,pending_bytes=''::bytea,next_sequence=1,rolling_hash=excluded.rolling_hash,updated_at=now()`, [this.tenantId, runId, chunk.generation, ZERO_HASH]); + cursor = { generation: chunk.generation, committed_offset: 0, pending_bytes: new Uint8Array(), next_sequence: 1, rolling_hash: ZERO_HASH }; + } + const committed = Number(cursor.committed_offset), endOffset = chunk.startOffset + chunk.bytes.byteLength; + 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"); + 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}`); + if (chunk.previousHash !== cursor.rolling_hash) throw new Error("Trace chunk hash chain mismatch"); + + const pending = cursor.pending_bytes instanceof Uint8Array ? cursor.pending_bytes : new Uint8Array(cursor.pending_bytes as any); + const combined = new Uint8Array(pending.byteLength + chunk.bytes.byteLength); combined.set(pending); combined.set(chunk.bytes, pending.byteLength); + let boundary = combined.lastIndexOf(10), remainder = new Uint8Array(), complete = combined; + if (boundary < 0) { complete = new Uint8Array(); remainder = combined; } + else { complete = combined.slice(0, boundary + 1); remainder = combined.slice(boundary + 1); } + if (remainder.byteLength > 16 * 1024 * 1024) throw new Error("Incomplete trace record exceeds 16 MiB"); + const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete)); + 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}`); + await client.query("INSERT INTO app.run_trace_chunks(tenant_id,run_id,generation,start_offset,end_offset,chunk_sha256,previous_hash,rolling_hash) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", [this.tenantId, runId, chunk.generation, chunk.startOffset, endOffset, chunk.chunkSha256, chunk.previousHash, rollingHash]); + await client.query("UPDATE app.run_trace_cursors SET committed_offset=$3,pending_bytes=$4,next_sequence=$5,rolling_hash=$6,updated_at=now() WHERE tenant_id=$1 AND run_id=$2", [this.tenantId, runId, endOffset, remainder, nextSequence + events.length, rollingHash]); + return { offset: endOffset, rollingHash, duplicate: false, events: events.length }; + }); + } + + private async insertBatch(client: DatabaseClient, runId: string, items: TraceEvent[]) { + if (!items.length) return; + await client.query(`INSERT INTO app.run_trace_events(tenant_id,run_id,sequence,id,parent_id,event_type,role,title,preview_text,display_data,occurred_at) + SELECT $1,$2,x.sequence,x.id,x.parent_id,x.event_type,x.role,x.title,x.preview_text,x.display_data,x.occurred_at + FROM jsonb_to_recordset($3::jsonb) AS x(sequence bigint,id text,parent_id text,event_type text,role text,title text,preview_text text,display_data jsonb,occurred_at timestamptz)`, [this.tenantId, runId, JSON.stringify(items.map(item => ({ sequence: item.sequence, id: item.id, parent_id: item.parentId ?? null, event_type: item.type, role: item.role ?? null, title: item.title, preview_text: item.preview, display_data: item.display, occurred_at: item.occurredAt ?? null })))]); + } +} diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index 21fe1829..25d17aa0 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -9,6 +9,7 @@ import type { Database } from "./database"; import { RunRepository, type PersistedRun } from "./run-repository"; import { AutomationScheduler } from "./automation-scheduler"; import { agentDriver, type AgentKind } from "../agent-driver"; +import { LiveTraceRepository } from "./live-trace-repository"; export class RunScheduler { private runs: RunRepository; @@ -40,12 +41,13 @@ export class RunScheduler { private async poll(run: PersistedRun) { const backend = await this.backend(run); if (!run.executionHandle) throw new Error("Execution handle is missing"); const observation = await backend.inspect(run.executionHandle); - if (["running", "blocked", "stopping"].includes(observation.state)) return this.runs.schedulePoll(run, observation.state as "running" | "blocked" | "stopping"); + if (["running", "blocked", "stopping"].includes(observation.state)) { + if (backend instanceof ExeVmBackend) await this.collectTraceChunk(run, backend).catch(() => undefined); + return this.runs.schedulePoll(run, observation.state as "running" | "blocked" | "stopping"); + } let artifactState: "stored" | "partial" | "failed" = "stored", artifactError: string | undefined; if (backend instanceof ExeVmBackend) { - const agentKind = run.executionTarget.agentKind as AgentKind, locator = agentDriver(agentKind).launch(run.id, {}).artifacts; - const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path: "native/session.jsonl", contentType: "application/x-ndjson", provider: agentKind, format: "jsonl", nativeSessionId: agentKind === "codex" ? undefined : run.id, expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); - const collected = await backend.collectArtifact!(run.executionHandle, { discoverCommand: locator.discoverCommand, contentType: "application/x-ndjson", uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` }); + const collected = await this.collectArtifact(run, backend); if (!collected.ok) { await this.runs.retryFinalization(run, "failed", collected.detail ?? "Native session upload failed"); return; } const stopped = await backend.stop(run.executionHandle); if (stopped.state !== "stopped") { await this.runs.retryFinalization(run, "stored", stopped.detail ?? "VM deletion failed after artifact upload"); return; } @@ -54,5 +56,20 @@ export class RunScheduler { await this.runs.terminal(run, state, artifactState, artifactError); } + private async collectArtifact(run: PersistedRun, backend: ExeVmBackend) { + if (!run.executionHandle) throw new Error("Execution handle is missing"); + const agentKind = run.executionTarget.agentKind as AgentKind, locator = agentDriver(agentKind).launch(run.id, {}).artifacts; + const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path: "native/session.jsonl", contentType: "application/x-ndjson", provider: agentKind, format: "jsonl", nativeSessionId: agentKind === "codex" ? undefined : run.id, expiresAt: Date.now() + 10 * 60_000 }, this.env.SESSION_SIGNING_SECRET); + return backend.collectArtifact(run.executionHandle, { discoverCommand: locator.discoverCommand, contentType: "application/x-ndjson", uploadUrl: `${this.env.APP_ORIGIN}/internal/run-artifacts/${encodeURIComponent(token)}` }); + } + + private async collectTraceChunk(run: PersistedRun, backend: ExeVmBackend) { + if (!run.executionHandle) throw new Error("Execution handle is missing"); + const agentKind = run.executionTarget.agentKind as AgentKind, locator = agentDriver(agentKind).launch(run.id, {}).artifacts; + const cursor = await new LiveTraceRepository(this.database, run.tenantId).cursor(run.id); + const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path: "native/live.jsonl", contentType: "application/octet-stream", provider: agentKind, format: "jsonl", nativeSessionId: agentKind === "codex" ? undefined : run.id, purpose: "trace_chunk", expiresAt: Date.now() + 60_000 }, this.env.SESSION_SIGNING_SECRET); + return backend.collectTraceChunk(run.executionHandle, { discoverCommand: locator.discoverCommand, generation: cursor.generation, offset: cursor.offset, previousHash: cursor.rollingHash, uploadUrl: `${this.env.APP_ORIGIN}/internal/run-trace-chunks/${encodeURIComponent(token)}` }); + } + private async fail(run: PersistedRun, error: unknown) { await this.runs.terminal(run, "failed", "failed", error instanceof Error ? error.message : "Run processing failed"); } } diff --git a/packages/app/src/trace-chunk-upload.ts b/packages/app/src/trace-chunk-upload.ts new file mode 100644 index 00000000..ef40a2e2 --- /dev/null +++ b/packages/app/src/trace-chunk-upload.ts @@ -0,0 +1,24 @@ +import { readArtifactUploadGrant } from "./artifact-upload"; +import { databaseFor } from "./postgres/database"; +import { LiveTraceRepository } from "./postgres/live-trace-repository"; +import type { Env } from "./types"; + +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" } }); + const grant = await readArtifactUploadGrant(token, env.SESSION_SIGNING_SECRET); + if (!grant || grant.purpose !== "trace_chunk") return new Response("Invalid or expired trace upload grant", { status: 401 }); + const generation = request.headers.get("X-Trace-Generation") ?? "", expectedGeneration = request.headers.get("X-Trace-Expected-Generation"), startOffset = Number(request.headers.get("X-Trace-Start")); + const chunkSha256 = request.headers.get("X-Trace-SHA256") ?? "", previousHash = request.headers.get("X-Trace-Previous-Hash") ?? ""; + const size = Number(request.headers.get("Content-Length")); + if (!generation || generation.length > 200 || !Number.isSafeInteger(startOffset) || startOffset < 0 || !HASH.test(chunkSha256) || !HASH.test(previousHash) || !Number.isSafeInteger(size) || size < 1 || size > 4 * 1024 * 1024) return new Response("Invalid trace chunk metadata", { status: 400 }); + 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 }); + return Response.json(result, { status: result.duplicate ? 200 : 201 }); + } catch (error) { + 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") ? 409 : 400 }); + } +} diff --git a/packages/app/src/worker.ts b/packages/app/src/worker.ts index 9e3561f6..556cbe06 100644 --- a/packages/app/src/worker.ts +++ b/packages/app/src/worker.ts @@ -6,6 +6,7 @@ import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegis import type { Env, OAuthProps } from "./types"; import { authenticateAccessToken } from "./access-tokens"; import { artifactUpload } from "./artifact-upload"; +import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; @@ -77,6 +78,8 @@ export { AlarmCoordinator } from "./alarm-coordinator"; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { const oauth = provider(env); const url = new URL(request.url); + const traceChunkMatch = url.pathname.match(/^\/internal\/run-trace-chunks\/([^/]+)$/); + if (traceChunkMatch) return traceChunkUpload(request, env, decodeURIComponent(traceChunkMatch[1]!)); const artifactMatch = url.pathname.match(/^\/internal\/run-artifacts\/([^/]+)$/); if (artifactMatch) return artifactUpload(request, env, decodeURIComponent(artifactMatch[1]!)); if (url.pathname.startsWith("/api/v1") && !request.headers.has("Authorization")) { diff --git a/packages/app/test/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index af808a1c..217b742e 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -86,6 +86,36 @@ describe("ExeVmBackend", () => { expect(requests.every(request => !request.includes("factorize.status"))).toBe(true); }); + it("uploads an immutable snapshot of a session that may still be growing", async () => { + let request = ""; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + request = String(init.body); + return new Response("uploaded", { headers: { "X-Exe-Exit": "0" } }); + })); + const result = await new ExeVmBackend(connection).collectArtifact( + { backendKind: "exe-vm", id: "factorize-run-1" }, + { discoverCommand: "find sessions -name '*.jsonl' | head -1", contentType: "application/x-ndjson", uploadUrl: "https://app.example/upload" }, + ); + expect(result.ok).toBe(true); + expect(request).toContain("snapshot=$(mktemp)"); + expect(request).toContain('cp "$file" "$snapshot"'); + expect(request).toContain('--data-binary @"$snapshot"'); + }); + + it("uploads only the uncommitted byte range for a live trace", async () => { + let request = ""; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { request = String(init.body); return new Response("uploaded", { headers: { "X-Exe-Exit": "0" } }); })); + const result = await new ExeVmBackend(connection).collectTraceChunk( + { backendKind: "exe-vm", id: "factorize-run-1" }, + { discoverCommand: "find sessions -name '*.jsonl' | head -1", generation: "1:2:3", offset: 1234, previousHash: "a".repeat(64), uploadUrl: "https://app.example/chunk" }, + ); + expect(result.ok).toBe(true); + expect(request).toContain("start=1234"); + expect(request).toContain("iflag=skip_bytes,count_bytes"); + expect(request).toContain("X-Trace-Expected-Generation: 1:2:3"); + expect(request).toContain("X-Trace-Previous-Hash: $previous"); + }); + it("rejects an HTTP-successful launch whose shell did not acknowledge startup", async () => { const requests: string[] = []; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { diff --git a/packages/app/test/postgres-live-trace-repository.test.ts b/packages/app/test/postgres-live-trace-repository.test.ts new file mode 100644 index 00000000..fb8ebc14 --- /dev/null +++ b/packages/app/test/postgres-live-trace-repository.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { LiveTraceRepository } from "../src/postgres/live-trace-repository"; + +const digest = async (value: string) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)))].map(x => x.toString(16).padStart(2, "0")).join(""); +const zero = "0".repeat(64); + +function fakeDatabase() { + let cursor: any = null; + const chunks = new Map(), events: any[] = []; + const query = async (sql: string, values: any[] = []) => { + 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 }; } + if (sql.startsWith("DELETE FROM app.run_trace_chunks")) { chunks.clear(); return { rows: [], rowCount: 0 }; } + if (sql.startsWith("INSERT INTO app.run_trace_cursors")) { cursor = { generation: values[2], committed_offset: 0, pending_bytes: new Uint8Array(), next_sequence: 1, rolling_hash: values[3] }; return { rows: [], rowCount: 1 }; } + if (sql.startsWith("SELECT chunk_sha256")) { const row = chunks.get(`${values[2]}:${values[3]}`); return { rows: row ? [row] : [], rowCount: row ? 1 : 0 }; } + if (sql.startsWith("INSERT INTO app.run_trace_events")) { events.push(...JSON.parse(values[2])); return { rows: [], rowCount: 1 }; } + if (sql.startsWith("INSERT INTO app.run_trace_chunks")) { chunks.set(`${values[2]}:${values[3]}`, { end_offset: values[4], chunk_sha256: values[5], previous_hash: values[6], rolling_hash: values[7] }); return { rows: [], rowCount: 1 }; } + if (sql.startsWith("UPDATE app.run_trace_cursors")) { cursor = { ...cursor, committed_offset: values[2], pending_bytes: values[3], next_sequence: values[4], rolling_hash: values[5] }; return { rows: [], rowCount: 1 }; } + throw new Error(`Unexpected query: ${sql}`); + }; + return { database: { pool: { query }, transaction: (work: any) => work({ query }) } as any, state: () => ({ cursor, chunks, events }) }; +} + +describe("LiveTraceRepository", () => { + it("atomically carries partial records across idempotent chunks", async () => { + const fake = fakeDatabase(), repository = new LiveTraceRepository(fake.database, "tenant-1"); + const firstText = '{"type":"session_meta","payload":{"id":"s1"}', first = new TextEncoder().encode(firstText); + const firstResult = await repository.append("run-1", "codex", { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await digest(firstText), previousHash: zero, bytes: first }); + expect(firstResult.events).toBe(0); + expect(fake.state().cursor.pending_bytes).toEqual(first); + + const duplicate = await repository.append("run-1", "codex", { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await digest(firstText), previousHash: zero, bytes: first }); + expect(duplicate.duplicate).toBe(true); + + const secondText = '}\n', second = new TextEncoder().encode(secondText); + const secondResult = await repository.append("run-1", "codex", { generation: "file-1", expectedGeneration: "file-1", startOffset: first.byteLength, chunkSha256: await digest(secondText), previousHash: firstResult.rollingHash, bytes: second }); + expect(secondResult.events).toBe(1); + expect(fake.state().events).toMatchObject([{ sequence: 1, event_type: "metadata", id: "s1" }]); + expect(fake.state().cursor.pending_bytes).toHaveLength(0); + }); + + it("rejects stale generation changes instead of rolling the cursor back", async () => { + const fake = fakeDatabase(), repository = new LiveTraceRepository(fake.database, "tenant-1"), bytes = new TextEncoder().encode("{}\n"), hash = await digest("{}\n"); + await repository.append("run-1", "codex", { generation: "file-2", expectedGeneration: null, startOffset: 0, chunkSha256: hash, previousHash: zero, bytes }); + await expect(repository.append("run-1", "codex", { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: hash, previousHash: zero, bytes })).rejects.toThrow("Stale trace generation transition"); + }); +});