Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
33f5d89
feat(runtime): emit versioned opt-in step timings
roodboi Nov 20, 2026
2bd0d41
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 20, 2026
684ac36
fix(timings): stream anchored spans over a dedicated descriptor
roodboi Nov 21, 2026
9f3750a
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 21, 2026
4807926
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 21, 2026
5c9ed8e
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 21, 2026
e75a9de
fix(runtime): make timing records extensible and bound child transport
roodboi Nov 21, 2026
148e501
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 21, 2026
638e031
fix(runtime): mark timing anchors that need observed bounds
roodboi Nov 21, 2026
a7e64be
fix(runtime): generate timing span ids on musl guests
roodboi Nov 21, 2026
48a063c
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 21, 2026
10a27d5
fix(runtime): include provider startup in boot timings
roodboi Nov 21, 2026
a0af326
Merge next into timing CLI work
roodboi Nov 21, 2026
6504af5
feat: add TypeScript command timing foundation
roodboi Nov 23, 2026
2e36052
Merge remote-tracking branch 'origin/next' into claude-lead/engine-a1…
roodboi Nov 23, 2026
dd014f1
test: focus the timing foundation on the opt-in child contract
roodboi Nov 23, 2026
8805c84
fix: keep command timing transport nonblocking and optional
roodboi Nov 23, 2026
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
4 changes: 1 addition & 3 deletions docs/reference/timings.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ that fails later still carries it. It is absent when no such sample was accepted
a pool that was already running, a Research pool, or a start refused before or at
that sample.

This slice implements the Rust contract and transport only. The TypeScript reader,
public `--timings`/`--json` integration, long-lived child transport wiring and measured
command coverage follow separately. No CLI join or performance acceptance is claimed.
TypeScript libraries share this contract; public CLI integration and performance qualification follow.

For image acquisition, `image.engine.preflight` measures the initial guest
check and `image.tag.resolve` measures mutable tag resolution.
Expand Down
9 changes: 9 additions & 0 deletions packages/runtime-core/tests/timings_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,12 @@ fn cold_boot_observation_includes_provider_start_and_its_early_errors() {
assert!(span < provider && provider < readiness && readiness < cleanup);
assert!(cold.trim_end().ends_with("})\n}"));
}

#[test]
fn parses_typescript_command_span() {
// Captured from the Bun collector, with normalized IDs and clock anchors.
let line = r#"{"schema":"hack.timings/1","trace":"11111111111111111111111111111111","span":"2222222222222222","parent":null,"proc":"cli","clock":"host","origin_unix_us":1,"origin_mono_us":1,"step":"command.total","start_us":0,"dur_us":1030674,"outcome":"ok","attrs":{}}"#;
let record = Record::parse_line(line).expect("TypeScript command span");
assert_eq!(record.step.as_str(), "command.total");
assert_eq!(record.outcome, Outcome::Ok);
}
235 changes: 235 additions & 0 deletions src/lib/command-timings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { randomBytes } from "node:crypto";
import { closeSync, openSync, writeSync } from "node:fs";
import { holdProcessUntil } from "./process-exit.ts";
import {
readTimingLine,
TIMING_SCHEMA,
type TimingRecord,
type TimingStep,
} from "./timing-record.ts";

type Transport = typeof import("./native-timing-transport.ts");
type RuntimeOptions = Bun.Spawn.SpawnOptions<"ignore" | "pipe", "pipe", "pipe">;
type Outcome = "ok" | "error";
const MAX_CHILD_RECORDS = 2046;
const context = new AsyncLocalStorage<CommandTimings>();
const ZERO_ID = /^0+$/;
function id(bytes = 8): string {
let value: string;
do {
value = randomBytes(bytes).toString("hex");
} while (ZERO_ID.test(value));
return value;
}

