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
6 changes: 5 additions & 1 deletion docs/process/ci-throughput.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,11 @@ bun scripts/ci-timings.ts record --event tmp/work-event.json --out tmp/ci-timing
```

The command supplies version, UUID, current timestamp and repository. Explicit
ID/time permit attributed historical observations. IDs cannot be overwritten
ID/time permit attributed historical observations. Optional `orchestrator` IDs
use the same opaque syntax as worker/task IDs. `preempted` records a preemption
without claiming a pass or failure; it requires worker/task IDs. Explicit
[publication](ci-timings.md#publish-local-coordination-events) appends these
local events to the durable measurement ref. IDs cannot be overwritten
with different content. Pairs are `work-started`/`work-finished` and
`wait-started`/`wait-finished`; waits require `reason` set to `reservation`,
`ci`, `review`, `conflict` or `other`. Each pair shares worker/task/reason.
Expand Down
47 changes: 47 additions & 0 deletions docs/process/ci-timings.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,50 @@ runner and runtime inputs, retaining the existing proof assertions and gates.
See [testing](testing.md#required-proof-for-a-pr),
[proof-domain reconciliation](proof-domains.md#resource-and-scheduling-reconciliation)
and [the CI measurement policy](../decisions/ci-utility.md#measuring-the-critical-path).

## Publish local coordination events

From a trusted repository checkout with Git push access to `origin`, publish
locally recorded work, wait and preemption events explicitly:

```sh
bun scripts/ci-timings.ts publish --repo odysseus/chronicle --out tmp/ci-events
```

Use the repository's own `owner/name` in place of the example. This internal
measurement script prints JSON with `added`, `existing` and `head`; it is not
the supported `brain --json` contract. Collection and report modes remain
read-only. Publication grants no proof, selection or merge authority.

The input directory holds `event-<id>.json` files from `record`. Each event
uses schema version 1, an immutable ID, repository and UTC ISO timestamp.
Allowed kinds are `work-started`, `work-finished`, `wait-started`,
`wait-finished` and `preempted`. Worker/task IDs are required; `orchestrator`
is optional. IDs contain only ASCII letters, digits, underscores and hyphens,
up to 100 characters. Use opaque generated identifiers, never people's names
or machine identifiers. Optional `pr` is a positive integer; optional `reason`
is `reservation`, `ci`, `review`, `conflict` or `other` and is required for wait
boundaries. Preemption remains neither pass nor failure. Event emission is the
orchestrator's responsibility; this command does not read the host ledger.

Each invocation accepts at most 100 events, 8 KiB per file and 256 KiB total.
For a larger backlog, select smaller input directories while retaining each
original event's ID and bytes. Non-event files are ignored; selected symlinks,
unknown versions, arbitrary fields, hostname/path-like IDs and personal-string
leakage are refused before contacting the remote. Incident/classification
annotations are outside this publisher's local-event schema: select a directory
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
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.

Every commit is parented by the inspected remote head and pushed with exact
`--force-with-lease`. A competing update causes a fresh read and merge, up to
five attempts. Persistent contention or access failure exits nonzero, retaining
all local inputs for a retry. Errors appear on stderr; preserve that diagnostic
with the command exit status. No input is deleted, including after success.
107 changes: 107 additions & 0 deletions scripts/ci-event-publish.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/** Publish local coordination evidence; never an input to integration policy. */
import { mkdtemp, readdir, lstat, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { scanText } from "./check-leakage";
import { validateWorkEvent, type WorkEvent } from "./ci-throughput";

export const EVENT_REF = "refs/heads/brain-ci-metrics";
const MAX_EVENTS = 100, MAX_BYTES = 256 * 1024, MAX_EVENT_BYTES = 8192;
const opaque = (value: unknown) => typeof value === "string" && /^[a-zA-Z0-9_-]{1,100}$/.test(value);

/** Strict local-event schema plus the same personal-string screen as the tree. */
export function screenPublishedEvent(value: unknown, repository: string): WorkEvent {
const e = validateWorkEvent(value);
if (e.repository !== repository) throw new Error("Event repository differs from --repo");
if (!["work-started", "work-finished", "wait-started", "wait-finished", "preempted"].includes(e.kind) ||
Object.keys(e).some(k => !["version", "id", "repository", "kind", "at", "worker", "task", "orchestrator", "reason", "pr"].includes(k)) ||
![e.id, e.worker, e.task].every(opaque) || (e.orchestrator !== undefined && !opaque(e.orchestrator)) ||
(e.reason !== undefined && !["reservation", "ci", "review", "conflict", "other"].includes(e.reason)) ||
!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(e.at)) throw new Error("Unsafe local event fields");
if (scanText("event", JSON.stringify(e)).length) throw new Error("Event refused by leakage screen");
return e;
}

/** Git plumbing uses an isolated index; the caller's files and index never move. */
export class GitEventStore {
constructor(readonly root: string, readonly remote = "origin") {}
async git(args: string[], input?: string, index?: string): Promise<string> {
const p = Bun.spawn(["git", ...args], { cwd: this.root, stdout: "pipe", stderr: "pipe",
stdin: input === undefined ? "ignore" : new TextEncoder().encode(input), env: { ...process.env,
...(index ? { GIT_INDEX_FILE: index } : {}),
GIT_AUTHOR_NAME: "brain-kit metrics", GIT_AUTHOR_EMAIL: "metrics@example.invalid",
GIT_COMMITTER_NAME: "brain-kit metrics", GIT_COMMITTER_EMAIL: "metrics@example.invalid" } });
const [code, out, err] = await Promise.all([p.exited, new Response(p.stdout).text(), new Response(p.stderr).text()]);
// Git's raw stderr may include a private remote URL or filesystem path.
if (code !== 0) throw new Error(`Event archive git ${args[0]} failed (${code}); check remote access`);
void err;
return out.trim();
}
async remoteOid(): Promise<string | null> {
const output = await this.git(["ls-remote", "--refs", this.remote, EVENT_REF]);
if (!output) return null;
const [oid, ref, ...extra] = output.split(/\s+/);
if (!/^[a-f0-9]{40}$/.test(oid!) || ref !== EVENT_REF || extra.length) throw new Error("Invalid event archive ref");
return oid!;
}
async read(): Promise<string | null> {
const oid = await this.remoteOid();
if (oid) await this.git(["fetch", "--no-tags", this.remote, oid]);
return oid;
}
async publish(parent: string | null, events: WorkEvent[], repository: string): Promise<{ head: string; added: number } | null> {
const pending: WorkEvent[] = [];
for (const event of events) {
const path = `events/${event.id}.json`;
const entry = parent ? await this.git(["ls-tree", parent, "--", path]) : "";
if (entry) {
if (!/^100644 blob [a-f0-9]{40}\t/.test(entry)) throw new Error("Invalid archived event entry");
const previous = screenPublishedEvent(JSON.parse(await this.git(["show", `${parent}:${path}`])), repository);
if (JSON.stringify(previous) !== JSON.stringify(event)) throw new Error("Event ID already exists with different content");
} else pending.push(event);
}
if (!pending.length && parent) return { head: parent, added: 0 };
const temporary = await mkdtemp(join(tmpdir(), "brain-event-index-")), index = join(temporary, "index");
try {
await this.git(["read-tree", ...(parent ? [parent] : ["--empty"])], undefined, index);
for (const event of pending) {
const blob = await this.git(["hash-object", "-w", "--stdin"], JSON.stringify(event) + "\n");
await this.git(["update-index", "--add", "--cacheinfo", `100644,${blob},events/${event.id}.json`], undefined, index);
}
const tree = await this.git(["write-tree"], undefined, index);
const head = await this.git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", "ci: append coordination events"]);
try {
await this.git(["push", "--porcelain", `--force-with-lease=${EVENT_REF}:${parent ?? ""}`, this.remote, `${head}:${EVENT_REF}`]);
return { head, added: pending.length };
} catch (error) {
if (await this.remoteOid() !== parent) return null;
throw error;
}
} finally { await rm(temporary, { recursive: true, force: true }); }
}
}

export async function publishEvents(options: { root: string; dir: string; repository: string; store?: GitEventStore }): Promise<{ added: number; existing: number; head: string | null }> {
const { root, dir, repository } = options;
if (!/^[\w-]+\/[\w-]+$/.test(repository)) throw new Error("Invalid publication repository");
const names = (await readdir(dir)).filter(name => /^event-[\w-]+\.json$/.test(name)).sort();
if (names.length > MAX_EVENTS) throw new Error(`Event batch exceeds ${MAX_EVENTS}; select a smaller input directory`);
const events: WorkEvent[] = [], ids = new Set<string>(); let bytes = 0;
for (const name of names) {
const path = join(dir, name), stat = await lstat(path);
bytes += stat.size;
if (!stat.isFile() || stat.size > MAX_EVENT_BYTES || bytes > MAX_BYTES) throw new Error("Event batch exceeds size bounds or contains a non-file");
const event = screenPublishedEvent(JSON.parse(await readFile(path, "utf8")), repository);
if (ids.has(event.id)) throw new Error("Duplicate event ID in batch");
ids.add(event.id); events.push(event);
}
if (!events.length) return { added: 0, existing: 0, head: null };
// All local input is screened before any network operation. A lost CAS is
// retried against the new tree, preserving unrelated archive/compaction work.
const store = options.store ?? new GitEventStore(root);
for (let attempt = 0; attempt < 5; attempt++) {
const parent = await store.read(), result = await store.publish(parent, events, repository);
if (result) return { ...result, existing: events.length - result.added };
}
throw new Error("Event publication contention exceeded five attempts; local events retained, retry publish");
}
11 changes: 6 additions & 5 deletions scripts/ci-throughput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export interface PullObservation {
mergeObject?: { sha: string; tree: string; parents: string[] };
}
export interface WorkEvent {
version: 1; id: string; repository: string; kind: "work-started" | "work-finished" | "wait-started" | "wait-finished" | "failure-classified" | "incident" | "revert" | "expedited-fix";
at: string; worker?: string; task?: string; reason?: "reservation" | "ci" | "review" | "conflict" | "other";
version: 1; id: string; repository: string; kind: "work-started" | "work-finished" | "wait-started" | "wait-finished" | "preempted" | "failure-classified" | "incident" | "revert" | "expedited-fix";
at: string; worker?: string; task?: string; orchestrator?: string; reason?: "reservation" | "ci" | "review" | "conflict" | "other";
pr?: number; run?: number; attempt?: number; job?: number; relatedPR?: number;
classification?: "product" | "test" | "infrastructure" | "stale-candidate" | "intentional-feedback";
evidence?: string;
Expand All @@ -38,12 +38,13 @@ function green(s: TimingSnapshot): boolean {
/** Only public operational references and opaque coordination IDs are retained. */
export function validateWorkEvent(value: unknown): WorkEvent {
const e = value as WorkEvent;
const allowed = new Set(["version", "id", "repository", "kind", "at", "worker", "task", "reason", "pr", "run", "attempt", "job", "relatedPR", "classification", "evidence"]);
const allowed = new Set(["version", "id", "repository", "kind", "at", "worker", "task", "orchestrator", "reason", "pr", "run", "attempt", "job", "relatedPR", "classification", "evidence"]);
if (!e || typeof e !== "object" || Object.keys(e).some(k => !allowed.has(k)) || e.version !== 1 ||
typeof e.id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(e.id) || !/^[\w.-]+\/[\w.-]+$/.test(e.repository) || !stamp(e.at) ||
!["work-started", "work-finished", "wait-started", "wait-finished", "failure-classified", "incident", "revert", "expedited-fix"].includes(e.kind)) throw new Error("Invalid coordination event");
!["work-started", "work-finished", "wait-started", "wait-finished", "preempted", "failure-classified", "incident", "revert", "expedited-fix"].includes(e.kind)) throw new Error("Invalid coordination event");
if (e.orchestrator !== undefined && (typeof e.orchestrator !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(e.orchestrator))) throw new Error("Opaque orchestrator ID required");
for (const field of ["pr", "run", "attempt", "job", "relatedPR"] as const) if (e[field] !== undefined && !number(e[field])) throw new Error(`Invalid event ${field}`);
if (/^(work|wait)-/.test(e.kind)) {
if (/^(work|wait)-/.test(e.kind) || e.kind === "preempted") {
if (![e.worker, e.task].every(x => typeof x === "string" && /^[a-zA-Z0-9_-]{1,100}$/.test(x))) throw new Error("Opaque worker/task IDs required");
if (e.kind.startsWith("wait-") && !["reservation", "ci", "review", "conflict", "other"].includes(e.reason ?? "")) throw new Error("Wait reason required");
} else {
Expand Down
10 changes: 7 additions & 3 deletions scripts/ci-timings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/** Read-only CI timing archive. Logs are data; no candidate code is executed. */
/** CI timing collection and explicit local-event publication. Logs are data; no candidate code is executed. */
import { publishEvents } from "./ci-event-publish";
import { mkdir, readdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { percentage, seconds, stats } from "./ci-timing-stats";
Expand Down Expand Up @@ -555,6 +556,7 @@ if (import.meta.main) {
if (!["--repo", "--since", "--until", "--run", "--out", "--event", "--scenario", "--seed", "--request-budget", "--reserve", "--history"].includes(flag) || !args.length || options.has(flag)) throw new Error("Invalid timing option");
options.set(flag, args.shift()!);
}
if (mode === "publish" && (resources || reservations || redMain || [...options.keys()].some(flag => !["--repo", "--out"].includes(flag)))) throw new Error("Publish accepts only --repo and --out");
const dir = resolve(options.get("--out") ?? "tmp/ci-timings");
// Proof-policy epochs read this ref's first-parent history from the local checkout.
const history = options.get("--history") ?? "origin/main";
Expand All @@ -580,7 +582,9 @@ if (import.meta.main) {
}
if (options.has("--scenario")) await Bun.write(join(dir, "scenario.json"), JSON.stringify(await Bun.file(options.get("--scenario")!).json(), null, 2));
if (options.has("--since") && options.has("--until")) await Bun.write(join(dir, "analysis-window.json"), JSON.stringify({ since: options.get("--since"), until: options.get("--until"), source: "explicit analysis interval" }));
if (mode === "record") {
if (mode === "publish") {
console.log(JSON.stringify(await publishEvents({ root: process.cwd(), dir, repository })));
} else if (mode === "record") {
if (!options.has("--event")) throw new Error("Record requires --event JSON-file");
const input = await Bun.file(options.get("--event")!).json();
if (input.repository && input.repository !== repository) throw new Error("Event repository differs from --repo");
Expand Down Expand Up @@ -697,6 +701,6 @@ if (import.meta.main) {
if (errors.some(e => !budgetProblem(e.error)) || enrichmentErrors.some(e => !budgetProblem(e.problem)) ||
(await readSnapshots(dir)).some(s => s.problems.some(p => !budgetProblem(p))) ||
!api.budget.stopped && report.collectionCoverage.missingAttempts.length) process.exitCode = 1;
} else throw new Error("usage: bun scripts/ci-timings.ts collect|enrich|report|record [--since ISO --until ISO] [--run ID] [--resources] [--seed DEFAULT_BRANCH] [--request-budget N --reserve N] [--reservations] [--red-main] [--event JSON] [--scenario JSON] [--history REF] [--repo owner/repo] [--out DIR]");
} else throw new Error("usage: bun scripts/ci-timings.ts collect|enrich|report|record|publish [--since ISO --until ISO] [--run ID] [--resources] [--seed DEFAULT_BRANCH] [--request-budget N --reserve N] [--reservations] [--red-main] [--event JSON] [--scenario JSON] [--history REF] [--repo owner/repo] [--out DIR]");
} catch (error) { console.error(error); process.exitCode = 1; }
}
Loading
Loading