From e7b1d8a1dfd6e70d11f9f2bf9d1ee70d9e1996ee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 09:29:20 +0000 Subject: [PATCH 1/2] chore(ci): partition archived runs by UTC day --- .github/workflows/ci-evidence-archive.yml | 1 + docs/decisions/ci-evidence.md | 22 +++++++ docs/process/ci-evidence.md | 10 +-- docs/process/ci-timings.md | 14 ++-- scripts/ci-archive.ts | 59 +++++++++++++---- scripts/ci-evidence-report.ts | 1 + scripts/ci-timings.ts | 3 +- tests/ci-archive.test.ts | 79 +++++++++++++++++++++-- 8 files changed, 163 insertions(+), 26 deletions(-) diff --git a/.github/workflows/ci-evidence-archive.yml b/.github/workflows/ci-evidence-archive.yml index 4468e19f2d..9b99ec4862 100644 --- a/.github/workflows/ci-evidence-archive.yml +++ b/.github/workflows/ci-evidence-archive.yml @@ -1,3 +1,4 @@ +# New runs use UTC run.createdAt day partitions; legacy monthly runs stay intact. # Daily compaction of the hourly ci-timings artifacts into the permanent # measurement data ref (docs/decisions/ci-evidence.md). Measurement only: never # a proof/merge gate. Executes trusted default-branch tooling with no dependency diff --git a/docs/decisions/ci-evidence.md b/docs/decisions/ci-evidence.md index 7458b44283..cafb93986c 100644 --- a/docs/decisions/ci-evidence.md +++ b/docs/decisions/ci-evidence.md @@ -100,3 +100,25 @@ service. Weekly delivery always provides a regular report, while daily comments are limited to the ruled changes. The 2026-11-08 ruling deliberately includes brief newly observed incidents instead of inventing a duration threshold or repeatedly notifying on unchanged incidents. + +## UTC-day run layout amendment — 2026-11-17 + +The [maintainer's option B ruling on #4130](https://github.com/schlessera/brain-kit/issues/4130#issuecomment-6943090694) +amends the monthly layout: new run records use `YYYY-MM/run/DD.json`, +partitioned by `run.createdAt` converted to UTC, including late arrivals and +repeated attempts. Other kinds retain `YYYY-MM/.json`. Collection and +compaction time never choose a run's partition. + +Legacy `YYYY-MM/run.json` blobs remain readable and are neither rewritten nor +deleted by compaction. When layouts coexist, readers join run/attempt identities +with the same deterministic observation/conflict rules as the writer before +reporting; a newer or richer legacy observation survives a replay into a daily +file. All historical commits remain intact. Per-kind schema versions and record +payloads are unchanged, and unknown versions still refuse reading. + +The 95 MiB limit applies separately to every output file: exactly the limit is +allowed; any larger daily file refuses the complete publication before a push. +There is no fallback partition or compression. Leakage screening and publication +parented by the inspected head with an exact ref lease remain unchanged. +Numbered monthly parts were rejected because late arrivals can reshuffle them; +compression hides text diffs and only postpones the size ceiling. diff --git a/docs/process/ci-evidence.md b/docs/process/ci-evidence.md index a12344fa79..460ce562dc 100644 --- a/docs/process/ci-evidence.md +++ b/docs/process/ci-evidence.md @@ -16,10 +16,12 @@ unknown, never zero. A successful hourly workflow can contain partial data. The following names identify normalized kinds, independent of individual file IDs. Every versioned kind below has integer `version: 1`, except `run`, which is v1 or v2 ([runner-slot wait](ci-throughput.md#runner-slot-wait)). The durable -layout is `YYYY-MM/.json` on `refs/heads/brain-ci-metrics`, with -per-record versions preserved. The daily writer and backfill -([#2955](https://github.com/schlessera/brain-kit/issues/2955)) are described in -the [durable archive guide](ci-timings.md#durable-archive). Unknown versions +layout is `YYYY-MM/run/DD.json` for new runs, by UTC `run.createdAt` day, +and `YYYY-MM/.json` for other kinds on `refs/heads/brain-ci-metrics`, with +per-record versions preserved. Legacy monthly run files remain readable and unchanged; readers merge duplicate +run/attempt identities across layouts before counting them. The daily writer +and backfill ([#2955](https://github.com/schlessera/brain-kit/issues/2955)) +are described in the [durable archive guide](ci-timings.md#durable-archive). Unknown versions are refused; future schemas append rather than rewrite history. | Kind (file) | Schema source and identity | Acquisition cadence | Raw-source retention | diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index 415cb68126..0af78ddd31 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -56,7 +56,7 @@ proof of a successful candidate. ## Automatic archival The [evidence archive and delivery decision](../decisions/ci-evidence.md) -records the permanent measurement ref, monthly schema rules, retention split, +records the permanent measurement ref, partition and schema rules, retention split, publication permissions and daily/weekly delivery cadence. Hourly collection, described here, uploads 90-day artifacts; the [durable archive](#durable-archive) compacts them into the permanent data ref daily. Scheduled report delivery is @@ -185,7 +185,8 @@ download per artifact. A budget stop keeps what it committed and leaves the rest pending, with exit status 0. The data ref is `refs/heads/brain-ci-metrics`. Each record kind lives in -`YYYY-MM/.json`, partitioned by UTC month, one record per line in +`YYYY-MM/run/DD.json` for runs (UTC `run.createdAt` day) and +`YYYY-MM/.json` for other kinds, partitioned by UTC month, one record per line in timestamp and identity order. Monthly files hold `run`, `pull`, `coordinator`, `event`, `collection`, `enrichment`, `reservations`, `red-main` and `source` records, keyed by the [inventory's](ci-evidence.md#record-kinds-schemas-and-retention) @@ -217,7 +218,7 @@ Each commit is parented by the inspected remote head and pushed with exact never move. A competing writer causes a fresh read and merge, skipping the artifacts it already archived, for up to five attempts. Sources commit in batches of 50, so a timeout keeps earlier batches. A run that finds nothing new -downloads nothing and commits nothing. A monthly file over 95 MiB stops the +downloads nothing and commits nothing. Any output file over 95 MiB stops the publication before the push, since GitHub refuses larger blobs. Explicit normalized directories, such as a budgeted `collect --since ... --until @@ -237,7 +238,10 @@ bun scripts/ci-timings.ts report --repo odysseus/chronicle --from-archive origin ``` Readers refuse an unknown kind, an unknown schema version, another repository's -record and a record outside its month partition. The archive is measurement +record and a record outside its month or day partition. Legacy monthly +`YYYY-MM/run.json` files remain readable and unchanged; mixed layouts join each +run/attempt once with the deterministic observation/conflict rules. The 95 MiB +limit applies to each daily output too, with no overflow fallback. The archive is measurement only and never an input to proof, selection or merging. ## Scheduled evidence reports @@ -431,7 +435,7 @@ containing only work, wait and preemption events. The publisher appends immutable `events/.json` files to `refs/heads/brain-ci-metrics`, preserving the inspected tree's other files. These are the dedicated published-event inputs for daily compaction (#2955), -which owns the monthly normalized archive. This command enables neither +which owns the partitioned normalized archive. This command enables neither compaction nor scheduled report delivery. Repeating a batch is a no-op; an existing ID with different content is refused. Unknown event versions are refused rather than rewritten. diff --git a/scripts/ci-archive.ts b/scripts/ci-archive.ts index 0c2d2e27a1..401aace08d 100644 --- a/scripts/ci-archive.ts +++ b/scripts/ci-archive.ts @@ -25,7 +25,7 @@ export const ARCHIVE_VERSIONS: Record = { /** GitHub refuses a blob over 100 MB; stop short of it rather than fail mid-push. */ export const MAX_FILE_BYTES = 95 * 1024 * 1024; const MONTH = /^\d{4}-\d{2}$/; -const ARCHIVE_PATH = /^(\d{4}-\d{2})\/([a-z-]+)\.json$/; +const ARCHIVE_PATH = /^(\d{4}-\d{2})\/(?:([a-z-]+)\.json|(run)\/(\d{2})\.json)$/; type Row = Record; export interface Refusal { kind: string; key: string; reason: string } @@ -59,6 +59,9 @@ const SPECS: Record r.collectedAt, key: r => digest(r) }, source: { at: r => r.createdAt, key: r => String(r.artifact) }, }; +const dayOf = (kind: ArchiveKind, record: Row) => new Date(SPECS[kind].at(record) as string).toISOString().slice(0, 10); +const partitionOf = (kind: ArchiveKind, record: Row) => kind === "run" + ? `${monthOf(kind, record)}/run/${dayOf(kind, record).slice(8)}.json` : `${monthOf(kind, record)}/${kind}.json`; export const monthOf = (kind: ArchiveKind, record: Row) => new Date(SPECS[kind].at(record) as string).toISOString().slice(0, 7); /** Schema, identity and leakage screen for one record. Returns why it is refused, or null. */ @@ -115,7 +118,7 @@ function mergeTwo(kind: ArchiveKind, old: Row, row: Row): Row { } } -/** One month and kind of the archive: identity → record. */ +/** One archive partition and kind: identity → record. */ export class MonthFile { readonly rows = new Map(); constructor(readonly kind: ArchiveKind) {} @@ -144,15 +147,16 @@ export class MonthFile { } } -/** Parses one archived month file, refusing unknown kinds, versions or repositories rather than guessing. */ +/** Parses a monthly or daily archive file, refusing unknown kinds, versions or repositories. */ export function parseMonthFile(path: string, text: string, repository: string): { kind: ArchiveKind; month: string; rows: Row[] } { const match = ARCHIVE_PATH.exec(path); - if (!match || !(ARCHIVE_KINDS as readonly string[]).includes(match[2]!)) throw new Error(`Unknown archive file ${path}`); - const kind = match[2] as ArchiveKind, rows = JSON.parse(text); + if (!match || !(ARCHIVE_KINDS as readonly string[]).includes((match[2] ?? match[3])!)) throw new Error(`Unknown archive file ${path}`); + const kind = (match[2] ?? match[3]) as ArchiveKind, rows = JSON.parse(text); if (!Array.isArray(rows)) throw new Error(`Invalid archive file ${path}`); for (const row of rows) { if (!ARCHIVE_VERSIONS[kind].includes(row?.version)) throw new Error(`Unknown ${kind} version ${JSON.stringify(row?.version)} in ${path}`); if (row.repository !== repository) throw new Error(`Archive ${path} belongs to another repository`); + if (match[4] && dayOf(kind, row) !== `${match[1]}-${match[4]}`) throw new Error(`Record outside its day partition in ${path}`); if (monthOf(kind, row) !== match[1]) throw new Error(`Record outside its month partition in ${path}`); } return { kind, month: match[1]!, rows }; @@ -199,7 +203,7 @@ export interface Batch { records: { kind: ArchiveKind; row: Row }[]; refused: Re /** * Merges a batch into the archive and publishes it. Each attempt reads the - * remote head, merges into the month files it touches, and pushes with an exact + * remote head, merges into the partition files it touches, and pushes with an exact * lease on that head; a lost race re-reads and re-merges, so a competing writer * is never overwritten. A source another writer archived meanwhile is skipped. * An unchanged tree makes no commit. @@ -210,9 +214,9 @@ export async function publishBatch(store: GitArchiveStore, repository: string, b const parent = await store.read(), tree = await store.files(parent), refused = [...batch.refused]; const archived = await archivedSources(store, parent, repository); const skip = new Set(batch.sources.filter(s => archived.has(s.artifact)).map(s => s.artifact)); + const legacyRuns = new Map(); const months = new Map(), original = new Map(); - const file = async (kind: ArchiveKind, month: string) => { - const path = `${month}/${kind}.json`; + const file = async (kind: ArchiveKind, path: string) => { let target = months.get(path); if (!target) { target = new MonthFile(kind); months.set(path, target); @@ -228,15 +232,40 @@ export async function publishBatch(store: GitArchiveStore, repository: string, b for (const { kind, row } of batch.records) { if (row.__source !== undefined && skip.has(row.__source)) continue; const { __source, ...clean } = row; - const reason = (await file(kind, monthOf(kind, clean))).add(clean); + const target = await file(kind, partitionOf(kind, clean)); + let incoming = clean; + if (kind === "run") { + const legacyPath = `${monthOf(kind, clean)}/run.json`, legacyBlob = tree.get(legacyPath); + if (legacyBlob) { + let legacy = legacyRuns.get(legacyPath); + if (!legacy) { + legacy = new MonthFile("run"); + for (const row of parseMonthFile(legacyPath, await store.blob(legacyBlob), repository).rows) { + const conflict = legacy.add(row); + if (conflict) throw new Error(conflict); + } + // Cache outside the output map: legacy files remain byte-identical. + legacyRuns.set(legacyPath, legacy); + } + const old = legacy.rows.get(SPECS.run.key(clean)); + if (old) { + try { incoming = mergeTwo("run", old, clean); } + catch (error) { + refused.push({ kind, key: SPECS.run.key(clean), reason: String(error instanceof Error ? error.message : error) }); + continue; + } + } + } + } + const reason = target.add(incoming); if (reason) refused.push({ kind, key: SPECS[kind].key(clean), reason }); } - for (const source of batch.sources) if (!skip.has(source.artifact)) (await file("source", monthOf("source", source))).add(source); + for (const source of batch.sources) if (!skip.has(source.artifact)) (await file("source", partitionOf("source", source))).add(source); // Coordination events published under events/ (#2954) are compaction inputs too; they stay where they are. for (const [path, blob] of tree) if (/^events\/[\w-]+\.json$/.test(path)) { const row = JSON.parse(await store.blob(blob)), reason = screenRecord("event", row, repository); if (reason) { refused.push({ kind: "event", key: path, reason }); continue; } - const conflict = (await file("event", monthOf("event", row))).add(row); + const conflict = (await file("event", partitionOf("event", row))).add(row); if (conflict) refused.push({ kind: "event", key: row.id, reason: conflict }); } const changes = new Map(); @@ -409,6 +438,14 @@ export async function readArchive(store: GitArchiveStore, repository: string, mo const parsed = parseMonthFile(path, await store.blob(blob), repository); rows[parsed.kind].push(...parsed.rows); } + // Both layouts may contain an attempt. Apply the writer's deterministic join + // before any consumer counts it; contradictions remain an explicit refusal. + const runs = new MonthFile("run"); + for (const row of rows.run) { + const conflict = runs.add(row); + if (conflict) throw new Error(`Conflicting archived run: ${conflict}`); + } + rows.run = JSON.parse(runs.serialize()); rows.event = [...new Map(rows.event.map(e => [JSON.stringify(e), e])).values()]; return { head, rows }; } diff --git a/scripts/ci-evidence-report.ts b/scripts/ci-evidence-report.ts index 112de432ec..4161d02c7d 100644 --- a/scripts/ci-evidence-report.ts +++ b/scripts/ci-evidence-report.ts @@ -383,6 +383,7 @@ if (import.meta.main) { if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) throw new Error("Invalid repository"); const now = new Date().toISOString(), until = options.get("--until") ?? iso(Math.floor(Date.parse(now) / DAY) * DAY); reportWindow(cadence, until); + // Shared archive loading joins legacy monthly and daily run attempts once. const inputs = await archiveInputs(options.get("--from-archive")!, repository, archiveSince(until), until); const report = evidenceReport(inputs, { cadence, until, now, archiveHead: inputs.head, epochSource: gitEpochSource(process.cwd(), options.get("--history") ?? "origin/main") }); diff --git a/scripts/ci-timings.ts b/scripts/ci-timings.ts index c01e4ffb05..c544b14d5a 100644 --- a/scripts/ci-timings.ts +++ b/scripts/ci-timings.ts @@ -433,7 +433,8 @@ function newestPulls(pulls: PullObservation[]): PullObservation[] { } /** * Report inputs from the durable data ref on `remote` (#2955). With an explicit - * window, months from one before `since` through one after `until` are read, so + * Legacy monthly and daily run partitions share the reader's deterministic + * run/attempt join. With an explicit window, months from one before `since` through one after `until` are read, so * a cohort's earlier PR attempts and later main proof stay in view. */ export async function archiveInputs(remote: string, repository: string, since?: string, until?: string, root = process.cwd()): Promise { diff --git a/tests/ci-archive.test.ts b/tests/ci-archive.test.ts index f19be6ec9e..a580b825d7 100644 --- a/tests/ci-archive.test.ts +++ b/tests/ci-archive.test.ts @@ -2,7 +2,9 @@ import { afterEach, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; -import { compactArtifacts, GitArchiveStore, MonthFile, parseMonthFile, type ArchiveAPI } from "../scripts/ci-archive"; +import { MAX_FILE_BYTES, publishBatch, readArchive, compactArtifacts, GitArchiveStore, MonthFile, parseMonthFile, type ArchiveAPI } from "../scripts/ci-archive"; +import { archiveInputs } from "../scripts/ci-timings"; +import { evidenceReport } from "../scripts/ci-evidence-report"; import { archiveWorkflowProblems } from "../scripts/check-ci-workflows"; const repository = "odysseus/chronicle", ref = "refs/heads/brain-ci-metrics"; @@ -93,7 +95,7 @@ test("backfilling the same artifacts twice adds no commit and downloads nothing expect(first, "FIRST_BACKFILL_COMMITS").toMatchObject({ commits: 1, sources: 2, pending: 0, refused: [] }); expect(api.calls.filter(p => p.endsWith("/zip")), "UNTRUSTED_ARTIFACT_NOT_DOWNLOADED").toEqual(["actions/artifacts/1/zip", "actions/artifacts/2/zip"]); expect(git(f.remote, "ls-tree", "-r", "--name-only", ref).split("\n")).toEqual(["2026-07/collection.json", "2026-07/enrichment.json", - "2026-07/pull.json", "2026-07/reservations.json", "2026-07/run.json", "2026-07/source.json"]); + "2026-07/pull.json", "2026-07/reservations.json", "2026-07/run/12.json", "2026-07/source.json"]); const head = git(f.remote, "rev-parse", ref); const again = f.api(), second = await compactArtifacts({ store, api: again, repository, branch: "main" }); expect(second, "SECOND_BACKFILL_IDEMPOTENT").toMatchObject({ commits: 0, sources: 0, pending: 0, head }); @@ -108,8 +110,8 @@ test("compaction keeps the newest observation per identity and stores a repeated f.add(2, at(120), hour(120, { "pull-42.json": pull(120, { changedFiles: 3 }) })); f.add(3, "2026-08-01T00:30:00Z", { "run-9-attempt-1.json": { ...run(9, "push", 0, 0), run: { ...run(9, "push", 0, 0).run, createdAt: "2026-08-01T00:10:00Z" } } }); await compactArtifacts({ store: new GitArchiveStore(one), api: f.api(), repository, branch: "main" }); - expect(month(f.remote, "2026-07/run.json").map(r => [r.run.id, r.collectedAt])).toEqual([[1, at(120)], [2, at(120)]]); - expect(month(f.remote, "2026-08/run.json").map(r => r.run.id), "MONTH_PARTITION").toEqual([9]); + expect(month(f.remote, "2026-07/run/12.json").map(r => [r.run.id, r.collectedAt])).toEqual([[1, at(120)], [2, at(120)]]); + expect(month(f.remote, "2026-08/run/01.json").map(r => r.run.id), "MONTH_PARTITION").toEqual([9]); expect(month(f.remote, "2026-07/pull.json").map(r => r.changedFiles)).toEqual([3]); expect(month(f.remote, "2026-07/event.json").map(r => r.id)).toEqual(["w1"]); const manifests = month(f.remote, "2026-07/collection.json"); @@ -131,7 +133,7 @@ test("a record that fails the leakage screen or carries an unknown version is re const published = git(f.remote, "log", "-p", ref); expect(published.toLowerCase(), "NOTHING_PERSONAL_PUBLISHED").not.toContain(personal); expect(month(f.remote, "2026-07/pull.json").map(p => p.number)).toEqual([42]); - expect(month(f.remote, "2026-07/run.json").map(r => r.run.id)).toEqual([1, 2]); + expect(month(f.remote, "2026-07/run/12.json").map(r => r.run.id)).toEqual([1, 2]); expect(month(f.remote, "2026-07/source.json")[0]).toMatchObject({ artifact: 1, refused: 2 }); }); @@ -263,3 +265,70 @@ test("only the archive job holds write authority, and only for contents", () => expect(problem(workflow.replace("mkdir -p tmp", "bun install --frozen-lockfile\n mkdir -p tmp"))) .toContain("ci-evidence-archive.yml: archive scripts must not interpolate events or install dependencies"); }); + +test("daily placement uses run creation UTC date across boundaries and late arrivals", async () => { + const f = setup(), store = new GitArchiveStore(f.clone("one")); + const dates = ["2026-07-12T23:59:59Z", "2026-07-13T00:00:00Z", "2026-08-01T00:30:00+01:00", "2026-08-01T00:00:00Z"]; + const records = dates.map((createdAt, i) => { + const row = run(i + 10, "push", 0, 200); + row.run.createdAt = createdAt; + return { kind: "run" as const, row }; + }); + const batch = { records, refused: [], sources: [] }; + const first = await publishBatch(store, repository, batch); + expect(first.files, "UTC_DAY_PARTITIONS").toEqual(["2026-07/run/12.json", "2026-07/run/13.json", "2026-07/run/31.json", "2026-08/run/01.json"]); + expect((await publishBatch(store, repository, { ...batch, records: [...records].reverse() })).committed).toBe(false); + expect(() => parseMonthFile("2026-07/run/13.json", JSON.stringify([records[0]!.row]), repository)).toThrow("outside its day partition"); +}); + +test("mixed layouts preserve legacy blobs and both reports count attempts once", async () => { + const f = setup(), one = f.clone("one"), store = new GitArchiveStore(one); + const legacy = new MonthFile("run"); legacy.add(run(1, "push", 4, 120)); legacy.add(run(2, "push", 5, 60)); + const text = legacy.serialize(); + await store.commit(null, new Map([["2026-07/run.json", text]]), "legacy runs"); + await publishBatch(store, repository, { records: [{ kind: "run", row: run(1, "push", 4, 60) }], refused: [], sources: [] }); + expect(git(f.remote, "show", `${ref}:2026-07/run.json`) + "\n", "LEGACY_UNCHANGED").toBe(text); + const loaded = await readArchive(store, repository); + expect(loaded.rows.run.map(r => [r.run.id, r.collectedAt]), "MIXED_LAYOUT_JOIN").toEqual([[1, at(120)], [2, at(60)]]); + const inputs = await archiveInputs("origin", repository, undefined, undefined, one); + expect(inputs.snapshots).toEqual(loaded.rows.run); + const options = { cadence: "daily" as const, until: "2026-07-13T00:00:00Z", now: "2026-07-13T00:00:00Z" }; + const mixed = evidenceReport(inputs, options); + const single = evidenceReport({ ...inputs, snapshots: [run(1, "push", 4, 120), run(2, "push", 5, 60)] }, options); + expect(mixed).toEqual(single); + expect(mixed.activity.find(d => d.day === "2026-07-12")?.observedRunAttempts).toBe(2); + const again = await publishBatch(store, repository, { records: [{ kind: "run", row: run(1, "push", 4, 60) }], refused: [], sources: [] }); + expect(again.committed).toBe(false); +}); + +test("daily output allows exactly 95 MiB and refuses one byte over before committing any file", async () => { + let commits = 0; + const store = { read: async () => null, files: async () => new Map(), commit: async () => { commits++; return sha; } } as unknown as GitArchiveStore; + const row = { ...run(1, "push", 0, 60), padding: "" }; + const file = new MonthFile("run"); file.add(row); + row.padding = "x".repeat(MAX_FILE_BYTES - Buffer.byteLength(file.serialize())); + const batch = { records: [{ kind: "run" as const, row }, { kind: "pull" as const, row: pull(60) }], refused: [], sources: [] }; + expect((await publishBatch(store, repository, batch)).committed, "AT_CAP_ALLOWED").toBe(true); + row.padding += "x"; + await expect(publishBatch(store, repository, batch)).rejects.toThrow("2026-07/run/12.json would exceed"); + expect(commits, "OVER_CAP_NO_PUBLICATION").toBe(1); +}); + +test("mixed layout joins are order independent and conflicting identities refuse", async () => { + const f = setup(), store = new GitArchiveStore(f.clone("one")); + const older = run(1, "push", 0, 60), newer = run(1, "push", 0, 120); + const monthly = new MonthFile("run"), daily = new MonthFile("run"); monthly.add(older); daily.add(newer); + await store.commit(null, new Map([["2026-07/run.json", monthly.serialize()], ["2026-07/run/12.json", daily.serialize()]]), "mixed layouts"); + const forward = await readArchive(store, repository); + const files = store.files.bind(store); + store.files = async oid => new Map([...(await files(oid))].reverse()); + expect((await readArchive(store, repository)).rows, "READER_ORDER_INDEPENDENT").toEqual(forward.rows); + const bad = { ...older, run: { ...older.run, head: "b".repeat(40) } }; + const refused = await publishBatch(store, repository, { records: [{ kind: "run", row: bad }], sources: [], refused: [] }); + expect(refused.refused, "LEGACY_CONFLICT_REFUSED").toEqual([{ kind: "run", key: "1/1", reason: "Conflicting archive identity" }]); + expect(refused.committed).toBe(false); + const head = await store.read(); + await store.commit(head, new Map([["2026-07/run/12.json", JSON.stringify([bad])]]), "conflicting identity"); + await expect(readArchive(store, repository)).rejects.toThrow("Conflicting archive identity"); + expect(() => parseMonthFile("2026-07/run/12.json", JSON.stringify([{ ...older, version: 9 }]), repository)).toThrow("Unknown run version 9"); +}); From 0b336f9b906c74c8b1e957b25f301935b294a4cc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 09:40:29 +0000 Subject: [PATCH 2/2] test(ci): type archived run fixtures as timing snapshots --- tests/ci-archive.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/ci-archive.test.ts b/tests/ci-archive.test.ts index a580b825d7..81a640ae36 100644 --- a/tests/ci-archive.test.ts +++ b/tests/ci-archive.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { MAX_FILE_BYTES, publishBatch, readArchive, compactArtifacts, GitArchiveStore, MonthFile, parseMonthFile, type ArchiveAPI } from "../scripts/ci-archive"; -import { archiveInputs } from "../scripts/ci-timings"; +import { archiveInputs, type TimingSnapshot } from "../scripts/ci-timings"; import { evidenceReport } from "../scripts/ci-evidence-report"; import { archiveWorkflowProblems } from "../scripts/check-ci-workflows"; @@ -19,7 +19,7 @@ function git(root: string, ...args: string[]) { return new TextDecoder().decode(p.stdout).trim(); } -function run(id: number, event: "pull_request" | "push", start: number, collected: number) { +function run(id: number, event: "pull_request" | "push", start: number, collected: number): TimingSnapshot { return { version: 1, repository, collectedAt: at(collected), run: { id, attempt: 1, workflow: "CI", path: ".github/workflows/ci.yml", event, head: event === "push" ? merge : sha, prs: [42], attribution: "run payload", createdAt: at(start), startedAt: at(start), status: "completed", conclusion: "success" }, jobs: [{ id: id * 10, name: "proof", category: "proof", conclusion: "success", labels: [], execution: "observed", @@ -291,7 +291,7 @@ test("mixed layouts preserve legacy blobs and both reports count attempts once", const loaded = await readArchive(store, repository); expect(loaded.rows.run.map(r => [r.run.id, r.collectedAt]), "MIXED_LAYOUT_JOIN").toEqual([[1, at(120)], [2, at(60)]]); const inputs = await archiveInputs("origin", repository, undefined, undefined, one); - expect(inputs.snapshots).toEqual(loaded.rows.run); + expect(loaded.rows.run).toEqual(inputs.snapshots); const options = { cadence: "daily" as const, until: "2026-07-13T00:00:00Z", now: "2026-07-13T00:00:00Z" }; const mixed = evidenceReport(inputs, options); const single = evidenceReport({ ...inputs, snapshots: [run(1, "push", 4, 120), run(2, "push", 5, 60)] }, options);