diff --git a/apps/brunch-agent/AGENTS.md b/apps/brunch-agent/AGENTS.md index 01759418291..352bd2e3e7a 100644 --- a/apps/brunch-agent/AGENTS.md +++ b/apps/brunch-agent/AGENTS.md @@ -4,7 +4,7 @@ HASH root guidance applies. Agents, their layout and how to add a candidate are This application composes the Flue runtime, HTTP routes, and Brunch agents. It must remain independent of Petrinaut UI (`@hashintel/petrinaut`); it may import published catalogs from `@hashintel/petrinaut-core`. `apps/petrinaut-website` meets the editor through the AI SDK/HTTP transport. -When diagnosing a slow, failed or stalled chat, start with `yarn workspace @apps/brunch-agent diagnose`, not raw logs or hand-written LogQL. For each model request it reports the provider and model, the time until the response started, retries, failures and idle timeouts, along with the request's span. The [`README.md`](README.md) gives its sources and flags. +When diagnosing a slow, failed or stalled chat, start with `yarn workspace @apps/brunch-agent diagnose`, not raw logs or hand-written LogQL. For each model request it reports the provider and model, when the provider's HTTP response arrived, retries, failures and idle timeouts, along with the request's span. For each step it shows where the time went (reasoning blocks, reply text, tool arguments), its tokens and estimated cost, and how long its tools took to run. The [`README.md`](README.md) gives its sources and flags. Before changing Flue or Pi versions or patches, read [`docs/dependency-patches.md`](docs/dependency-patches.md) for the retained contracts, removed interventions and removal proofs. Upgrade the pair together and verify the built application; package-definition tests alone do not prove native validation, projection or crash recovery. diff --git a/apps/brunch-agent/README.md b/apps/brunch-agent/README.md index dc14666db8c..ab149876a71 100644 --- a/apps/brunch-agent/README.md +++ b/apps/brunch-agent/README.md @@ -35,7 +35,7 @@ Print a human-readable transcript of one conversation from that same Flue histor yarn workspace @apps/brunch-agent transcript -- --actor-key --id ``` -Read the provider telemetry back with `diagnose`. For each model request it shows the provider and model, the time until the response started, retries, failures and idle timeouts, and the request's span with the HTTP requests under it. It shows metadata only, never prompts or output. It reads Loki and Tempo through Grafana, by default the local stack's at `http://localhost:3001`. Locally, the server exports only when started with `HASH_OTLP_ENDPOINT=http://localhost:4317 yarn dev:brunch`. Another Grafana takes `--grafana ` with a token in `GRAFANA_TOKEN`; the token is only sent over HTTPS or to `localhost`. To read a saved server log or piped output instead, pass `--log ` or `--log -`; that has no spans. Unreadable lines, and reads cut off at Loki's or Tempo's limit, are reported on stderr so a short count is not taken for a complete one. +Read the provider telemetry back with `diagnose`. For each model request it shows the provider and model, when the provider's HTTP response arrived (Pi's first event comes with the response headers, before any output), retries, failures and idle timeouts, and the request's span with the HTTP requests under it. For each step it shows where the time went: the time spent in reasoning blocks and how many there were, when the reply text and the tool arguments started and stopped streaming, which tools the step called, the tokens in with cache reads and cache writes apart, the tokens out with the reasoning tokens among them, and Pi's catalogue estimate of the step's cost. Under each step it shows how long its tools took to run, from their spans; calls of a step whose spans overlap ran as one batch, so a batch shows once with its call count, timed from its earliest start to its latest end. Lines logged before a field existed show it as `–`. It shows metadata only, never prompts or output. It reads Loki and Tempo through Grafana, by default the local stack's at `http://localhost:3001`. Locally, the server exports only when started with `HASH_OTLP_ENDPOINT=http://localhost:4317 yarn dev:brunch`. Another Grafana takes `--grafana ` with a token in `GRAFANA_TOKEN`; the token is only sent over HTTPS or to `localhost`. To read a saved server log or piped output instead, pass `--log ` or `--log -`; that has no spans. Spans are searched from the submission's first step to its settlement, so `--since` can reach back further than Tempo's 168-hour search limit; without a chronology line that places them, the search covers the whole window, and over 168 hours `diagnose` says so and exits with an error, asking for `--since 7d` or less. When Tempo no longer holds a submission's spans, the chronology is still shown and the output says the spans are out of reach; when only some steps lack their `chat` span, it names them. Unreadable lines and reads cut off at Loki's or Tempo's limit are reported on stderr so a short count is not taken for a complete one. ```sh yarn workspace @apps/brunch-agent diagnose # settled submissions in the last hour @@ -168,7 +168,11 @@ The application exports Flue traces, logs, and metrics through HASH's shared Ope tool payloads, and credentials are not recorded, and the app's own failure spans carry an error code rather than a message. On SIGTERM Flue drains active work for up to 30 seconds, then closes the Postgres runner, whose close hook shuts the OpenTelemetry providers down; a 60-second outer timer -force-exits. Give the ECS task a stop timeout above 60 seconds. +force-exits. Give the ECS task a stop timeout above 60 seconds. The local SQLite store's close +sends the spans and metrics already recorded without shutting the providers down, because a source +change under `vite dev` closes the store while the server and its exporters run on. Log records are +not sent on that close: those from the last second before a stop can still be lost, and only a flush +exposed by the shared setup would cover them. Brunch does not mount the retired `/api/chat` path; requests to it return 404. `/agents/petrinaut/:instanceId` is the product door required by Petrinaut; `/agents/chat/:instanceId` diff --git a/apps/brunch-agent/evals/persona/README.md b/apps/brunch-agent/evals/persona/README.md index 00e4702d096..6a7e079f45e 100644 --- a/apps/brunch-agent/evals/persona/README.md +++ b/apps/brunch-agent/evals/persona/README.md @@ -93,6 +93,8 @@ The persona stops by its own rule: when the person has what they came for, when **Persona runs have no automatic accounting cutoff.** The launcher disables the campaign accounting wrapper for Brunch even if `BRUNCH_STEP_A_ACCOUNTING` was inherited. `--max-messages ` stops the run once Brunch has replied to the persona's nth message; the case's opening is not counted, and the run packet is written as on any other stop. With `--hold`, the persona stopping, whether at that limit, by `persona end` or by its agent exiting, closes nothing: the bridge refuses any further persona messages and you carry on in the same Chrome window and conversation. Ctrl-C in the launcher (once a foreground agent has exited) or closing Chrome then stops the run as usual. A live-provider run requires explicit model and spend authorization; the existence of this command grants none. +Stopping a run sends SIGTERM to the `yarn` process that leads each service it started, and each yarn layer passes it on, so the dev server receives it once and closes: Flue stops, and the store's close sends the spans and metrics already recorded. A service still running 10 seconds after the signal is killed with its whole process group. For that case the launcher also starts the services with `OTEL_BSP_SCHEDULE_DELAY=200`, so a settled turn's spans leave for the collector within 200 ms. Log records are not sent on the close, so those from the last second before the stop can still be lost. + ## Guidance provenance `run.json` records a fingerprint of the agent's guidance and Ledger sources (`guidance-manifest.ts`), the case hash and the model settings. Guidance drift is checked before each subsequent persona turn, and a resume refuses changed guidance. These are source fingerprints, not a complete environment snapshot. diff --git a/apps/brunch-agent/evals/persona/launch.test.ts b/apps/brunch-agent/evals/persona/launch.test.ts index 927bda6871f..d517d7317cc 100644 --- a/apps/brunch-agent/evals/persona/launch.test.ts +++ b/apps/brunch-agent/evals/persona/launch.test.ts @@ -1,4 +1,5 @@ -import { execFile } from "node:child_process"; +import { execFile, spawn } from "node:child_process"; +import { once } from "node:events"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, relative } from "node:path"; @@ -21,6 +22,7 @@ import { recordingReadySummary, responds, settlePersonaLauncherStop, + stopServiceGroups, } from "./launch.ts"; import { appendAdmittedUtterance } from "./launch/bridge-log.ts"; import { resolvePersonaDriver } from "./launch/driver.ts"; @@ -84,6 +86,60 @@ test("launcher Stop bounds an unobserved settlement", async () => { }); }); +// A server that closes on its first SIGTERM, as Vite does, behind a parent that +// forwards every SIGTERM it receives to it, as each yarn layer does. +const closingServer = ` +process.once("SIGTERM", () => { + // The close takes a moment, as Vite's does while Flue stops. + setTimeout(() => { + process.stdout.write("closed\\n"); + process.exit(143); + }, 200); +}); +process.stdout.write("ready\\n"); +setInterval(() => {}, 1000); +`; +const forwardingParent = ` +const { spawn } = require("node:child_process"); +const server = spawn(process.execPath, ["-e", ${JSON.stringify(closingServer)}], { + stdio: ["ignore", "inherit", "inherit"], +}); +process.on("SIGTERM", () => server.kill()); +server.on("exit", (code) => process.exit(code ?? 129)); +`; + +test("stopping a service lets its server finish closing", async () => { + const leader = spawn(process.execPath, ["-e", forwardingParent], { + detached: true, + stdio: ["ignore", "pipe", "inherit"], + }); + let output = ""; + leader.stdout.setEncoding("utf8"); + const ready = new Promise((resolve) => { + leader.stdout.on("data", (chunk: string) => { + output += chunk; + if (output.includes("ready")) resolve(); + }); + }); + const exited = once(leader, "exit"); + const { pid } = leader; + if (pid === undefined) throw new Error("The test service did not start"); + try { + await ready; + + await stopServiceGroups([pid]); + + expect(await exited).toEqual([143, null]); + expect(output).toContain("closed"); + } finally { + try { + process.kill(-pid, "SIGKILL"); + } catch { + // The group has already exited. + } + } +}); + const loadingRuntimeUnavailable = { error: { type: "runtime_unavailable", meta: { state: "loading" } }, }; @@ -105,6 +161,12 @@ test("both launcher children override inherited campaign accounting", () => { ).toBeUndefined(); }); +test("services export finished spans well inside the launcher's stop gap", () => { + vi.stubEnv("DEBUG", ""); + vi.stubEnv("OTEL_BSP_SCHEDULE_DELAY", "5000"); + expect(personaEnvironment().OTEL_BSP_SCHEDULE_DELAY).toBe("200"); +}); + test.each([false, true])( "resume reads original stores without consulting accounting (legacy: %s)", async (legacy) => { diff --git a/apps/brunch-agent/evals/persona/launch.ts b/apps/brunch-agent/evals/persona/launch.ts index f3c5e79a17e..5f66145d3de 100644 --- a/apps/brunch-agent/evals/persona/launch.ts +++ b/apps/brunch-agent/evals/persona/launch.ts @@ -150,9 +150,54 @@ export const personaEnvironment = ( // An explicit empty value also overrides Vite env files on backend startup. // Historical campaign ledgers must not gate persona requests or resumed runs. loaded[brunchEnv.stepAAccounting] = ""; + // The dev server sends waiting spans when its store closes on stop. A server + // that does not close in time is killed, and then only spans already sent + // arrive: the SDK's default 5 s span delay is longer than the seconds + // between a run's last turn settling and the stop; 200 ms sends them inside + // that gap. + loaded.OTEL_BSP_SCHEDULE_DELAY = "200"; return loaded; }; +/** Whether the signal reached the process or group; false once it has gone. */ +const signalProcess = (pid: number, signal: NodeJS.Signals | 0) => { + try { + process.kill(pid, signal); + return true; + } catch (error) { + if ( + !(error instanceof Error) || + !("code" in error) || + error.code !== "ESRCH" + ) { + throw error; + } + return false; + } +}; + +/** + * Stops each service started as its own process group, led by `yarn`, and + * settles once every group has exited. + * + * Only the leader is signalled: each yarn layer forwards SIGTERM to its child, + * so the dev server receives it once. Vite handles only the first SIGTERM; + * a second, which signalling the whole group adds, kills it before its close, + * Flue's stop with it, has finished. A group still alive after the wait is + * killed so the launcher can finish. + */ +export const stopServiceGroups = async (leaders: readonly number[]) => { + const groups = leaders.filter((pid) => signalProcess(pid, "SIGTERM")); + const deadline = Date.now() + 10_000; + while (groups.some((pid) => signalProcess(-pid, 0))) { + if (Date.now() > deadline) { + for (const pid of groups) signalProcess(-pid, "SIGKILL"); + return; + } + await delay(100); + } +}; + export const recordingReadySummary = ({ title, url, @@ -389,45 +434,18 @@ const launchPersona = async ({ if (!resume) await save(join(run, "run.json"), record); report(`Run: ${run}`); const started: ChildProcess[] = []; - /** Whether the signal reached the process group; false once it has gone. */ - const signalGroup = (pid: number, signal: NodeJS.Signals | 0) => { - try { - process.kill(-pid, signal); - return true; - } catch (error) { - if ( - !(error instanceof Error) || - !("code" in error) || - error.code !== "ESRCH" - ) { - throw error; - } - return false; - } - }; let servicesStopped: Promise | undefined; /** Ends the owned process groups and settles once every one has exited. */ const stopStartedServices = () => { - servicesStopped ??= (async () => { - const groups = started.flatMap((child) => + servicesStopped ??= stopServiceGroups( + started.flatMap((child) => child.pid !== undefined && child.exitCode === null && - child.signalCode === null && - signalGroup(child.pid, "SIGTERM") + child.signalCode === null ? [child.pid] : [], - ); - // Services flush their logs and the conversation store on SIGTERM; - // one that has not exited by then is killed so the launcher can finish. - const deadline = Date.now() + 10_000; - while (groups.some((pid) => signalGroup(pid, 0))) { - if (Date.now() > deadline) { - for (const pid of groups) signalGroup(pid, "SIGKILL"); - return; - } - await delay(100); - } - })(); + ), + ); return servicesStopped; }; let browser: diff --git a/apps/brunch-agent/evals/petrinaut/README.md b/apps/brunch-agent/evals/petrinaut/README.md index 0cc3c6a2a5f..eb1866e4712 100644 --- a/apps/brunch-agent/evals/petrinaut/README.md +++ b/apps/brunch-agent/evals/petrinaut/README.md @@ -50,7 +50,8 @@ The arguments are the case, the `provider/id` model and the thinking level; they Every persona run and probe ends by writing `evidence/packet.json` and `evidence/packet.md` into its directory. The packet accounts for each exchange's time, which is what a change to turn time is judged by: - active time (wall time less approval waits) and time until the first reply text; -- model steps, each split into time before first output (hidden reasoning), tool-argument streaming and reply text, and tool phases; +- model steps, each split into time before first output, tool-argument streaming and reply text, and tool phases; +- the time before first output split in two: time inside reasoning blocks before the output, and the rest of the wait (time to the provider's first event, and generating tool arguments the provider then delivers in one burst). A call whose first and last argument delta come under 50 ms apart is marked as a burst, and each step, exchange and the summary total the burst calls' argument characters; like argument streaming, bursts are unknown without a chronology; - each step's shape (its tool categories, in order); - the tool mix, skill activations, Ledger commit sizes, net growth, tokens and cost; - each model request's provider and model, and which requests failed and which were retries, including failed requests that left no step; diff --git a/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.test.ts b/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.test.ts index 388cd6bbab5..5c52ca17614 100644 --- a/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.test.ts +++ b/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.test.ts @@ -113,16 +113,26 @@ const chronology: LoggedSubmissionChronology = { isError: false, error: null, inputTokens: 3, + cacheReadTokens: null, + cacheWriteTokens: null, outputTokens: 200, + reasoningTokens: null, + costEstimateUsd: null, + reasoningBlocks: null, + reasoningMs: null, + firstTextDeltaMs: null, + lastTextDeltaMs: null, toolCalls: [ { toolCallId: "call-place", + toolName: "addPlace", firstDeltaMs: 6_000, lastDeltaMs: 6_500, argumentChars: 40, }, { toolCallId: "call-commit", + toolName: "ledger_commit", firstDeltaMs: 6_600, lastDeltaMs: 8_900, argumentChars: 3_600, @@ -377,7 +387,7 @@ test("an unsettled exchange is counted but left out of the time sums, and the pa skipped: { batches: 1, events: 0, chronologyLines: 0 }, }); - expect(packet.version).toBe(3); + expect(packet.version).toBe(4); expect(packet.sources.skipped).toEqual({ batches: 1, events: 0, @@ -562,8 +572,20 @@ const chronologyTurn = ( isError: false, error: null, inputTokens: null, + cacheReadTokens: null, + cacheWriteTokens: null, outputTokens: null, - toolCalls: toolCalls.map((call) => ({ ...call, argumentChars: 10 })), + reasoningTokens: null, + costEstimateUsd: null, + reasoningBlocks: null, + reasoningMs: null, + firstTextDeltaMs: null, + lastTextDeltaMs: null, + toolCalls: toolCalls.map((call) => ({ + ...call, + toolName: "addPlace", + argumentChars: 10, + })), }); // Each turn starts after its step's request: 500 ms after the run starts, @@ -691,3 +713,266 @@ test("a user message sent with submission context is excerpted as the user's own expect(packet.exchanges[0]?.userExcerpt).toBe("We run two bays."); }); + +const singleStepPacket = (stepEvents: readonly [string, number, string?][]) => + buildRunPacket({ + ...input, + submissions: [ + { submissionId: "wait", acceptedAt: t0, settledAt: t0 + 10_000 }, + ], + events: [ + event("agent_start_run", 0, {}, "wait"), + event("assistant_message_started", 0, { turnId: "turn-w" }, "wait"), + ...stepEvents.map(([type, offsetMs, blockId]) => + event(type, offsetMs, blockId === undefined ? {} : { blockId }, "wait"), + ), + event("submission_settled", 10_000, { outcome: "completed" }, "wait"), + ], + chronology: new Map(), + }).exchanges[0]?.steps[0]; + +test("a step's wait splits into reasoning before output and the rest, which add to the wait", () => { + const [buildStep, replyStep] = + buildRunPacket(input).exchanges[0]?.steps ?? []; + + // No reasoning block: the whole wait is the rest. + expect(buildStep).toMatchObject({ + beforeOutputMs: 6_000, + reasoningBeforeOutputMs: 0, + restBeforeOutputMs: 6_000, + }); + // A reasoning block that ends before the reply text starts. + expect(replyStep).toMatchObject({ + beforeOutputMs: 6_000, + reasoningSummaryMs: 2_000, + reasoningBeforeOutputMs: 2_000, + restBeforeOutputMs: 4_000, + }); +}); + +test("a reasoning block still open when output starts counts only up to the output", () => { + const step = singleStepPacket([ + ["assistant_reasoning_started", 1_000, "r1"], + ["assistant_text_started", 3_000, "x1"], + ["assistant_reasoning_completed", 4_000, "r1"], + ["assistant_text_completed", 5_000, "x1"], + ["assistant_message_completed", 5_000], + ]); + + expect(step).toMatchObject({ + beforeOutputMs: 3_000, + reasoningSummaryMs: 3_000, + reasoningBeforeOutputMs: 2_000, + restBeforeOutputMs: 1_000, + }); +}); + +test("a reasoning block still open when the step is cut off counts up to the cut", () => { + const step = singleStepPacket([["assistant_reasoning_started", 4_000, "r1"]]); + + expect(step).toMatchObject({ + cutOffIn: "message", + beforeOutputMs: 10_000, + reasoningBeforeOutputMs: 6_000, + restBeforeOutputMs: 4_000, + }); +}); + +test("a reasoning block after output has begun is not part of the wait", () => { + const step = singleStepPacket([ + ["assistant_text_started", 2_000, "x1"], + ["assistant_text_completed", 2_500, "x1"], + ["assistant_reasoning_started", 3_000, "r1"], + ["assistant_reasoning_completed", 4_000, "r1"], + ["assistant_message_completed", 5_000], + ]); + + expect(step).toMatchObject({ + beforeOutputMs: 2_000, + reasoningSummaryMs: 1_000, + reasoningBeforeOutputMs: 0, + restBeforeOutputMs: 2_000, + }); +}); + +const withPlaceDeltasChronology = ( + firstDeltaMs: number, + lastDeltaMs: number, +): ReadonlyMap => { + const [turn] = chronology.turns; + const [place, commit] = turn?.toolCalls ?? []; + if (!turn || !place || !commit) throw new Error("fixture has no turn"); + return new Map([ + [ + "sub-1", + { + ...chronology, + turns: [ + { + ...turn, + toolCalls: [{ ...place, firstDeltaMs, lastDeltaMs }, commit], + }, + ], + }, + ], + ]); +}; + +const withPlaceDeltas = (firstDeltaMs: number, lastDeltaMs: number) => + buildRunPacket({ + ...input, + chronology: withPlaceDeltasChronology(firstDeltaMs, lastDeltaMs), + }); + +test("tool calls whose arguments streamed over time are not bursts", () => { + const [step] = buildRunPacket(input).exchanges[0]?.steps ?? []; + + expect(step).toMatchObject({ + burstArgumentChars: 0, + toolCalls: [{ argumentsInBurst: false }, { argumentsInBurst: false }], + }); +}); + +test("a call whose arguments arrived within 50 ms is a burst, and the step totals its characters", () => { + const [step] = withPlaceDeltas(6_000, 6_049).exchanges[0]?.steps ?? []; + + // The place's arguments burst; the commit's streamed over 2.3 s. + expect(step).toMatchObject({ + burstArgumentChars: 40, + toolCalls: [ + { toolCallId: "call-place", argumentsInBurst: true }, + { toolCallId: "call-commit", argumentsInBurst: false }, + ], + }); + expect( + withPlaceDeltas(6_000, 6_050).exchanges[0]?.steps[0]?.burstArgumentChars, + ).toBe(0); +}); + +test("a step whose only call arrived in one burst totals that call's characters", () => { + const [turn] = chronology.turns; + if (!turn) throw new Error("fixture has no turn"); + const packet = buildRunPacket({ + ...input, + events: events.filter( + (streamEvent) => streamEvent.payload.toolCallId !== "call-commit", + ), + chronology: new Map([ + [ + "sub-1", + { + ...chronology, + turns: [ + { + ...turn, + toolCalls: [ + { + toolCallId: "call-place", + toolName: "addPlace", + firstDeltaMs: 8_000, + lastDeltaMs: 8_000, + argumentChars: 6_400, + }, + ], + }, + ], + }, + ], + ]), + }); + + expect(packet.exchanges[0]?.steps[0]).toMatchObject({ + burstArgumentChars: 6_400, + toolCalls: [{ argumentsInBurst: true }], + }); +}); + +test("without a chronology, bursts are unknown rather than absent", () => { + const packet = buildRunPacket({ ...input, chronology: new Map() }); + const [step] = packet.exchanges[0]?.steps ?? []; + + expect(step?.burstArgumentChars).toBeNull(); + expect(step?.toolCalls.map((call) => call.argumentsInBurst)).toEqual([ + null, + null, + ]); + expect(packet.exchanges[0]?.burstArgumentChars).toBeNull(); + expect(packet.summary.burstArgumentChars).toBeNull(); +}); + +test("exchange and summary totals of the split sum their steps, leaving out unsettled exchanges and steps without a chronology", () => { + const packet = buildRunPacket({ + ...input, + chronology: withPlaceDeltasChronology(6_000, 6_010), + submissions: [ + ...input.submissions, + { submissionId: "sub-3", acceptedAt: t0 + 40_000, settledAt: null }, + ], + events: [ + ...input.events, + event("agent_start_run", 40_000, {}, "sub-3"), + event("assistant_message_started", 40_100, { turnId: "turn-4" }, "sub-3"), + event("assistant_reasoning_started", 40_200, { blockId: "r9" }, "sub-3"), + event( + "assistant_reasoning_completed", + 41_200, + { blockId: "r9" }, + "sub-3", + ), + event( + "assistant_message_completed", + 45_000, + { turnId: "turn-4" }, + "sub-3", + ), + ], + }); + const [first, second, unsettled] = packet.exchanges; + const stepSum = ( + exchange: (typeof packet.exchanges)[number] | undefined, + pick: (step: (typeof packet.exchanges)[number]["steps"][number]) => number, + ) => (exchange?.steps ?? []).reduce((total, step) => total + pick(step), 0); + + for (const exchange of [first, second, unsettled]) { + expect(exchange?.reasoningBeforeOutputMs).toBe( + stepSum(exchange, (step) => step.reasoningBeforeOutputMs), + ); + expect(exchange?.restBeforeOutputMs).toBe( + stepSum(exchange, (step) => step.restBeforeOutputMs), + ); + expect( + (exchange?.reasoningBeforeOutputMs ?? 0) + + (exchange?.restBeforeOutputMs ?? 0), + ).toBe(exchange?.beforeOutputMs); + } + expect(first).toMatchObject({ + reasoningBeforeOutputMs: 2_000, + restBeforeOutputMs: 10_000, + burstArgumentChars: 40, + }); + // No chronology line for the second and third exchanges. + expect(second?.burstArgumentChars).toBeNull(); + expect(unsettled?.reasoningBeforeOutputMs).toBe(1_000); + expect(packet.summary).toMatchObject({ + beforeOutputMs: + (first?.beforeOutputMs ?? 0) + (second?.beforeOutputMs ?? 0), + reasoningBeforeOutputMs: + (first?.reasoningBeforeOutputMs ?? 0) + + (second?.reasoningBeforeOutputMs ?? 0), + restBeforeOutputMs: + (first?.restBeforeOutputMs ?? 0) + (second?.restBeforeOutputMs ?? 0), + burstArgumentChars: 40, + }); +}); + +test("packet.md shows how the wait before output divides", () => { + const markdown = renderRunPacket(withPlaceDeltas(6_000, 6_010)); + + expect(markdown).toContain( + "| … before first output | 13 s | 67% |\n| … … in reasoning blocks | 2.0 s | 11% |\n| … … rest of the wait (first event, burst tool arguments: 40 chars) | 11 s | 56% |", + ); + expect(markdown).toContain("| Before output (reasoning + rest) |"); + // The second exchange has no reasoning: 0.5 s of wait, all of it the rest. + expect(markdown).toContain("| 12 s (2.0 s + 10 s) |"); + expect(markdown).toContain("| 0.5 s (0.0 s + 0.5 s) |"); +}); diff --git a/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.ts b/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.ts index 235025a44ed..01c60859cc5 100644 --- a/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.ts +++ b/apps/brunch-agent/evals/petrinaut/run-packet/build-run-packet.ts @@ -99,6 +99,12 @@ export interface PacketToolCall { */ readonly firstDeltaMs: number | null; readonly lastDeltaMs: number | null; + /** + * Whether the first and last argument delta came under `burstMs` apart: the + * provider delivered the arguments in one burst, so the model generated + * them inside the step's wait before output. Null without a chronology. + */ + readonly argumentsInBurst: boolean | null; readonly executionMs: number | null; readonly isError: boolean | null; } @@ -112,15 +118,28 @@ export interface PacketStep { */ readonly durationMs: number; /** - * Request sent to the first reply text or tool-argument delta: hidden - * reasoning, time to first event and any reasoning summary. Tool-argument - * deltas count only when the chronology places them (see `firstDeltaMs`). + * Request sent to the first reply text or tool-argument delta: the wait + * before the person sees output. It holds the time inside reasoning blocks + * before that output, the time to the provider's first event, and the + * generation of tool arguments delivered in one burst (see + * `burstArgumentChars`). Tool-argument deltas count as output only when the + * chronology places them (see `firstDeltaMs`). */ readonly beforeOutputMs: number; + /** The part of `beforeOutputMs` spent inside reasoning blocks. */ + readonly reasoningBeforeOutputMs: number; + /** `beforeOutputMs` less `reasoningBeforeOutputMs`. */ + readonly restBeforeOutputMs: number; + /** + * Every reasoning block in the step, summed, including blocks after output + * began; a block never completed is left out. + */ readonly reasoningSummaryMs: number; readonly textMs: number; /** First to last tool-argument delta; null without a server-log chronology. */ readonly argumentStreamingMs: number | null; + /** Argument characters of the calls delivered in one burst; null without a server-log chronology. */ + readonly burstArgumentChars: number | null; /** * Message completed to tool results committed: execution, browser round * trips and approval waits. Tools never committed end where the message @@ -167,7 +186,10 @@ export interface PacketExchange { readonly untilFirstTextMs: number | null; readonly modelMs: number; readonly beforeOutputMs: number; + readonly reasoningBeforeOutputMs: number; + readonly restBeforeOutputMs: number; readonly argumentStreamingMs: number | null; + readonly burstArgumentChars: number | null; readonly textMs: number; readonly toolPhaseMs: number; readonly otherMs: number | null; @@ -211,7 +233,7 @@ export interface Distribution { } export interface RunPacket { - readonly version: 3; + readonly version: 4; readonly label: string; readonly metadata: RunMetadata | null; readonly sources: { @@ -250,7 +272,11 @@ export interface RunPacket { }; readonly modelMs: number; readonly beforeOutputMs: number; + readonly reasoningBeforeOutputMs: number; + readonly restBeforeOutputMs: number; readonly argumentStreamingMs: number | null; + /** Covers exchanges with a chronology line, as `argumentStreamingMs` does. */ + readonly burstArgumentChars: number | null; readonly textMs: number; readonly toolPhaseMs: number; readonly categories: Readonly>; @@ -280,6 +306,12 @@ export interface RunPacket { const longToolCallMs = 30_000; +/** + * Arguments whose first and last delta come closer than this arrived in one burst. + * A call's arguments either arrive at once or stream for hundreds of milliseconds, and few calls fall between. + */ +const burstMs = 50; + const zeroUsage: Usage = { inputTokens: 0, outputTokens: 0, @@ -421,6 +453,30 @@ const distributionOf = (values: readonly number[]): Distribution => { return { median: rank(0.5), p90: rank(0.9), max: sorted.at(-1) ?? null }; }; +/** + * Time inside reasoning blocks between `from` and `until`, counting a block + * still open as running to `until`. A message's blocks are sequential, so + * their times are summed, and the sum never exceeds the span. + */ +const reasoningWithin = ( + blocks: readonly { startedAt: number; completedAt: number | null }[], + from: number, + until: number, +): number => + Math.min( + until - from, + blocks.reduce( + (total, block) => + total + + Math.max( + 0, + Math.min(until, block.completedAt ?? until) - + Math.max(from, block.startedAt), + ), + 0, + ), + ); + type TimelineEntry = | { readonly at: number; readonly kind: "activation"; readonly name: string } | { readonly at: number; readonly kind: "compaction" }; @@ -446,6 +502,8 @@ interface MutableStep { toolsCommittedAt: number | null; firstTextAt: number | null; reasoningSummaryMs: number; + /** Reasoning blocks by start, with their end; null while still open. */ + reasoningBlocks: { startedAt: number; completedAt: number | null }[]; textMs: number; openBlocks: Map; toolCalls: MutableToolCall[]; @@ -497,6 +555,7 @@ const buildExchange = ( toolsCommittedAt: null, firstTextAt: null, reasoningSummaryMs: 0, + reasoningBlocks: [], textMs: 0, openBlocks: new Map(), toolCalls: [], @@ -506,6 +565,12 @@ const buildExchange = ( case "assistant_reasoning_started": case "assistant_text_started": current?.openBlocks.set(blockId, event.at); + if (event.type === "assistant_reasoning_started" && current) { + current.reasoningBlocks.push({ + startedAt: event.at, + completedAt: null, + }); + } if (event.type === "assistant_text_started" && current) { current.firstTextAt ??= event.at; firstTextAt ??= event.at; @@ -517,7 +582,15 @@ const buildExchange = ( if (current && startedAt !== undefined) { if (event.type === "assistant_text_completed") current.textMs += event.at - startedAt; - else current.reasoningSummaryMs += event.at - startedAt; + else { + current.reasoningSummaryMs += event.at - startedAt; + const block = current.reasoningBlocks.find( + (candidate) => + candidate.startedAt === startedAt && + candidate.completedAt === null, + ); + if (block) block.completedAt = event.at; + } } break; } @@ -609,6 +682,10 @@ const buildExchange = ( streamed === undefined || turnStartOffsetMs === null ? null : turnStartOffsetMs + streamed.lastDeltaMs, + argumentsInBurst: + streamed === undefined + ? null + : streamed.lastDeltaMs - streamed.firstDeltaMs < burstMs, executionMs: call.executionMs, isError: call.isError, }; @@ -630,10 +707,18 @@ const buildExchange = ( call.firstDeltaMs === null ? [] : [call.firstDeltaMs], ), ]; + const beforeOutputMs = Math.min(durationMs, ...firstOutputOffsets); + const reasoningBeforeOutputMs = reasoningWithin( + step.reasoningBlocks, + step.requestStartAt, + step.requestStartAt + beforeOutputMs, + ); return { turnId: step.turnId, durationMs, - beforeOutputMs: Math.min(durationMs, ...firstOutputOffsets), + beforeOutputMs, + reasoningBeforeOutputMs, + restBeforeOutputMs: beforeOutputMs - reasoningBeforeOutputMs, reasoningSummaryMs: step.reasoningSummaryMs, textMs: step.textMs, argumentStreamingMs: @@ -643,6 +728,15 @@ const buildExchange = ( ? 0 : Math.max(...streamedCalls.map((call) => call.lastDeltaMs)) - Math.min(...streamedCalls.map((call) => call.firstDeltaMs)), + burstArgumentChars: + turn === undefined + ? null + : toolCalls.reduce( + (total, call) => + total + + (call.argumentsInBurst === true ? call.argumentChars : 0), + 0, + ), toolPhaseMs: cutOffIn === "message" || step.toolCalls.length === 0 ? 0 @@ -739,9 +833,14 @@ const buildExchange = ( firstTextAt === null ? null : firstTextAt - submission.acceptedAt, modelMs, beforeOutputMs: sum((step) => step.beforeOutputMs), + reasoningBeforeOutputMs: sum((step) => step.reasoningBeforeOutputMs), + restBeforeOutputMs: sum((step) => step.restBeforeOutputMs), argumentStreamingMs: chronology ? sum((step) => step.argumentStreamingMs ?? 0) : null, + burstArgumentChars: chronology + ? sum((step) => step.burstArgumentChars ?? 0) + : null, textMs: sum((step) => step.textMs), toolPhaseMs, otherMs: wallMs === null ? null : wallMs - modelMs - toolPhaseMs, @@ -855,7 +954,7 @@ export const buildRunPacket = (input: RunPacketInput): RunPacket => { }; return { - version: 3, + version: 4, label: input.label, metadata: input.metadata, sources: { chronology: hasChronology, skipped: input.skipped }, @@ -894,9 +993,18 @@ export const buildRunPacket = (input: RunPacketInput): RunPacket => { }, modelMs: totalSettled((exchange) => exchange.modelMs), beforeOutputMs: totalSettled((exchange) => exchange.beforeOutputMs), + reasoningBeforeOutputMs: totalSettled( + (exchange) => exchange.reasoningBeforeOutputMs, + ), + restBeforeOutputMs: totalSettled( + (exchange) => exchange.restBeforeOutputMs, + ), argumentStreamingMs: hasChronology ? totalSettled((exchange) => exchange.argumentStreamingMs ?? 0) : null, + burstArgumentChars: hasChronology + ? totalSettled((exchange) => exchange.burstArgumentChars ?? 0) + : null, textMs: totalSettled((exchange) => exchange.textMs), toolPhaseMs: totalSettled((exchange) => exchange.toolPhaseMs), categories, diff --git a/apps/brunch-agent/evals/petrinaut/run-packet/render-run-packet.ts b/apps/brunch-agent/evals/petrinaut/run-packet/render-run-packet.ts index e69cc346897..97a00b34b12 100644 --- a/apps/brunch-agent/evals/petrinaut/run-packet/render-run-packet.ts +++ b/apps/brunch-agent/evals/petrinaut/run-packet/render-run-packet.ts @@ -106,10 +106,20 @@ export const renderRunPacket = (packet: RunPacket): string => { share(summary.modelMs, summary.activeMs), ], [ - "… before first output (hidden reasoning)", + "… before first output", seconds(summary.beforeOutputMs), share(summary.beforeOutputMs, summary.activeMs), ], + [ + "… … in reasoning blocks", + seconds(summary.reasoningBeforeOutputMs), + share(summary.reasoningBeforeOutputMs, summary.activeMs), + ], + [ + `… … rest of the wait (first event, burst tool arguments: ${summary.burstArgumentChars === null ? "unknown" : `${summary.burstArgumentChars} chars`})`, + seconds(summary.restBeforeOutputMs), + share(summary.restBeforeOutputMs, summary.activeMs), + ], [ "… tool-argument streaming", seconds(summary.argumentStreamingMs), @@ -175,7 +185,7 @@ export const renderRunPacket = (packet: RunPacket): string => { "First text", "Steps", "Retries", - "Before output", + "Before output (reasoning + rest)", "Args", "Tools", "Commit chars", @@ -197,7 +207,7 @@ export const renderRunPacket = (packet: RunPacket): string => { (request) => request.retryOf !== null, ).length, ), - seconds(exchange.beforeOutputMs), + `${seconds(exchange.beforeOutputMs)} (${seconds(exchange.reasoningBeforeOutputMs)} + ${seconds(exchange.restBeforeOutputMs)})`, seconds(exchange.argumentStreamingMs), seconds(exchange.toolPhaseMs), String(exchange.ledger.argumentChars), diff --git a/apps/brunch-agent/src/db.test.ts b/apps/brunch-agent/src/db.test.ts new file mode 100644 index 00000000000..f6f53a1fb23 --- /dev/null +++ b/apps/brunch-agent/src/db.test.ts @@ -0,0 +1,40 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, expect, test, vi } from "vitest"; + +const telemetry = vi.hoisted(() => ({ + flush: vi.fn<() => Promise>(async () => undefined), + shutdown: vi.fn<() => Promise>(async () => undefined), +})); + +vi.mock("./server/telemetry-bootstrap.ts", () => ({ + shutdownBrunchTelemetry: telemetry.shutdown, +})); +vi.mock("./server/telemetry.ts", async (importOriginal) => ({ + ...(await importOriginal()), + flushBrunchTelemetry: telemetry.flush, +})); + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +test("closing the SQLite store sends recorded telemetry and leaves the exporters running", async () => { + const directory = await mkdtemp(join(tmpdir(), "TEST-brunch-db-")); + try { + vi.stubEnv("BRUNCH_DB_KIND", "sqlite"); + vi.stubEnv("BRUNCH_DEV_DB_PATH", join(directory, "conversation.db")); + const { default: adapter } = await import("./db.ts"); + await adapter.migrate?.(); + await adapter.connect(); + + await adapter.close?.(); + + expect(telemetry.flush).toHaveBeenCalledOnce(); + expect(telemetry.shutdown).not.toHaveBeenCalled(); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/apps/brunch-agent/src/db.ts b/apps/brunch-agent/src/db.ts index 7ade7e892c4..698673458d9 100644 --- a/apps/brunch-agent/src/db.ts +++ b/apps/brunch-agent/src/db.ts @@ -5,7 +5,10 @@ import { loadDatabaseConfig } from "./server/database-config.ts"; import { createPostgresRunner } from "./server/postgres.ts"; import { diagnostics } from "./server/runtime-diagnostics.ts"; import { shutdownBrunchTelemetry } from "./server/telemetry-bootstrap.ts"; -import { recordOperationalFailure } from "./server/telemetry.ts"; +import { + flushBrunchTelemetry, + recordOperationalFailure, +} from "./server/telemetry.ts"; /** * The substrate's conversation storage — host-authored because Flue requires @@ -19,7 +22,19 @@ const openDatabase = async () => { const config = loadDatabaseConfig(); if (config.kind === "postgres") return postgres(createPostgresRunner(config, shutdownBrunchTelemetry)); - return (await import("@flue/runtime/node")).sqlite(conversationDbPath()); + const sqlite = (await import("@flue/runtime/node")).sqlite( + conversationDbPath(), + ); + return { + ...sqlite, + // Flue's stop does not dispose Brunch's exporters, so send what they + // hold here. Flush, not shut down: when a source change reloads the dev + // app, Flue closes this store while the server, and its exporters, run on. + close: async () => { + await sqlite.close?.(); + await flushBrunchTelemetry(); + }, + }; } catch (error) { diagnostics.report("database.configuration", error); // The process exits right after this, so flush the failure span first. diff --git a/apps/brunch-agent/src/server/diagnose-cli.ts b/apps/brunch-agent/src/server/diagnose-cli.ts index cbb8749117b..733362b6e54 100644 --- a/apps/brunch-agent/src/server/diagnose-cli.ts +++ b/apps/brunch-agent/src/server/diagnose-cli.ts @@ -1,8 +1,9 @@ /** - * Read Brunch's provider telemetry back: which model served each call, how - * long until it started responding, which calls were retries, which failed, - * and the idle timeouts and output-limit stops, joined with each call's span. - * Metadata only. + * Read Brunch's provider telemetry back: which model served each call, when + * the provider's HTTP response arrived, which calls were retries, which + * failed, the idle timeouts and output-limit stops, and where each step's + * time went (reasoning, reply text, tool arguments, tokens and cost), joined + * with each call's span and its tools' execution. Metadata only. * * From Grafana (the local stack at http://localhost:3001 by default; run the * server with `HASH_OTLP_ENDPOINT=http://localhost:4317` so it exports): @@ -29,6 +30,7 @@ import { parseBrunchLog, renderSubmissionDetail, renderSubmissionList, + spanSearchWindow, summarizeSubmission, type LoggedIdleTimeout, type LoggedOutputLimit, @@ -183,14 +185,22 @@ if (values.log !== undefined) { ); } else { const submissionId = values.submission; - const [chronologies, idleTimeouts, outputLimits, spans] = - await Promise.all([ - reader.chronologies(window, submissionId), - reader.idleTimeouts(window), - reader.outputLimits(window), - reader.modelCallSpans(window, submissionId), - ]); + const [chronologies, idleTimeouts, outputLimits] = await Promise.all([ + reader.chronologies(window, submissionId), + reader.idleTimeouts(window), + reader.outputLimits(window), + ]); const chronology = chronologies.records[0] ?? null; + // Tempo refuses a long range, so spans are searched around the + // submission's own logged time. + const spanSearch = spanSearchWindow(chronology, window); + if (spanSearch === undefined) { + process.stderr.write( + `Tempo searches at most 168 hours, and ${submissionId} has no chronology line in the last ${since} that places its spans. Rerun with --since 7d or less.\n`, + ); + process.exit(1); + } + const spans = await reader.spans(spanSearch, submissionId); printDetail( { submissionId, @@ -198,7 +208,7 @@ if (values.log !== undefined) { chronology, idleTimeouts: notesOf(submissionId, chronology, idleTimeouts.records), outputLimits: notesOf(submissionId, chronology, outputLimits.records), - spans: spans.records, + spans: { modelCalls: spans.modelCalls, toolCalls: spans.toolCalls }, }, [ ...coverageWarnings("chronology lines", chronologies), diff --git a/apps/brunch-agent/src/server/observe-turn-chronology.ts b/apps/brunch-agent/src/server/observe-turn-chronology.ts index e54e2056aea..ae579049e90 100644 --- a/apps/brunch-agent/src/server/observe-turn-chronology.ts +++ b/apps/brunch-agent/src/server/observe-turn-chronology.ts @@ -1,8 +1,8 @@ /** - * Per-submission chronology of model requests and argument streaming. One + * Per-submission chronology of model requests: time in reasoning blocks, reply + * text and argument streaming, tokens and the catalogue cost of each step. One * structured log line per settled submission tells a provider stall (no - * observed progress) from slow generation (deltas still arriving); it does not - * by itself separate provider failure from hidden reasoning. + * observed progress) from reasoning or slow generation. * * Content policy: ids, counts, durations, turn start times, provider and model * ids, and error classifications only — never argument text or error messages. @@ -61,7 +61,11 @@ type TurnChronology = { * submission past a failed turn only to retry it. */ readonly retryOf: string | null; - /** Milliseconds from `turn_start` to the first model event; null when none arrived. */ + /** + * Milliseconds from `turn_start` to the first model event; null when none + * arrived. Pi emits its start event when the provider's HTTP response + * arrives, before any stream event, so this times the response, not output. + */ readonly timeToFirstEventMs: number | null; /** Milliseconds from `turn_start` to `turn`, or to settlement when no `turn` arrived. */ readonly durationMs: number; @@ -71,7 +75,18 @@ type TurnChronology = { readonly error: ClassifiedError | null; readonly inputTokens: number | null; readonly cacheReadTokens: number | null; + readonly cacheWriteTokens: number | null; readonly outputTokens: number | null; + /** Reasoning tokens within `outputTokens`; null when the provider reports no count. */ + readonly reasoningTokens: number | null; + /** Pi's catalogue estimate for the step (USD for built-in models), not an invoiced amount. */ + readonly costEstimateUsd: number | null; + /** Reasoning blocks in the step and their summed time; a block still open is counted until the step ended. */ + readonly reasoningBlocks: number; + readonly reasoningMs: number; + /** Milliseconds from `turn_start` to the reply text's first and last delta; null without text. */ + readonly firstTextDeltaMs: number | null; + readonly lastTextDeltaMs: number | null; /** Model-visible context and normalized output, without their contents. */ readonly requestShape: RequestShape | null; readonly responseShape: ResponseShape | null; @@ -114,7 +129,16 @@ type TurnState = { error: ClassifiedError | null; inputTokens: number | null; cacheReadTokens: number | null; + cacheWriteTokens: number | null; outputTokens: number | null; + reasoningTokens: number | null; + costEstimateUsd: number | null; + /** Start times of reasoning blocks not yet ended, by content index. */ + openReasoning: Map; + reasoningBlocks: number; + reasoningMs: number; + firstTextAt: number | null; + lastTextAt: number | null; requestShape: RequestShape | null; responseShape: ResponseShape | null; toolCalls: Map; @@ -134,6 +158,8 @@ const submissionOf = ( const finishTurn = (turn: TurnState, terminalAt: number): TurnChronology => { const endedAt = turn.endedAt ?? terminalAt; + const offset = (time: number | null) => + time === null ? null : time - turn.startedAt; return { turnId: turn.turnId, purpose: turn.purpose, @@ -150,7 +176,17 @@ const finishTurn = (turn: TurnState, terminalAt: number): TurnChronology => { error: turn.error, inputTokens: turn.inputTokens, cacheReadTokens: turn.cacheReadTokens, + cacheWriteTokens: turn.cacheWriteTokens, outputTokens: turn.outputTokens, + reasoningTokens: turn.reasoningTokens, + costEstimateUsd: turn.costEstimateUsd, + reasoningBlocks: turn.reasoningBlocks + turn.openReasoning.size, + reasoningMs: [...turn.openReasoning.values()].reduce( + (total, startedAt) => total + (endedAt - startedAt), + turn.reasoningMs, + ), + firstTextDeltaMs: offset(turn.firstTextAt), + lastTextDeltaMs: offset(turn.lastTextAt), requestShape: turn.requestShape, responseShape: turn.responseShape, toolCalls: [...turn.toolCalls.values()].map((call) => ({ @@ -175,21 +211,21 @@ export const createTurnChronologyObserver = ( } => { const submissions = new Map>(); - const turnsOf = (submissionId: string): Map => { - const existing = submissions.get(submissionId); - if (existing) return existing; - const created = new Map(); - submissions.set(submissionId, created); - return created; - }; + /** Only `turn_start` opens a submission's state; a late event finds nothing and leaves nothing. */ + const turnOf = ( + submissionId: string, + turnId: string | undefined, + ): TurnState | undefined => + turnId === undefined + ? undefined + : submissions.get(submissionId)?.get(turnId); const markFirstEvent = ( submissionId: string, turnId: string | undefined, at: number, ): TurnState | undefined => { - if (turnId === undefined) return undefined; - const turn = turnsOf(submissionId).get(turnId); + const turn = turnOf(submissionId, turnId); if (turn && turn.firstEventAt === null) turn.firstEventAt = at; return turn; }; @@ -203,7 +239,9 @@ export const createTurnChronologyObserver = ( switch (event.type) { case "turn_start": { - const turns = turnsOf(submissionId); + const turns = + submissions.get(submissionId) ?? new Map(); + submissions.set(submissionId, turns); if (!turns.has(event.turnId)) { const previousAgentTurn = event.purpose === "agent" @@ -228,7 +266,15 @@ export const createTurnChronologyObserver = ( error: null, inputTokens: null, cacheReadTokens: null, + cacheWriteTokens: null, outputTokens: null, + reasoningTokens: null, + costEstimateUsd: null, + openReasoning: new Map(), + reasoningBlocks: 0, + reasoningMs: 0, + firstTextAt: null, + lastTextAt: null, requestShape: null, responseShape: null, toolCalls: new Map(), @@ -237,7 +283,7 @@ export const createTurnChronologyObserver = ( return; } case "turn_request": { - const turn = turnsOf(submissionId).get(event.turnId); + const turn = turnOf(submissionId, event.turnId); if (!turn) return; turn.provider = event.request.providerId; turn.requestedModel = event.request.requestedModel; @@ -264,10 +310,29 @@ export const createTurnChronologyObserver = ( return; } case "message_start": - case "thinking_start": - case "text_delta": markFirstEvent(submissionId, event.turnId, at); return; + case "thinking_start": { + const turn = markFirstEvent(submissionId, event.turnId, at); + turn?.openReasoning.set(event.contentIndex, at); + return; + } + case "thinking_end": { + const turn = markFirstEvent(submissionId, event.turnId, at); + const startedAt = turn?.openReasoning.get(event.contentIndex); + if (!turn || startedAt === undefined) return; + turn.openReasoning.delete(event.contentIndex); + turn.reasoningBlocks += 1; + turn.reasoningMs += at - startedAt; + return; + } + case "text_delta": { + const turn = markFirstEvent(submissionId, event.turnId, at); + if (!turn) return; + turn.firstTextAt ??= at; + turn.lastTextAt = at; + return; + } case "toolcall_delta": { const turn = markFirstEvent(submissionId, event.turnId, at); if (!turn) return; @@ -292,9 +357,15 @@ export const createTurnChronologyObserver = ( return; } case "turn": { - const turn = turnsOf(submissionId).get(event.turnId); + const turn = turnOf(submissionId, event.turnId); if (!turn) return; turn.endedAt = at; + // A reasoning block the step ended inside counts until the step's end. + for (const startedAt of turn.openReasoning.values()) { + turn.reasoningBlocks += 1; + turn.reasoningMs += at - startedAt; + } + turn.openReasoning.clear(); turn.isError = event.isError; turn.responseModel = event.response.responseModel ?? null; const cause = event.response.error ?? event.errorInfo; @@ -325,10 +396,21 @@ export const createTurnChronologyObserver = ( if (usage) { turn.inputTokens = usage.input; turn.cacheReadTokens = usage.cacheRead; + turn.cacheWriteTokens = usage.cacheWrite; turn.outputTokens = usage.output; + turn.costEstimateUsd = usage.cost.total; } return; } + // Flue's `turn` usage drops Pi's reasoning count; the message it + // settles from still carries it. + case "message_end": { + if (event.message.role !== "assistant") return; + const turn = turnOf(submissionId, event.turnId); + if (turn) + turn.reasoningTokens = event.message.usage.reasoning ?? null; + return; + } case "submission_settled": { const turns = submissions.get(submissionId); submissions.delete(submissionId); diff --git a/apps/brunch-agent/src/server/telemetry-readback.ts b/apps/brunch-agent/src/server/telemetry-readback.ts index 499525df583..1231d93da20 100644 --- a/apps/brunch-agent/src/server/telemetry-readback.ts +++ b/apps/brunch-agent/src/server/telemetry-readback.ts @@ -10,6 +10,7 @@ export { createGrafanaReader, + spanSearchWindow, type TimeWindow, } from "./telemetry-readback/grafana.ts"; export { parseBrunchLog } from "./telemetry-readback/parse-log-text.ts"; diff --git a/apps/brunch-agent/src/server/telemetry-readback/grafana.test.ts b/apps/brunch-agent/src/server/telemetry-readback/grafana.test.ts index e301af0fdf6..4e3e1ffdb0d 100644 --- a/apps/brunch-agent/src/server/telemetry-readback/grafana.test.ts +++ b/apps/brunch-agent/src/server/telemetry-readback/grafana.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "vitest"; -import { createGrafanaReader } from "./grafana.ts"; +import { createGrafanaReader, spanSearchWindow } from "./grafana.ts"; const window = { start: new Date("2026-11-03T10:00:00.000Z"), @@ -22,21 +22,51 @@ const turn = { terminal: "turn", isError: false, inputTokens: 9_416, + cacheReadTokens: 0, + cacheWriteTokens: 0, outputTokens: 49, + reasoningTokens: 0, + costEstimateUsd: 0.004, + reasoningBlocks: 0, + reasoningMs: 0, + firstTextDeltaMs: null, + lastTextDeltaMs: null, toolCalls: [], }; /** The same turn as the server logs it, with fields readback does not read. */ -const loggedTurn = { - ...turn, - cacheReadTokens: 0, - requestShape: null, - responseShape: null, -}; +const loggedTurn = { ...turn, requestShape: null, responseShape: null }; const string = (value: string) => ({ stringValue: value }); -/** Tempo's v2 trace shape: a chat span with one HTTP request under it, and an unrelated tool span. */ +/** One `execute_tool` span; times in milliseconds since the epoch. */ +const toolSpan = ( + spanId: string, + turnId: string, + toolName: string, + startMs: number, + endMs: number, +) => ({ + spanId, + parentSpanId: "agent-span", + name: `execute_tool ${toolName}`, + startTimeUnixNano: `${startMs}000000`, + endTimeUnixNano: `${endMs}000000`, + status: {}, + attributes: [ + { key: "gen_ai.operation.name", value: string("execute_tool") }, + { key: "flue.submission.id", value: string("sub-1") }, + { key: "flue.turn.id", value: string(turnId) }, + { key: "gen_ai.tool.name", value: string(toolName) }, + { key: "gen_ai.tool.call.id", value: string(`call-${spanId}`) }, + ], +}); + +/** + * Tempo's v2 trace shape: a chat span with one HTTP request under it, a + * batch of three browser-run calls that the panel returned together, and + * one server-run call. + */ const trace = { trace: { resourceSpans: [ @@ -83,20 +113,28 @@ const trace = { }, ], }, - { - spanId: "tool-span", - parentSpanId: "agent-span", - name: "execute_tool addPlace", - startTimeUnixNano: "1793701803000000000", - endTimeUnixNano: "1793701803010000000", - attributes: [ - { - key: "gen_ai.operation.name", - value: string("execute_tool"), - }, - { key: "flue.submission.id", value: string("sub-1") }, - ], - }, + toolSpan("b3", "turn-1", "addArc", 1793701802601, 1793701803046), + toolSpan( + "b1", + "turn-1", + "addPlace", + 1793701802600, + 1793701803046, + ), + toolSpan( + "b2", + "turn-1", + "addPlace", + 1793701802600, + 1793701803046, + ), + toolSpan( + "s1", + "turn-2", + "ledger_commit", + 1793701810000, + 1793701810010, + ), ], }, ], @@ -282,13 +320,13 @@ test("output-limit stops read their string-typed token count back as a number, b test("model-call spans are the submission's chat spans, with the HTTP requests beneath them", async () => { const { requests, fetchImpl } = fakeGrafana(); - const spans = await createGrafanaReader(config, fetchImpl).modelCallSpans( + const spans = await createGrafanaReader(config, fetchImpl).spans( window, "sub-1", ); - expect(spans).toEqual({ - records: [ + expect(spans).toMatchObject({ + modelCalls: [ { traceId: "trace-1", turnId: "turn-1", @@ -314,6 +352,144 @@ test("model-call spans are the submission's chat spans, with the HTTP requests b expect(search?.searchParams.get("q")).toBe( '{resource.service.name="Brunch Agent" && span.flue.submission.id="sub-1"}', ); + expect(search?.searchParams.get("start")).toBe( + String(window.start.getTime() / 1000), + ); + expect(search?.searchParams.get("end")).toBe( + String(window.end.getTime() / 1000), + ); +}); + +test("tool spans are the submission's execute_tool spans, each with its step, name and times", async () => { + const { fetchImpl } = fakeGrafana(); + + const { toolCalls } = await createGrafanaReader(config, fetchImpl).spans( + window, + "sub-1", + ); + + expect(toolCalls).toEqual([ + { + traceId: "trace-1", + turnId: "turn-1", + toolName: "addPlace", + startedAt: "2026-11-03T10:30:02.600Z", + endedAt: "2026-11-03T10:30:03.046Z", + durationMs: 446, + }, + { + traceId: "trace-1", + turnId: "turn-1", + toolName: "addPlace", + startedAt: "2026-11-03T10:30:02.600Z", + endedAt: "2026-11-03T10:30:03.046Z", + durationMs: 446, + }, + { + traceId: "trace-1", + turnId: "turn-1", + toolName: "addArc", + startedAt: "2026-11-03T10:30:02.601Z", + endedAt: "2026-11-03T10:30:03.046Z", + durationMs: 445, + }, + { + traceId: "trace-1", + turnId: "turn-2", + toolName: "ledger_commit", + startedAt: "2026-11-03T10:30:10.000Z", + endedAt: "2026-11-03T10:30:10.010Z", + durationMs: 10, + }, + ]); +}); + +const hours = (count: number) => count * 3_600_000; + +test("spans are searched around the submission's own steps: its first step's start to its settlement", () => { + const settledAt = "2026-11-20T10:05:00.000Z"; + const searched = spanSearchWindow( + { + submissionId: "sub-1", + outcome: "completed", + timestamp: settledAt, + turns: [ + { ...turn, startedAt: "2026-11-20T10:01:00.000Z" }, + { ...turn, startedAt: "2026-11-20T10:00:00.000Z" }, + ], + }, + { + start: new Date("2026-11-19T00:00:00.000Z"), + end: new Date("2026-12-03T00:00:00.000Z"), + }, + ); + + expect(searched).toEqual({ + start: new Date("2026-11-20T10:00:00.000Z"), + end: new Date("2026-11-20T10:05:00.000Z"), + }); +}); + +test("a line with a step lacking its start time places nothing: the searched window is used, or nothing beyond Tempo's 168 hours", () => { + const end = new Date("2026-12-03T00:00:00.000Z"); + const day = { start: new Date(end.getTime() - hours(24)), end }; + const fortnight = { start: new Date(end.getTime() - hours(24 * 14)), end }; + const untimed = { + submissionId: "sub-1", + outcome: "completed", + timestamp: "2026-12-02T10:05:00.000Z", + turns: [turn, { ...turn, startedAt: null }], + }; + + expect(spanSearchWindow(untimed, day)).toEqual(day); + expect(spanSearchWindow(untimed, fortnight)).toBeUndefined(); +}); + +test("without a chronology line, the searched window is used up to Tempo's 168 hours, and beyond it there is nothing to search", () => { + const end = new Date("2026-12-03T00:00:00.000Z"); + const week = { start: new Date(end.getTime() - hours(168)), end }; + const fortnight = { start: new Date(end.getTime() - hours(24 * 14)), end }; + + expect(spanSearchWindow(null, week)).toEqual(week); + expect(spanSearchWindow(null, fortnight)).toBeUndefined(); +}); + +test("a 168-hour window reaches Tempo as at most 168 hours in whole seconds, however its end falls within a second", async () => { + const { requests, fetchImpl } = fakeGrafana(); + const end = new Date("2026-12-03T00:00:00.250Z"); + + await createGrafanaReader(config, fetchImpl).spans( + { start: new Date(end.getTime() - hours(168)), end }, + "sub-1", + ); + + const search = requests + .map((request) => new URL(request.url)) + .find((url) => url.pathname.endsWith("/api/search")); + expect( + Number(search?.searchParams.get("end")) - + Number(search?.searchParams.get("start")), + ).toBe(168 * 3_600); +}); + +test("a submission Tempo no longer holds reads as no spans, not as a failure", async () => { + const { fetchImpl } = fakeGrafana(); + const emptyTempo = (async ( + input: string | URL | Request, + init?: RequestInit, + ) => + new URL(new Request(input, init).url).pathname.endsWith("/api/search") + ? new Response(JSON.stringify({ traces: [] })) + : fetchImpl(input, init)) as typeof fetch; + + await expect( + createGrafanaReader(config, emptyTempo).spans(window, "sub-1"), + ).resolves.toEqual({ + modelCalls: [], + toolCalls: [], + skipped: 0, + truncated: false, + }); }); test("a token is sent over HTTPS or to a local Grafana, never over plain HTTP elsewhere", async () => { diff --git a/apps/brunch-agent/src/server/telemetry-readback/grafana.ts b/apps/brunch-agent/src/server/telemetry-readback/grafana.ts index 3a3fbeda62e..79db3d22b1f 100644 --- a/apps/brunch-agent/src/server/telemetry-readback/grafana.ts +++ b/apps/brunch-agent/src/server/telemetry-readback/grafana.ts @@ -10,6 +10,8 @@ import { type LoggedSubmissionChronology, type ModelCallSpan, type ReadResult, + type SubmissionSpans, + type ToolCallSpan, } from "./shared/records.ts"; type GrafanaConfig = { @@ -59,6 +61,39 @@ type OtlpTrace = { const lokiLineLimit = 1000; const tempoTraceLimit = 20; +/** Tempo refuses a search over a longer range. */ +const tempoSearchLimitMs = 168 * 3_600_000; + +/** + * Where to look for a submission's spans: from its first step's start to its + * settlement, when its chronology line gives both; otherwise the searched + * window. Undefined when that window is longer than Tempo searches. + */ +export const spanSearchWindow = ( + chronology: LoggedSubmissionChronology | null, + searched: TimeWindow, +): TimeWindow | undefined => { + const settledAt = + chronology?.timestamp === undefined + ? Number.NaN + : Date.parse(chronology.timestamp); + const starts = + chronology?.turns.map((turn) => + turn.startedAt === null ? Number.NaN : Date.parse(turn.startedAt), + ) ?? []; + if ( + !Number.isNaN(settledAt) && + starts.length > 0 && + starts.every((start) => !Number.isNaN(start)) + ) + return { + start: new Date(Math.min(...starts)), + end: new Date(settledAt), + }; + return searched.end.getTime() - searched.start.getTime() <= tempoSearchLimitMs + ? searched + : undefined; +}; const loopbackHosts = new Set(["localhost", "127.0.0.1", "[::1]"]); @@ -104,22 +139,56 @@ const numberAttribute = ( return typeof value === "number" ? value : null; }; -/** The chat spans of one submission, each with the HTTP requests beneath it. */ -const modelCallSpansOf = ( - traceId: string, - trace: OtlpTrace, - submissionId: string, -): ModelCallSpan[] => { - const spans = (trace.trace?.resourceSpans ?? []).flatMap((resource) => +const spansOf = (trace: OtlpTrace): OtlpSpan[] => + (trace.trace?.resourceSpans ?? []).flatMap((resource) => (resource.scopeSpans ?? []).flatMap((scope) => scope.spans ?? []), ); - return spans + +/** One submission's spans of one operation, with their attributes. */ +const operationSpansOf = ( + spans: readonly OtlpSpan[], + operation: "chat" | "execute_tool", + submissionId: string, +) => + spans .map((span) => ({ span, attributes: attributesOf(span) })) .filter( ({ attributes }) => - attributes.get("gen_ai.operation.name") === "chat" && + attributes.get("gen_ai.operation.name") === operation && attributes.get("flue.submission.id") === submissionId, - ) + ); + +/** + * The execute_tool spans of one submission. A browser-run call's span covers + * the round trip of the whole batch the panel ran, not its own work. + */ +const toolCallSpansOf = ( + traceId: string, + trace: OtlpTrace, + submissionId: string, +): ToolCallSpan[] => + operationSpansOf(spansOf(trace), "execute_tool", submissionId).map( + ({ span, attributes }) => ({ + traceId, + turnId: stringAttribute(attributes, "flue.turn.id"), + toolName: stringAttribute(attributes, "gen_ai.tool.name"), + startedAt: isoFromNanoseconds(span.startTimeUnixNano), + endedAt: isoFromNanoseconds(span.endTimeUnixNano), + durationMs: millisecondsBetween( + span.startTimeUnixNano, + span.endTimeUnixNano, + ), + }), + ); + +/** The chat spans of one submission, each with the HTTP requests beneath it. */ +const modelCallSpansOf = ( + traceId: string, + trace: OtlpTrace, + submissionId: string, +): ModelCallSpan[] => { + const spans = spansOf(trace); + return operationSpansOf(spans, "chat", submissionId) .map(({ span, attributes }) => { const finishReasons = attributes.get("gen_ai.response.finish_reasons"); return { @@ -284,16 +353,18 @@ export const createGrafanaReader = ( ): Promise> => notes(outputLimitMarker, window, toOutputLimit), - modelCallSpans: async ( + /** A submission's model-call and tool spans, from the traces Tempo finds for it in the window. */ + spans: async ( window: TimeWindow, submissionId: string, - ): Promise> => { + ): Promise => { const uid = await datasource("tempo"); const search = (await get( `/api/datasources/proxy/uid/${uid}/api/search`, { q: `{resource.service.name=${quoted(config.service)} && span.flue.submission.id=${quoted(submissionId)}}`, - start: String(Math.floor(window.start.getTime() / 1000)), + // Tempo takes whole seconds; rounding the start up keeps a 168-hour window within its limit. + start: String(Math.ceil(window.start.getTime() / 1000)), end: String(Math.ceil(window.end.getTime() / 1000)), limit: String(tempoTraceLimit), }, @@ -307,14 +378,21 @@ export const createGrafanaReader = ( )) as OtlpTrace, })), ); + const byStart = ( + left: { readonly startedAt: string }, + right: { readonly startedAt: string }, + ) => left.startedAt.localeCompare(right.startedAt); return { - records: traces + modelCalls: traces .flatMap(({ traceID, trace }) => modelCallSpansOf(traceID, trace, submissionId), ) - .toSorted((left, right) => - left.startedAt.localeCompare(right.startedAt), - ), + .toSorted(byStart), + toolCalls: traces + .flatMap(({ traceID, trace }) => + toolCallSpansOf(traceID, trace, submissionId), + ) + .toSorted(byStart), skipped: 0, truncated: found.length >= tempoTraceLimit, }; diff --git a/apps/brunch-agent/src/server/telemetry-readback/parse-log-text.test.ts b/apps/brunch-agent/src/server/telemetry-readback/parse-log-text.test.ts index 181e46f1f20..14598511038 100644 --- a/apps/brunch-agent/src/server/telemetry-readback/parse-log-text.test.ts +++ b/apps/brunch-agent/src/server/telemetry-readback/parse-log-text.test.ts @@ -3,6 +3,7 @@ import { expect, test } from "vitest"; import { parseBrunchLog } from "./parse-log-text.ts"; import type { ModelCallScope } from "../model-call-scope.ts"; +import type { SubmissionChronology } from "../observe-turn-chronology.ts"; import type { ModelOutputLimit, ModelStreamIdleTimeout, @@ -69,13 +70,125 @@ test("a turn logged before turns named their provider, start time, retry or erro isError: false, error: null, inputTokens: 1, + cacheReadTokens: 0, + cacheWriteTokens: null, outputTokens: 1, + reasoningTokens: null, + costEstimateUsd: null, + reasoningBlocks: null, + reasoningMs: null, + firstTextDeltaMs: null, + lastTextDeltaMs: null, toolCalls: [], }, ], } satisfies LoggedSubmissionChronology); }); +test("a current turn keeps its reasoning, reply-text timing, tokens, cost and each tool call's name and argument timing, and drops the shapes and streaming profile", () => { + const loggedTurn = { + turnId: "t1", + purpose: "agent", + provider: "openai", + requestedModel: "gpt-6.1-sol", + responseModel: null, + startedAt: "2026-12-02T10:00:00.000Z", + retryOf: null, + timeToFirstEventMs: 450, + durationMs: 12_000, + terminal: "turn", + isError: false, + error: null, + inputTokens: 1_200, + cacheReadTokens: 44_000, + cacheWriteTokens: 300, + outputTokens: 436, + reasoningTokens: 96, + costEstimateUsd: 0.0123, + reasoningBlocks: 1, + reasoningMs: 9_789, + firstTextDeltaMs: 10_100, + lastTextDeltaMs: 11_000, + requestShape: { + messages: 12, + userMessages: 3, + toolResults: 8, + firstUserTextChars: 140, + }, + responseShape: { + finishReason: "toolUse", + textParts: 1, + textChars: 900, + thinkingParts: 1, + thinkingChars: 40, + toolCallParts: 1, + }, + toolCalls: [ + { + toolCallId: "call-1", + toolName: "ledger_commit", + firstDeltaMs: 11_100, + lastDeltaMs: 11_900, + deltaCount: 14, + argumentChars: 29, + maxGapMs: 300, + lastDeltaToTerminalMs: 100, + }, + ], + } satisfies SubmissionChronology["turns"][number]; + + const { chronologies } = parseBrunchLog( + `[brunch] flue.submission chronology ${JSON.stringify({ submissionId: "sub-1", outcome: "completed", turns: [loggedTurn] })}`, + ); + const [read] = chronologies.get("sub-1")?.turns ?? []; + + const { + requestShape: _request, + responseShape: _response, + ...readFields + } = loggedTurn; + expect(read).toEqual({ + ...readFields, + toolCalls: [ + { + toolCallId: "call-1", + toolName: "ledger_commit", + firstDeltaMs: 11_100, + lastDeltaMs: 11_900, + argumentChars: 29, + }, + ], + }); +}); + +test("a chronology line with a tool call missing its name is skipped and counted", () => { + const { chronologies, skipped } = parseBrunchLog( + `[brunch] flue.submission chronology ${JSON.stringify({ + submissionId: "sub-1", + outcome: "completed", + turns: [ + { + turnId: "t1", + purpose: "agent", + durationMs: 200, + terminal: "turn", + toolCalls: [ + { + toolCallId: "call-1", + firstDeltaMs: 10, + lastDeltaMs: 20, + argumentChars: 30, + }, + ], + }, + ], + })}`, + ); + + expect(chronologies.size).toBe(0); + expect(skipped.chronologyLines).toBe(1); +}); + test("only the turn fields readback reads survive, so error messages and unknown fields in a log are dropped", () => { const turn = { turnId: "t1", @@ -110,6 +223,7 @@ test("only the turn fields readback reads survive, so error messages and unknown expect(read?.toolCalls).toEqual([ { toolCallId: "call-1", + toolName: "addPlace", firstDeltaMs: 10, lastDeltaMs: 20, argumentChars: 30, diff --git a/apps/brunch-agent/src/server/telemetry-readback/render.test.ts b/apps/brunch-agent/src/server/telemetry-readback/render.test.ts index 92ff2b84438..9089986ce58 100644 --- a/apps/brunch-agent/src/server/telemetry-readback/render.test.ts +++ b/apps/brunch-agent/src/server/telemetry-readback/render.test.ts @@ -31,7 +31,15 @@ const turn = ( terminal: "turn", isError: false, inputTokens: 100, + cacheReadTokens: 40_000, + cacheWriteTokens: 0, outputTokens: 20, + reasoningTokens: null, + costEstimateUsd: 0.0123, + reasoningBlocks: 0, + reasoningMs: 0, + firstTextDeltaMs: null, + lastTextDeltaMs: null, toolCalls: [], ...overrides, }); @@ -129,9 +137,12 @@ test("a submission's detail lists each call with who served it, its retry, its e }); expect(markdown).toContain( - "| turn-1 | agent | anthropic/claude-sonnet-4-6 | claude-sonnet-4-6-20260101 | 2026-11-03T10:00:00.000Z | – | 3.0 s | – | model_stream_idle | request_dispatch idle 60 s, retry claimed | 100/20 |", + "| Turn | Purpose | Model | Served by | Started | HTTP response | Duration | Retry of | Error | Idle timeout |", ); - expect(markdown).toContain("| 12 s | 3.0 s | turn-1 | – | – | 100/20 |"); + expect(markdown).toContain( + "| turn-1 | agent | anthropic/claude-sonnet-4-6 | claude-sonnet-4-6-20260101 | 2026-11-03T10:00:00.000Z | – | 3.0 s | – | model_stream_idle | request_dispatch idle 60 s, retry claimed |", + ); + expect(markdown).toContain("| 12 s | 3.0 s | turn-1 | – | – |"); // Every timeout sits beside its call, so there is no separate list. expect(markdown).not.toContain("## Idle timeouts"); // No trace source was read, so there is no spans section. @@ -177,7 +188,7 @@ test("an unsettled submission says where its chronology was looked for", () => { chronology: null, idleTimeouts: [], outputLimits: [], - spans: [], + spans: { modelCalls: [], toolCalls: [] }, }); expect(markdown).toContain("No chronology line in the last 24h"); @@ -208,3 +219,291 @@ test("an output-limit stop names its call's error, which the turn reports only a "## Output limits outside these calls\n\n- 2026-11-03T10:00:25.000Z turn-9 anthropic/claude-sonnet-4-6: output limit at 8192 tokens", ); }); + +test("each step shows its reasoning, reply-text timing, tool-argument streaming with the tools called, tokens with cache read and write apart, and its cost", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology: { + ...chronology, + turns: [ + turn("turn-1", { + durationMs: 11_268, + reasoningBlocks: 1, + reasoningMs: 9_789, + firstTextDeltaMs: 10_100, + lastTextDeltaMs: 11_000, + outputTokens: 436, + reasoningTokens: 96, + toolCalls: [ + { + toolCallId: "call-1", + toolName: "ledger_commit", + firstDeltaMs: 11_100, + lastDeltaMs: 11_140, + argumentChars: 29, + }, + ], + }), + turn("turn-2", { reasoningBlocks: 2, reasoningMs: 4_000 }), + turn("turn-3", { + toolCalls: ( + [ + ["call-2", "addPlace", 1_000], + ["call-3", "addArc", 1_100], + ["call-4", "addPlace", 1_200], + ] as const + ).map(([toolCallId, toolName, at]) => ({ + toolCallId, + toolName, + firstDeltaMs: at, + lastDeltaMs: at, + argumentChars: 40, + })), + }), + ], + }, + idleTimeouts: [], + outputLimits: [], + spans: null, + }); + + expect(markdown).toContain( + "| Turn | Duration | Reasoning | Reply text | Tool arguments | Tokens in | Tokens out | Cost |", + ); + expect(markdown).toContain( + "| turn-1 | 11 s | 9.8 s in 1 block | 10.1 s to 11.0 s | 11.1 s to 11.1 s: ledger_commit | 100 + 40000 cache read + 0 cache write | 436 (96 reasoning) | $0.0123 |", + ); + expect(markdown).toContain( + "| turn-2 | 3.0 s | 4.0 s in 2 blocks | none | none | 100 + 40000 cache read + 0 cache write | 20 | $0.0123 |", + ); + expect(markdown).toContain( + "| turn-3 | 3.0 s | none | none | 1.0 s to 1.2 s: addPlace ×2, addArc |", + ); +}); + +test("a step logged before these fields shows them as unknown, not as none", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology: { + ...chronology, + turns: [ + turn("turn-1", { + cacheReadTokens: null, + cacheWriteTokens: null, + costEstimateUsd: null, + reasoningBlocks: null, + reasoningMs: null, + }), + ], + }, + idleTimeouts: [], + outputLimits: [], + spans: null, + }); + + expect(markdown).toContain( + "| turn-1 | 3.0 s | – | – | none | 100 + – cache read + – cache write | 20 | – |", + ); +}); + +const toolSpan = ( + turnId: string, + toolName: string, + startedAt: string, + endedAt: string, +) => ({ + traceId: "trace-1", + turnId, + toolName, + startedAt, + endedAt, + durationMs: Date.parse(endedAt) - Date.parse(startedAt), +}); + +test("tool execution is shown under each step, with the calls a browser batch returned together timed once, not summed", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology, + idleTimeouts: [], + outputLimits: [], + spans: { + modelCalls: [], + toolCalls: [ + toolSpan( + "turn-1", + "addPlace", + "2026-11-03T10:00:03.600Z", + "2026-11-03T10:00:04.046Z", + ), + toolSpan( + "turn-1", + "addPlace", + "2026-11-03T10:00:03.600Z", + "2026-11-03T10:00:04.046Z", + ), + toolSpan( + "turn-1", + "addArc", + "2026-11-03T10:00:03.601Z", + "2026-11-03T10:00:04.046Z", + ), + toolSpan( + "turn-2", + "ledger_commit", + "2026-11-03T10:00:10.000Z", + "2026-11-03T10:00:10.010Z", + ), + ], + }, + }); + + expect(markdown).toContain( + "## Tool execution\n\n| Turn | Tools | Calls | Execution |\n| --- | --- | --- | --- |\n| turn-1 | addPlace ×2, addArc | 3 | 446 ms |\n| turn-2 | ledger_commit | 1 | 10 ms |", + ); +}); + +const toolExecutionOf = ( + toolCalls: readonly ReturnType[], +): string => + renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology, + idleTimeouts: [], + outputLimits: [], + spans: { modelCalls: [], toolCalls }, + }).split("## Tool execution\n\n")[1] ?? ""; + +test("a browser batch whose calls ended over adjacent milliseconds is one row, timed from its earliest start to its latest end", () => { + const batch = Array.from({ length: 16 }, (_, index) => + toolSpan( + "turn-1", + index < 8 ? "addPlace" : "addArc", + `2026-11-03T10:00:03.${String(600 + (index % 3)).padStart(3, "0")}Z`, + index < 14 ? "2026-11-03T10:00:04.094Z" : "2026-11-03T10:00:04.095Z", + ), + ); + + expect(toolExecutionOf(batch)).toBe( + "| Turn | Tools | Calls | Execution |\n| --- | --- | --- | --- |\n| turn-1 | addPlace ×8, addArc ×8 | 16 | 495 ms |", + ); +}); + +test("two server calls in one step that ran one after the other are two rows", () => { + expect( + toolExecutionOf([ + toolSpan( + "turn-2", + "ledger_commit", + "2026-11-03T10:00:10.010Z", + "2026-11-03T10:00:10.030Z", + ), + toolSpan( + "turn-2", + "ledger_read", + "2026-11-03T10:00:10.000Z", + "2026-11-03T10:00:10.010Z", + ), + ]), + ).toBe( + "| Turn | Tools | Calls | Execution |\n| --- | --- | --- | --- |\n| turn-2 | ledger_read | 1 | 10 ms |\n| turn-2 | ledger_commit | 1 | 20 ms |", + ); +}); + +const modelSpan = (turnId: string) => ({ + traceId: "trace-1", + turnId, + provider: "anthropic", + requestedModel: "claude-sonnet-4-6", + startedAt: "2026-11-03T10:00:00.000Z", + durationMs: 3_000, + failed: false, + errorType: null, + finishReasons: ["stop"], + httpRequests: [], +}); + +test("steps the chronology lists without a chat span are counted and named under the spans", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology: { + ...chronology, + turns: [turn("turn-1"), turn("turn-2"), turn("turn-3")], + }, + idleTimeouts: [], + outputLimits: [], + spans: { modelCalls: [modelSpan("turn-1")], toolCalls: [] }, + }); + + expect(markdown).toContain( + "2 of 3 steps have no `chat` span in Tempo: turn-2, turn-3.", + ); +}); + +test("when every step lacks a chat span, all are counted and named", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology, + idleTimeouts: [], + outputLimits: [], + spans: { + modelCalls: [], + toolCalls: [ + toolSpan( + "turn-2", + "ledger_commit", + "2026-11-03T10:00:10.000Z", + "2026-11-03T10:00:10.010Z", + ), + ], + }, + }); + + expect(markdown).toContain( + "No model-call spans found.\n\n2 of 2 steps have no `chat` span in Tempo: turn-1, turn-2.", + ); +}); + +test("a step list whose every step has its chat span says nothing about missing spans", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 24h", + chronology, + idleTimeouts: [], + outputLimits: [], + spans: { + modelCalls: [modelSpan("turn-1"), modelSpan("turn-2")], + toolCalls: [], + }, + }); + + expect(markdown).not.toContain("no `chat` span"); +}); + +test("a submission whose spans Tempo no longer holds still shows its chronology and says the spans are out of reach", () => { + const markdown = renderSubmissionDetail({ + submissionId: "sub-1", + searched: "in the last 14d", + chronology, + idleTimeouts: [], + outputLimits: [], + spans: { modelCalls: [], toolCalls: [] }, + }); + + expect(markdown).toContain("## Model calls"); + expect(markdown).toContain( + "## Spans\n\nNo spans for this submission: Tempo no longer holds them, or the server did not export them.", + ); + expect(markdown).not.toContain("## Tool execution"); +}); + +test("the submission list names its slowest provider response as such", () => { + expect( + renderSubmissionList([summarizeSubmission(chronology, [], [])]), + ).toContain("Slowest HTTP response"); +}); diff --git a/apps/brunch-agent/src/server/telemetry-readback/render.ts b/apps/brunch-agent/src/server/telemetry-readback/render.ts index b85c096b480..25db6cbce54 100644 --- a/apps/brunch-agent/src/server/telemetry-readback/render.ts +++ b/apps/brunch-agent/src/server/telemetry-readback/render.ts @@ -6,6 +6,8 @@ import { type LoggedSubmissionChronology, type LoggedTurnChronology, type ModelCallSpan, + type SubmissionSpans, + type ToolCallSpan, } from "./shared/records.ts"; export const seconds = (ms: number | null | undefined): string => @@ -13,6 +15,15 @@ export const seconds = (ms: number | null | undefined): string => ? "–" : `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)} s`; +/** Milliseconds below a second, seconds above. */ +const duration = (ms: number): string => (ms < 1000 ? `${ms} ms` : seconds(ms)); + +/** A time within a step, to a tenth of a second however late in it. */ +const offset = (ms: number): string => `${(ms / 1000).toFixed(1)} s`; + +const plural = (count: number, noun: string): string => + `${count} ${noun}${count === 1 ? "" : "s"}`; + export const table = ( header: readonly string[], rows: readonly (readonly string[])[], @@ -137,7 +148,7 @@ export const renderSubmissionList = ( "Outcome", "Calls", "Models", - "Slowest first event", + "Slowest HTTP response", "Retries", "Failed", "Idle timeouts", @@ -166,7 +177,121 @@ export type SubmissionDetail = { readonly idleTimeouts: readonly LoggedIdleTimeout[]; readonly outputLimits: readonly LoggedOutputLimit[]; /** Null when no trace source was read. */ - readonly spans: readonly ModelCallSpan[] | null; + readonly spans: Pick | null; +}; + +/** Whether the line carries the per-step timing fields, so a missing value means none rather than unknown. */ +const hasStepTiming = (turn: LoggedTurnChronology): boolean => + turn.reasoningMs !== null; + +const reasoningCell = (turn: LoggedTurnChronology): string => + turn.reasoningMs === null || turn.reasoningBlocks === null + ? "–" + : turn.reasoningBlocks === 0 + ? "none" + : `${seconds(turn.reasoningMs)} in ${plural(turn.reasoningBlocks, "block")}`; + +/** From the step's start to the reply text's first and last delta. */ +const replyTextCell = (turn: LoggedTurnChronology): string => + turn.firstTextDeltaMs === null || turn.lastTextDeltaMs === null + ? hasStepTiming(turn) + ? "none" + : "–" + : `${offset(turn.firstTextDeltaMs)} to ${offset(turn.lastTextDeltaMs)}`; + +/** From the step's start to the first and last argument delta of any of its tool calls, and the tools called. */ +const toolArgumentsCell = (turn: LoggedTurnChronology): string => + turn.toolCalls.length === 0 + ? "none" + : `${offset(Math.min(...turn.toolCalls.map((call) => call.firstDeltaMs)))} to ${offset( + Math.max(...turn.toolCalls.map((call) => call.lastDeltaMs)), + )}: ${toolNamesCell(turn.toolCalls.map((call) => call.toolName))}`; + +const count = (value: number | null): string => + value === null ? "–" : String(value); + +const tokensInCell = (turn: LoggedTurnChronology): string => + `${count(turn.inputTokens)} + ${count(turn.cacheReadTokens)} cache read + ${count(turn.cacheWriteTokens)} cache write`; + +const tokensOutCell = (turn: LoggedTurnChronology): string => + turn.reasoningTokens === null + ? count(turn.outputTokens) + : `${count(turn.outputTokens)} (${turn.reasoningTokens} reasoning)`; + +const costCell = (turn: LoggedTurnChronology): string => + turn.costEstimateUsd === null ? "–" : `$${turn.costEstimateUsd.toFixed(4)}`; + +/** Calls of one step that ran together: a browser batch the panel ran at once, or one call. */ +type ToolBatch = { + readonly turnId: string | null; + readonly toolNames: (string | null)[]; + readonly startedAt: number; + endedAt: number; +}; + +/** + * A step's calls whose time ranges overlap form one batch: the panel runs a + * batch's calls together, though their ends can fall on different + * milliseconds, while a server tool that runs after another does not overlap it. + */ +const toolBatchesOf = (spans: readonly ToolCallSpan[]) => { + const batches: ToolBatch[] = []; + const open = new Map(); + const byStart = spans + .map((span) => ({ + span, + startedAt: Date.parse(span.startedAt), + endedAt: Date.parse(span.endedAt), + })) + .toSorted((left, right) => left.startedAt - right.startedAt); + for (const { span, startedAt, endedAt } of byStart) { + const batch = open.get(span.turnId); + if (batch && startedAt < batch.endedAt) { + batch.toolNames.push(span.toolName); + batch.endedAt = Math.max(batch.endedAt, endedAt); + continue; + } + const next = { + turnId: span.turnId, + toolNames: [span.toolName], + startedAt, + endedAt, + }; + batches.push(next); + open.set(span.turnId, next); + } + return batches.map((batch) => ({ + turnId: batch.turnId, + toolNames: batch.toolNames, + durationMs: batch.endedAt - batch.startedAt, + })); +}; + +/** The chronology's steps that have no `chat` span, said in one line; null when none is missing. */ +const missingModelSpansText = ( + chronology: LoggedSubmissionChronology | null, + modelCalls: readonly ModelCallSpan[], +): string | null => { + const steps = chronology?.turns ?? []; + const spanned = new Set(modelCalls.map((span) => span.turnId)); + const missing = steps.filter((step) => !spanned.has(step.turnId)); + return missing.length === 0 + ? null + : `${missing.length} of ${plural(steps.length, "step")} ${ + missing.length === 1 ? "has" : "have" + } no \`chat\` span in Tempo: ${missing.map((step) => step.turnId).join(", ")}.`; +}; + +/** Tool names in first-seen order, repeats counted: `addPlace ×2, addArc`. */ +const toolNamesCell = (names: readonly (string | null)[]): string => { + const counts = new Map(); + for (const name of names) { + const key = name ?? "?"; + counts.set(key, (counts.get(key) ?? 0) + 1); + } + return [...counts] + .map(([name, calls]) => (calls === 1 ? name : `${name} ×${calls}`)) + .join(", "); }; export const renderSubmissionDetail = (detail: SubmissionDetail): string => { @@ -195,12 +320,11 @@ export const renderSubmissionDetail = (detail: SubmissionDetail): string => { "Model", "Served by", "Started", - "First event", + "HTTP response", "Duration", "Retry of", "Error", "Idle timeout", - "Tokens in/out", ], chronology.turns.map((turn) => [ turn.turnId, @@ -221,7 +345,33 @@ export const renderSubmissionDetail = (detail: SubmissionDetail): string => { .filter((timeout) => timeout.turnId === turn.turnId) .map(timeoutCell) .join("; ") || "–", - `${turn.inputTokens ?? "–"}/${turn.outputTokens ?? "–"}`, + ]), + ), + "", + "## Where each step's time went", + "", + "Times are from the step's start.", + "", + table( + [ + "Turn", + "Duration", + "Reasoning", + "Reply text", + "Tool arguments", + "Tokens in", + "Tokens out", + "Cost", + ], + chronology.turns.map((turn) => [ + turn.turnId, + seconds(turn.durationMs), + reasoningCell(turn), + replyTextCell(turn), + toolArgumentsCell(turn), + tokensInCell(turn), + tokensOutCell(turn), + costCell(turn), ]), ), ); @@ -249,41 +399,64 @@ export const renderSubmissionDetail = (detail: SubmissionDetail): string => { ); } if (spans !== null) { - const traceIds = [...new Set(spans.map((span) => span.traceId))]; + const { modelCalls, toolCalls } = spans; + const traceIds = [ + ...new Set([...modelCalls, ...toolCalls].map((span) => span.traceId)), + ]; lines.push( "", `## Spans${traceIds.length === 0 ? "" : ` (trace ${traceIds.join(", ")})`}`, "", - spans.length === 0 - ? "No model-call spans found." - : table( - [ - "Turn", - "Model", - "Started", - "Duration", - "Status", - "Finish", - "HTTP requests", - ], - spans.map((span) => [ - span.turnId ?? "–", - `${span.provider ?? "?"}/${span.requestedModel ?? "?"}`, - span.startedAt, - seconds(span.durationMs), - span.failed - ? `error${span.errorType ? ` ${span.errorType}` : ""}` - : "ok", - span.finishReasons.join(", ") || "–", - span.httpRequests - .map( - (request) => - `${request.statusCode ?? "?"} (${seconds(request.durationMs)})`, - ) - .join(", ") || "–", - ]), - ), + traceIds.length === 0 + ? "No spans for this submission: Tempo no longer holds them, or the server did not export them." + : modelCalls.length === 0 + ? "No model-call spans found." + : table( + [ + "Turn", + "Model", + "Started", + "Duration", + "Status", + "Finish", + "HTTP requests", + ], + modelCalls.map((span) => [ + span.turnId ?? "–", + `${span.provider ?? "?"}/${span.requestedModel ?? "?"}`, + span.startedAt, + seconds(span.durationMs), + span.failed + ? `error${span.errorType ? ` ${span.errorType}` : ""}` + : "ok", + span.finishReasons.join(", ") || "–", + span.httpRequests + .map( + (request) => + `${request.statusCode ?? "?"} (${seconds(request.durationMs)})`, + ) + .join(", ") || "–", + ]), + ), ); + const missingSpans = missingModelSpansText(chronology, modelCalls); + if (traceIds.length > 0 && missingSpans !== null) + lines.push("", missingSpans); + if (toolCalls.length > 0) + lines.push( + "", + "## Tool execution", + "", + table( + ["Turn", "Tools", "Calls", "Execution"], + toolBatchesOf(toolCalls).map((batch) => [ + batch.turnId ?? "–", + toolNamesCell(batch.toolNames), + String(batch.toolNames.length), + duration(batch.durationMs), + ]), + ), + ); } return lines.join("\n"); }; diff --git a/apps/brunch-agent/src/server/telemetry-readback/shared/records.ts b/apps/brunch-agent/src/server/telemetry-readback/shared/records.ts index 2be4c400a28..9a38e52cc86 100644 --- a/apps/brunch-agent/src/server/telemetry-readback/shared/records.ts +++ b/apps/brunch-agent/src/server/telemetry-readback/shared/records.ts @@ -24,6 +24,7 @@ type ToolCallChronology = TurnChronology["toolCalls"][number]; /** A logged tool call, reduced to the fields readback reads. */ export type LoggedToolCall = { readonly toolCallId: string; + readonly toolName: string; readonly firstDeltaMs: number; readonly lastDeltaMs: number; readonly argumentChars: number; @@ -51,7 +52,15 @@ export type LoggedTurnChronology = { readonly code: string | null; } | null; readonly inputTokens: number | null; + readonly cacheReadTokens: number | null; + readonly cacheWriteTokens: number | null; readonly outputTokens: number | null; + readonly reasoningTokens: number | null; + readonly costEstimateUsd: number | null; + readonly reasoningBlocks: number | null; + readonly reasoningMs: number | null; + readonly firstTextDeltaMs: number | null; + readonly lastTextDeltaMs: number | null; readonly toolCalls: readonly LoggedToolCall[]; }; @@ -126,6 +135,16 @@ export type ModelCallSpan = { }[]; }; +/** One tool call's execute_tool span, reduced to metadata. */ +export type ToolCallSpan = { + readonly traceId: string; + readonly turnId: string | null; + readonly toolName: string | null; + readonly startedAt: string; + readonly endedAt: string; + readonly durationMs: number; +}; + /** Records read from one source, with what the read could not cover. */ export type ReadResult = { readonly records: readonly Item[]; @@ -135,6 +154,12 @@ export type ReadResult = { readonly truncated: boolean; }; +/** A submission's spans, read from the traces found for it, with what the read could not cover. */ +export type SubmissionSpans = Omit, "records"> & { + readonly modelCalls: readonly ModelCallSpan[]; + readonly toolCalls: readonly ToolCallSpan[]; +}; + const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -177,7 +202,11 @@ const allOf = ( }; const toToolCall = (value: unknown): LoggedToolCall | undefined => { - if (!isRecord(value) || typeof value.toolCallId !== "string") + if ( + !isRecord(value) || + typeof value.toolCallId !== "string" || + typeof value.toolName !== "string" + ) return undefined; const firstDeltaMs = numberOrNull(value.firstDeltaMs); const lastDeltaMs = numberOrNull(value.lastDeltaMs); @@ -186,6 +215,7 @@ const toToolCall = (value: unknown): LoggedToolCall | undefined => { return undefined; return { toolCallId: value.toolCallId, + toolName: value.toolName, firstDeltaMs, lastDeltaMs, argumentChars, @@ -230,7 +260,15 @@ const toTurn = (value: unknown): LoggedTurnChronology | undefined => { isError: booleanOrNull(value.isError), error: toTurnError(value.error), inputTokens: numberOrNull(value.inputTokens), + cacheReadTokens: numberOrNull(value.cacheReadTokens), + cacheWriteTokens: numberOrNull(value.cacheWriteTokens), outputTokens: numberOrNull(value.outputTokens), + reasoningTokens: numberOrNull(value.reasoningTokens), + costEstimateUsd: numberOrNull(value.costEstimateUsd), + reasoningBlocks: numberOrNull(value.reasoningBlocks), + reasoningMs: numberOrNull(value.reasoningMs), + firstTextDeltaMs: numberOrNull(value.firstTextDeltaMs), + lastTextDeltaMs: numberOrNull(value.lastTextDeltaMs), toolCalls, } satisfies Partial>; }; diff --git a/apps/brunch-agent/src/server/telemetry.test.ts b/apps/brunch-agent/src/server/telemetry.test.ts index da5e9c7bd0e..5be047c5658 100644 --- a/apps/brunch-agent/src/server/telemetry.test.ts +++ b/apps/brunch-agent/src/server/telemetry.test.ts @@ -2,6 +2,8 @@ import { type AddressInfo, createServer } from "node:net"; import { createOpenTelemetryInstrumentation } from "@flue/opentelemetry"; import { + type MeterProvider, + metrics, type Span, type SpanOptions, trace, @@ -12,6 +14,7 @@ import { afterEach, expect, test, vi } from "vitest"; import { createBrunchTelemetryInstrumentation, errorCode, + flushBrunchTelemetry, probeCollector, recordOperationalFailure, withReachableCollector, @@ -29,6 +32,7 @@ const setupWith = (shutdown: () => Promise): OpenTelemetrySetup => afterEach(() => { trace.disable(); + metrics.disable(); }); test("production requires a HASH collector endpoint", () => { @@ -231,3 +235,31 @@ test("reads machine codes from Node, TLS, and pg errors only", () => { expect(errorCode(new Error("x"))).toBe(undefined); expect(errorCode("not an error")).toBe(undefined); }); + +test("flushes registered spans and metrics without shutting their providers down", async () => { + const flushed: string[] = []; + const shutdown = vi.fn<() => Promise>(); + trace.setGlobalTracerProvider({ + getTracer: () => trace.getTracer("unused"), + forceFlush: async () => { + flushed.push("spans"); + }, + shutdown, + } as TracerProvider); + metrics.setGlobalMeterProvider({ + getMeter: () => metrics.getMeter("unused"), + forceFlush: async () => { + flushed.push("metrics"); + }, + shutdown, + } as MeterProvider); + + await flushBrunchTelemetry(); + + expect(flushed.sort()).toEqual(["metrics", "spans"]); + expect(shutdown).not.toHaveBeenCalled(); +}); + +test("flushing without registered providers does nothing", async () => { + await expect(flushBrunchTelemetry()).resolves.toBeUndefined(); +}); diff --git a/apps/brunch-agent/src/server/telemetry.ts b/apps/brunch-agent/src/server/telemetry.ts index c06c637d065..b020535ec2d 100644 --- a/apps/brunch-agent/src/server/telemetry.ts +++ b/apps/brunch-agent/src/server/telemetry.ts @@ -2,7 +2,12 @@ import { connect } from "node:net"; import { createOpenTelemetryInstrumentation } from "@flue/opentelemetry"; import { instrument } from "@flue/runtime"; -import { SpanStatusCode, trace } from "@opentelemetry/api"; +import { + metrics, + ProxyTracerProvider, + SpanStatusCode, + trace, +} from "@opentelemetry/api"; import { createHttpInstrumentation, @@ -120,6 +125,34 @@ export const withReachableCollector = async ( return rest; }; +interface FlushableProvider { + forceFlush(): Promise; +} + +const isFlushable = (provider: object): provider is FlushableProvider => + "forceFlush" in provider && typeof provider.forceFlush === "function"; + +/** + * Send the spans and metrics recorded so far without shutting the exporters + * down, so a development server whose app reloads keeps exporting after the + * old store closes. The shared setup exposes only `shutdown`, so this reaches + * the providers through the OpenTelemetry globals it registered them with. + * Log records are not reached: their global lives in a package this app does + * not depend on. With no providers registered, it does nothing. + */ +export const flushBrunchTelemetry = async (): Promise => { + const tracerProvider = trace.getTracerProvider(); + const providers: object[] = [ + tracerProvider instanceof ProxyTracerProvider + ? tracerProvider.getDelegate() + : tracerProvider, + metrics.getMeterProvider(), + ]; + await Promise.all( + providers.filter(isFlushable).map((provider) => provider.forceFlush()), + ); +}; + export const installBrunchTelemetry = async (): Promise<() => Promise> => instrument( createBrunchTelemetryInstrumentation(await withReachableCollector()), diff --git a/apps/brunch-agent/src/server/turn-chronology.test.ts b/apps/brunch-agent/src/server/turn-chronology.test.ts index 45fdada820a..34efb88a8f8 100644 --- a/apps/brunch-agent/src/server/turn-chronology.test.ts +++ b/apps/brunch-agent/src/server/turn-chronology.test.ts @@ -60,7 +60,22 @@ test("one delta then silence reports the silence as last-delta to terminal and n durationMs: 21_700, isError: false, request: {}, - response: { usage: { input: 100, output: 20, cacheRead: 90 } }, + response: { + usage: { + input: 100, + output: 20, + cacheRead: 90, + cacheWrite: 0, + totalTokens: 210, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + total: 0.002, + }, + }, + }, }), // A second turn that never receives a model event or a `turn`. event(22_000, { type: "turn_start", turnId: "t2", purpose: "prompt" }), @@ -108,7 +123,14 @@ test("one delta then silence reports the silence as last-delta to terminal and n error: null, inputTokens: 100, cacheReadTokens: 90, + cacheWriteTokens: 0, outputTokens: 20, + reasoningTokens: null, + costEstimateUsd: 0.002, + reasoningBlocks: 1, + reasoningMs: 21_700 - 1_200, + firstTextDeltaMs: null, + lastTextDeltaMs: null, requestShape: null, responseShape: { finishReason: null, @@ -146,7 +168,14 @@ test("one delta then silence reports the silence as last-delta to terminal and n error: null, inputTokens: null, cacheReadTokens: null, + cacheWriteTokens: null, outputTokens: null, + reasoningTokens: null, + costEstimateUsd: null, + reasoningBlocks: 0, + reasoningMs: 0, + firstTextDeltaMs: null, + lastTextDeltaMs: null, requestShape: null, responseShape: null, toolCalls: [ @@ -215,7 +244,20 @@ test("a read-then-empty completion records context and response shapes without c response: { finishReason: "stop", output: { role: "assistant", content: [] }, - usage: { input: 3, output: 4, cacheRead: 37_000 }, + usage: { + input: 3, + output: 4, + cacheRead: 37_000, + cacheWrite: 0, + totalTokens: 37_007, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + total: 0, + }, + }, }, }), event(35, { type: "submission_settled", outcome: "completed" }), @@ -384,3 +426,184 @@ test("each turn names its provider and models, classifies a failure without its expect.objectContaining({ turnId: "t3", retryOf: null }), ]); }); + +const usage = (overrides: Record = {}) => ({ + input: 1_000, + output: 300, + cacheRead: 40_000, + cacheWrite: 2_000, + totalTokens: 43_300, + cost: { + input: 0.001, + output: 0.003, + cacheRead: 0.004, + cacheWrite: 0.002, + total: 0.01, + }, + ...overrides, +}); + +/** One step's events, observed and settled; returns the step's chronology. */ +const observeStep = (events: readonly FlueObservation[]) => { + const lines: SubmissionChronology[] = []; + const observer = createTurnChronologyObserver("chat", (line) => + lines.push(line), + ); + for (const observed of events) void observer.observe(observed, context); + return lines[0]?.turns[0]; +}; + +test("a step with two reasoning blocks sums their time and counts them, with cache writes, reasoning tokens and the catalogue cost", () => { + const step = observeStep([ + event(0, { type: "turn_start", turnId: "t1", purpose: "agent" }), + event(500, { type: "message_start", turnId: "t1" }), + event(1_000, { type: "thinking_start", turnId: "t1", contentIndex: 0 }), + event(1_200, { + type: "thinking_delta", + turnId: "t1", + contentIndex: 0, + delta: SENTINEL, + }), + event(4_000, { + type: "thinking_end", + turnId: "t1", + contentIndex: 0, + content: SENTINEL, + }), + event(4_500, { type: "thinking_start", turnId: "t1", contentIndex: 1 }), + event(5_500, { + type: "thinking_end", + turnId: "t1", + contentIndex: 1, + content: SENTINEL, + }), + event(6_000, { + type: "turn", + turnId: "t1", + isError: false, + response: { usage: usage() }, + }), + event(6_001, { + type: "message_end", + turnId: "t1", + message: { + role: "assistant", + content: [{ type: "thinking", thinking: SENTINEL }], + usage: usage({ reasoning: 120 }), + }, + }), + event(6_100, { type: "submission_settled", outcome: "completed" }), + ]); + + expect(step).toMatchObject({ + timeToFirstEventMs: 500, + reasoningBlocks: 2, + reasoningMs: 3_000 + 1_000, + firstTextDeltaMs: null, + lastTextDeltaMs: null, + inputTokens: 1_000, + cacheReadTokens: 40_000, + cacheWriteTokens: 2_000, + outputTokens: 300, + reasoningTokens: 120, + costEstimateUsd: 0.01, + }); + expect(JSON.stringify(step)).not.toContain(SENTINEL); +}); + +test("a step with reply text then a tool call times the text's first and last delta from the step's start", () => { + const step = observeStep([ + event(0, { type: "turn_start", turnId: "t1", purpose: "agent" }), + event(400, { type: "message_start", turnId: "t1" }), + event(2_000, { type: "text_delta", turnId: "t1", text: SENTINEL }), + event(2_300, { type: "text_delta", turnId: "t1", text: "more" }), + event(3_100, { type: "text_delta", turnId: "t1", text: "end" }), + event(3_500, { + type: "toolcall_delta", + turnId: "t1", + toolCallId: "call-a", + toolName: "ledger_commit", + argumentTextDelta: "{}", + }), + event(4_000, { + type: "turn", + turnId: "t1", + isError: false, + response: { usage: usage() }, + }), + event(4_100, { type: "submission_settled", outcome: "completed" }), + ]); + + expect(step).toMatchObject({ + reasoningBlocks: 0, + reasoningMs: 0, + firstTextDeltaMs: 2_000, + lastTextDeltaMs: 3_100, + toolCalls: [expect.objectContaining({ firstDeltaMs: 3_500 })], + }); + expect(JSON.stringify(step)).not.toContain(SENTINEL); +}); + +test("a step with neither reasoning nor text, from a provider that reports no reasoning count, records zero blocks and null text and reasoning tokens", () => { + const step = observeStep([ + event(0, { type: "turn_start", turnId: "t1", purpose: "agent" }), + event(300, { + type: "toolcall_delta", + turnId: "t1", + toolCallId: "call-a", + toolName: "activate_skill", + argumentTextDelta: "{}", + }), + event(900, { + type: "turn", + turnId: "t1", + isError: false, + response: { usage: usage() }, + }), + event(901, { + type: "message_end", + turnId: "t1", + message: { role: "assistant", content: [], usage: usage() }, + }), + event(1_000, { type: "submission_settled", outcome: "completed" }), + ]); + + expect(step).toMatchObject({ + reasoningBlocks: 0, + reasoningMs: 0, + firstTextDeltaMs: null, + lastTextDeltaMs: null, + reasoningTokens: null, + costEstimateUsd: 0.01, + }); +}); + +test("a reasoning block cut off before it ended counts until the step ended, or until the submission settled when the step never did", () => { + const ended = observeStep([ + event(0, { type: "turn_start", turnId: "t1", purpose: "agent" }), + event(1_000, { type: "thinking_start", turnId: "t1", contentIndex: 0 }), + event(7_000, { + type: "turn", + turnId: "t1", + isError: true, + response: {}, + }), + event(9_000, { type: "submission_settled", outcome: "failed" }), + ]); + const unended = observeStep([ + event(0, { type: "turn_start", turnId: "t1", purpose: "agent" }), + event(1_000, { type: "thinking_start", turnId: "t1", contentIndex: 0 }), + event(9_000, { type: "submission_settled", outcome: "aborted" }), + ]); + + expect(ended).toMatchObject({ + terminal: "turn", + reasoningBlocks: 1, + reasoningMs: 6_000, + }); + expect(unended).toMatchObject({ + terminal: "settlement", + reasoningBlocks: 1, + reasoningMs: 8_000, + }); +});