class CommandTimings {
private readonly trace = id(16);
private readonly root = id();
private readonly originUnix = Date.now() * 1000;
private readonly cliSpans = new Set([this.root]);
private readonly records: TimingRecord[] = [];
private readonly children = new Set<Promise<void>>();
private dropped = 0;

private readonly fd: number;
private readonly transport: Transport;
private readonly originMono: number;

constructor(fd: number, transport: Transport, originMono: number) {
this.fd = fd;
this.transport = transport;
this.originMono = originMono;
}

private now() {
return Math.max(
0,
(this.transport.hostMonotonicUs() ?? this.originMono) - this.originMono
);
}

private record(
span: string,
step: TimingStep,
start_us: number,
outcome: Outcome
): TimingRecord {
return {
schema: TIMING_SCHEMA,
trace: this.trace,
span,
parent: span === this.root ? null : this.root,
proc: "cli",
clock: "host",
origin_unix_us: this.originUnix,
origin_mono_us: this.originMono,
step,
start_us,
dur_us: Math.max(0, this.now() - start_us),
outcome,
attrs: {},
};
}

private add(record: TimingRecord) {
if (this.records.length < MAX_CHILD_RECORDS) {
this.records.push(record);
} else {
this.dropped++;
}
}

/** Only finite subprocesses belong to this collector. The caller owns long-lived children. */
spawn(command: string[], options: RuntimeOptions) {
const [executable, ...args] = command;
const spawn = this.transport.hostMonotonicUs();
const span = id();
const start = this.now();
let channel: ReturnType<Transport["timingChannel"]>;
if (
spawn === undefined ||
!executable ||
(options.stdio?.length ?? 0) > 3 ||
this.cliSpans.size > MAX_CHILD_RECORDS
) {
return Bun.spawn(command, options);
}
try {
channel = this.transport.timingChannel();
} catch {
this.add(this.record(span, "runtime.request", start, "error"));
this.cliSpans.add(span);
return Bun.spawn(command, options);
}
this.cliSpans.add(span);
const drain = () => {
channel.drain((line) => {
if (!line.endsWith("\n")) {
return;
}
const record = readTimingLine(line);
if (
record?.trace === this.trace &&
record.parent !== null &&
record.proc !== "cli" &&
!this.cliSpans.has(record.span)
) {
this.add(record);
}
});
};

try {
const stdio: NonNullable<RuntimeOptions["stdio"]> = options.stdio
? [...options.stdio]
: [options.stdin ?? "ignore", "pipe", "pipe"];
stdio[3] = channel.sender;
const child = Bun.spawn(
[
executable,
`--internal-timings=3:${this.trace}:${span}:${spawn}:runtime`,
...args,
],
{
...options,
stdio,
}
);
channel.closeSender();
const timer = setInterval(drain, 2);
const finish = (outcome: Outcome) => {
clearInterval(timer);
try {
drain();
this.add(this.record(span, "runtime.request", start, outcome));
} finally {
channel.close();
}
};
const done = child.exited.then(
(code) => finish(code === 0 ? "ok" : "error"),
() => finish("error")
);
this.children.add(done);
const remove = () => {
this.children.delete(done);
};
void done.then(remove, remove);
holdProcessUntil(done);
return child;
} catch (error) {
channel.close();
this.add(this.record(span, "runtime.request", start, "error"));
throw error;
}
}

async finish(outcome: Outcome) {
await Promise.allSettled(this.children);
try {
for (const record of this.records) {
if (record.proc !== "cli" && this.cliSpans.has(record.span)) {
continue;
}
writeSync(this.fd, `${JSON.stringify(record)}\n`);
}
writeSync(
this.fd,
`${JSON.stringify(this.record(this.root, "command.total", 0, outcome))}\n`
);
if (this.dropped) {
const marker = this.record(id(), "timings.truncated", this.now(), "ok");
marker.attrs.dropped = this.dropped;
writeSync(this.fd, `${JSON.stringify(marker)}\n`);
}
} catch {
// Timing I/O must preserve the command result.
} finally {
try {
closeSync(this.fd);
} catch {
// The file is diagnostic only.
}
}
}
}

/** A collector exists only for an explicitly selected command with a host clock. */
export async function withCommandTimings<T>(
file: string,
action: () => Promise<T>
): Promise<T> {
let trace: CommandTimings | undefined;
try {
const transport = await import("./native-timing-transport.ts");
const origin = transport.hostMonotonicUs();
if (origin !== undefined) {
trace = new CommandTimings(
openSync(file, "wx", 0o600),
transport,
origin
);
}
} catch {
// Unsupported libc, clock, or output file.
}
if (!trace) {
return action();
}
let outcome: Outcome = "error";
try {
const result = await context.run(trace, action);
outcome = "ok";
return result;
} finally {
await trace.finish(outcome);
}
}

/** fd 3 must be free. Use this only for a finite child owned by the command. */
export function timedNativeSpawn(command: string[], options: RuntimeOptions) {
return (
context.getStore()?.spawn(command, options) ?? Bun.spawn(command, options)
);
}
121 changes: 121 additions & 0 deletions src/lib/native-timing-transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/** Loaded only for explicitly requested timings; no filesystem/socket paths. */
import { dlopen, ptr, FFIType as T } from "bun:ffi";

