diff --git a/docs/execution-trace-stream.md b/docs/execution-trace-stream.md new file mode 100644 index 00000000..0305dac9 --- /dev/null +++ b/docs/execution-trace-stream.md @@ -0,0 +1,46 @@ +# Execution trace stream contract + +An agent launch may declare `traceSources.primary` with `kind: execution_stream`, +an absolute guest `path`, `mediaType: application/x-ndjson`, and its `provider`. +`formatVersion`, `cliVersion`, and `harnessVersion` identify the producing harness +when known. Declare the native audit session separately as `nativeSession`; +native discovery commands remain supported. Existing drivers declare a native +primary until GEN-2137/2138/2139 implement their stream producers. + +Execution streams contain UTF-8, newline-terminated JSON objects in append order: + +```json +{"version":1,"id":"event-1","type":"assistant_message","title":"Assistant","preview":"Hello","display":{}} +``` + +Required fields: `version` (1), `id`, `type`, `title`, `preview`. Optional fields: +`parentId`, `role`, `occurredAt` (ISO timestamp), `display` (object). Event types +match `TraceEventType` in `packages/app/src/trace.ts`. Sequence is assigned by the +projection, never trusted from the producer. Producers must append whole records +and finish each with LF. They must write human stdout/stderr to their separate +supervisor logs, never to the stream. The supervisor creates the stream directory +and file without truncating it; the harness owns JSONL serialization. + +The backend tails the declared primary file in bounded byte chunks. PostgreSQL +commits offset, pending bytes, events and hash-chain receipt atomically. An +incomplete trailing line waits for a later chunk; terminal reconciliation ignores +an unterminated trailing line, preserving it in the exact artifact. Invalid +complete execution records reject the chunk/projection rather than create events. +Retries use the same generation, offset and hash. Rename rotation starts a new +projection generation; observable same-inode truncation does likewise. Producers +must use rename rotation, never truncate and regrow between polls: an unobserved +rewrite violates the append-only contract. File descriptors pin the file identity +during each read, avoiding rename/read races. + +At termination (including process failure), the exact stream snapshot is uploaded +to `trace/.jsonl`, separately from `native/session.jsonl`. Reprojection +reads that durable snapshot. Its stored artifact receipt and final projection +commit together under the same run lock as live ingestion. Later chunks are +rejected, terminal retries cannot replace the snapshot with different bytes, and +native audit uploads cannot overwrite its projection. Failed collection is retried +and ultimately reported as partial using the existing finalization policy. + +Launch source declarations are persisted on the run (`trace_sources`), exposed +by run detail and diagnostics. Artifact rows retain source kind, guest path, +media type, provider, format/CLI/harness versions where supplied. Historical +native-only runs still use their existing provider parser and artifact semantics. diff --git a/packages/app/migrations/0010_trace_sources.sql b/packages/app/migrations/0010_trace_sources.sql new file mode 100644 index 00000000..7c0b6523 --- /dev/null +++ b/packages/app/migrations/0010_trace_sources.sql @@ -0,0 +1,6 @@ +ALTER TABLE app.run_artifacts DROP CONSTRAINT IF EXISTS run_artifacts_kind_check; +ALTER TABLE app.run_artifacts ADD CONSTRAINT run_artifacts_kind_check CHECK (kind IN ('execution_stream','native_session','related_session','terminal_log','manifest')); +ALTER TABLE app.run_artifacts ADD COLUMN source_path text; +ALTER TABLE app.run_artifacts ADD COLUMN media_type text; +ALTER TABLE app.run_artifacts ADD COLUMN harness_version text; +ALTER TABLE app.runs ADD COLUMN trace_sources jsonb; diff --git a/packages/app/src/agent-driver.ts b/packages/app/src/agent-driver.ts index fd87b95b..5f25ccb2 100644 --- a/packages/app/src/agent-driver.ts +++ b/packages/app/src/agent-driver.ts @@ -1,3 +1,4 @@ +import type { TraceSources } from "./trace-source"; export type AgentKind = "codex" | "claude" | "pi"; export interface AgentConfiguration { model?: string; effort?: string; } @@ -15,6 +16,7 @@ export interface AgentLaunchSpec { env: Record; stdin: "prompt"; artifacts: ArtifactLocator; + traceSources?: TraceSources; } export interface AgentDriver { readonly kind: AgentKind; @@ -53,4 +55,12 @@ class PiDriver implements AgentDriver { } const drivers: Record = { codex: new CodexDriver(), claude: new ClaudeDriver(), pi: new PiDriver() }; -export function agentDriver(kind: AgentKind): AgentDriver { return drivers[kind]; } +export function agentDriver(kind: AgentKind): AgentDriver { + const driver = drivers[kind]; + return { kind, launch(runId, config) { const spec = driver.launch(runId, config); return { ...spec, traceSources: driverTraceSources(kind, spec) }; } }; +} + +/** Compatibility for drivers and historical runs that only declare native sessions. */ +export function driverTraceSources(kind: AgentKind, launch: AgentLaunchSpec): TraceSources { + return launch.traceSources ?? { primary: { kind: "native_session", path: launch.artifacts.roots[0], mediaType: "application/x-ndjson", provider: kind, discoverCommand: launch.artifacts.discoverCommand } }; +} diff --git a/packages/app/src/artifact-upload.ts b/packages/app/src/artifact-upload.ts index b775a479..c5744580 100644 --- a/packages/app/src/artifact-upload.ts +++ b/packages/app/src/artifact-upload.ts @@ -1,3 +1,4 @@ +import type { DatabaseClient } from "./postgres/database"; import { artifactKey } from "./artifacts"; import { hmac } from "./crypto"; import type { Env } from "./types"; @@ -13,6 +14,12 @@ export interface ArtifactUploadGrant { provider: "codex" | "claude" | "pi"; format: "jsonl"; nativeSessionId?: string; + sourceKind?: "execution_stream" | "native_session"; + sourcePath?: string; + formatVersion?: string; + cliVersion?: string; + harnessVersion?: string; + primary?: boolean; purpose?: "artifact" | "trace_chunk"; expiresAt: number; } @@ -37,6 +44,7 @@ export async function readArtifactUploadGrant(token: string, secret: string, now try { const value = JSON.parse(fromB64url(payload)) as ArtifactUploadGrant; if (!value.tenantId || !value.runId || !value.path || !value.contentType || !Number.isSafeInteger(value.expiresAt) || value.expiresAt < now) return null; + if (value.sourceKind && !["execution_stream", "native_session"].includes(value.sourceKind)) return null; artifactKey(value.tenantId, value.runId, value.path); return value; } catch { return null; } @@ -54,11 +62,28 @@ 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 }); - const key = artifactKey(grant.tenantId, grant.runId, grant.path); + // 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 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"); + if (grant.sourceKind === "execution_stream" && terminal && terminal.sha256 !== sha256) return new Response("Terminal trace stream is immutable", { status: 409 }); const object = await env.RUN_ARTIFACTS.put(key, request.body, { httpMetadata: { contentType: grant.contentType }, customMetadata: { tenantId: grant.tenantId, runId: grant.runId }, sha256 }); - await new ArtifactRepository(databaseFor(env), grant.tenantId).record({ runId: grant.runId, kind: "native_session", objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }); + const record = (client: DatabaseClient) => repository.record({ runId: grant.runId, kind: grant.sourceKind ?? "native_session", sourcePath: grant.sourcePath, mediaType: grant.contentType, harnessVersion: grant.harnessVersion, formatVersion: grant.formatVersion, cliVersion: grant.cliVersion, objectKey: key, provider: grant.provider, format: grant.format, nativeSessionId: grant.nativeSessionId, byteSize: size, sha256 }, client); const stored = await env.RUN_ARTIFACTS.get(key); if (!stored) return new Response("Artifact disappeared after upload", { status: 502 }); - await new TraceRepository(databaseFor(env), grant.tenantId).replaceStream(grant.runId, grant.provider, stored.body); + const database = databaseFor(env); + 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]; + 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; + 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); + await record(client); + return false; + }); + if (conflict) return new Response("Terminal trace stream is immutable", { status: 409 }); return Response.json({ key, etag: object.httpEtag }, { status: 201 }); } diff --git a/packages/app/src/artifacts.ts b/packages/app/src/artifacts.ts index 45c55e06..ab26bfd9 100644 --- a/packages/app/src/artifacts.ts +++ b/packages/app/src/artifacts.ts @@ -1,4 +1,4 @@ -export type ArtifactKind = "native_session" | "related_session" | "terminal_log" | "manifest"; +export type ArtifactKind = "execution_stream" | "native_session" | "related_session" | "terminal_log" | "manifest"; export type ArtifactState = "pending" | "collecting" | "stored" | "partial" | "failed"; export interface RunArtifact { @@ -10,6 +10,9 @@ export interface RunArtifact { format: string; formatVersion?: string; cliVersion?: string; + harnessVersion?: string; + sourcePath?: string; + mediaType?: string; nativeSessionId?: string; byteSize: number; sha256: string; diff --git a/packages/app/src/exe-vm-backend.ts b/packages/app/src/exe-vm-backend.ts index aa8915ee..ac52d3a7 100644 --- a/packages/app/src/exe-vm-backend.ts +++ b/packages/app/src/exe-vm-backend.ts @@ -1,3 +1,5 @@ +import { sourceCommand, validateTraceSources } from "./trace-source"; +import type { ArtifactCollectionRequest, TraceChunkCollectionRequest } from "./execution"; import type { BackendCommandResult, ExecutionBackend, ExecutionObservation, LaunchReceipt, LaunchRequest, RunHandle } from "./execution"; import { base64 } from "./crypto"; import { shellAtom, type ExeConnection, type ExeRunConnection } from "./exe"; @@ -89,6 +91,7 @@ export class ExeVmBackend implements ExecutionBackend { const connection = this.connection as ExeRunConnection; if (!connection.agentKind) throw new Error("The job is missing its agent configuration"); if (!request.harness) throw new Error("The run is missing its agent harness launch plan"); + if (request.traceSources) validateTraceSources(request.traceSources); const vm = vmNameFor(request.runId); const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim()); @@ -102,6 +105,7 @@ export class ExeVmBackend implements ExecutionBackend { "set -eu", "mkdir -p /home/exedev/workspace", "cd /home/exedev/workspace", + ...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []), `printf '%s' ${shellAtom(prompt)} | base64 -d > /tmp/factorize-prompt.md`, `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=file:/tmp/factorize-prompt.md --property=StandardOutput=append:${output} --property=StandardError=append:/tmp/factorize.stderr ${harnessCommand(request.harness)}; fi`, "echo started", @@ -155,15 +159,15 @@ export class ExeVmBackend implements ExecutionBackend { return result.ok ? result.body : null; } - async collectArtifact(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; contentType: string }) { - 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)}`; + async collectArtifact(handle: RunHandle, request: ArtifactCollectionRequest) { + const remote = `set -eu; file=$(${request.source ? sourceCommand(request.source) : 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 }; + return { ok: result.ok, detail: result.ok ? undefined : `Artifact 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 }) { + async collectTraceChunk(handle: RunHandle, request: TraceChunkCollectionRequest) { 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 remote = `set -eu; file=$(${request.source ? sourceCommand(request.source) : request.discoverCommand}); test -n "$file"; test -f "$file"; exec 3<"$file"; file=/proc/$$/fd/3; identity=$(stat -Lc '%d:%i:%W' "$file"); generation="$identity"; case ${shellAtom(expectedGeneration)} in "$identity":*) generation=${shellAtom(expectedGeneration)};; esac; 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" -lt "$start" ]; then generation="$identity:$(date +%s%N)"; start=0; previous=${shellAtom(zeroHash)}; fi; 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 }; } diff --git a/packages/app/src/execution.ts b/packages/app/src/execution.ts index 2339973f..20986b50 100644 --- a/packages/app/src/execution.ts +++ b/packages/app/src/execution.ts @@ -1,3 +1,4 @@ +import type { TraceSource, TraceSources } from "./trace-source"; export type ExecutionState = "queued" | "starting" | "running" | "blocked" | "stopping" | "stopped" | "succeeded" | "failed"; export type ExecutionCapability = "output" | "prompt-delivery" | "recovery" | "stop"; export type PromptDeliveryState = "pending" | "submitting" | "accepted" | "ambiguous" | "failed"; @@ -13,6 +14,7 @@ export interface BackendCommandResult { export interface LaunchRequest { runId: string; prompt: string; + traceSources?: TraceSources; harness?: { executable: string; args: string[]; env: Record }; } @@ -38,6 +40,8 @@ export interface PromptDeliveryReceipt { state: Exclude; command?: BackendCommandResult; } +export interface ArtifactCollectionRequest { uploadUrl: string; contentType: string; source?: TraceSource; discoverCommand?: string; } +export interface TraceChunkCollectionRequest { uploadUrl: string; source?: TraceSource; discoverCommand?: string; generation: string | null; offset: number; previousHash: string; } export interface ArtifactCollectionReceipt { ok: boolean; detail?: string; command?: BackendCommandResult; } /** Provider-neutral boundary. Output and recovery are opt-in capabilities. */ @@ -49,7 +53,8 @@ export interface ExecutionBackend { stop(handle: RunHandle): Promise; deliverPrompt?(handle: RunHandle, prompt: string): Promise; readOutput?(handle: RunHandle): Promise; - collectArtifact?(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; contentType: string }): Promise; + collectArtifact?(handle: RunHandle, request: ArtifactCollectionRequest): Promise; + collectTraceChunk?(handle: RunHandle, request: TraceChunkCollectionRequest): Promise; } /** Maps persisted execution states onto the public contract. */ diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 40b6d61b..971c005c 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -86,9 +86,9 @@ 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.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.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, 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); 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 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/artifact-repository.ts b/packages/app/src/postgres/artifact-repository.ts index 29207f6d..b84f807d 100644 --- a/packages/app/src/postgres/artifact-repository.ts +++ b/packages/app/src/postgres/artifact-repository.ts @@ -1,20 +1,21 @@ import type { ArtifactKind, ArtifactState } from "../artifacts"; -import type { Database } from "./database"; +import type { Database, DatabaseClient } from "./database"; import { and, eq } from "drizzle-orm"; import { runArtifacts, runs } from "./schema"; export class ArtifactRepository { constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); } - async record(input: { runId: string; kind: ArtifactKind; objectKey: string; provider: string; format: string; formatVersion?: string; cliVersion?: string; nativeSessionId?: string; byteSize: number; sha256: string; state?: ArtifactState }) { + async record(input: { runId: string; kind: ArtifactKind; objectKey: string; provider: string; format: string; formatVersion?: string; cliVersion?: string; nativeSessionId?: string; sourcePath?: string; mediaType?: string; harnessVersion?: string; byteSize: number; sha256: string; state?: ArtifactState }, client?: DatabaseClient) { const id = crypto.randomUUID(); - await this.database.transaction(async client => { - await client.query(`INSERT INTO app.run_artifacts(tenant_id,run_id,id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13) - ON CONFLICT (tenant_id,object_key) DO UPDATE SET byte_size=excluded.byte_size,sha256=excluded.sha256,state=excluded.state`, [this.tenantId, input.runId, id, input.kind, input.objectKey, input.provider, input.format, input.formatVersion ?? null, input.cliVersion ?? null, input.nativeSessionId ?? null, input.byteSize, input.sha256, input.state ?? "stored"]); + const write = async (client: DatabaseClient) => { + await client.query(`INSERT INTO app.run_artifacts(tenant_id,run_id,id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,source_path,media_type,harness_version) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16) + ON CONFLICT (tenant_id,object_key) DO UPDATE SET byte_size=excluded.byte_size,sha256=excluded.sha256,state=excluded.state`, [this.tenantId, input.runId, id, input.kind, input.objectKey, input.provider, input.format, input.formatVersion ?? null, input.cliVersion ?? null, input.nativeSessionId ?? null, input.byteSize, input.sha256, input.state ?? "stored", input.sourcePath ?? null, input.mediaType ?? null, input.harnessVersion ?? null]); await client.query("UPDATE app.runs SET artifact_state='stored',updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, input.runId]); - }); + }; + if (client) await write(client); else await this.database.transaction(write); } - async list(runId: string) { return (await this.database.pool.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } + async list(runId: string, client: DatabaseClient = this.database.pool) { return (await client.query("SELECT id,kind,object_key,provider,format,format_version,cli_version,native_session_id,byte_size,sha256,state,source_path,media_type,harness_version,created_at FROM app.run_artifacts WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } async keysForJob(jobId: string): Promise { const rows = await this.database.orm.select({ key: runArtifacts.objectKey }).from(runArtifacts).innerJoin(runs, and(eq(runs.tenantId, runArtifacts.tenantId), eq(runs.id, runArtifacts.runId))).where(and(eq(runArtifacts.tenantId, this.tenantId), eq(runs.jobId, jobId))); return rows.map(row => row.key); diff --git a/packages/app/src/postgres/live-trace-repository.ts b/packages/app/src/postgres/live-trace-repository.ts index 53084b44..d8bfd304 100644 --- a/packages/app/src/postgres/live-trace-repository.ts +++ b/packages/app/src/postgres/live-trace-repository.ts @@ -1,3 +1,4 @@ +import type { TraceSource } from "../trace-source"; import { parseTrace, type TraceEvent } from "../trace"; import type { Database, DatabaseClient } from "./database"; @@ -19,11 +20,14 @@ 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) { + async append(runId: string, provider: "codex" | "claude" | "pi", chunk: TraceChunk, sourceKind: TraceSource["kind"] = "native_session") { 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; + 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) { if (chunk.startOffset !== 0) throw new Error("Trace generation changed; restart at offset zero"); @@ -49,7 +53,14 @@ export class LiveTraceRepository { 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)); + if (sourceKind === "execution_stream") { + let start = 0; + for (let index = 0; index < complete.length; index++) if (complete[index] === 10) { + if (index - start > 16 * 1024 * 1024) throw new Error("Execution stream record exceeds 16 MiB"); + start = index + 1; + } + } + const parsed = parseTrace(provider, new TextDecoder("utf-8", { fatal: true }).decode(complete), sourceKind); 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-repository.ts b/packages/app/src/postgres/run-repository.ts index bb3760a7..84d5cac6 100644 --- a/packages/app/src/postgres/run-repository.ts +++ b/packages/app/src/postgres/run-repository.ts @@ -1,3 +1,4 @@ +import type { TraceSources } from "../trace-source"; import { terminalDiagnostics, safeDiagnosticText, type ExecutionDiagnostics } from "../harness-diagnostics"; import type { ExecutionObservation } from "../execution"; import type { ExecutionState, RunHandle } from "../execution"; @@ -33,7 +34,7 @@ export class RunRepository { ), claimed AS ( UPDATE app.job_runs r SET state='starting',launch_lease_expires_at=now()+interval '5 minutes',updated_at=now() FROM candidate c WHERE r.tenant_id=c.tenant_id AND r.id=c.id RETURNING r.* - ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,c.created_at,c.updated_at + ) SELECT c.tenant_id,c.id,c.job_id,c.invocation_id,c.state,c.encrypted_prompt,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort,'traceSources',x.trace_sources) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,c.created_at,c.updated_at FROM claimed c JOIN app.jobs j ON j.tenant_id=c.tenant_id AND j.id=c.job_id JOIN app.runs x ON x.tenant_id=c.tenant_id AND x.id=c.id`, []); const row = result.rows[0]; if (!row) return null; @@ -43,16 +44,16 @@ export class RunRepository { } async dueForPoll(limit = 40): Promise { - const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,r.created_at,r.updated_at + const result = await this.database.pool.query(`SELECT r.tenant_id,r.id,r.job_id,r.invocation_id,r.state,r.encrypted_prompt,j.execution_target || jsonb_build_object('model',j.model,'effort',j.effort,'traceSources',x.trace_sources) execution_target,x.execution_handle,x.execution_backend_kind,x.execution_capabilities,x.execution_diagnostics,x.vm_cleanup_attempt,x.artifact_state,r.created_at,r.updated_at FROM app.job_runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.runs x ON x.tenant_id=r.tenant_id AND x.id=r.id WHERE r.state IN ('running','blocked','stopping') AND (r.next_poll_at IS NULL OR r.next_poll_at<=now()) ORDER BY r.next_poll_at NULLS FIRST,r.updated_at LIMIT $1`, [limit]); return result.rows.map(mapped); } - async markLaunched(run: PersistedRun, handle: RunHandle, destinationUrl: string, capabilities: readonly string[]): Promise { + async markLaunched(run: PersistedRun, handle: RunHandle, destinationUrl: string, capabilities: readonly string[], traceSources?: TraceSources): Promise { await this.database.transaction(async client => { await client.query("UPDATE app.job_runs SET state='running',started_at=COALESCE(started_at,now()),launch_lease_expires_at=NULL,next_poll_at=now()+interval '3 seconds',updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id]); - await client.query("UPDATE app.runs SET state='running',execution_handle=$3,execution_backend_kind=$4,execution_capabilities=$5,destination_url=$6,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, handle, handle.backendKind, JSON.stringify(capabilities), destinationUrl]); + await client.query("UPDATE app.runs SET state='running',execution_handle=$3,execution_backend_kind=$4,execution_capabilities=$5,destination_url=$6,trace_sources=$7,updated_at=now() WHERE tenant_id=$1 AND id=$2", [run.tenantId, run.id, handle, handle.backendKind, JSON.stringify(capabilities), destinationUrl, traceSources ? JSON.stringify(traceSources) : null]); }); } diff --git a/packages/app/src/postgres/run-scheduler.ts b/packages/app/src/postgres/run-scheduler.ts index a44edcdb..62071f22 100644 --- a/packages/app/src/postgres/run-scheduler.ts +++ b/packages/app/src/postgres/run-scheduler.ts @@ -1,3 +1,4 @@ +import { validateTraceSources, type TraceSource, type TraceSources } from "../trace-source"; import { AmpBackend, type AmpConnection } from "../amp-backend"; import { issueArtifactUploadGrant } from "../artifact-upload"; import { artifactKey } from "../artifacts"; @@ -11,7 +12,7 @@ import { ConnectionRepository } from "./connection-repository"; 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 { agentDriver, driverTraceSources, type AgentKind } from "../agent-driver"; import { LiveTraceRepository } from "./live-trace-repository"; export class RunScheduler { @@ -35,8 +36,10 @@ 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 launched = await backend.launch({ runId: run.id, prompt: await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY), harness: { executable: harness.executable, args: harness.args, env: harness.env } }); - await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities); + const sources = driverTraceSources(driver.kind, harness); + 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); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } @@ -60,6 +63,13 @@ export class RunScheduler { try { await this.collectHarnessLog(run, backend, artifacts); } catch { errors.push("Harness log collection or storage failed"); } } + const sources = this.sources(run); + if (sources.primary.kind === "execution_stream" && !stored.some(item => item.kind === "execution_stream" && item.state === "stored")) { + try { + const collected = await this.collectArtifact(run, backend, sources.primary, true); + if (!collected.ok) errors.push("Primary trace stream upload failed"); + } catch { errors.push("Primary trace stream collection or reconciliation failed"); } + } if (!stored.some(item => item.kind === "native_session" && item.state === "stored")) { try { const collected = await this.collectArtifact(run, backend); @@ -93,19 +103,25 @@ export class RunScheduler { await artifacts.record({ runId: run.id, kind: "terminal_log", objectKey: key, provider: String(run.executionTarget.agentKind), format: "text", byteSize: bytes.length, sha256 }); } - private async collectArtifact(run: PersistedRun, backend: ExeVmBackend) { + private sources(run: PersistedRun): TraceSources { + return run.executionTarget.traceSources ?? driverTraceSources(run.executionTarget.agentKind as AgentKind, agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {})); + } + + private async collectArtifact(run: PersistedRun, backend: ExeVmBackend, source?: TraceSource, primary?: boolean) { 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)}` }); + const sources = this.sources(run); + source ??= sources.nativeSession ?? (sources.primary.kind === "native_session" ? sources.primary : driverTraceSources(run.executionTarget.agentKind as AgentKind, agentDriver(run.executionTarget.agentKind as AgentKind).launch(run.id, {})).primary); + 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); + return backend.collectArtifact(run.executionHandle, { source, contentType: source.mediaType, 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 source = this.sources(run).primary; 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)}` }); + const token = await issueArtifactUploadGrant({ tenantId: run.tenantId, runId: run.id, path: "trace/live.jsonl", contentType: source.mediaType, provider: source.provider, format: "jsonl", sourceKind: source.kind, sourcePath: source.path, purpose: "trace_chunk", expiresAt: Date.now() + 60_000 }, this.env.SESSION_SIGNING_SECRET); + return backend.collectTraceChunk(run.executionHandle, { source, 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) { diff --git a/packages/app/src/postgres/schema.ts b/packages/app/src/postgres/schema.ts index bb953740..f7188a9f 100644 --- a/packages/app/src/postgres/schema.ts +++ b/packages/app/src/postgres/schema.ts @@ -52,10 +52,10 @@ export const jobRuns = app.table("job_runs", { }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`)]); export const runs = app.table("runs", { - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]); export const runArtifacts = app.table("run_artifacts", { - tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), id: uuid("id").notNull(), kind: text("kind").$type().notNull(), objectKey: text("object_key").notNull(), provider: text("provider").notNull(), format: text("format").notNull(), formatVersion: text("format_version"), cliVersion: text("cli_version"), nativeSessionId: text("native_session_id"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type().notNull(), createdAt: createdAt(), + tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), id: uuid("id").notNull(), kind: text("kind").$type().notNull(), objectKey: text("object_key").notNull(), provider: text("provider").notNull(), format: text("format").notNull(), formatVersion: text("format_version"), cliVersion: text("cli_version"), nativeSessionId: text("native_session_id"), sourcePath: text("source_path"), mediaType: text("media_type"), harnessVersion: text("harness_version"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type().notNull(), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.objectKey), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("run_artifacts_by_run").on(t.tenantId, t.runId, t.createdAt, t.id)]); export const runTraceEvents = app.table("run_trace_events", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), sequence: bigint("sequence", { mode: "number" }).notNull(), id: text("id").notNull(), parentId: text("parent_id"), eventType: text("event_type").notNull(), role: text("role"), title: text("title").notNull(), previewText: text("preview_text").notNull(), displayData: jsonb("display_data").$type>().notNull().default({}), occurredAt: timestamp("occurred_at", { withTimezone: true }), createdAt: createdAt(), searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', title || ' ' || preview_text)`), diff --git a/packages/app/src/postgres/trace-repository.ts b/packages/app/src/postgres/trace-repository.ts index 1c343845..51e1e811 100644 --- a/packages/app/src/postgres/trace-repository.ts +++ b/packages/app/src/postgres/trace-repository.ts @@ -1,3 +1,4 @@ +import type { TraceSource } from "../trace-source"; import { consumeTraceStream, type TraceEvent } from "../trace"; import type { Database, DatabaseClient } from "./database"; @@ -34,11 +35,12 @@ export class TraceRepository { }); } - async replaceStream(runId: string, provider: "codex" | "claude" | "pi", stream: ReadableStream): Promise { - return this.database.transaction(async client => { + 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)); - }); + return consumeTraceStream(provider, stream, items => this.insertBatch(client, runId, items), 250, sourceKind); + }; + return client ? project(client) : this.database.transaction(project); } private async insertBatch(client: DatabaseClient, runId: string, items: TraceEvent[]): Promise { diff --git a/packages/app/src/trace-chunk-upload.ts b/packages/app/src/trace-chunk-upload.ts index ef40a2e2..47c3620c 100644 --- a/packages/app/src/trace-chunk-upload.ts +++ b/packages/app/src/trace-chunk-upload.ts @@ -15,10 +15,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 }); + const result = await new LiveTraceRepository(databaseFor(env), grant.tenantId).append(grant.runId, grant.provider, { generation, expectedGeneration: expectedGeneration || null, startOffset, chunkSha256, previousHash, bytes }, grant.sourceKind); 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 }); + 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-source.ts b/packages/app/src/trace-source.ts new file mode 100644 index 00000000..9be2f4d9 --- /dev/null +++ b/packages/app/src/trace-source.ts @@ -0,0 +1,33 @@ +import { shellAtom } from "./exe"; + +/** A guest file, never a terminal log. Execution streams use Factorize JSONL v1. */ +export interface TraceSource { + kind: "execution_stream" | "native_session"; + path: string; + mediaType: "application/x-ndjson"; + provider: "codex" | "claude" | "pi"; + formatVersion?: string; + cliVersion?: string; + harnessVersion?: string; + /** Native sessions may require discovery; execution streams always use path. */ + discoverCommand?: string; +} +export interface TraceSources { primary: TraceSource; nativeSession?: TraceSource; } +export function sourceCommand(source: TraceSource): string { + if (source.kind === "native_session" && source.discoverCommand) return source.discoverCommand; + if (!source.path.startsWith("/") || source.path.includes("\n") || source.path.includes("\0") || source.path.split("/").some(part => part === ".." || part === ".")) throw new Error("Trace source requires an absolute guest path"); + return `printf '%s' ${shellAtom(source.path)}`; +} +export function validateTraceSources(sources: TraceSources): void { + for (const source of [sources.primary, sources.nativeSession].filter(Boolean) as TraceSource[]) { + sourceCommand(source); + if (source.mediaType !== "application/x-ndjson") throw new Error("Trace sources must be JSONL"); + if (!["execution_stream", "native_session"].includes(source.kind) || !["codex", "claude", "pi"].includes(source.provider)) throw new Error("Invalid trace source"); + if (source.kind === "execution_stream" && source.formatVersion && source.formatVersion !== "1") throw new Error("Unsupported execution stream version"); + } + if (sources.primary.kind === "execution_stream" && ["/tmp/factorize.log", "/tmp/factorize.stderr", "/tmp/factorize-prompt.md"].includes(sources.primary.path)) throw new Error("Trace stream path is reserved for JSONL only"); + if (sources.nativeSession) { + sourceCommand(sources.nativeSession); + 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"); + } +} diff --git a/packages/app/src/trace.ts b/packages/app/src/trace.ts index 68cbc720..a9b4977d 100644 --- a/packages/app/src/trace.ts +++ b/packages/app/src/trace.ts @@ -1,3 +1,4 @@ +import type { TraceSource } from "./trace-source"; export type TraceEventType = "user_message" | "assistant_message" | "reasoning" | "tool_call" | "tool_result" | "command" | "file_change" | "compaction" | "branch" | "usage" | "warning" | "error" | "metadata"; export interface TraceEvent { @@ -78,28 +79,63 @@ function parseClaude(value: any, sequence: number): TraceEvent[] { return value.type === "summary" ? [event(sequence, "compaction", "Context summary", value.summary, value)] : []; } -/** Parses a native JSONL artifact into bounded, provider-neutral display events. */ -export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string): TraceEvent[] { +/** Parses source JSONL into bounded, provider-neutral display events. */ +export function parseTrace(provider: "codex" | "claude" | "pi", jsonl: string, sourceKind: TraceSource["kind"] = "native_session"): TraceEvent[] { const events: TraceEvent[] = []; for (const line of jsonl.split(/\r?\n/)) { if (!line.trim()) continue; let value: unknown; - try { value = JSON.parse(line); } catch { events.push(event(events.length + 1, "warning", "Unparseable session record", line, {})); continue; } + try { value = JSON.parse(line); } catch { if (sourceKind === "execution_stream") throw new Error("Invalid execution stream JSON"); events.push(event(events.length + 1, "warning", "Unparseable session record", line, {})); continue; } + if (sourceKind === "execution_stream") { + const record = value as any; + if (!record || record.version !== 1 || typeof record.id !== "string" || typeof record.title !== "string" || typeof record.preview !== "string" || !["user_message", "assistant_message", "reasoning", "tool_call", "tool_result", "command", "file_change", "compaction", "branch", "usage", "warning", "error", "metadata"].includes(record.type)) throw new Error("Invalid execution stream record"); + if (record.occurredAt !== undefined && (typeof record.occurredAt !== "string" || !Number.isFinite(Date.parse(record.occurredAt)))) throw new Error("Invalid execution stream timestamp"); + events.push({ sequence: events.length + 1, id: record.id, type: record.type, title: clipped(record.title), preview: clipped(record.preview), ...(typeof record.parentId === "string" ? { parentId: record.parentId } : {}), ...(typeof record.role === "string" ? { role: record.role } : {}), ...(typeof record.occurredAt === "string" ? { occurredAt: record.occurredAt } : {}), display: record.display && typeof record.display === "object" && !Array.isArray(record.display) ? record.display : {} }); + continue; + } const parsed = provider === "codex" ? parseCodex(value, events.length + 1) : provider === "claude" ? parseClaude(value, events.length + 1) : parsePi(value, events.length + 1); events.push(...parsed); } return events.map((item, index) => ({ ...item, sequence: index + 1 })); } +/** Byte framing matches live ingestion, including an incomplete UTF-8 tail at exit. */ +async function consumeExecutionStream(provider: "codex" | "claude" | "pi", stream: ReadableStream, consumeBatch: (events: TraceEvent[]) => Promise, batchSize: number): Promise { + const reader = stream.getReader(), decoder = new TextDecoder("utf-8", { fatal: true }); + let pending = new Uint8Array(), sequence = 0, batch: TraceEvent[] = []; + const flush = async () => { if (batch.length) { const ready = batch; batch = []; await consumeBatch(ready); } }; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; // Preserve, but never project, an unterminated record. + const combined = new Uint8Array(pending.length + value.length); + combined.set(pending); combined.set(value, pending.length); + let start = 0; + for (let index = 0; index < combined.length; index++) { + if (combined[index] !== 10) continue; + if (index - start > 16 * 1024 * 1024) throw new Error("Execution stream record exceeds 16 MiB"); + const events = parseTrace(provider, decoder.decode(combined.subarray(start, index)), "execution_stream"); + for (const item of events) { batch.push({ ...item, sequence: ++sequence }); if (batch.length >= batchSize) await flush(); } + start = index + 1; + } + pending = combined.slice(start); + if (pending.length > 16 * 1024 * 1024) throw new Error("Execution stream record exceeds 16 MiB"); + } + await flush(); + return sequence; + } finally { reader.releaseLock(); } +} + /** Incrementally parses JSONL and emits bounded batches without loading the artifact or projection in full. */ -export async function consumeTraceStream(provider: "codex" | "claude" | "pi", stream: ReadableStream, consumeBatch: (events: TraceEvent[]) => Promise, batchSize = 250): Promise { +export async function consumeTraceStream(provider: "codex" | "claude" | "pi", stream: ReadableStream, consumeBatch: (events: TraceEvent[]) => Promise, batchSize = 250, sourceKind: TraceSource["kind"] = "native_session"): Promise { + if (sourceKind === "execution_stream") return consumeExecutionStream(provider, stream, consumeBatch, batchSize); const reader = stream.getReader(), decoder = new TextDecoder(); let batch: TraceEvent[] = [], sequence = 0; let pending = ""; const flush = async () => { if (!batch.length) return; const ready = batch; batch = []; await consumeBatch(ready); }; const consume = async (line: string) => { if (!line.trim()) return; - const parsed = parseTrace(provider, line); + const parsed = parseTrace(provider, line, sourceKind); for (const item of parsed) { batch.push({ ...item, sequence: ++sequence }); if (batch.length >= batchSize) await flush(); } }; for (;;) { @@ -110,7 +146,8 @@ export async function consumeTraceStream(provider: "codex" | "claude" | "pi", st if (done) break; if (pending.length > 16 * 1024 * 1024) { batch.push(event(++sequence, "warning", "Oversized session record", "A native JSONL record exceeded the 16 MiB trace parsing limit.", {})); pending = ""; if (batch.length >= batchSize) await flush(); } } - await consume(pending); await flush(); + await consume(pending); + await flush(); return sequence; } diff --git a/packages/app/test/artifact-upload.test.ts b/packages/app/test/artifact-upload.test.ts index 5f76e06b..584165c0 100644 --- a/packages/app/test/artifact-upload.test.ts +++ b/packages/app/test/artifact-upload.test.ts @@ -27,4 +27,33 @@ describe("artifact upload grants", () => { expect(response.status).toBe(400); expect(put).not.toHaveBeenCalled(); }); + it("stores and reprojects the primary copy while keeping native uploads separate", async () => { + const query = vi.fn(async (sql: string, _values?: any[]) => ({ rows: sql.startsWith("SELECT id,trace_sources") ? [{ trace_sources: { primary: { kind: "execution_stream" } } }] : [], rowCount: 1 })); + 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 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); + }; + expect((await upload(primary)).status).toBe(201); + expect(put.mock.calls[0][0]).toBe(`tenants/tenant-1/runs/run-1/trace/${"b".repeat(64)}.jsonl`); + const inserts = query.mock.calls.filter(([sql]) => sql.startsWith("INSERT INTO app.run_trace_events")); + expect(inserts).toHaveLength(1); + const recorded = query.mock.calls.find(([sql]) => sql.startsWith("INSERT INTO app.run_artifacts")); + expect((recorded as any)[1]).toEqual(expect.arrayContaining(["execution_stream", "/tmp/events.jsonl", "h1", "p1", "1"])); + 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"); + }); + 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 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/execution-backend.test.ts b/packages/app/test/execution-backend.test.ts index 415a674f..8912a262 100644 --- a/packages/app/test/execution-backend.test.ts +++ b/packages/app/test/execution-backend.test.ts @@ -43,7 +43,7 @@ describe("ExeVmBackend", () => { requests.push(String(init.body)); return new Response(requests.length === 1 ? '{"name":"factorize-run-1"}' : "started", { headers: { "X-Exe-Exit": "0" } }); })); - const launched = await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "do the work", harness: agentDriver("codex").launch("run-1", {}) }); + const launched = await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "do the work", harness: agentDriver("codex").launch("run-1", {}), traceSources: { primary: { kind: "execution_stream", path: "/tmp/trace/events.jsonl", mediaType: "application/x-ndjson", provider: "codex" } } }); expect(launched.handle).toEqual({ backendKind: "exe-vm", id: "factorize-run-1" }); expect(requests[0]).toContain("new --name='factorize-run-1'"); expect(requests[0]).toContain("--tag='github'"); @@ -62,6 +62,8 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("--property=StandardInput=file:/tmp/factorize-prompt.md"); expect(requests[1]).toContain("--property=StandardOutput=append:/tmp/factorize.log"); expect(requests[1]).toContain("--property=StandardError=append:/tmp/factorize.stderr"); + expect(requests[1]).toContain("/tmp/trace/events.jsonl"); + expect(requests[1]).not.toContain("StandardOutput=append:/tmp/trace/events.jsonl"); expect(requests[1]).not.toContain("nohup"); expect(requests[1]).toContain("; echo started"); expect(requests[1]).toContain("systemctl show"); diff --git a/packages/app/test/postgres-live-trace-repository.test.ts b/packages/app/test/postgres-live-trace-repository.test.ts index fb8ebc14..66c4327d 100644 --- a/packages/app/test/postgres-live-trace-repository.test.ts +++ b/packages/app/test/postgres-live-trace-repository.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { parseTrace, consumeTraceStream } from "../src/trace"; 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(""); @@ -8,6 +9,7 @@ function fakeDatabase() { let cursor: any = null; const chunks = new Map(), events: any[] = []; const query = async (sql: string, values: any[] = []) => { + 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 }; } if (sql.startsWith("DELETE FROM app.run_trace_chunks")) { chunks.clear(); return { rows: [], rowCount: 0 }; } @@ -44,4 +46,29 @@ describe("LiveTraceRepository", () => { 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"); }); + it("projects declared execution records live, retries safely, and agrees with terminal reconciliation", async () => { + const fake = fakeDatabase(), repository = new LiveTraceRepository(fake.database, "tenant-1"); + const record = JSON.stringify({ version: 1, id: "event-1", type: "assistant_message", title: "Assistant", preview: "hello 😀" }); + const text = `${record}\n{"version":1`, bytes = new TextEncoder().encode(text); + const split = bytes.indexOf(240) + 2; // split inside the multibyte emoji + const chunks = [bytes.slice(0, split), bytes.slice(split)]; + let offset = 0, previousHash = zero; + for (const bytes of chunks) { + const chunkSha256 = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map(x => x.toString(16).padStart(2, "0")).join(""); + const chunk = { generation: "file-1", expectedGeneration: offset ? "file-1" : null, startOffset: offset, chunkSha256, previousHash, bytes }; + const receipt = await repository.append("run-1", "codex", chunk, "execution_stream"); + expect((await repository.append("run-1", "codex", chunk, "execution_stream")).duplicate).toBe(true); + offset = receipt.offset; previousHash = receipt.rollingHash; + } + expect(fake.state().events).toMatchObject([{ id: "event-1", sequence: 1, event_type: "assistant_message", preview_text: "hello 😀" }]); + const terminal: any[] = []; + await consumeTraceStream("codex", new Response(bytes).body!, async items => { terminal.push(...items); }, 250, "execution_stream"); + expect(terminal).toEqual(parseTrace("codex", record, "execution_stream")); + expect(fake.state().events.length).toBe(terminal.length); + const rotated = new TextEncoder().encode(`${record}\n`); + await repository.append("run-1", "codex", { generation: "file-2", expectedGeneration: "file-1", startOffset: 0, chunkSha256: await digest(`${record}\n`), previousHash: zero, bytes: rotated }, "execution_stream"); + expect(fake.state().events).toHaveLength(1); + expect(fake.state().cursor.pending_bytes).toHaveLength(0); + }); + }); diff --git a/packages/app/test/postgres-run-repository.test.ts b/packages/app/test/postgres-run-repository.test.ts index f3504deb..adda1ef9 100644 --- a/packages/app/test/postgres-run-repository.test.ts +++ b/packages/app/test/postgres-run-repository.test.ts @@ -12,6 +12,17 @@ describe("RunRepository", () => { expect(calls.every(([sql]) => !sql.includes("created_at="))).toBe(true); }); + it("persists the source declaration at launch and reads it independently of current driver defaults", async () => { + const query = vi.fn(async (_sql: string, _values: unknown[]) => ({ rows: [], rowCount: 1 })); + const repository = new RunRepository({ transaction: (work: any) => work({ query }), pool: { query } } as any); + const sources = { primary: { kind: "execution_stream" as const, path: "/tmp/stream.jsonl", mediaType: "application/x-ndjson" as const, provider: "codex" as const, harnessVersion: "v1" } }; + await repository.markLaunched({ tenantId: "tenant", id: "run" } as any, { backendKind: "exe-vm", id: "factorize-run" }, "https://vm", [], sources); + expect(query.mock.calls[1][0]).toContain("trace_sources=$7"); + expect(query.mock.calls[1][1][6]).toBe(JSON.stringify(sources)); + await repository.dueForPoll(); + expect(query.mock.calls.at(-1)![0]).toContain("'traceSources',x.trace_sources"); + }); + it("claims queue work with row locking and persisted concurrency", async () => { const query = vi.fn(async (sql: string) => ({ rows: sql.includes("WITH candidate") ? [] : [], rowCount: 0 })); const database = { transaction: (work: any) => work({ query }), pool: { query } } as any; diff --git a/packages/app/test/run-diagnostics-contract.test.ts b/packages/app/test/run-diagnostics-contract.test.ts index 31079eea..dc528a9a 100644 --- a/packages/app/test/run-diagnostics-contract.test.ts +++ b/packages/app/test/run-diagnostics-contract.test.ts @@ -7,6 +7,7 @@ import { isDeclaredApiOperation } from "../src/api-contract"; afterEach(() => vi.restoreAllMocks()); const execution = { state: "failed", detail: "Process exited with status 42", systemd: { loadState: "loaded", activeState: "failed", subState: "failed", result: "exit-code", execMainCode: 1, execMainStatus: 42 } }; +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"]) { @@ -14,7 +15,7 @@ async function fixture(tenantId = "tenant", scopes = ["runs:read"]) { vi.spyOn(IdentityRepository.prototype, "member").mockResolvedValue({ role: "owner", sessionVersion: 1 } as any); const query = vi.fn(async (sql: string, values: any[]) => { if (values[0] !== "tenant") return { rows: [] }; - if (sql.includes("SELECT r.*")) return { rows: [{ id: "run", job_id: "job", state: "failed", encrypted_prompt: encryptedPrompt, execution_diagnostics: execution, execution_backend_kind: "exe-vm", artifact_state: "partial", artifact_error: "Native session upload failed" }] }; + if (sql.includes("SELECT r.*")) return { rows: [{ id: "run", job_id: "job", state: "failed", encrypted_prompt: encryptedPrompt, execution_diagnostics: execution, trace_sources: traceSources, execution_backend_kind: "exe-vm", artifact_state: "partial", artifact_error: "Native session upload failed" }] }; if (sql.includes("app.run_artifacts")) return { rows: [artifact] }; return { rows: [] }; }); @@ -26,9 +27,9 @@ describe("run diagnostics API boundary", () => { const service = await fixture(); expect(isDeclaredApiOperation("GET", "/api/v1/runs/run")).toBe(true); expect(isDeclaredApiOperation("GET", "/api/v1/runs/run/diagnostics")).toBe(true); - expect(await service.getRun("run")).toMatchObject({ execution_diagnostics: execution, harness_log: artifact }); + 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, harnessLog: artifact, artifact: { state: "partial", error: "Native session upload failed" } }); + expect(diagnostics).toMatchObject({ 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"); }); @@ -43,11 +44,11 @@ describe("run diagnostics API boundary", () => { const key = btoa("a".repeat(32)); vi.spyOn(RunQueryRepository.prototype, "get").mockResolvedValue({ id: "old", encrypted_prompt: await encrypt("", key) }); vi.spyOn(ArtifactRepository.prototype, "list").mockResolvedValue([]); - expect(await service.getRunDiagnostics("old")).toMatchObject({ execution: null, harnessLog: null }); + expect(await service.getRunDiagnostics("old")).toMatchObject({ execution: null, harnessLog: null, traceSources: null }); }); 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 ["execution_diagnostics", "harness_log", "execution:", "harnessLog:", "execMainCode", "execMainStatus", "activeState", "subState", "object_key"]) + for (const field of ["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/run-finalization.test.ts b/packages/app/test/run-finalization.test.ts index 58e65c6a..c051d06b 100644 --- a/packages/app/test/run-finalization.test.ts +++ b/packages/app/test/run-finalization.test.ts @@ -96,4 +96,15 @@ describe("durable run finalization", () => { expect(f.recordObservation).not.toHaveBeenCalled(); expect(f.stop).not.toHaveBeenCalled(); }); + it("collects a failed process primary stream and native audit session independently", async () => { + const f = fixture(); + const source = { kind: "execution_stream", path: "/tmp/events.jsonl", mediaType: "application/x-ndjson", provider: "codex" }; + f.run.executionTarget.traceSources = { primary: source }; + f.native.mockImplementation(async (_run: any, _backend: any, source?: any) => { f.events.push(source ? "stream" : "native"); f.artifacts.push({ kind: source ? "execution_stream" : "native_session", state: "stored" }); return { ok: true }; }); + await f.scheduler.poll(f.run); + expect(f.events).toEqual(["observation", "log", "stream", "native", "cleanup"]); + expect((f.native.mock.calls as any)[0].slice(2)).toEqual([source, true]); + expect(f.terminal).toHaveBeenCalledWith(f.run, "failed", "stored", undefined, true); + }); + }); diff --git a/packages/app/test/trace-source.postgres.test.ts b/packages/app/test/trace-source.postgres.test.ts new file mode 100644 index 00000000..be21c0b8 --- /dev/null +++ b/packages/app/test/trace-source.postgres.test.ts @@ -0,0 +1,77 @@ +import { readFile, readdir } from "node:fs/promises"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +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 { artifactUpload, issueArtifactUploadGrant } from "../src/artifact-upload"; + +const url = process.env.TRACE_TEST_DATABASE_URL ?? process.env.AUTH_TEST_DATABASE_URL; +const zero = "0".repeat(64), secret = "test-signing-secret"; +const hash = async (bytes: Uint8Array) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer))].map(x => x.toString(16).padStart(2, "0")).join(""); +const record = (id: string) => JSON.stringify({ version: 1, id, type: "assistant_message", title: "Assistant", preview: id }) + "\n"; + +describe.skipIf(!url)("trace sources with PostgreSQL", () => { + let database: Database, admin: Database; + const databaseName = `trace_test_${crypto.randomUUID().replaceAll("-", "")}`; + beforeAll(async () => { + admin = new Database({ connectionString: url }); + await admin.pool.query(`CREATE DATABASE ${databaseName}`); + const connection = new URL(url!); connection.pathname = `/${databaseName}`; + database = new Database({ connectionString: connection.toString() }); + const directory = new URL("../migrations/", import.meta.url); + for (const file of (await readdir(directory)).filter(file => file.endsWith(".sql")).sort()) await database.pool.query(await readFile(new URL(file, directory), "utf8")); + }); + afterAll(async () => { await database?.close(); if (admin) { await admin.pool.query(`DROP DATABASE IF EXISTS ${databaseName} WITH (FORCE)`); await admin.close(); } }); + + async function fixture() { + const tenantId = crypto.randomUUID(), jobId = crypto.randomUUID(), triggerId = crypto.randomUUID(), invocationId = crypto.randomUUID(), runId = crypto.randomUUID(); + await database.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [tenantId]); + await database.pool.query("INSERT INTO app.jobs(tenant_id,id,name,slug,encrypted_prompt_template,execution_target,concurrency_limit) VALUES ($1,$2,'Trace test','trace-test','test','{}',1)", [tenantId, jobId]); + await database.pool.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES ($1,$2,$3,'manual','manual')", [tenantId, triggerId, jobId]); + await database.pool.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual','test',$4,'{}')", [tenantId, invocationId, jobId, triggerId]); + await database.pool.query("INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,agent_name,state,trace_sources) VALUES ($1,$2,$3,$4,'manual','test','test','running',$5)", [tenantId, runId, jobId, invocationId, { primary: { kind: "execution_stream" } }]); + 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, + } } 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: "codex", 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) }; + } + + it("reconciles durable bytes, preserves native audit data, and rejects late chunks", async () => { + const f = await fixture(), text = record("event-1") + '{"partial":', bytes = new TextEncoder().encode(text); + const chunk = { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await hash(bytes), previousHash: zero, bytes }; + const receipts = await Promise.all([f.live.append(f.runId, "codex", chunk, "execution_stream"), f.live.append(f.runId, "codex", chunk, "execution_stream")]); + expect(receipts.filter(receipt => receipt.duplicate)).toHaveLength(1); + const live = await f.trace.page(f.runId); + expect(live.items).toHaveLength(1); + expect((await f.upload(text)).status).toBe(201); + expect(await f.trace.page(f.runId)).toEqual(live); + 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); + expect(artifacts.map(item => item.kind).sort()).toEqual(["execution_stream", "native_session"]); + const stream = artifacts.find(item => item.kind === "execution_stream")!; + expect(stream).toMatchObject({ source_path: "/tmp/trace.jsonl", media_type: "application/x-ndjson", format_version: "1", cli_version: "p1", harness_version: "h1" }); + expect(new TextDecoder().decode(f.blobs.get(stream.object_key))).toBe(text); + expect((await f.upload(text)).status).toBe(201); + expect((await f.upload(record("replacement"))).status).toBe(409); + await expect(f.live.append(f.runId, "codex", chunk, "execution_stream")).rejects.toThrow("already finalized"); + }); + + it("rolls back corrupt final projection and its receipt without losing live events", async () => { + const f = await fixture(), bytes = new TextEncoder().encode(record("live")); + await f.live.append(f.runId, "codex", { generation: "file-1", expectedGeneration: null, startOffset: 0, chunkSha256: await hash(bytes), previousHash: zero, bytes }, "execution_stream"); + const live = await f.trace.page(f.runId); + await expect(f.upload(record("new") + "invalid\n")).rejects.toThrow("Invalid execution stream JSON"); + expect(await f.trace.page(f.runId)).toEqual(live); + expect(await f.artifacts.list(f.runId)).toHaveLength(0); + expect((await f.upload(record("live"))).status).toBe(201); + }); +}); diff --git a/packages/app/test/trace-source.test.ts b/packages/app/test/trace-source.test.ts new file mode 100644 index 00000000..f2d5f783 --- /dev/null +++ b/packages/app/test/trace-source.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { agentDriver } from "../src/agent-driver"; +import { sourceCommand, validateTraceSources, type TraceSource } from "../src/trace-source"; +import { consumeTraceStream, parseTrace } from "../src/trace"; + +const source: TraceSource = { kind: "execution_stream", path: "/tmp/trace/events.jsonl", mediaType: "application/x-ndjson", provider: "codex", formatVersion: "1", harnessVersion: "test" }; +export const record = JSON.stringify({ version: 1, id: "a", type: "assistant_message", title: "Assistant", preview: "hello 😀", display: { model: "test" } }); + +describe("execution stream contract", () => { + it("declares native-only compatibility explicitly for all existing drivers", () => { + for (const provider of ["codex", "claude", "pi"] as const) { + const launch = agentDriver(provider).launch("run-1", {}); + expect(launch.traceSources?.primary).toMatchObject({ kind: "native_session", mediaType: "application/x-ndjson", provider }); + validateTraceSources(launch.traceSources!); + } + }); + it("reserves JSONL paths and keeps native sessions separate", () => { + expect(sourceCommand({ ...source, discoverCommand: "untrusted ignored discovery" })).toBe("printf '%s' '/tmp/trace/events.jsonl'"); + expect(() => validateTraceSources({ primary: { ...source, path: "/tmp/factorize.stderr" } })).toThrow("reserved"); + expect(() => validateTraceSources({ primary: source, nativeSession: { ...source, kind: "native_session" } })).toThrow("separate"); + }); + it("uses the same normalized events for every provider", () => { + for (const provider of ["codex", "claude", "pi"] as const) expect(parseTrace(provider, record, "execution_stream")).toEqual([{ sequence: 1, id: "a", type: "assistant_message", title: "Assistant", preview: "hello 😀", display: { model: "test" } }]); + }); + it("reconciles only complete records, including across UTF-8 byte boundaries", async () => { + const bytes = new TextEncoder().encode(`${record}\n{"version":1`); + const stream = new ReadableStream({ start(controller) { for (const byte of bytes) controller.enqueue(new Uint8Array([byte])); controller.close(); } }); + const events: any[] = []; + expect(await consumeTraceStream("codex", stream, async items => { events.push(...items); }, 1, "execution_stream")).toBe(1); + expect(events).toEqual(parseTrace("codex", record, "execution_stream")); + const truncatedUtf8 = new Uint8Array([...new TextEncoder().encode(`${record}\n{"preview":"`), 240, 159]); + const complete: any[] = []; + await consumeTraceStream("codex", new Response(truncatedUtf8).body!, async items => { complete.push(...items); }, 250, "execution_stream"); + expect(complete).toEqual(events); + expect(() => parseTrace("codex", "{}", "execution_stream")).toThrow("Invalid execution stream record"); + expect(() => parseTrace("codex", "invalid", "execution_stream")).toThrow("Invalid execution stream JSON"); + }); +}); diff --git a/packages/app/test/trace-tail-boundary.test.ts b/packages/app/test/trace-tail-boundary.test.ts new file mode 100644 index 00000000..7a59e35f --- /dev/null +++ b/packages/app/test/trace-tail-boundary.test.ts @@ -0,0 +1,45 @@ +import { mkdtempSync, writeFileSync, appendFileSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { afterEach, expect, it, vi } from "vitest"; +import { ExeVmBackend } from "../src/exe-vm-backend"; +import type { TraceSource } from "../src/trace-source"; + +afterEach(() => vi.unstubAllGlobals()); + +it("tails the declared stream before exit, resumes by offset, and detects truncation", async () => { + const directory = mkdtempSync(join(tmpdir(), "factorize-trace-")); + const path = join(directory, "stream.jsonl"), captured = join(directory, "captured"), headers = join(directory, "headers"); + try { + writeFileSync(path, '{"version":1}\n'); + vi.stubGlobal("fetch", vi.fn(async (_url, init) => { + // Exercise the exact generated guest command, replacing only transport/upload. + const shim = `ssh() { bash -c "$2"; }; export -f curl; curl() { printf '%s\\n' "$@" > '${headers}'; for arg in "$@"; do case "$arg" in @*) cat "\${arg#@}" > '${captured}';; esac; done; }; export -f curl;`; + const result = spawnSync("bash", ["-c", shim + String(init.body)], { encoding: "utf8" }); + return new Response(result.stdout + result.stderr, { headers: { "X-Exe-Exit": String(result.status) } }); + })); + const source: TraceSource = { kind: "execution_stream", path, mediaType: "application/x-ndjson", provider: "codex" }; + const backend = new ExeVmBackend({ apiToken: "test", tags: [] }), handle = { backendKind: "exe-vm", id: "factorize-test" }; + const request = { source, uploadUrl: "https://app.example/chunk", generation: null as string | null, offset: 0, previousHash: "0".repeat(64) }; + expect((await backend.collectTraceChunk(handle, request)).ok).toBe(true); + expect(readFileSync(captured, "utf8")).toBe('{"version":1}\n'); + request.generation = readFileSync(headers, "utf8").match(/X-Trace-Generation: ([^\n]+)/)![1]; + request.offset = readFileSync(path).length; + appendFileSync(path, '{"version":2}\n'); + expect((await backend.collectTraceChunk(handle, request)).ok).toBe(true); + expect(readFileSync(captured, "utf8")).toBe('{"version":2}\n'); + writeFileSync(path, '{}\n'); + expect((await backend.collectTraceChunk(handle, request)).ok).toBe(true); + expect(readFileSync(headers, "utf8")).toContain("X-Trace-Start: 0"); + expect(readFileSync(captured, "utf8")).toBe('{}\n'); + const generation = readFileSync(headers, "utf8").match(/X-Trace-Generation: ([^\n]+)/)![1]; + expect(generation).not.toBe(request.generation); + request.generation = generation; + request.offset = 3; + appendFileSync(path, '{}\n'); + expect((await backend.collectTraceChunk(handle, request)).ok).toBe(true); + expect(readFileSync(headers, "utf8")).toContain(`X-Trace-Generation: ${generation}`); + expect(readFileSync(headers, "utf8")).toContain("X-Trace-Start: 3"); + } finally { rmSync(directory, { recursive: true, force: true }); } +}); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index ee30f00c..07579fbc 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -66,6 +66,23 @@ components: sha256: { type: string, pattern: '^[a-f0-9]{64}$' } state: { type: string, enum: [stored] } created_at: { type: string, format: date-time } + TraceSource: + type: object + required: [kind, path, mediaType, provider] + properties: + kind: { type: string, enum: [execution_stream, native_session] } + path: { type: string, description: Guest source path; historical native sources may use a discovery root } + mediaType: { type: string, const: application/x-ndjson } + provider: { type: string, enum: [codex, claude, pi] } + formatVersion: { type: string } + cliVersion: { type: string } + harnessVersion: { type: string } + discoverCommand: { type: string, description: Native session discovery only } + TraceSources: + type: [object, 'null'] + properties: + primary: { $ref: '#/components/schemas/TraceSource' } + nativeSession: { $ref: '#/components/schemas/TraceSource' } RunDetail: allOf: - $ref: '#/components/schemas/Run' @@ -74,6 +91,7 @@ components: properties: id: { type: string } state: { type: string } + trace_sources: { $ref: '#/components/schemas/TraceSources' } execution_diagnostics: { $ref: '#/components/schemas/ExecutionDiagnostics' } harness_log: { $ref: '#/components/schemas/HarnessLog' } artifact_error: { type: [string, 'null'], description: Secondary artifact or cleanup error; does not replace execution_diagnostics } @@ -86,6 +104,7 @@ components: state: { type: string } provider: { type: string } backendKind: { type: string } + traceSources: { $ref: '#/components/schemas/TraceSources' } execution: { $ref: '#/components/schemas/ExecutionDiagnostics' } harnessLog: { $ref: '#/components/schemas/HarnessLog' } artifact: