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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/app/migrations/0003_incremental_trace_ingestion.sql
Original file line number Diff line number Diff line change
@@ -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;
3 changes: 2 additions & 1 deletion packages/app/src/artifact-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface ArtifactUploadGrant {
provider: "codex" | "claude" | "pi";
format: "jsonl";
nativeSessionId?: string;
purpose?: "artifact" | "trace_chunk";
expiresAt: number;
}

Expand Down Expand Up @@ -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 });
Expand Down
9 changes: 8 additions & 1 deletion packages/app/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ExecutionObservation> {
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 };
Expand Down
68 changes: 68 additions & 0 deletions packages/app/src/postgres/live-trace-repository.ts
Original file line number Diff line number Diff line change
@@ -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<LiveTraceCursor> {
const row = (await this.database.pool.query<CursorRow>("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<CursorRow>("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 })))]);
}
}
25 changes: 21 additions & 4 deletions packages/app/src/postgres/run-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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; }
Expand All @@ -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"); }
}
24 changes: 24 additions & 0 deletions packages/app/src/trace-chunk-upload.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
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 });
}
}
Loading
Loading