const mac = process.platform === "darwin";
const HOST_CLOCK = mac ? 8 : 1; // CLOCK_UPTIME_RAW / CLOCK_MONOTONIC
const AF_UNIX = 1,
SOCK_DGRAM = 2;
const F_SETFD = 2,
FD_CLOEXEC = 1,
F_GETFL = 3,
F_SETFL = 4;
const F_GETFD = 1;
const O_NONBLOCK = mac ? 4 : 2048;
const MSG_DONTWAIT = mac ? 0x80 : 0x40;
const stackVararg = mac && process.arch === "arm64";
const SOL_SOCKET = mac ? 0xff_ff : 1,
SO_RCVBUF = mac ? 0x10_02 : 8;
const { symbols: c } = dlopen(
mac ? "/usr/lib/libSystem.B.dylib" : "libc.so.6",
{
clock_gettime: { args: [T.i32, T.ptr], returns: T.i32 },
socketpair: { args: [T.i32, T.i32, T.i32, T.ptr], returns: T.i32 },
fcntl: {
args: new Array<T>(stackVararg ? 9 : 3).fill(T.i32),
returns: T.i32,
},
setsockopt: { args: [T.i32, T.i32, T.i32, T.ptr, T.u32], returns: T.i32 },
getsockopt: { args: [T.i32, T.i32, T.i32, T.ptr, T.ptr], returns: T.i32 },
recv: { args: [T.i32, T.ptr, T.u64, T.i32], returns: T.i64 },
close: { args: [T.i32], returns: T.i32 },
}
);
// Apple arm64 passes the variadic argument on the stack. Fill the eight
// integer registers in the fixed FFI signature to place it there.
function fcntl(fd: number, command: number, value = 0) {
return stackVararg
? c.fcntl(fd, command, 0, 0, 0, 0, 0, 0, value)
: c.fcntl(fd, command, value);
}
export function hostMonotonicUs(): number | undefined {
// All supported CLI targets have a 64-bit timespec (two 64-bit longs).
const time = new BigInt64Array(2);
if (c.clock_gettime(HOST_CLOCK, ptr(time)) !== 0) {
return;
}
const us = Number((time[0] ?? 0n) * 1000000n + (time[1] ?? 0n) / 1000n);
return Number.isSafeInteger(us) && us >= 0 ? us : undefined;
}
export function timingChannel() {
const fds = new Int32Array(2);
if (c.socketpair(AF_UNIX, SOCK_DGRAM, 0, ptr(fds)) !== 0) {
throw new Error("Timing socket creation failed; values omitted.");
}
const receiver = fds[0] as number,
sender = fds[1] as number;
let sent = false,
closed = false;
const closeSender = () => {
if (!sent) {
sent = true;
c.close(sender);
}
};
const close = () => {
if (!closed) {
closed = true;
closeSender();
c.close(receiver);
}
};
try {
const flags = fcntl(receiver, F_GETFL);
if (
flags < 0 ||
fcntl(receiver, F_SETFD, FD_CLOEXEC) < 0 ||
fcntl(sender, F_SETFD, FD_CLOEXEC) < 0 ||
fcntl(receiver, F_SETFL, flags | O_NONBLOCK) < 0 ||
fcntl(receiver, F_GETFD) !== FD_CLOEXEC ||
fcntl(sender, F_GETFD) !== FD_CLOEXEC ||
fcntl(receiver, F_GETFL) !== (flags | O_NONBLOCK)
) {
throw new Error("Timing socket setup failed.");
}
const size = new Int32Array([256 * 1024]);
if (c.setsockopt(receiver, SOL_SOCKET, SO_RCVBUF, ptr(size), 4) !== 0) {
throw new Error("Timing receive buffer setup failed; values omitted.");
}
const length = new Uint32Array([4]);
if (
c.getsockopt(receiver, SOL_SOCKET, SO_RCVBUF, ptr(size), ptr(length)) !==
0 ||
(size[0] ?? 0) < 64 * 1024
) {
throw new Error("Timing receive buffer too small; values omitted.");
}
} catch (error) {
close();
throw error;
}
const bytes = new Uint8Array(16_384),
decoder = new TextDecoder();
return {
sender,
close,
closeSender,
drain(consume: (line: string) => void) {
if (closed) {
return;
}
for (let i = 0; i < 4096; i++) {
const count = Number(
c.recv(receiver, ptr(bytes), bytes.length, MSG_DONTWAIT)
);
if (count <= 0) {
break;
}
consume(decoder.decode(bytes.subarray(0, count)));
}
},
};
}
Loading
Loading