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
46 changes: 46 additions & 0 deletions docs/execution-trace-stream.md
Original file line number Diff line number Diff line change
@@ -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/<sha256>.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.
6 changes: 6 additions & 0 deletions packages/app/migrations/0010_trace_sources.sql
Original file line number Diff line number Diff line change
@@ -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;
12 changes: 11 additions & 1 deletion packages/app/src/agent-driver.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { TraceSources } from "./trace-source";
export type AgentKind = "codex" | "claude" | "pi";

export interface AgentConfiguration { model?: string; effort?: string; }
Expand All @@ -15,6 +16,7 @@ export interface AgentLaunchSpec {
env: Record<string, string>;
stdin: "prompt";
artifacts: ArtifactLocator;
traceSources?: TraceSources;
}
export interface AgentDriver {
readonly kind: AgentKind;
Expand Down Expand Up @@ -53,4 +55,12 @@ class PiDriver implements AgentDriver {
}

const drivers: Record<AgentKind, AgentDriver> = { 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 } };
}
31 changes: 28 additions & 3 deletions packages/app/src/artifact-upload.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { DatabaseClient } from "./postgres/database";
import { artifactKey } from "./artifacts";
import { hmac } from "./crypto";
import type { Env } from "./types";
Expand All @@ -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;
}
Expand All @@ -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; }
Expand All @@ -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 });
}
5 changes: 4 additions & 1 deletion packages/app/src/artifacts.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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;
Expand Down
14 changes: 9 additions & 5 deletions packages/app/src/exe-vm-backend.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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());
Expand All @@ -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",
Expand Down Expand Up @@ -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 };
}
Expand Down
7 changes: 6 additions & 1 deletion packages/app/src/execution.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -13,6 +14,7 @@ export interface BackendCommandResult {
export interface LaunchRequest {
runId: string;
prompt: string;
traceSources?: TraceSources;
harness?: { executable: string; args: string[]; env: Record<string, string> };
}

Expand All @@ -38,6 +40,8 @@ export interface PromptDeliveryReceipt {
state: Exclude<PromptDeliveryState, "pending" | "submitting">;
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. */
Expand All @@ -49,7 +53,8 @@ export interface ExecutionBackend {
stop(handle: RunHandle): Promise<ExecutionObservation>;
deliverPrompt?(handle: RunHandle, prompt: string): Promise<PromptDeliveryReceipt>;
readOutput?(handle: RunHandle): Promise<string | null>;
collectArtifact?(handle: RunHandle, request: { uploadUrl: string; discoverCommand: string; contentType: string }): Promise<ArtifactCollectionReceipt>;
collectArtifact?(handle: RunHandle, request: ArtifactCollectionRequest): Promise<ArtifactCollectionReceipt>;
collectTraceChunk?(handle: RunHandle, request: TraceChunkCollectionRequest): Promise<ArtifactCollectionReceipt>;
}

/** Maps persisted execution states onto the public contract. */
Expand Down
Loading
Loading