diff --git a/docs/calibration-tree-artifacts.md b/docs/calibration-tree-artifacts.md index 0e99462a..472179e8 100644 --- a/docs/calibration-tree-artifacts.md +++ b/docs/calibration-tree-artifacts.md @@ -369,10 +369,17 @@ built its tree and, when the run's files declare the diagnostics' digest (in a structured run manifest or a staged bundle's receipt), only while the tree holds those diagnostics. While a run's copy records no end and the page's state for it comes from the collector's record, its Stage timeline and -calibration progress come from that record too, without heartbeats, and only -the newest events of each that fit a size limit. The release pages read -each build's copies of its original files and the copy of `releases.json` the -same way. +calibration progress come from that record too. The Stage timeline lists the +record's stage changes, including the stage ends the emitter adds, and its +calibration events, in the record's order. It leaves out heartbeats +(including those whose reading the collector removed) and progress reports, +which no run's events file holds; a progress report is an event other than a +calibration event whose details hold both `done` and `total`, whatever its +status. Within a size limit, the newest stage changes are kept first and the +newest calibration events fill what is left; the calibration progress keeps +its newest events within a limit of its own of the same size. The release +pages read each build's copies of its original files and the copy of +`releases.json` the same way. ## Browser loading diff --git a/frontend/app/api/microcosm/staging/run/route.test.ts b/frontend/app/api/microcosm/staging/run/route.test.ts index c0752088..5a671aa6 100644 --- a/frontend/app/api/microcosm/staging/run/route.test.ts +++ b/frontend/app/api/microcosm/staging/run/route.test.ts @@ -222,48 +222,233 @@ type RecordInternalsBody = { calibration_progress: { events: { epoch: number }[] }; }; -test("an unfinished run's events from the collector's record leave out heartbeats", async () => { - // Every emitter attaches a resource sample to every event. - const resources = { rss_bytes: 1 }; - const stageEvents = ["created", "target_compilation", "calibrating"].map((stage, index) => ({ +// Every emitter attaches a resource sample to every event. +const RESOURCES = { rss_bytes: 1 }; + +function minutesAfter(start: string, minutes: number): string { + return new Date(Date.parse(start) + minutes * 60_000).toISOString(); +} + +// A stage start or end as the record's events list carries one. +function stageChange(index: number, stage = `stage-${index}`): Record { + return { event_type: "stage", stage, stage_id: stage, - status: "started", - time: new Date(Date.parse("2026-10-20T00:00:00Z") + index * 1_000).toISOString(), + status: index % 2 === 0 ? "started" : "completed", + message: `Stage ${stage}.`, + time: minutesAfter("2026-10-23T15:00:00Z", index), details: {}, - resources, - })); - const workReport = { + resources: RESOURCES, + }; +} + +// A US scoring-batch progress report as the record carries one: status +// `progress`, with the batch counts the build sent only to the emitter. +function scoringBatchReport(index: number): Record { + return { event_type: "stage", - stage: "calibrating", - stage_id: "calibrating", + stage: "post_export_scoring", + stage_id: "post_export_scoring", status: "progress", - time: "2026-10-20T00:10:00Z", - details: { done: 50, total: 500, unit: "epochs" }, - resources, + message: null, + time: minutesAfter("2026-10-23T20:00:00Z", index / 12), + details: { + done: (index % 177) + 1, + total: 177, + unit: "scoring_batch", + elapsed_seconds: index * 5.1, + batch: index % 177, + batches: 177, + pass_name: "reform_coverage_smoke baseline plan", + outer: { done: 1, total: 4, unit: "reform_pass" }, + }, + resources: { ...RESOURCES, cpu_user_seconds: index, cpu_system_seconds: index, peak_rss_bytes: 2 }, }; - // A stage update with a message and nothing else, as a stage transition - // can send: not a heartbeat. - const stageUpdate = { +} + +// A UK graph-node progress report as the record carries one: status +// `completed`, with the node counts the build sent only to the emitter. +function graphNodeReport(done: number): Record { + return { event_type: "stage", + stage: `uk.full.node-${done}`, + stage_id: `uk.full.node-${done}`, + status: "completed", + message: null, + time: minutesAfter("2026-11-23T08:00:00Z", done), + details: { done, total: 25, unit: "graph_nodes", elapsed_seconds: 12.5 }, + resources: RESOURCES, + }; +} + +// A calibration event as the record's events list carries one. +function calibrationEvent(epoch: number, padding = ""): Record { + return { + event_type: "calibration", stage: "calibrating", stage_id: "calibrating", status: "progress", - message: "Fitting weights.", - time: "2026-10-20T00:11:00Z", - details: {}, - resources, + message: null, + time: minutesAfter("2026-10-23T18:00:00Z", epoch / 60), + details: { epoch, epochs: 1_500, loss: 0.2, padding }, + resources: RESOURCES, + }; +} + +test("an unfinished run's events from the collector's record leave out heartbeats and progress reports", async () => { + const stages = ["created", "target_compilation", "calibrating"].map((stage, index) => + stageChange(index, stage), + ); + // A stage row the US build sent with a status the emitter doesn't know + // (`retained`), which reaches the record as `progress`; the run's own + // events file holds it. + const retainedRow = { + ...stageChange(1, "capital_gains_tail_presence"), + status: "progress", + message: "Retained the capital gains tail.", + details: { retained_records: 12 }, + }; + // A stage update with a message and nothing else, as a stage transition + // can send: neither a heartbeat nor a progress report. + const stageUpdate = { ...stageChange(2, "calibrating"), status: "progress", message: "Fitting weights." }; + // A stage row whose details hold `done` but no `total`: not a progress + // report. + const doneOnly = { ...stageChange(3, "export_dataset"), details: { done: true } }; + // Nor is one whose details hold `total` but no `done`. + const totalOnly = { ...stageChange(5, "export_dataset"), details: { total: 4 } }; + // A stage end the emitter adds when the next stage starts. + const emitterStageEnd = { + ...stageChange(1, "target_compilation"), + message: null, + details: { stage_span: { occurrence: 1, closed_by: "next_stage_started", awake_seconds: 60 } }, }; + // A calibration event is never a progress report, whatever its details. + const calibration = [calibrationEvent(1), { ...calibrationEvent(2), details: { done: 2, total: 9 } }]; const heartbeats = Array.from({ length: 10 }, (_, index) => heartbeatEvent(index)); const body = (await loadRun( - handlerWithLargeRecord([...stageEvents, ...heartbeats, workReport, stageUpdate], []), + handlerWithLargeRecord( + [ + stages[0], + ...heartbeats.slice(0, 5), + retainedRow, + stages[1], + graphNodeReport(1), + graphNodeReport(2), + emitterStageEnd, + stages[2], + calibration[0], + stageUpdate, + calibration[1], + scoringBatchReport(0), + ...heartbeats.slice(5), + scoringBatchReport(1), + doneOnly, + totalOnly, + ], + [], + ), )) as unknown as RecordInternalsBody; + // In the record's order, calibration events among the stage changes. expect(body.events).toEqual( - JSON.parse(JSON.stringify([...stageEvents, workReport, stageUpdate])), + JSON.parse( + JSON.stringify([ + stages[0], + retainedRow, + stages[1], + emitterStageEnd, + stages[2], + calibration[0], + stageUpdate, + calibration[1], + doneOnly, + totalOnly, + ]), + ), + ); +}); + +test("heartbeats whose reading the collector dropped are left out", async () => { + // A heartbeat reading that doesn't match the collector's model (from an + // emitter newer than the collector) is removed and named in + // `dropped_emitter_details`; the heartbeat keeps any sleep it carries. + const withoutReading = Array.from({ length: 4 }, (_, index) => ({ + ...heartbeatEvent(index), + details: + index % 2 === 0 + ? { dropped_emitter_details: ["reading"] } + : { sleep: { asleep_seconds: 120 }, dropped_emitter_details: ["reading"] }, + })); + // A stage end whose span the collector dropped is still a stage change. + const stageEndWithoutSpan = { + ...stageChange(1, "target_compilation"), + details: { dropped_emitter_details: ["stage_span"] }, + }; + const stages = [stageChange(0, "created"), stageChange(2, "calibrating")]; + + const body = (await loadRun( + handlerWithLargeRecord( + [stages[0], ...withoutReading.slice(0, 2), stageEndWithoutSpan, ...withoutReading.slice(2), stages[1]], + [], + ), + )) as unknown as RecordInternalsBody; + + expect(body.events).toEqual(JSON.parse(JSON.stringify([stages[0], stageEndWithoutSpan, stages[1]]))); +}); + +test("a long record's progress reports no longer crowd out the run's stages", async () => { + // As the US run of 2026-10-23 recorded it: its stage changes, 1,500 + // calibration epochs, then thousands of scoring-batch progress reports + // between its last stages, with heartbeats throughout. + const stages = Array.from({ length: 42 }, (_, index) => stageChange(index)); + const calibration = Array.from({ length: 1_500 }, (_, index) => calibrationEvent(index + 1)); + const reports = Array.from({ length: 3_000 }, (_, index) => scoringBatchReport(index)); + const heartbeats = Array.from({ length: 400 }, (_, index) => heartbeatEvent(index)); + + const body = (await loadRun( + handlerWithLargeRecord( + [ + ...stages.slice(0, 38), + ...heartbeats.slice(0, 200), + ...calibration, + ...stages.slice(38, 41), + ...reports, + ...heartbeats.slice(200), + stages[41], + ], + [], + ), + )) as unknown as RecordInternalsBody; + + expect(body.events.filter((event) => event.event_type === "stage")).toEqual( + JSON.parse(JSON.stringify(stages)), ); + expect(body.events.filter((event) => event.event_type === "calibration")).toHaveLength(1_500); +}); + +test("calibration events past the size limit give way before stage changes", async () => { + const stages = Array.from({ length: 30 }, (_, index) => stageChange(index)); + const calibration = Array.from({ length: 10_000 }, (_, index) => + calibrationEvent(index + 1, "x".repeat(300)), + ); + + const body = (await loadRun( + handlerWithLargeRecord([...stages.slice(0, 15), ...calibration, ...stages.slice(15)], []), + )) as unknown as RecordInternalsBody; + + expect(body.events.filter((event) => event.event_type === "stage")).toEqual( + JSON.parse(JSON.stringify(stages)), + ); + const keptCalibration = body.events.filter((event) => event.event_type === "calibration"); + expect(keptCalibration.length).toBeGreaterThan(0); + expect(keptCalibration.length).toBeLessThan(10_000); + // The newest calibration events are the ones kept, in the record's order. + expect((keptCalibration.at(-1)?.details as { epoch: number }).epoch).toBe(10_000); + // They fill what the stage changes leave of the limit. + expect(JSON.stringify(body.events).length).toBeLessThanOrEqual(1_500_000); + expect(JSON.stringify(body.events).length).toBeGreaterThan(1_490_000); }); test("an unfinished run's internals from the collector's record keep the newest within a size limit", async () => { diff --git a/frontend/app/api/microcosm/staging/run/route.ts b/frontend/app/api/microcosm/staging/run/route.ts index cd882c52..7013ced9 100644 --- a/frontend/app/api/microcosm/staging/run/route.ts +++ b/frontend/app/api/microcosm/staging/run/route.ts @@ -77,7 +77,9 @@ function huggingFaceRunState(detail: StagingRunDetail): HuggingFaceRunState { // when the collector has a record of the run. While the copy records no end, // a copy changes only when the run writes its files, so the Stage timeline's // events and the calibration progress come from the collector's record (read -// API v2) when it has one; `run_internals_source` says which. The progress +// API v2) when it has one (`recordInternals`: its stage changes and +// calibration events, without the heartbeats and progress reports a run's +// events file never holds); `run_internals_source` says which. The progress // document and the run manifest, with its uploaded files, stay the copy's. export function createStagingRunHandler( dependencies: StagingRunRouteDependencies = { diff --git a/frontend/lib/microcosm/staging-run-state.ts b/frontend/lib/microcosm/staging-run-state.ts index 19f4b91d..f86852bf 100644 --- a/frontend/lib/microcosm/staging-run-state.ts +++ b/frontend/lib/microcosm/staging-run-state.ts @@ -18,10 +18,11 @@ import type { StagingRunSummary } from "@policyengine/calibration-tree/staging-a export type RunStateSource = "collector" | "hugging_face"; -// An unfinished run's events and calibration events from the collector's -// record are kept newest first up to this many characters of JSON each, so -// the Candidate tab's answer stays well within the platform's 4.5 MB -// response limit. A record can hold far more than a run's copied files. +// The most characters of JSON an unfinished run's Stage timeline events, and +// separately its calibration progress events, from the collector's record +// may take (see `recordInternals`), so the Candidate tab's answer stays well +// within the platform's 4.5 MB response limit. A record can hold far more +// than a run's copied files. export const RECORD_EVENTS_JSON_LIMIT = 1_500_000; type JsonDocument = Record; @@ -34,15 +35,17 @@ function jsonObject(value: unknown): JsonDocument | null { // A heartbeat as the collector serves it in a run's documents: a `progress` // event that is not a calibration event and carries the emitter's machine -// reading or, from emitters before 0.14.0, no message and no details beside -// its resource sample. It names the stage the run is in. A run's own events -// file never holds one. (A heartbeat whose reading the collector dropped -// looks like an older emitter's and is left out the same way only when it -// has no message.) +// reading, or a reading the collector removed because it didn't match the +// collector's model (named in `dropped_emitter_details`; only a heartbeat's +// details hold a reading), or, from emitters before 0.14.0, no message and +// no details beside its resource sample. It names the stage the run is in. +// A run's own events file never holds one. function isHeartbeat(event: JsonDocument): boolean { if (event.event_type === "calibration" || event.status !== "progress") return false; const details = jsonObject(event.details); if (jsonObject(details?.reading)) return true; + const dropped = details?.dropped_emitter_details; + if (Array.isArray(dropped) && dropped.includes("reading")) return true; const message = typeof event.message === "string" ? event.message.trim() : ""; return ( message === "" && @@ -51,10 +54,25 @@ function isHeartbeat(event: JsonDocument): boolean { ); } -// The newest items whose JSON fits the limit, in their order. -function newestWithin(items: readonly T[]): T[] { - // The brackets, less the comma the first item has none of. - let size = 1; +// A progress report as the collector serves it in a run's documents: an +// event that is not a calibration event and whose details hold both `done` +// and `total`, the counts of a stage's work, whatever its status. Builds send +// these only to the emitter: the US builder's work counters (engine batches +// in target compilation, scoring batches after export) with status +// `progress`, the UK builders' graph nodes with status `completed`. A run's +// own events file never holds one; a long record holds thousands. The emitter +// and the collector read a progress report's counts by the same two keys. +function isProgressReport(event: JsonDocument): boolean { + if (event.event_type === "calibration") return false; + const details = jsonObject(event.details); + return details != null && "done" in details && "total" in details; +} + +// The newest items whose JSON, added to JSON of `used` characters, stays +// within the limit; in their order. An empty list's JSON (`[]`) counts as 1: +// the brackets, less the comma the first item has none of. +function newestWithin(items: readonly T[], used = 1): { kept: T[]; size: number } { + let size = used; let first = items.length; while (first > 0) { const itemSize = JSON.stringify(items[first - 1]).length + 1; @@ -62,26 +80,42 @@ function newestWithin(items: readonly T[]): T[] { size += itemSize; first -= 1; } - return items.slice(first); + return { kept: items.slice(first), size }; } /** * An unfinished run's Stage timeline events and calibration progress, from - * the collector's record: heartbeats left out, and the newest of each kept - * within `RECORD_EVENTS_JSON_LIMIT`. + * the collector's record. The events are the record's stage changes, + * including the stage rows a build sends with a status of its own, and its + * calibration events, in the record's order; heartbeats and progress + * reports, which the run's own events file never holds, are left out. Within + * `RECORD_EVENTS_JSON_LIMIT`, the newest stage changes are kept first and + * the newest calibration events fill what is left, so calibration never + * crowds out the run's stages. The calibration progress keeps its newest + * events within a limit of its own of the same size. */ export function recordInternals(record: { events: JsonDocument[]; calibration_progress: JsonDocument | null; }): { events: JsonDocument[]; calibration_progress: JsonDocument | null } { - const events = newestWithin(record.events.filter((event) => !isHeartbeat(event))); + const timeline = record.events.filter( + (event) => !isHeartbeat(event) && !isProgressReport(event), + ); + const stageChanges = newestWithin( + timeline.filter((event) => event.event_type !== "calibration"), + ); + const calibrationRows = newestWithin( + timeline.filter((event) => event.event_type === "calibration"), + stageChanges.size, + ); + const kept = new Set([...stageChanges.kept, ...calibrationRows.kept]); const calibration = record.calibration_progress; const calibrationEvents = Array.isArray(calibration?.events) ? calibration.events : null; return { - events, + events: timeline.filter((event) => kept.has(event)), calibration_progress: calibration && calibrationEvents - ? { ...calibration, events: newestWithin(calibrationEvents) } + ? { ...calibration, events: newestWithin(calibrationEvents).kept } : calibration, }; }