diff --git a/docs/reference/timings.md b/docs/reference/timings.md index 82026a6db..a8d772d13 100644 --- a/docs/reference/timings.md +++ b/docs/reference/timings.md @@ -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. diff --git a/packages/runtime-core/tests/timings_contract.rs b/packages/runtime-core/tests/timings_contract.rs index b50acc242..1e11594d7 100644 --- a/packages/runtime-core/tests/timings_contract.rs +++ b/packages/runtime-core/tests/timings_contract.rs @@ -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); +} diff --git a/src/lib/command-timings.ts b/src/lib/command-timings.ts new file mode 100644 index 000000000..7a7bdd60b --- /dev/null +++ b/src/lib/command-timings.ts @@ -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(); +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>(); + 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; + 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 = 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( + file: string, + action: () => Promise +): Promise { + 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) + ); +} diff --git a/src/lib/native-timing-transport.ts b/src/lib/native-timing-transport.ts new file mode 100644 index 000000000..3f75f0edc --- /dev/null +++ b/src/lib/native-timing-transport.ts @@ -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(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))); + } + }, + }; +} diff --git a/src/lib/timing-record.ts b/src/lib/timing-record.ts new file mode 100644 index 000000000..0a9dc19db --- /dev/null +++ b/src/lib/timing-record.ts @@ -0,0 +1,107 @@ +/** Wire reader: opaque names are data, never trusted display labels. */ +import { isRecord } from "./guards.ts"; +export const TIMING_SCHEMA = "hack.timings/1"; +const NAME = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+)*$/; +const ID = /^[a-f0-9]+$/; +const NONZERO = /[1-9a-f]/; +export type TimingStep = + | "command.total" + | "runtime.request" + | "timings.truncated"; +export interface TimingRecord { + schema: typeof TIMING_SCHEMA; + trace: string; + span: string; + parent: string | null; + proc: string; + clock: string; + origin_unix_us: number; + origin_mono_us: number; + step: string; + start_us: number; + dur_us: number; + outcome: string; + cached?: true; + code?: string; + attrs: Record; +} +const name = (v: unknown): v is string => + typeof v === "string" && v.length <= 128 && NAME.test(v); +const id = (v: unknown, n: number): v is string => + typeof v === "string" && v.length === n && ID.test(v) && NONZERO.test(v); +const number = (v: unknown): v is number => + typeof v === "number" && Number.isSafeInteger(v) && v >= 0; +function known(value: unknown, allowed: readonly string[]): string { + return typeof value === "string" && allowed.includes(value) + ? value + : "unknown"; +} +export function readTimingLine(line: string): TimingRecord | undefined { + if (Buffer.byteLength(line) > 16_384) { + return; + } + let v: unknown; + try { + v = JSON.parse(line); + } catch { + return; + } + if ( + !isRecord(v) || + v.schema !== TIMING_SCHEMA || + !id(v.trace, 32) || + !id(v.span, 16) || + !(v.parent === undefined || v.parent === null || id(v.parent, 16)) || + v.parent === v.span || + !name(v.step) || + typeof v.proc !== "string" || + typeof v.clock !== "string" || + typeof v.outcome !== "string" || + (v.cached !== undefined && (v.cached !== true || v.outcome !== "ok")) || + (v.attrs !== undefined && !isRecord(v.attrs)) || + !number(v.origin_unix_us) || + !number(v.origin_mono_us) || + !number(v.start_us) || + !number(v.dur_us) || + !number(v.start_us + v.dur_us) + ) { + return; + } + const attrs: TimingRecord["attrs"] = {}; + if (isRecord(v.attrs)) { + for (const [key, value] of Object.entries(v.attrs)) { + if ( + name(key) && + (typeof value === "boolean" || + (typeof value === "number" && + Number.isFinite(value) && + Math.abs(value) <= Number.MAX_SAFE_INTEGER)) + ) { + attrs[key] = value; + } + } + } + return { + schema: TIMING_SCHEMA, + trace: v.trace, + span: v.span, + parent: v.parent ?? null, + proc: known(v.proc, ["cli", "runtime", "owner", "guest"]), + clock: known(v.clock, ["host", "guest"]), + origin_unix_us: v.origin_unix_us, + origin_mono_us: v.origin_mono_us, + step: v.step, + start_us: v.start_us, + dur_us: v.dur_us, + outcome: known(v.outcome, [ + "ok", + "error", + "cancelled", + "incomplete", + "skipped", + ]), + ...(v.cached && { cached: v.cached }), + ...(name(v.code) ? { code: v.code } : {}), + attrs, + }; +} diff --git a/tests/command-timings.test.ts b/tests/command-timings.test.ts new file mode 100644 index 000000000..eca9fd9c8 --- /dev/null +++ b/tests/command-timings.test.ts @@ -0,0 +1,81 @@ +import { expect, test } from "bun:test"; +import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + timedNativeSpawn, + withCommandTimings, +} from "../src/lib/command-timings.ts"; +import { readTimingLine } from "../src/lib/timing-record.ts"; + +const options = { stdin: "ignore", stdout: "pipe", stderr: "pipe" } as const; +const childSource = ` +import { fstatSync, writeSync } from "node:fs"; +const flag = process.argv.find((arg) => arg.startsWith("--internal-timings=")); +let fdOpen = true; +try { fdOpen = fstatSync(3).isSocket(); } catch { fdOpen = false; } +console.log(JSON.stringify([Boolean(flag), fdOpen])); +if (flag) { + const [fd, trace, parent, spawn] = flag.split("=")[1].split(":"); + await Bun.sleep(200); + const record = { + schema: "hack.timings/1", trace, parent, span: "00f067aa0ba902b7", + proc: "runtime", clock: "host", origin_unix_us: 1, + origin_mono_us: Number(spawn), step: "container.start", + start_us: 0, dur_us: 1, outcome: "ok", + }; + const send = (value, suffix = "\\n") => writeSync(Number(fd), JSON.stringify(value) + suffix); + send({...record, step: "forged.root", parent: null}); + send({...record, step: "forged.cli", proc: "cli"}); + send({...record, step: "forged.collision", span: parent, parent: record.span}); + send({...record, step: "forged.partial"}, ""); + send({...record, step: "forged.cached", cached: false}); + send({...record, step: "forged.attrs", attrs: []}); + send({...record, step: "forged.outcome", outcome: 1}); + for (let i = 0; i < 1100; i++) { + send({...record, span: (i + 1).toString(16).padStart(16,"0")}); + if (i % 8 === 0) await Bun.sleep(2); + } +}`; + +test("child timing is opt-in, nonblocking, validated and capped across children", async () => { + const root = await mkdtemp(join(tmpdir(), "hack-timings-")); + const file = join(root, "timings.jsonl"); + const script = join(root, "child"); + const run = async (enabled: boolean) => { + const child = timedNativeSpawn([script], options); + const stdout = await new Response(child.stdout).text(); + expect(JSON.parse(stdout)).toEqual([enabled, enabled]); + expect(await new Response(child.stderr).text()).toBe(""); + expect(await child.exited).toBe(0); + }; + try { + await writeFile(script, `#!${process.execPath}\n${childSource}`, { + mode: 0o700, + }); + await run(false); + expect(await readdir(root)).toEqual(["child"]); + await withCommandTimings(file, async () => { + const first = run(true); + const elapsed = performance.now(); + await Bun.sleep(30); + expect(performance.now() - elapsed).toBeLessThan(180); + await first; + await run(true); + }); + const lines = (await Bun.file(file).text()).trim().split("\n"); + const records = lines.map(readTimingLine); + expect(records).toHaveLength(2048); + expect(records.every((r) => r && !r.step.startsWith("forged."))).toBe(true); + const service = records[0]; + const request = records.find((r) => r?.step === "runtime.request"); + expect(service?.step).toBe("container.start"); + expect(service?.parent).toBe(request?.span); + expect(service?.trace).toBe(request?.trace); + expect(records.at(-1)?.step).toBe("timings.truncated"); + expect(records.at(-1)?.attrs.dropped).toBe(156); + await withCommandTimings(file, () => run(false)); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/tests/process-exit-holds.test.ts b/tests/process-exit-holds.test.ts index a9f9401f0..1b0225a83 100644 --- a/tests/process-exit-holds.test.ts +++ b/tests/process-exit-holds.test.ts @@ -24,6 +24,10 @@ type Reason = | { readonly kind: "owned-elsewhere"; readonly what: string }; const CLASSIFIED: Readonly> = { + "src/lib/command-timings.ts": { + kind: "held", + what: "child timing drains; callers await trace finalization", + }, "src/mcp/server.ts": { kind: "held", what: "stdio MCP session and each tool call",