Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci-evidence-archive.yml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
22 changes: 22 additions & 0 deletions docs/decisions/ci-evidence.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<kind>.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.
10 changes: 6 additions & 4 deletions docs/process/ci-evidence.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<record-kind>.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/<record-kind>.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 |
Expand Down
14 changes: 9 additions & 5 deletions docs/process/ci-timings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/<kind>.json`, partitioned by UTC month, one record per line in
`YYYY-MM/run/DD.json` for runs (UTC `run.createdAt` day) and
`YYYY-MM/<kind>.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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -431,7 +435,7 @@ containing only work, wait and preemption events.
The publisher appends immutable `events/<id>.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.
Expand Down
59 changes: 48 additions & 11 deletions scripts/ci-archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const ARCHIVE_VERSIONS: Record<ArchiveKind, readonly number[]> = {
/** 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<string, any>;
export interface Refusal { kind: string; key: string; reason: string }
Expand Down Expand Up @@ -59,6 +59,9 @@ const SPECS: Record<ArchiveKind, { at(r: Row): unknown; key(r: Row): string; lis
"red-main": { at: r => 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. */
Expand Down Expand Up @@ -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<string, Row>();
constructor(readonly kind: ArchiveKind) {}
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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.
Expand All @@ -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<string, MonthFile>();
const months = new Map<string, MonthFile>(), original = new Map<string, string>();
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);
Expand All @@ -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<string, string>();
Expand Down Expand Up @@ -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 };
}
1 change: 1 addition & 0 deletions scripts/ci-evidence-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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") });
Expand Down
3 changes: 2 additions & 1 deletion scripts/ci-timings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReportInputs & { head: string | null }> {
Expand Down
Loading
Loading