diff --git a/.changeset/2915-observation-steps.md b/.changeset/2915-observation-steps.md new file mode 100644 index 0000000000..b5f16f5763 --- /dev/null +++ b/.changeset/2915-observation-steps.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Attribute more of journal begin in a turn's lifecycle steps. The `journal` phase now also reports `observe_reserve` (the wait for room behind earlier checkpoint releases), `observe_release_reads`, `observe_worktrees`, and `observe_publish` and `observe_facts` beside `observe_record`. The record steps now repeat once per other active turn the observation records, and are absent when there is none. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 40cb19f644..a056711d9c 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1976,6 +1976,61 @@ send 1 to 2 ms each); the rest of the hold is not attributed (#2915). The targets are reported as unmet, not relaxed. +### Where an observation's time goes — 2026-11-15 (#2915) + +**What is measured.** `--observation-timing` now attributes each observed +writer's worker hold and each harbour turn's journal begin and finish to their +steps. The journal reports every step of a held observation to an internal +trace (`observationTrace`, `packages/ui-server/src/brain/turn-journal.ts`), +the hold itself last, and the native manager reports each request's wait for +its single operation lock, the operation it waited behind, and its checkpoint, +release and delta steps (`trace`, `NativeBrainManagerOptions`, +`packages/ui-sdk/src/server/native-brain-manager.ts`). The app child and the +fixture's manager stamp both with `performance.timeOrigin + performance.now()`. +A checkpoint or delta step is broken down by the one manager request that +arrived inside it. The run fails unless every such step pairs with exactly one +request and each checkpoint answered before its step ended: that is the proof +that the two processes' clocks agree +(`scripts/native-proof/observation-phases.ts`). Nothing is traced unless a +caller passes a trace, and no step, check or durability write changed. +Admission's lifecycle steps gain the same new names (`observe_reserve`, +`observe_release_reads`, `observe_worktrees`, `observe_publish`, +`observe_facts`), additively. + +**Measured.** pi, governed, UID 1000, 2,000 notes, on hosted GitHub runners +(1-minute load 1 to 2), on 2026-11-15. The first row is one run; the other two +ran back to back on one runner. Median added ms / p95 with the median worker +hold, and journal begin plus finish as the median / p95 of paired totals: + +| | `write_file` | `edit_file` | Writing `bash` | Begin + finish | +| --- | --- | --- | --- | --- | +| This change, run 1 | 71 / 494, held 45 | 59 / 249, held 33 | 86 / 614, held 57 | 218 / 1,577 | +| Base `3f8ff293`, paired | 67 / 97, held 38 | 69 / 74, held 38 | 76 / 96, held 40 | 62 / 181 | +| This change, paired | 68 / 126, held 38 | 68 / 80, held 40 | 72 / 79, held 38 | 68 / 144 | + +The paired runs show the trace costs nothing measurable. The phases cover +98 to 99 % of the measured hold, begin and finish by median, and at least +92.9 % of every single sample. In the paired run a writer's 38 ms hold is the +queue for the journal and the workers' freeze (3.7 ms), the checkpoint +(18.1 ms: qualification 4.5, the two fsynced intents 4.3, the snapshot 5.8, the +Unix round trip 2.4), the delta (3.9), content capture of the written file +(6.9), and the record, publication and facts query (about 3). Finish is the +same observation plus its end record (1.2) and object collection (0.7). The +release owner (#2872) rarely delays anything any more: a writer's checkpoint +waited behind a release in 2 of 60 calls in run 1. + +**Targets.** On these runners both #2834 targets are met, at the base and with +this change: writers add 67 to 76 ms (target under 150) and begin plus finish +takes 62 to 68 ms (target at most 300). Run 1 shows what the slower host in +#2872's runs paid for. Finish's median was 139 ms and its p95 1.6 s, and almost +all of it sat in two required durability steps: the checkpoint's intent fsync +(110 ms median) or the snapshot, whichever met the btrfs writeback of the +turn's and the index refresh's dirty data first. Nothing was cut. Every +remaining phase is a qualification check, an identity check, a durability +write, a journal capture or the hold mechanism itself, and none may be skipped +or cached. Moving that writeback out of the hold is a separate question +(#4019). + ## Monitoring **Where it lives.** All monitoring is host operational state in `brain-ui.db` diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 962702142a..623ffb91e9 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -599,8 +599,13 @@ not apply to a turn is absent. The current names are: `type_translation_refresh`, `peer_folder_plans`, `private_index`, `data_tree`, `record_policy`, `startup_view_cleanup`, `exposure_records`, `manifest_begin`. - `journal`: `hold_wait`, `initialize`, `refused_admissions`, `observe` (with - `observe_checkpoint`, `observe_delta`, `observe_metadata`, `observe_capture`, - `observe_record`, `observe_commit`), `expiry`, `turn_insert`, `policy`. + `observe_release_reads`, `observe_reserve`, `observe_checkpoint`, + `observe_delta`, `observe_metadata`, `observe_capture`, `observe_worktrees`, + `observe_record`, `observe_publish`, `observe_facts`, `observe_commit`), + `expiry`, `turn_insert`, `policy`. `observe_reserve` waits for room behind + earlier checkpoint releases; `observe_record`, `observe_publish` and + `observe_facts` repeat once per other active turn the observation records, + and are absent when there is none (#2915). Records written before this field have no `subPhases`; nothing is backfilled. diff --git a/packages/ui-sdk/src/server/native-brain-manager.ts b/packages/ui-sdk/src/server/native-brain-manager.ts index 37c57d12a8..121e639860 100644 --- a/packages/ui-sdk/src/server/native-brain-manager.ts +++ b/packages/ui-sdk/src/server/native-brain-manager.ts @@ -47,6 +47,18 @@ export interface NativeBrainManagerConfig { /** Optional separate Btrfs reference volume (#2428); no consumer is enabled by configuring it. */ referencePool?: NativeReferencePoolConfig; } +/** + * @internal One timed span of a manager operation (#2915), stamped with + * `performance.timeOrigin + performance.now()` so another process on the host + * can align it with its own. `lock_wait` names the operation that held the + * single operation lock when the wait began; `held` spans the lock itself. + * `request` numbers one operation's spans. + */ +export interface NativeManagerSpan { request: number; operation: string; phase: string; startedAt: number; endedAt: number; holder?: string | null } +export interface NativeBrainManagerOptions { + /** @internal Diagnostic timing only; called synchronously, so it must be cheap. */ + trace?: (span: NativeManagerSpan) => void; +} type RootInfo = { rootId: string; uuid: string; parentUuid: string; receivedUuid: string; transaction: string; readOnly: boolean; fsid: string; devices: number }; type Intent = NativeRecoveryRecord & { version: 1; sourceUuid: string }; @@ -114,7 +126,7 @@ async function collect(stream: ReadableStream, maximum: number): Pro for (const part of pieces) { result.set(part, offset); offset += part.byteLength; } return result; } -export async function createNativeBrainManager(config: NativeBrainManagerConfig) { +export async function createNativeBrainManager(config: NativeBrainManagerConfig, options: NativeBrainManagerOptions = {}) { validateNativeBrainManagerConfig(config); if (process.platform !== "linux" || process.arch !== "x64" || process.geteuid?.() !== 0) throw new NativeBrainManagerError("unsupported", "Native manager requires the separately qualified trusted Linux x86-64 root service; the app and workers remain unprivileged."); @@ -131,13 +143,19 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) const stageReservations = new Map(); const checkpointReaders = new Map }>(); let stagedBytes = 0; - async function acquire(signal?: AbortSignal): Promise<() => void> { + const trace = options.trace, clock = () => performance.timeOrigin + performance.now(); + /** The operation holding the lock, for a traced wait behind it. */ + let holder: string | null = null, requests = 0; + async function acquire(signal?: AbortSignal, operation: string | null = null): Promise<() => void> { signal?.throwIfAborted(); if (closed) throw new NativeBrainManagerError("unavailable", "Native manager is closing."); let release!: () => void; const before = pending; pending = new Promise(done => { release = done; }); await before; if (closed || signal?.aborted) { release(); signal?.throwIfAborted(); throw new NativeBrainManagerError("unavailable", "Native manager is closing."); } - return release; + if (!trace) return release; + holder = operation; + let released = false; + return () => { if (released) return; released = true; holder = null; release(); }; } function spawn(command: string[], signal?: AbortSignal) { const controller = new AbortController(); active.add(controller); @@ -429,7 +447,15 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) stagingChargedBytes: Number.isSafeInteger(stagedBytes + quarantinedStageBytes) ? stagedBytes + quarantinedStageBytes : null, diagnosticsPath: join(privateRoot, "recovery-diagnostics") } } : {}) }; } async function run(request: NativeManagerRequest, signal?: AbortSignal): Promise { - nativeManagerRequest.parse(request); const release = await acquire(signal); let handedToStream = false; + nativeManagerRequest.parse(request); + const operation = request.operation, waited = trace ? clock() : 0, behind = holder, id = ++requests; + const step = trace ? (phase: string) => { const startedAt = clock(); return () => trace({ request: id, operation, phase, startedAt, endedAt: clock() }); } : undefined; + const locked = await acquire(signal, operation); + if (trace) trace({ request: id, operation, phase: "lock_wait", startedAt: waited, endedAt: clock(), holder: behind }); + // A streamed send keeps the lock until it ends; `sending` times that part. + const held = step?.("held"); let sending: (() => void) | undefined; + const release = held ? () => { sending?.(); sending = undefined; held(); locked(); } : locked; + let handedToStream = false, end: (() => void) | undefined; try { if (request.operation === "ready") return Response.json(await ready(signal)); if (!request.operation.startsWith("pool") && request.operation !== "listPoolRecovery") recoveryIndex.ensureAvailable(); @@ -486,7 +512,9 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) const intent = readIntent(request.id); if (!intent || intent.kind === "stage" || intent.state !== "sealed") throw new NativeBrainManagerError("unknown", "Checkpoint reading requires one retained sealed checkpoint identity."); + end = step?.("verify"); checkpoint = await verifyOwned(intent, signal); + end?.(); } const maximum = Math.min(request.maximum, request.action === "file" ? fixed.capacityBytes : fixed.maxDeltaBytes); const id = randomUUID(), token = randomUUID(), socketPath = nativeCheckpointReaderPath(fixed.socketPath, id); @@ -635,22 +663,33 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) "x-brain-stage-checkpoint": handle.stage.checkpointId, "x-brain-stage-lower": handle.stage.checkpointUuid } }); } if (request.operation === "checkpoint") { + end = step?.("qualify"); await qualify(signal); + end?.(); let createdNow = false; let intent = readIntent(request.id); - if (intent) intent = await reconcile(intent, signal); + if (intent) { end = step?.("reconcile"); intent = await reconcile(intent, signal); end?.(); } if (intent?.state === "deleted" || intent?.state === "deleting") throw new NativeBrainManagerError("released", "This checkpoint identity was released; it cannot be recreated."); if (intent?.state === "sealed") return Response.json(await verifyOwned(intent, signal)); + end = step?.("reserve"); await ensureReserve(signal); + end?.(); if (!intent) { if (existsSync(rootPath(request.id))) throw new NativeBrainManagerError("unknown", "An unrecorded checkpoint occupies the requested identity."); + end = step?.("intent"); intent = { version: 1, id: request.id, sourceUuid: fixed.brainUuid, state: "creating" }; await writeIntent(intent); + end?.(); createdNow = true; } if (reserveConsumed) throw new NativeBrainManagerError("capacity", "Native recovery consumed emergency allocation; rearm capacity before checkpoint admission."); signal?.throwIfAborted(); + end = step?.("snapshot"); await command([BTRFS, "subvolume", "snapshot", "-r", brain, rootPath(request.id)], signal); - const checkpoint = await verifyOwned(intent, signal); await writeIntent({ ...intent, state: "sealed", checkpoint }); + end?.(); end = step?.("verify"); + const checkpoint = await verifyOwned(intent, signal); + end?.(); end = step?.("intent"); + await writeIntent({ ...intent, state: "sealed", checkpoint }); + end?.(); if (createdNow) createdAfterRecovery.add(request.id); return Response.json(checkpoint); } @@ -671,20 +710,31 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) await writeIntent({ version: 1, id: request.id, sourceUuid: fixed.brainUuid, state: "deleted" }); return Response.json({ id: request.id, state: "deleted" }); } + end = step?.("reconcile"); intent = await reconcile(intent, signal); + end?.(); if (intent.state === "deleted") return Response.json({ id: request.id, state: "deleted" }); if (intent.state === "creating" && !existsSync(rootPath(request.id))) { await writeIntent({ ...intent, state: "deleted" }); return Response.json({ id: request.id, state: "deleted" }); } + end = step?.("verify"); const checkpoint = await verifyOwned(intent, signal); + end?.(); end = step?.("intent"); await writeIntent({ ...intent, state: "deleting", checkpoint }); + end?.(); signal?.throwIfAborted(); + end = step?.("delete"); await command([BTRFS, "subvolume", "delete", "--commit-after", rootPath(request.id)], signal); + end?.(); end = step?.("sync"); await syncDeleted(checkpoint.rootId, signal); + end?.(); end = step?.("intent"); await writeIntent({ ...intent, state: "deleted", checkpoint }); + end?.(); return Response.json({ id: request.id, state: "deleted" }); } const from = readIntent(request.from), to = readIntent(request.to); if (!from || !to || from.state !== "sealed" || to.state !== "sealed") throw new NativeBrainManagerError("unknown", "Native delta requires two retained sealed checkpoint identities."); + end = step?.("verify"); await verifyOwned(from, signal); await verifyOwned(to, signal); + end?.(); sending = step?.("send"); const response = sendDelta(rootPath(from.id), rootPath(to.id), signal, release); handedToStream = true; return response; @@ -737,8 +787,8 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig) } /** Unix socket only; filesystem ownership is authentication, and workers must mask the endpoint. */ -export async function serveNativeBrainManager(config: NativeBrainManagerConfig) { - const fixed = Object.freeze({ ...config }), manager = await createNativeBrainManager(fixed); +export async function serveNativeBrainManager(config: NativeBrainManagerConfig, options: NativeBrainManagerOptions = {}) { + const fixed = Object.freeze({ ...config }), manager = await createNativeBrainManager(fixed, options); if (existsSync(fixed.socketPath)) { await manager.close(); throw new NativeBrainManagerError("unsupported", "Native manager socket already exists; reconcile its service ownership before starting."); } let server: ReturnType; try { diff --git a/packages/ui-server/src/brain/native-journal-observer.ts b/packages/ui-server/src/brain/native-journal-observer.ts index 0c00b10e7c..0f89ebddeb 100644 --- a/packages/ui-server/src/brain/native-journal-observer.ts +++ b/packages/ui-server/src/brain/native-journal-observer.ts @@ -388,11 +388,14 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker } async function prepare(signal?: AbortSignal, timing?: PhaseTimer): Promise { await initialize(signal); + // The wait for room behind earlier releases (#2915), before any checkpoint. + let end = timing?.("observe_reserve"); await reserveRelease(); + end?.(); const active = signalFor(signal), before = root!; let after: NativeJournalCheckpoint | undefined, reader: RootMetadataReader | undefined; try { - let end = timing?.("observe_checkpoint"); + end = timing?.("observe_checkpoint"); after = await checkpoint(active); end?.(); end = timing?.("observe_delta"); const job = await native.delta(before.id, after.id, active); diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 5251c6f38f..34eb56c2d3 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -101,7 +101,19 @@ export interface TurnJournalOptions { idleObservationMs?: number; /** Structured log for cleanup retries; absent, they are recorded durably only. */ log?: Logger; + /** + * @internal Diagnostic timing of one held observation (#2915): admission, + * finish, a call's result or the periodic pass. Every step reports to the + * returned timer, `hold` last, spanning the whole worker hold. + */ + observationTrace?: (kind: JournalTraceKind, turnId: string | null, toolUseId?: string) => PhaseTimer | undefined; } +export type JournalTraceKind = "begin" | "finish" | "tool" | "periodic"; +/** Both timers see every step; either may be absent. */ +const bothTimers = (a?: PhaseTimer, b?: PhaseTimer): PhaseTimer | undefined => !a ? b : !b ? a : name => { + const first = a(name), second = b(name); + return () => { first(); second(); }; +}; export function createTurnJournal(db: Database, options: TurnJournalOptions) { const now = options.now ?? Date.now; @@ -276,7 +288,9 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const callKey = (turnId: string, toolUseId: string) => JSON.stringify([turnId, toolUseId]); let holds = 0; let observationFailures = 0; - function held(operation: () => Promise, admission = false): Promise { + /** `trace` also times the hold itself; `lifecycle` sees every step but that one. */ + function held(operation: (timing?: PhaseTimer) => Promise, admission = false, trace?: PhaseTimer, lifecycle?: PhaseTimer): Promise { + const hold = trace?.("hold"), timing = bothTimers(lifecycle, trace), waited = timing?.("hold_wait"); // Backend event emission is synchronous: establish the hold before yielding // or queueing so a provider cannot launch another tool past this boundary. const holders = [...periodicObservers]; @@ -285,15 +299,17 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { try { for (const holder of holders) { acquired++; holder.before(); } } catch (error) { holds--; for (const holder of holders.slice(0, acquired)) holder.after(false); return Promise.reject(error); } return serialize(async () => { + waited?.(); let completed = false; const failedBefore = observationFailures; - try { const result = await operation(); completed = true; return result; } + try { const result = await operation(timing); completed = true; return result; } finally { // A cancelled/refused new admission made no worker writes. Existing // participants resume when their shared observation itself succeeded, // even if reclaiming a superseded checkpoint failed. const safe = (completed || admission && observationFailures === failedBefore); holds--; for (const holder of holders) holder.after(safe); + hold?.(); } }); } @@ -411,7 +427,9 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { entry?.hash ? [statement("INSERT OR IGNORE INTO turn_journal_object_refs VALUES (?,?)", turnId, entry.hash)] : []; async function observe(userPolicy: boolean = false, timing?: PhaseTimer, signal?: AbortSignal): Promise { + const released = pendingReadReleases.size ? timing?.("observe_release_reads") : undefined; await releaseReads(); + released?.(); const overlaps = [...active.keys()]; const changed = new Map(); const stopActive = async (error: unknown) => { @@ -429,6 +447,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { catch (error) { observationFailures++; const failure = storageError(error); await stopActive(failure); throw failure; } // Each managed worktree is observed through its own checkpoints, for the one turn that holds it. const separate: { worktreeId: string; turnId: string; observation: Awaited> }[] = []; + const separated = worktrees.size ? timing?.("observe_worktrees") : undefined; for (const [worktreeId, root] of [...worktrees]) { const holder = active.get(root.turnId); if (!holder) continue; @@ -442,6 +461,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { await recorded; } } + separated?.(); try { for (const changes of observation.changes.values()) for (const item of changes) { if (identity(item.before) === identity(item.after)) continue; @@ -449,18 +469,20 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { changed.set(JSON.stringify(value), value); } const steering = observation.steering; - const recorded = timing?.("observe_record"); for (const [turnId, turn] of active) { const worktree = separate.filter(root => root.turnId === turnId).flatMap(root => (root.observation.changes.get(turnId) ?? []) .filter(change => identity(change.before) !== identity(change.after)) .map(change => ({ path: referenceWorktreeJournalPath(root.worktreeId, change.path), scope: REFERENCE_WORKTREE_JOURNAL_SCOPE, before: version(change.before), after: version(change.after) }))); const unreadable = [...observation.unreadable, ...separate.filter(root => root.turnId === turnId).flatMap(root => root.observation.unreadable .map(item => ({ ...item, path: referenceWorktreeJournalPath(root.worktreeId, item.path === "." ? "" : item.path) })))]; + let step = timing?.("observe_record"); turn.sequence = await retain(() => call("recordObservation", { turnId, sequence: turn.sequence, at: now(), userPolicy, changed: [...changed.values()], steeringPaths: [...steering.paths], overlaps, worktree, steeringUnavailable: [...steering.unavailable], steeringInventoried: steering.inventoried === true, unreadable, })); + step?.(); step = timing?.("observe_publish"); publish(turnId); + step?.(); step = timing?.("observe_facts"); // Ignored and metadata-only versions have no content hash: count their // largest observed size once per path, independently of hashed changed // versions. The disposable index is counted the same way, ignored or not, @@ -477,8 +499,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { AND path=change.path ORDER BY sequence DESC LIMIT 1) IS NULL)) GROUP BY path )`).get(DISPOSABLE_INDEX_PATHS, turnId, INDEX_PUBLICATION_COPY) as { changedPaths: number; observedBytes: number }; for (const observer of observers) observer(turnId, { ...facts, partial: summary(turnId).state === "partial" }); + step?.(); } - recorded?.(); const committed = timing?.("observe_commit"); await observation.commit(); for (const root of separate) await root.observation.commit(); @@ -500,34 +522,32 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, begin(turnId: string, metadata: { sessionId: string | null; actor: "interactive" | "voice" | "user"; model: string | null; profile: "strict" | "governed"; policyHash: string | null; coveredPaths?: readonly string[] }, stop: (error: Error) => void, signal?: AbortSignal, /** Each step of the admission (#3355); a failed step is left unended. */ timing?: PhaseTimer) { - const waited = timing?.("hold_wait"); - return held(async () => { - waited?.(); + return held(async steps => { signal?.throwIfAborted(); - let end = timing?.("initialize"); + let end = steps?.("initialize"); try { await capture.initialize(signal); } catch (error) { if (signal?.aborted) throw error; throw storageError(error); } end?.(); - if (failedAdmissions.size) { end = timing?.("refused_admissions"); for (const refused of failedAdmissions) await finalizeRefusedAdmission(refused); end?.(); } - end = timing?.("observe"); - await observe(false, timing); + if (failedAdmissions.size) { end = steps?.("refused_admissions"); for (const refused of failedAdmissions) await finalizeRefusedAdmission(refused); end?.(); } + end = steps?.("observe"); + await observe(false, steps); end?.(); signal?.throwIfAborted(); - end = timing?.("expiry"); + end = steps?.("expiry"); await expireBacklog(); - end?.(); end = timing?.("turn_insert"); + end?.(); end = steps?.("turn_insert"); await retain(() => write([statement("INSERT INTO turn_journal_turns (turn_id,session_id,actor,model,profile,policy_hash,pid,pid_start,started_at,state) VALUES (?,?,?,?,?,?,?,?,?,'recording') ON CONFLICT(turn_id) DO UPDATE SET started_at=excluded.started_at WHERE turn_journal_turns.kind='revert' AND turn_journal_turns.ended_at IS NULL", turnId, metadata.sessionId, metadata.actor, metadata.model, metadata.profile, metadata.policyHash, SELF.pid, SELF.start, now())])); end?.(); try { - end = timing?.("policy"); + end = steps?.("policy"); const policy = await capture.policy(metadata.coveredPaths); end?.(); signal?.throwIfAborted(); active.set(turnId, { policy, stop, sequence: 0, sessionId: metadata.sessionId }); publish(turnId); if (!scopeTimer) { scopeTimer = setInterval(() => { - void held(() => observe()).catch(error => { + void held(timing => observe(false, timing), false, options.observationTrace?.("periodic", null)).catch(error => { for (const [id, turn] of active) { void fail(id, error).catch(() => {}); turn.stop(error instanceof Error ? error : new Error(String(error))); } }); }, 15_000); @@ -541,7 +561,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { throw error instanceof JournalCapacityError || error instanceof JournalStorageUnavailable ? error : new JournalStorageUnavailable("native journal admission could not be prepared"); } - }, true); }, + }, true, options.observationTrace?.("begin", turnId), timing); }, async bindSession(turnId: string, sessionId: string): Promise { const turn = active.get(turnId); if (!turn) return; @@ -587,7 +607,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const effect = call ? toolObservation(call.name, call.path) : "unproven"; if (effect === "unproven" && active.has(turnId)) lasting.add(turnId); if (effect === "read" && !lasting.size && !calls.size) return Promise.resolve(); - return held(() => observe()); + return held(timing => observe(false, timing), false, options.observationTrace?.("tool", turnId, toolUseId)); }, /** * Cover one managed worktree (#2430) for an active turn before any of its @@ -649,23 +669,30 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (summary(turnId).state !== "recording") throw new JournalStorageUnavailable("policy observation became incomplete before the approved write"); try { await approvedWrite(); } finally { await observe(true); } }); }, - finish(turnId: string) { return held(async () => { + finish(turnId: string) { return held(async timing => { if (!active.has(turnId)) { if (failedAdmissions.has(turnId)) await finalizeRefusedAdmission(turnId); return; } - try { await observe(); } + try { await observe(false, timing); } finally { active.delete(turnId); lasting.delete(turnId); for (const [key, call] of calls) if (call.turnId === turnId) calls.delete(key); + let step = worktrees.size ? timing?.("finish_worktrees") : undefined; await dropWorktrees(turnId); + step?.(); if (!active.size) { clearInterval(scopeTimer); scopeTimer = undefined; } + step = timing?.("finish_record"); await write([ ...(failures.has(turnId) ? [statement("UPDATE turn_journal_turns SET state='partial',failure=? WHERE turn_id=?", failures.get(turnId)!.padEnd(64), turnId)] : []), statement("UPDATE turn_journal_turns SET ended_at=?,failure=trim(failure),state=CASE WHEN state='partial' OR missing!='[]' THEN 'partial' ELSE 'complete' END WHERE turn_id=?", now(), turnId), statement("DELETE FROM turn_journal_manifests WHERE turn_id=?", turnId), statement("DELETE FROM turn_journal_object_refs WHERE turn_id=? AND NOT EXISTS (SELECT 1 FROM turn_journal_changes c WHERE c.turn_id=? AND (json_extract(c.before_json,'$.hash')=turn_journal_object_refs.hash OR json_extract(c.after_json,'$.hash')=turn_journal_object_refs.hash)) AND NOT EXISTS (SELECT 1 FROM turn_journal_claude_memory m WHERE m.turn_id=? AND m.state!='saved' AND (json_extract(m.before_json,'$.hash')=turn_journal_object_refs.hash OR json_extract(m.after_json,'$.hash')=turn_journal_object_refs.hash))", turnId, turnId, turnId), ]); - await collectObjects(); publish(turnId); + step?.(); step = timing?.("finish_collect"); + await collectObjects(); + step?.(); step = timing?.("finish_publish"); + publish(turnId); + step?.(); } - }); }, + }, false, options.observationTrace?.("finish", turnId)); }, /** Ordinary current coverage only; never adds selected paths to ignored content. */ removalCoverage(paths: readonly string[], signal?: AbortSignal, absent = false): Promise { return held(async () => { if (paths.length > 32) throw new JournalStorageUnavailable("Too many selected attachments."); diff --git a/packages/ui-server/tests/admission-sub-phases.test.ts b/packages/ui-server/tests/admission-sub-phases.test.ts index e4a2012404..66025242e4 100644 --- a/packages/ui-server/tests/admission-sub-phases.test.ts +++ b/packages/ui-server/tests/admission-sub-phases.test.ts @@ -87,8 +87,9 @@ test("real journal begin records each step inside journalBeginMs", async () => { error => { throw error; }, undefined, lifecycle.timer("journal")); lifecycle.mark("journalBeganAt"); const record = store.lifecycle("turn-ithaca")!; - expect(names(record.subPhases!, "journal"), "JOURNAL_BEGIN_STEPS").toEqual(["hold_wait", "initialize", "observe", "observe_checkpoint", "observe_delta", - "observe_metadata", "observe_capture", "observe_record", "observe_commit", "expiry", "turn_insert", "policy"]); + // The first admission has no active turn to record, so no record steps apply (#2915). + expect(names(record.subPhases!, "journal"), "JOURNAL_BEGIN_STEPS").toEqual(["hold_wait", "initialize", "observe", "observe_reserve", "observe_checkpoint", "observe_delta", + "observe_metadata", "observe_capture", "observe_commit", "expiry", "turn_insert", "policy"]); expectWithin(record.subPhases!, "journal", record.journalStartedAt!, record.journalBeganAt!); const observe = record.subPhases!.find(step => step.name === "observe")!; expectWithin(record.subPhases!.filter(step => step.name.startsWith("observe_")), "journal", observe.startedAt, observe.endedAt!); diff --git a/packages/ui-server/tests/journal-observation-trace.test.ts b/packages/ui-server/tests/journal-observation-trace.test.ts new file mode 100644 index 0000000000..d866d85ddc --- /dev/null +++ b/packages/ui-server/tests/journal-observation-trace.test.ts @@ -0,0 +1,84 @@ +/** #2915: a held observation reports every step to its diagnostic trace, on one clock, inside its hold. */ +import { expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ActivityTurnLifecycle } from "@schlessera/brain-ui-sdk/protocol"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { createTurnJournal, type JournalTraceKind } from "../src/brain/turn-journal.js"; +import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; + +interface Step { name: string; startedAt: number; endedAt: number | null } +interface Trace { kind: JournalTraceKind; turnId: string | null; toolUseId?: string; steps: Step[]; done: boolean } +/** Steps that contain others; every other step is a leaf, and leaves never overlap. */ +const CONTAINERS = new Set(["hold", "observe"]); +const OBSERVE = ["observe_reserve", "observe_checkpoint", "observe_delta", "observe_metadata", "observe_capture"]; +const RECORD = ["observe_record", "observe_publish", "observe_facts"]; + +function expectNested(trace: Trace) { + const hold = trace.steps.find(step => step.name === "hold")!; + expect(trace.steps[0]?.name, `TRACE_HOLD_STARTS_FIRST ${trace.kind}`).toBe("hold"); + expect(trace.done, `TRACE_HOLD_ENDS_LAST ${trace.kind}`).toBe(true); + let previous = hold.startedAt; + for (const step of trace.steps.filter(item => !CONTAINERS.has(item.name))) { + expect(step.endedAt, `TRACE_STEP_ENDED ${trace.kind} ${step.name}`).not.toBeNull(); + // Sequential leaves: their sum never counts one interval twice. + expect(step.startedAt, `TRACE_LEAVES_DO_NOT_OVERLAP ${trace.kind} ${step.name}`).toBeGreaterThanOrEqual(previous); + expect(step.endedAt!, `TRACE_STEP_INSIDE_HOLD ${trace.kind} ${step.name}`).toBeLessThanOrEqual(hold.endedAt!); + previous = step.endedAt!; + } +} + +test("admission, a writer's result and finish trace each step inside the hold; the lifecycle never sees the hold", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-observation-trace-")), brain = join(root, "brain"), path = join(root, "ui.db"); + mkdirSync(join(brain, "notes"), { recursive: true }); + writeFileSync(join(brain, "notes", "ithaca.md"), "# Ithaca\n"); + const traces: Trace[] = []; + const native = createNativeJournalFixture(brain, root); + const db = createUiDb(path), journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: join(root, "objects"), + observationTrace(kind, turnId, toolUseId) { + const trace: Trace = { kind, turnId, ...(toolUseId ? { toolUseId } : {}), steps: [], done: false }; + traces.push(trace); + return name => { + const step: Step = { name, startedAt: performance.now(), endedAt: null }; + trace.steps.push(step); + return () => { step.endedAt = performance.now(); if (name === "hold") trace.done = true; }; + }; + } }); + const store = createActivityStore(createUiDb(":memory:")); + const metadata = { sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", policyHash: null } as const; + try { + await journal.ready; + await journal.begin("turn-telemachus", metadata, error => { throw error; }); + // A second admission records the active turn's observation, so its record steps apply. + const lifecycle = createTurnLifecycle(store, "turn-penelope", "ithaca", Date.now(), () => {}); + lifecycle.mark("journalStartedAt"); + await journal.begin("turn-penelope", metadata, error => { throw error; }, undefined, lifecycle.timer("journal")); + lifecycle.mark("journalBeganAt"); + writeFileSync(join(brain, "notes", "loom.md"), "Penelope weaves.\n"); + journal.toolStarted("turn-penelope", "write-1", "write_file", true); + journal.toolExecuted("turn-penelope", "write-1", "worker_write"); + await journal.toolEnded("turn-penelope", "write-1"); + await journal.finish("turn-penelope"); + await journal.finish("turn-telemachus"); + + expect(traces.map(trace => trace.kind), "TRACE_EVERY_HELD_OBSERVATION").toEqual(["begin", "begin", "tool", "finish", "finish"]); + const begin = traces.find(trace => trace.kind === "begin" && trace.turnId === "turn-penelope")!; + const names = (trace: Trace) => trace.steps.map(step => step.name); + expect(names(begin), "TRACE_BEGIN_STEPS").toEqual(["hold", "hold_wait", "initialize", "observe", ...OBSERVE, ...RECORD, "observe_commit", "expiry", "turn_insert", "policy"]); + const steps = (store.lifecycle("turn-penelope")!.subPhases ?? []) as NonNullable; + // The lifecycle keeps its own vocabulary: every traced step but the hold. + expect(steps.map(step => step.name), "LIFECYCLE_SEES_EVERY_STEP_BUT_THE_HOLD").toEqual(names(begin).slice(1)); + + const writer = traces.find(trace => trace.kind === "tool" && trace.toolUseId === "write-1")!; + expect(writer?.turnId, "TRACE_NAMES_THE_CALL").toBe("turn-penelope"); + expect(names(writer), "TRACE_WRITER_STEPS").toEqual(["hold", "hold_wait", ...OBSERVE, ...RECORD, ...RECORD, "observe_commit"]); + + const finish = traces.find(trace => trace.kind === "finish" && trace.turnId === "turn-penelope")!; + expect(names(finish), "TRACE_FINISH_STEPS").toEqual(["hold", "hold_wait", ...OBSERVE, ...RECORD, ...RECORD, "observe_commit", + "finish_record", "finish_collect", "finish_publish"]); + for (const trace of traces) expectNested(trace); + } finally { await journal.close(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index bdf52e5d43..09cff0defc 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -54,6 +54,22 @@ phases and steps per scenario, and the host load before and after are in `observation-timing.json`. It is a measurement, not part of the default qualification. +Its `phases` section (#2915) attributes each observed writer's worker hold and +each harbour turn's journal begin and finish to their steps: the queue for the +journal, the wait for room behind earlier releases, checkpoint, delta, +metadata reads, capture, each turn's record, publication and facts query, the +commit and, for finish, its end record, object collection and publication. The +app child stamps the journal's internal observation trace, and the fixture's +manager stamps each request's lock wait (with the operation it waited behind) +and its steps, both with `performance.timeOrigin + performance.now()`. A +checkpoint or delta step is broken down by the one manager request that arrived +inside it; the run fails unless every such step pairs with exactly one request +and each checkpoint answered before its step ended, which is the proof that +the two processes' clocks agree. Per-phase medians count an absent phase as +zero; coverage is attributed time over the independently measured hold or +journal call. `observation-traces.json` keeps the raw traces and manager spans +(`scripts/native-proof/observation-phases.ts`). + `bun scripts/prove-worker-identity.ts` is a separate required runtime cell for the host identity protocol. It compiles the test-only helper on the host without setuid permissions, then installs it as root-owned setuid only inside its owned, diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 23036fd2ff..759f60c895 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -66,8 +66,17 @@ if (OBSERVATION_TIMING) { // clock reads 31 days earlier, so the turns it records end past retention. const journals = await import(join(source!, "packages/ui-server/src/brain/turn-journal.ts")); const createTurnJournal = journals.createTurnJournal, backdated = join(dir!, "journal-backdated"); + // #2915: every step of every held observation, on the clock the fixture's manager stamps its spans with. + const clock = () => performance.timeOrigin + performance.now(); + const observationTrace = (traceKind: string, turnId: string | null, toolUseId?: string) => { + const steps: { name: string; startedAt: number; endedAt: number | null }[] = []; + return (name: string) => { + const step = { name, startedAt: clock(), endedAt: null as number | null }; steps.push(step); + return () => { step.endedAt = clock(); if (name === "hold") event("observation_trace", { traceKind, turnId, toolUseId: toolUseId ?? null, steps }); }; + }; + }; spyOn(journals, "createTurnJournal").mockImplementation((...args: Parameters) => - createTurnJournal(args[0], { ...(args[1] as object), now: () => Date.now() - (existsSync(backdated) ? 31 * 24 * 60 * 60 * 1000 : 0) })); + createTurnJournal(args[0], { ...(args[1] as object), now: () => Date.now() - (existsSync(backdated) ? 31 * 24 * 60 * 60 * 1000 : 0), observationTrace })); const bridges = await import(join(source!, "packages/ui-server/src/ws/bridge.ts")); const makeBridge = bridges.makeBridge; spyOn(bridges, "makeBridge").mockImplementation(async (...args: Parameters) => { diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index fda71e7be3..9d5e5e9857 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -9,6 +9,7 @@ import { nativeReleaseObservations } from "./native-release-observation.js"; import { Database } from "bun:sqlite"; import { NativeEventLog } from "./event-log.js"; import { proveRecoveryInventory } from "./recovery-inventory.js"; +import { observationPhases, summarizePhases, median as phaseMedian, type ManagerSpan, type ObservationTrace, type PhaseSample } from "./observation-phases.js"; const SOURCE = "/repo"; const ARTIFACTS = "/proof/run"; @@ -74,9 +75,11 @@ print(json.dumps(result))`; const fsid = /^fsid\s+([0-9a-f-]+)/m.exec(fs.stdout.toString())![1]!; mkdirSync("/native-runtime", { mode: 0o755, recursive: true }); const socket = "/native-runtime/manager.sock"; + // #2915: every manager operation's lock wait and steps, kept in memory so recording adds no write to its path. + const managerSpans: ManagerSpan[] = []; const service = await serveNativeBrainManager({ storePath: "/brain-fixture", devicePath: "/dev/brain-native-proof-loop", fsid, brainUuid, socketPath: socket, appUid: APP_UID, appGid: APP_UID, stageAllowanceBytes: staging.allowanceBytes, stageBudgetBytes: staging.budgetBytes, - capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * 1024 ** 2 }); + capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * 1024 ** 2 }, OBSERVATION_TIMING ? { trace: (span: ManagerSpan) => { managerSpans.push(span); } } : {}); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const admitted = await createNativeBrainManagerClient({ socketPath: socket }).ready(); expect(admitted.privatePaths, "NATIVE_ADMITTED_EXACT_BACKING_PRIVATE_PATH").toContain("/native-backing/fixture.img"); @@ -349,7 +352,7 @@ print(json.dumps(result))`; const within = (at: number) => result && next && at >= result.at - 1 && at <= next.at; const observed = captures.filter(row => within(row.at)); const frozenAt = freezes.find(row => within(row.at))?.at, resumedAt = frozenAt === undefined ? undefined : resumes.find(row => row.at >= frozenAt && (!next || row.at <= next.at))?.at; - return { step: response.step, tool: response.tool, label: response.label as string, isError: result?.isError ?? null, roundTripMs, toolMs, + return { step: response.step, tool: response.tool, label: response.label as string, toolUseId: response.toolUseId as string, isError: result?.isError ?? null, roundTripMs, toolMs, addedMs: roundTripMs !== null && toolMs !== null ? roundTripMs - toolMs : null, resultToNextRequestMs: result && next ? next.at - result.at : null, captures: observed.length, frozenMs: frozenAt !== undefined && resumedAt !== undefined ? resumedAt - frozenAt : null, resumeToNextRequestMs: resumedAt !== undefined && next ? next.at - resumedAt : null }; @@ -428,12 +431,41 @@ print(json.dumps(result))`; const beginFinish = harbour.map(turnId => ({ turnId, beginMs: elapsed("journal_begin_end", turnId) ?? null, finishMs: elapsed("journal_finish_end", turnId) ?? null })) .map(row => ({ ...row, totalMs: row.beginMs !== null && row.finishMs !== null ? row.beginMs + row.finishMs : null })); const total = (field: "beginMs" | "finishMs" | "totalMs") => beginFinish.map(row => row[field]).filter((value): value is number => value !== null); + // #2915: each writer's hold and each harbour turn's begin and finish, attributed to its steps. + const traces: ObservationTrace[] = eventLog.read("observation-trace").filter(row => row.kind === "observation_trace") + .map(row => ({ kind: row.traceKind, turnId: row.turnId, ...(row.toolUseId ? { toolUseId: row.toolUseId } : {}), steps: row.steps })); + writeFileSync(join(ARTIFACTS, "observation-traces.json"), JSON.stringify({ traces, managerSpans })); + const WRITERS = ["write_file", "edit_file", "bash write"]; + const writers = (timeline?.calls ?? []).filter(call => WRITERS.includes(call.label)).flatMap(call => { + const trace = traces.find(item => item.kind === "tool" && item.toolUseId === call.toolUseId); + return trace ? [{ label: call.label, sample: { phases: observationPhases(trace, managerSpans), measuredMs: call.frozenMs } as PhaseSample }] : []; + }); + const journalSamples = (kind: "begin" | "finish", field: "beginMs" | "finishMs") => beginFinish.flatMap(row => { + const trace = traces.find(item => item.kind === kind && item.turnId === row.turnId); + return trace ? [{ phases: observationPhases(trace, managerSpans), measuredMs: row[field] }] : []; + }); + const begins = journalSamples("begin", "beginMs"), finishes = journalSamples("finish", "finishMs"); + const pairedTotals = begins.flatMap((begin, i) => finishes[i] ? [begin.phases.holdMs + finishes[i]!.phases.holdMs] : []); + const begin = summarizePhases(begins), finish = summarizePhases(finishes); + const observationSteps = { + clock: "performance.timeOrigin + performance.now() in the app child and the fixture's manager; a manager request counts toward the app step it arrived in", + writer: { all: summarizePhases(writers.map(item => item.sample)), + byTool: Object.fromEntries(WRITERS.map(label => [label, summarizePhases(writers.filter(item => item.label === label).map(item => item.sample))])) }, + begin, finish, + beginPlusFinish: { pairedHoldMedianMs: phaseMedian(pairedTotals), sumOfHoldMediansMs: begin.hold.medianMs !== null && finish.hold.medianMs !== null ? begin.hold.medianMs + finish.hold.medianMs : null, pairs: pairedTotals.length }, + traces: traces.length, managerSpans: managerSpans.length, + }; const result = { backend: BACKEND, appUid: APP_UID, files: FILES, bytes: BYTES, loadBefore, loadAfter: load(), elapsedMs: performance.now() - timingStart, timelineTurnIds, tools: timeline?.tools ?? null, admission, journal: { begin: { medianMs: median(total("beginMs")), p95Ms: p95(total("beginMs")) }, finish: { medianMs: median(total("finishMs")), p95Ms: p95(total("finishMs")) }, - beginPlusFinish: { medianMs: median(total("totalMs")), p95Ms: p95(total("totalMs")) }, turns: beginFinish }, calls: timeline?.calls ?? null }; + beginPlusFinish: { medianMs: median(total("totalMs")), p95Ms: p95(total("totalMs")) }, turns: beginFinish }, phases: observationSteps, calls: timeline?.calls ?? null }; writeFileSync(join(ARTIFACTS, "observation-timing.json"), JSON.stringify(result, null, 2)); console.log(JSON.stringify({ observationTiming: { ...result, calls: undefined, journal: { ...result.journal, turns: undefined } } })); expect(total("totalMs"), "OBSERVATION_TIMING_10_HARBOUR_TURNS").toHaveLength(10); + expect([begins.length, finishes.length], "OBSERVATION_TIMING_HARBOUR_TRACES").toEqual([10, 10]); + if (timeline) expect(writers.length, "OBSERVATION_TIMING_EVERY_OBSERVED_WRITER_TRACED").toBe(timeline.calls.filter(call => WRITERS.includes(call.label) && call.captures).length); + // One clock: every native step paired with exactly one request that arrived in it, and each checkpoint answered before its step ended. + for (const [name, summary] of Object.entries({ writer: observationSteps.writer.all, begin, finish })) + expect([name, summary.clock.unpaired, (summary.clock.minEndSlackMs ?? 0) >= 0], "OBSERVATION_TIMING_ONE_CLOCK").toEqual([name, [], true]); for (const [name, row] of Object.entries({ ...admission.scenarios, ...Object.fromEntries(warm.map((row, i) => [`warm-${i}`, row])) })) expect(row?.journalBeginMs !== null && row?.governedAdmissionMs !== null && Object.keys(row?.steps ?? {}).length > 0, `OBSERVATION_TIMING_ADMISSION_STEPS_RECORDED ${name}`).toBe(true); if (timeline) { diff --git a/scripts/native-proof/observation-phases.ts b/scripts/native-proof/observation-phases.ts new file mode 100644 index 0000000000..852dba312a --- /dev/null +++ b/scripts/native-proof/observation-phases.ts @@ -0,0 +1,120 @@ +/** + * #2915: attribute a journal observation's hold, and journal begin and finish, + * to their steps on one clock. The app child stamps its journal trace and the + * fixture's manager stamps its spans with `performance.timeOrigin + + * performance.now()`; a manager request counts toward an app step only when + * it arrived inside that step, and each pairing's slack is kept as the proof + * that the two processes' clocks agree. + */ + +export interface TraceStep { name: string; startedAt: number; endedAt: number | null } +export interface ObservationTrace { kind: string; turnId: string | null; toolUseId?: string; steps: TraceStep[] } +export interface ManagerSpan { request: number; operation: string; phase: string; startedAt: number; endedAt: number; holder?: string | null } + +/** Steps that contain other steps; every other step is a leaf, and leaves never overlap. */ +const CONTAINERS = new Set(["hold", "observe"]); +/** The manager operation an app step calls, for its finer breakdown. */ +const NATIVE_STEPS: Record = { observe_checkpoint: "checkpoint", observe_delta: "delta" }; + +export interface ObservationPhases { + /** The traced hold, `hold` itself. */ + holdMs: number; + /** Leaf steps, a repeated name summed. */ + phases: Record; + /** Each app step's manager request: its spans by phase, `transport` outside the manager and `other` inside it but in no span. */ + native: Record; + /** The operation that held the manager lock when each native request began to wait, with the time waited. */ + lockWaits: { step: string; holder: string | null; ms: number }[]; + attributedMs: number; + incomplete: string[]; + clock: { paired: number; unpaired: string[]; minStartSlackMs: number | null; minEndSlackMs: number | null }; +} + +const duration = (step: { startedAt: number; endedAt: number | null }) => step.endedAt === null ? 0 : Math.max(0, step.endedAt - step.startedAt); +const add = (into: Record, key: string, ms: number) => { into[key] = (into[key] ?? 0) + ms; }; + +export function observationPhases(trace: ObservationTrace, spans: readonly ManagerSpan[]): ObservationPhases { + const hold = trace.steps.find(step => step.name === "hold"); + if (!hold || hold.endedAt === null) throw Error(`OBSERVATION_TRACE_HAS_NO_ENDED_HOLD ${trace.kind} ${trace.turnId}`); + const phases: Record = {}, native: Record = {}, incomplete: string[] = [], unpaired: string[] = []; + const lockWaits: ObservationPhases["lockWaits"] = []; + let minStartSlackMs: number | null = null, minEndSlackMs: number | null = null, paired = 0; + const requests = new Map(); + for (const span of spans) requests.set(span.request, [...(requests.get(span.request) ?? []), span]); + for (const step of trace.steps) { + if (CONTAINERS.has(step.name)) continue; + if (step.endedAt === null) { incomplete.push(step.name); continue; } + add(phases, step.name, duration(step)); + const operation = NATIVE_STEPS[step.name]; + if (!operation) continue; + // The one request of that operation which arrived inside this step. + const matches = [...requests.values()].filter(request => { + const wait = request.find(span => span.phase === "lock_wait"); + return request[0]!.operation === operation && wait && wait.startedAt >= step.startedAt && wait.startedAt <= step.endedAt!; + }); + if (matches.length !== 1) { unpaired.push(`${step.name}:${matches.length}`); continue; } + const request = matches[0]!, wait = request.find(span => span.phase === "lock_wait")!, lock = request.find(span => span.phase === "held"); + paired++; + const startSlack = wait.startedAt - step.startedAt; + minStartSlackMs = minStartSlackMs === null ? startSlack : Math.min(minStartSlackMs, startSlack); + lockWaits.push({ step: step.name, holder: wait.holder ?? null, ms: duration(wait) }); + let inside = 0; + for (const span of request) { + if (span.phase === "held") continue; + add(native, `${operation}.${span.phase}`, duration(span)); + if (span.phase !== "lock_wait") inside += duration(span); + } + if (lock) { + add(native, `${operation}.other`, Math.max(0, duration(lock) - inside)); + // A control response returns before its step ends; a streamed send may end with it. + if (operation === "checkpoint") { + const endSlack = step.endedAt! - lock.endedAt; + minEndSlackMs = minEndSlackMs === null ? endSlack : Math.min(minEndSlackMs, endSlack); + } + add(native, `${operation}.transport`, Math.max(0, duration(step) - (lock.endedAt - wait.startedAt))); + } + } + const attributedMs = Object.values(phases).reduce((sum, ms) => sum + ms, 0); + return { holdMs: duration(hold), phases, native, lockWaits, attributedMs, incomplete, clock: { paired, unpaired, minStartSlackMs, minEndSlackMs } }; +} + +const sorted = (values: number[]) => [...values].sort((a, b) => a - b); +export const median = (values: number[]) => values.length ? sorted(values)[Math.floor(values.length / 2)]! : null; +export const p95 = (values: number[]) => values.length ? sorted(values)[Math.ceil(values.length * 0.95) - 1]! : null; +const round = (value: number | null) => value === null ? null : Math.round(value * 10) / 10; + +export interface PhaseSample { phases: ObservationPhases; /** The independently measured hold or call: freeze to resume, or the journal method's own time. */ measuredMs: number | null } + +/** + * Per-phase medians over the samples, a phase absent from a sample counting as + * zero, and the coverage of each sample: attributed leaf time over its measured + * time (the traced hold when nothing else measured it). + */ +export function summarizePhases(samples: readonly PhaseSample[]) { + const names = (pick: (sample: PhaseSample) => Record) => [...new Set(samples.flatMap(sample => Object.keys(pick(sample))))]; + const table = (pick: (sample: PhaseSample) => Record) => Object.fromEntries(names(pick).map(name => { + const values = samples.map(sample => pick(sample)[name] ?? 0); + return [name, { medianMs: round(median(values)), p95Ms: round(p95(values)), present: samples.filter(sample => name in pick(sample)).length }]; + })); + const coverage = samples.map(sample => sample.phases.attributedMs / (sample.measuredMs ?? sample.phases.holdMs)); + const holders: Record = {}; + for (const sample of samples) for (const wait of sample.phases.lockWaits) if (wait.ms >= 1) holders[`${wait.step}:${wait.holder ?? "none"}`] = (holders[`${wait.step}:${wait.holder ?? "none"}`] ?? 0) + 1; + const measured = samples.map(sample => sample.measuredMs).filter((value): value is number => value !== null); + const startSlacks = samples.map(sample => sample.phases.clock.minStartSlackMs).filter((value): value is number => value !== null); + const endSlacks = samples.map(sample => sample.phases.clock.minEndSlackMs).filter((value): value is number => value !== null); + return { + samples: samples.length, + measured: { medianMs: round(median(measured)), p95Ms: round(p95(measured)), samples: measured.length }, + hold: { medianMs: round(median(samples.map(sample => sample.phases.holdMs))), p95Ms: round(p95(samples.map(sample => sample.phases.holdMs))) }, + attributed: { medianMs: round(median(samples.map(sample => sample.phases.attributedMs))) }, + unattributed: { medianMs: round(median(samples.map(sample => (sample.measuredMs ?? sample.phases.holdMs) - sample.phases.attributedMs))) }, + coverage: { medianPct: round(median(coverage) === null ? null : median(coverage)! * 100), minPct: round(coverage.length ? Math.min(...coverage) * 100 : null) }, + phases: table(sample => sample.phases.phases), + native: table(sample => sample.phases.native), + /** Native requests that waited at least 1 ms, by step and the operation they waited behind. */ + lockWaitsBehind: holders, + incomplete: samples.filter(sample => sample.phases.incomplete.length).length, + clock: { paired: samples.reduce((sum, sample) => sum + sample.phases.clock.paired, 0), unpaired: samples.flatMap(sample => sample.phases.clock.unpaired), + minStartSlackMs: round(startSlacks.length ? Math.min(...startSlacks) : null), minEndSlackMs: round(endSlacks.length ? Math.min(...endSlacks) : null) }, + }; +} diff --git a/tests/native-observation-phases.test.ts b/tests/native-observation-phases.test.ts new file mode 100644 index 0000000000..db8a8cedd7 --- /dev/null +++ b/tests/native-observation-phases.test.ts @@ -0,0 +1,68 @@ +/** #2915: attributing a native journal observation's hold to its steps on one clock. */ +import { expect, test } from "bun:test"; +import { observationPhases, summarizePhases, type ManagerSpan, type ObservationTrace } from "../scripts/native-proof/observation-phases.js"; + +const step = (name: string, startedAt: number, endedAt: number | null) => ({ name, startedAt, endedAt }); +/** A writer's hold at 1000-1100: it waited 5 ms, took a checkpoint that queued behind a release, then a delta. */ +const writer: ObservationTrace = { kind: "tool", turnId: "turn-telemachus", toolUseId: "write-1", steps: [ + step("hold", 1000, 1100), step("hold_wait", 1000, 1005), step("observe_reserve", 1005, 1006), + step("observe_checkpoint", 1006, 1066), step("observe_delta", 1066, 1080), step("observe_metadata", 1080, 1082), + step("observe_record", 1082, 1090), step("observe_commit", 1090, 1092), +] }; +const spans: ManagerSpan[] = [ + // A release handed off by the previous observation, still holding the lock. + { request: 1, operation: "release", phase: "lock_wait", startedAt: 990, endedAt: 990, holder: null }, + { request: 1, operation: "release", phase: "held", startedAt: 990, endedAt: 1040 }, + { request: 2, operation: "checkpoint", phase: "lock_wait", startedAt: 1007, endedAt: 1040, holder: "release" }, + { request: 2, operation: "checkpoint", phase: "held", startedAt: 1040, endedAt: 1064 }, + { request: 2, operation: "checkpoint", phase: "qualify", startedAt: 1040, endedAt: 1045 }, + { request: 2, operation: "checkpoint", phase: "intent", startedAt: 1045, endedAt: 1048 }, + { request: 2, operation: "checkpoint", phase: "snapshot", startedAt: 1048, endedAt: 1058 }, + { request: 2, operation: "checkpoint", phase: "verify", startedAt: 1058, endedAt: 1060 }, + { request: 2, operation: "checkpoint", phase: "intent", startedAt: 1060, endedAt: 1063 }, + { request: 3, operation: "delta", phase: "lock_wait", startedAt: 1067, endedAt: 1067, holder: null }, + { request: 3, operation: "delta", phase: "held", startedAt: 1067, endedAt: 1079 }, + { request: 3, operation: "delta", phase: "verify", startedAt: 1067, endedAt: 1069 }, + { request: 3, operation: "delta", phase: "send", startedAt: 1069, endedAt: 1079 }, +]; + +test("leaves sum without the containers; each native step is broken down by its own request", () => { + const phases = observationPhases(writer, spans); + expect(phases.holdMs, "PHASES_HOLD").toBe(100); + expect(phases.phases, "PHASES_LEAVES").toEqual({ hold_wait: 5, observe_reserve: 1, observe_checkpoint: 60, observe_delta: 14, observe_metadata: 2, observe_record: 8, observe_commit: 2 }); + expect(phases.attributedMs, "PHASES_ATTRIBUTED_IS_THE_LEAF_SUM").toBe(92); + // 60 ms of checkpoint: 33 queued behind the release, 23 in spans, 1 in the manager outside them, 3 in transport. + expect(phases.native, "PHASES_NATIVE_BREAKDOWN").toEqual({ "checkpoint.lock_wait": 33, "checkpoint.qualify": 5, "checkpoint.intent": 6, "checkpoint.snapshot": 10, + "checkpoint.verify": 2, "checkpoint.other": 1, "checkpoint.transport": 3, + "delta.lock_wait": 0, "delta.verify": 2, "delta.send": 10, "delta.other": 0, "delta.transport": 2 }); + expect(phases.lockWaits, "PHASES_LOCK_WAIT_NAMES_ITS_HOLDER").toEqual([{ step: "observe_checkpoint", holder: "release", ms: 33 }, { step: "observe_delta", holder: null, ms: 0 }]); + expect(phases.clock, "PHASES_CLOCK_PROOF").toEqual({ paired: 2, unpaired: [], minStartSlackMs: 1, minEndSlackMs: 2 }); +}); + +test("a request outside its step stays unpaired, and an unended step is reported, not counted", () => { + // A manager clock 10 ms ahead puts the checkpoint's arrival after its step began, but the + // control response after the step ended: the end slack turns negative. + const late = spans.map(span => span.request === 2 ? { ...span, startedAt: span.startedAt + 10, endedAt: span.endedAt + 10 } : span); + expect(observationPhases(writer, late).clock.minEndSlackMs, "PHASES_CLOCK_SKEW_SHOWS_IN_END_SLACK").toBe(-8); + // 30 ms behind, it arrived before the step began: no request pairs with it. + const early = spans.map(span => span.request === 2 ? { ...span, startedAt: span.startedAt - 30, endedAt: span.endedAt - 30 } : span); + const unpaired = observationPhases(writer, early); + expect(unpaired.clock.unpaired, "PHASES_UNPAIRED_STEP_REPORTED").toEqual(["observe_checkpoint:0"]); + expect(Object.keys(unpaired.native).some(name => name.startsWith("checkpoint.")), "PHASES_UNPAIRED_STEP_HAS_NO_BREAKDOWN").toBe(false); + const failed = observationPhases({ ...writer, steps: [...writer.steps.slice(0, 4), step("observe_delta", 1066, null)] }, spans); + expect([failed.incomplete, "observe_delta" in failed.phases], "PHASES_UNENDED_STEP_NOT_COUNTED").toEqual([["observe_delta"], false]); + expect(() => observationPhases({ ...writer, steps: writer.steps.slice(1) }, spans), "PHASES_REQUIRE_AN_ENDED_HOLD").toThrow("OBSERVATION_TRACE_HAS_NO_ENDED_HOLD"); +}); + +test("summaries take medians per phase with an absent phase as zero, and cover the independently measured time", () => { + const one = observationPhases(writer, spans); + const two = observationPhases({ ...writer, steps: writer.steps.filter(item => item.name !== "observe_reserve") }, spans); + const summary = summarizePhases([{ phases: one, measuredMs: 100 }, { phases: two, measuredMs: 120 }, { phases: two, measuredMs: 200 }]); + expect(summary.phases.observe_reserve, "SUMMARY_ABSENT_PHASE_IS_ZERO").toEqual({ medianMs: 0, p95Ms: 1, present: 1 }); + expect(summary.measured, "SUMMARY_MEASURED").toEqual({ medianMs: 120, p95Ms: 200, samples: 3 }); + // 92/100, 91/120 and 91/200 of the measured time. + expect(summary.coverage, "SUMMARY_COVERAGE_AGAINST_MEASURED").toEqual({ medianPct: 75.8, minPct: 45.5 }); + expect(summary.unattributed.medianMs, "SUMMARY_UNATTRIBUTED").toBe(29); + expect(summary.lockWaitsBehind, "SUMMARY_LOCK_WAITS_BEHIND").toEqual({ "observe_checkpoint:release": 3 }); + expect(summary.clock, "SUMMARY_CLOCK").toEqual({ paired: 6, unpaired: [], minStartSlackMs: 1, minEndSlackMs: 2 }); +});