Public: anyone can read this; the crew can change it.

One green result per commit: a check on a commit already proven green is skipped, and a land does not re-run fast on a moved base #1835

Closed opened this in answer to
Closed without merging

mason/forge:mason/1795-one-green-result-per-commit-a-check-on-a → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +266 −34
README.md +1 −1
@@ -874,7 +874,7 @@ Invariants are proven by faults, not by hope. No dependencies were added.
874874
875875 `forge.json`'s `check` may declare `fast` beside `run` (the full gate; `full` names it explicitly). `bun scripts/test-shards.ts --tier fast --diff <base>..<head>` runs the tests that touch the diff (changed, named for a changed source file, or importing one within two hops), every test the times table records under 1 s, and any named by `--learned a,b`. `src/checks/tiers.ts` decides; it adds no dependency.
876876
877 In the forge itself: a pull's check runs `fast` when the manifest has one, in a clone holding the fork point and the head as `FORGE_CHECK_BASE` and `HEAD` (`origin/main` is not a ref there), with `FORGE_CHECK_LEARNED` naming tests earlier land attempts taught the pull (`src/checks/history.ts`, `learned.ts`). Landing (`landIfGreen`) runs `full` once on the merge with its base before merging (`src/checks/landing.ts`); red comments on the pull with the tests named, is remembered per head and base, and the files ride the pull's next fast run. The pull page's checks line shows the tier words.
877 In the forge itself: a pull's check runs `fast` when the manifest has one, in a clone holding the fork point and the head as `FORGE_CHECK_BASE` and `HEAD` (`origin/main` is not a ref there), with `FORGE_CHECK_LEARNED` naming tests earlier land attempts taught the pull (`src/checks/history.ts`, `learned.ts`). Landing (`landIfGreen`) runs `full` once on the merge with its base before merging (`src/checks/landing.ts`); red comments on the pull with the tests named, is remembered per head and base, and the files ride the pull's next fast run. The pull page's checks line shows the tier words. A check is keyed by its tree, its gate (command, install, timeout, egress, limits) and, for the fast tier, its base and learned tests (`src/checks/proven.ts`); a key already proven green is not run again — asking again at a green head answers with that run, a second gate on the same commit and the push of the landed commit to main pass as `already proven green by …`. Only green is kept; a red is always asked again.
878878
879879 ## Limits
880880
src/checks/proven.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * One green result per commit (#1795): a check is keyed by what decides its
3 * verdict — the tree it runs on, the gate it runs, and for the fast tier the
4 * base it diffs against and the tests it has learned — and a key already
5 * proven green is not run again. The full gate on land and the push of the
6 * landed commit to the base share a key whenever they share a tree, so the
7 * landed commit is gated once.
8 *
9 * Only green is kept: a red may be the environment's, and is asked again.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { createHash } from "node:crypto";
14 import type { CheckManifest } from "../apps/manifest.ts";
15 import { runGit } from "../git/env.ts";
16 import { isSafeOid } from "../git/guard.ts";
17
18 export interface CheckKeyInput {
19 /** The tree the check runs on: the commit's, or the merge's for a pull. */
20 readonly tree: string;
21 /** The command the tier runs, from the gate's manifest. */
22 readonly command: string;
23 readonly manifest: Pick<CheckManifest, "install" | "timeout" | "egress" | "limits">;
24 /** The fast tier's diff base; absent for the whole check. */
25 readonly base?: string | undefined;
26 /** The fast tier's learned tests (`learned.ts`). */
27 readonly learned?: readonly string[] | undefined;
28 }
29
30 /** Plain data in, a hex digest out: equal inputs, equal keys. */
31 export function checkKey(input: CheckKeyInput): string {
32 const { manifest } = input;
33 return createHash("sha256")
34 .update(
35 JSON.stringify([
36 input.tree,
37 input.command,
38 manifest.install,
39 manifest.timeout,
40 [...manifest.egress],
41 manifest.limits,
42 input.base ?? "",
43 [...(input.learned ?? [])],
44 ]),
45 )
46 .digest("hex");
47 }
48
49 /** The tree a commit names, or `undefined` when it names none. */
50 export async function treeOf(dir: string, commit: string): Promise<string | undefined> {
51 if (!isSafeOid(commit)) return undefined;
52 const result = await runGit(["rev-parse", "--verify", `${commit}^{tree}`], { cwd: dir });
53 return result.ok ? result.value.trim() : undefined;
54 }
55
56 /** What proved this key green: a run's id, or `gate-…` for a full gate on land. */
57 export function provenBy(db: Database, key: string): string | undefined {
58 return (
59 db
60 .query<{ proven_by: string }, [string]>(
61 "SELECT proven_by FROM check_proven WHERE key = ?1",
62 )
63 .get(key)?.proven_by ?? undefined
64 );
65 }
66
67 /** Remember a green verdict; the first to prove a key keeps it. */
68 export function recordProven(db: Database, key: string, by: string): void {
69 db.query(
70 "INSERT INTO check_proven (key, proven_by) VALUES (?1, ?2) ON CONFLICT (key) DO NOTHING",
71 ).run(key, by);
72 }
src/checks/service.ts +108 −29
@@ -28,6 +28,7 @@ import {
2828 claimRun,
2929 createRun,
3030 finishRun,
31 getRun,
3132 listActive,
3233 noteRunProgress,
3334 overranBefore,
@@ -41,6 +42,7 @@ import { resolveOid } from "../git/merge.ts";
4142 import { mergeForCheck } from "./merged.ts";
4243 import { giveHistory } from "./history.ts";
4344 import { readLearned } from "./learned.ts";
45 import { checkKey, provenBy, recordProven, treeOf } from "./proven.ts";
4446 import { getIssueById } from "../core/issues.ts";
4547 import { repoDir } from "../git/repos.ts";
4648 import { BUDGETS, budgetSummary } from "../kernel/budgets.ts";
@@ -49,7 +51,7 @@ import { createLog } from "../kernel/log.ts";
4951 import { holdLease } from "../runs/lease.ts";
5052 import { appendRunLog } from "../runs/log.ts";
5153 import { exportTree, readFileAt } from "../apps/checkout.ts";
52 import { parseCheck } from "../apps/manifest.ts";
54 import { parseCheck, type CheckManifest } from "../apps/manifest.ts";
5355 import { accountActive } from "../core/accounts.ts";
5456 import { childEnv, runStep } from "../apps/process.ts";
5557 import { noteReached } from "../apps/egress_report.ts";
@@ -221,6 +223,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
221223 ]);
222224 const declared = parseCheck(forgeJson, packageJson);
223225 if (declared.ok && declared.value === undefined) return undefined;
226 // Asked again of a head this environment already proved green, on the
227 // same base and the same gate: the answer is that green run (#1795).
228 const again = await provenHere(bare, repo, env, commitOid, issueId);
229 if (again !== undefined) return again;
224230 // One check per environment at a time: a newer commit supersedes what
225231 // is still waiting, and the same commit is not checked twice. Looked for
226232 // and written in one write transaction, so a second forge process over
@@ -254,6 +260,39 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
254260 return run;
255261 }
256262
263 /** The green run of this environment at this commit whose key still holds, if any. */
264 async function provenHere(
265 bare: string,
266 repo: Repo,
267 env: string,
268 commitOid: string,
269 issueId: string | undefined,
270 ): Promise<Run | undefined> {
271 const pull = pullOf(repo, issueId ?? null);
272 const prepared = await prepare({
273 bare,
274 commitOid,
275 pull,
276 tier: pull === undefined ? "run" : "fast",
277 });
278 if (!prepared.ok) return undefined;
279 const by = provenBy(app.db, prepared.value.key);
280 const run = by === undefined ? undefined : getRun(app.db, by);
281 return run !== undefined &&
282 run.state === "ok" &&
283 run.repoId === repo.id &&
284 run.env === env &&
285 run.commitOid === commitOid
286 ? run
287 : undefined;
288 }
289
290 /** The pull a run's issue is, when it is one. */
291 function pullOf(repo: Repo, issueId: string | null): Pull | undefined {
292 const issue = issueId === null ? undefined : getIssueById(app.db, issueId);
293 return issue?.kind === "pull" ? getPull(app.db, repo.id, issue.number) : undefined;
294 }
295
257296 /** Run a queued check here, whichever forge queued it. */
258297 function start(run: Run, repo: Repo): void {
259298 if (inFlight.has(run.id)) return;
@@ -410,16 +449,19 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
410449 return;
411450 }
412451 const seconds = Math.round((Date.now() - started) / 1000);
452 const passed = !outcome.ok
453 ? ""
454 : outcome.provenBy === undefined
455 ? `passed in ${seconds}s`
456 : `passed: already proven green by ${outcome.provenBy}`;
413457 const done = finishRun(app.db, run.id, {
414458 state: outcome.ok ? "ok" : "failed",
415 summary: outcome.ok
416 ? `check passed in ${seconds}s`
417 : `check failed: ${outcome.error}`,
459 summary: outcome.ok ? `check ${passed}` : `check failed: ${outcome.error}`,
418460 ...(outcome.ok || outcome.detail === undefined
419461 ? {}
420462 : { checkDetail: outcome.detail }),
421463 });
422 write(outcome.ok ? `passed in ${seconds}s` : `failed: ${outcome.error}`);
464 write(outcome.ok ? passed : `failed: ${outcome.error}`);
423465 if (done) announceRun(app, done);
424466 } finally {
425467 release();
@@ -432,16 +474,13 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
432474 write: (line: string) => void,
433475 signal: AbortSignal,
434476 ): Promise<
435 | { ok: true }
477 | { ok: true; provenBy?: string | undefined }
436478 | { ok: false; error: string; detail?: CheckDetail | undefined }
437479 > {
438480 const bare = await runDir(app.db, app.reposRoot, repo, run.issueId);
439481 // A pull's check is the fast tier, judged against where the pull left
440482 // the base; anything else is the whole check (`apps/manifest.ts`).
441 const issue =
442 run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
443 const pull =
444 issue?.kind === "pull" ? getPull(app.db, repo.id, issue.number) : undefined;
483 const pull = pullOf(repo, run.issueId);
445484 const outcome = await runTier({
446485 bare,
447486 repo,
@@ -470,13 +509,25 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
470509 readonly signal: AbortSignal;
471510 }
472511
473 async function runTier(
474 x: Execution,
475 ): Promise<
476 | { ok: true }
477 | { ok: false; error: string; detail?: CheckDetail | undefined }
478 > {
479 const { bare, repo, write, signal } = x;
512 /** What a tier runs, resolved before anything is checked out. */
513 interface Prepared {
514 /** The commit checked out: the pull's merge with its base, or the commit. */
515 readonly source: string;
516 readonly mergeLine: string;
517 readonly gateLine: string;
518 readonly manifest: CheckManifest;
519 readonly command: string;
520 /** The fast tier's diff base. */
521 readonly base: string | undefined;
522 readonly learned: readonly string[];
523 /** `proven.ts`: equal keys, equal verdicts. */
524 readonly key: string;
525 }
526
527 async function prepare(
528 x: Pick<Execution, "bare" | "commitOid" | "pull" | "tier">,
529 ): Promise<{ ok: true; value: Prepared } | { ok: false; error: string }> {
530 const { bare } = x;
480531 // A pull's fast check is of the pull as it would land: its head merged
481532 // into the base's tip. The gate comes from that tree, so a pull forked
482533 // before the base learned something is judged with it.
@@ -492,10 +543,9 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
492543 source = merged.commit;
493544 mergeLine = merged.line;
494545 }
495 const run = { id: x.id, commitOid: source };
496546 const [forgeJson, packageJson] = await Promise.all([
497 readFileAt(bare, run.commitOid, "forge.json"),
498 readFileAt(bare, run.commitOid, "package.json"),
547 readFileAt(bare, source, "forge.json"),
548 readFileAt(bare, source, "package.json"),
499549 ]);
500550 const declared = parseCheck(forgeJson, packageJson);
501551 if (!declared.ok)
@@ -513,9 +563,9 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
513563 // branch's own supplies only what it needs to run (install, egress,
514564 // limits).
515565 let manifest = declared.value;
516 let baseTip: string | undefined;
566 let gateLine = "";
517567 if (x.pull !== undefined) {
518 baseTip = await resolveOid(bare, `refs/heads/${x.pull.baseBranch}`);
568 const baseTip = await resolveOid(bare, `refs/heads/${x.pull.baseBranch}`);
519569 if (baseTip === undefined)
520570 return { ok: false, error: "the pull's base branch could not be found" };
521571 const [baseJson, basePackage] = await Promise.all([
@@ -539,9 +589,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
539589 full: gate.value.full,
540590 timeout: gate.value.timeout,
541591 };
542 write(
543 `tier ${x.tier} from ${x.pull.baseBranch}@${baseTip.slice(0, 7)}`,
544 );
592 gateLine = `tier ${x.tier} from ${x.pull.baseBranch}@${baseTip.slice(0, 7)}`;
545593 }
546594 }
547595 const command =
@@ -554,6 +602,39 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
554602 // which the clone is given as a repository of its own: `origin/main` is
555603 // not a ref there.
556604 const base = manifest.fast !== null ? tip : undefined;
605 const learned =
606 base === undefined || x.pull === undefined
607 ? []
608 : readLearned(app.config.dataDir, x.pull.id);
609 const tree = await treeOf(bare, source);
610 if (tree === undefined)
611 return { ok: false, error: `the tree of ${source.slice(0, 7)} could not be read` };
612 const key = checkKey({ tree, command, manifest, base, learned });
613 return {
614 ok: true,
615 value: { source, mergeLine, gateLine, manifest, command, base, learned, key },
616 };
617 }
618
619 async function runTier(
620 x: Execution,
621 ): Promise<
622 | { ok: true; provenBy?: string | undefined }
623 | { ok: false; error: string; detail?: CheckDetail | undefined }
624 > {
625 const { bare, repo, write, signal } = x;
626 const prepared = await prepare(x);
627 if (!prepared.ok) return prepared;
628 const { source, mergeLine, gateLine, manifest, command, base, learned, key } =
629 prepared.value;
630 if (gateLine !== "") write(gateLine);
631 // Already green on this tree, this gate and this base: nothing to run.
632 const proven = provenBy(app.db, key);
633 if (proven !== undefined) {
634 write(`already proven green by ${proven}`);
635 return { ok: true, provenBy: proven };
636 }
637 const run = { id: x.id, commitOid: source };
557638 const dir = join(checksRoot(app.config.dataDir), run.id);
558639 mkdirSync(dir, { recursive: true });
559640 write(mergeLine === "" ? `checking out ${run.commitOid.slice(0, 7)}` : mergeLine);
@@ -603,10 +684,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
603684 ? {}
604685 : {
605686 FORGE_CHECK_BASE: base,
606 FORGE_CHECK_LEARNED: readLearned(
607 app.config.dataDir,
608 x.pull!.id,
609 ).join(","),
687 FORGE_CHECK_LEARNED: learned.join(","),
610688 }),
611689 // A cell inside a cell is not a cell. This check's own cell is the
612690 // boundary; a forge the tests boot inside it would wrap its apps in
@@ -651,6 +729,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
651729 );
652730 return { ok: false, error: summary, detail };
653731 }
732 recordProven(app.db, key, x.runId ?? x.id);
654733 return { ok: true };
655734 } finally {
656735 if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
src/core/schema.ts +10
@@ -1771,6 +1771,16 @@ export const migrations: readonly string[] = [
17711771 times INTEGER NOT NULL DEFAULT 1
17721772 );
17731773 `,
1774 // 88 — one green result per commit (#1795): a check's key (its tree, its
1775 // gate, its base) once proven green, and what proved it. An index over
1776 // runs already finished: losing it only costs a check run again.
1777 `
1778 CREATE TABLE check_proven (
1779 key TEXT PRIMARY KEY,
1780 proven_by TEXT NOT NULL,
1781 proven_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
1782 );
1783 `,
17741784 ];
17751785
17761786 /**
test/check-tiers.test.ts +71 −2
@@ -32,6 +32,10 @@ import {
3232 reach,
3333 } from "../src/checks/impact.ts";
3434 import { parseCheck } from "../src/apps/manifest.ts";
35 import { Database } from "bun:sqlite";
36 import { migrate } from "../src/kernel/migrate.ts";
37 import { migrations } from "../src/core/schema.ts";
38 import { checkKey, provenBy, recordProven } from "../src/checks/proven.ts";
3539
3640 const tests = [
3741 "test/snapshot-store.test.ts",
@@ -423,6 +427,14 @@ describe("the tiers in the forge's own checks service", () => {
423427 const green = await checks.gate(repo, pull, branched.value.commitOid);
424428 expect(green.ok).toBe(true);
425429 expect(green.lines.join("\n")).toContain("FULL-GREEN");
430
431 // The same commit gated again is answered by the first green, not run.
432 const again = await checks.gate(repo, pull, branched.value.commitOid);
433 expect(again.ok).toBe(true);
434 expect(again.lines.join("\n")).not.toContain("FULL-GREEN");
435 expect(again.lines.join("\n")).toContain(
436 `already proven green by gate-${branched.value.commitOid.slice(0, 12)}`,
437 );
426438 });
427439
428440 test("a red full gate names its tests and the pull learns the files", async () => {
@@ -636,13 +648,70 @@ describe("a pull's fast check is of the merge", () => {
636648 expect(clash.summary).toContain("does not merge into main: shared.txt");
637649 });
638650
639 test("a writer asks for a check again at the current head", async () => {
651 test("a writer asks for a check again at a red head and a new one runs", async () => {
640652 const pull = listPulls(app.db, repo.id, { state: "open", limit: 5 }).find(
641 (p) => p.headBranch === "late",
653 (p) => p.headBranch === "clash",
642654 )!;
643655 const asked = await askCheck(app, alice, repo, pull);
644656 if (!asked.ok) throw new Error(asked.message);
645657 expect(asked.run.reason).toBe("asked");
646658 expect(asked.run.commitOid).toBe(pull.headOid);
647659 });
660
661 test("asked again at a head proven green on the same base, the answer is that green run", async () => {
662 const pull = listPulls(app.db, repo.id, { state: "open", limit: 5 }).find(
663 (p) => p.headBranch === "late",
664 )!;
665 const green = await settled(pull.headOid);
666 expect(green.state).toBe("ok");
667 const asked = await askCheck(app, alice, repo, pull);
668 if (!asked.ok) throw new Error(asked.message);
669 expect(asked.run.id).toBe(green.id);
670 expect(asked.run.state).toBe("ok");
671 const runs = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).filter(
672 (r) => r.issueId === pull.id,
673 );
674 expect(runs.length).toBe(1);
675 });
676 });
677
678 const provenManifest = {
679 install: "",
680 timeout: 600,
681 egress: [] as string[],
682 limits: { memory: 1024, cpus: 1, disk: 1024 },
683 };
684 const provenInput = {
685 tree: "a".repeat(40),
686 command: "bun test",
687 manifest: provenManifest,
688 base: "b".repeat(40),
689 learned: ["test/x.test.ts"],
690 };
691
692 describe("a check's key (#1795)", () => {
693 test("equal inputs, equal keys", () => {
694 expect(checkKey(provenInput)).toBe(checkKey({ ...provenInput, manifest: { ...provenManifest } }));
695 });
696
697 test("the tree, the gate, the base and the learned tests each change it", () => {
698 const key = checkKey(provenInput);
699 expect(checkKey({ ...provenInput, tree: "c".repeat(40) })).not.toBe(key);
700 expect(checkKey({ ...provenInput, command: "bun test --bail" })).not.toBe(key);
701 expect(checkKey({ ...provenInput, manifest: { ...provenManifest, timeout: 601 } })).not.toBe(key);
702 expect(checkKey({ ...provenInput, base: "d".repeat(40) })).not.toBe(key);
703 expect(checkKey({ ...provenInput, learned: [] })).not.toBe(key);
704 expect(checkKey({ ...provenInput, base: undefined })).not.toBe(key);
705 });
706
707 test("a green verdict is kept by whoever proved it first", () => {
708 const db = new Database(":memory:");
709 migrate(db, migrations);
710 const key = checkKey(provenInput);
711 expect(provenBy(db, key)).toBeUndefined();
712 recordProven(db, key, "run-1");
713 recordProven(db, key, "run-2");
714 expect(provenBy(db, key)).toBe("run-1");
715 db.close();
716 });
648717 });
test/checks.test.ts +2 −1
@@ -544,7 +544,8 @@ describe("checks", () => {
544544 files: [
545545 {
546546 path: "forge.json",
547 content: checkJson("sleep 2 && test -f OK.md"),
547 // A gate never proven green before, so the lane is really held.
548 content: checkJson(`sleep 2 && test -f OK.md # ${ending}`),
548549 },
549550 ],
550551 });
test/pull-check-again.test.ts +2 −1
@@ -77,8 +77,9 @@ beforeAll(async () => {
7777 });
7878 if (!done.ok) throw new Error(JSON.stringify(done.error));
7979 };
80 // A red gate: a head proven green answers with that run, never a new one.
8081 await commit(undefined, [
81 { path: "forge.json", content: JSON.stringify({ check: { run: "echo ok" } }) },
82 { path: "forge.json", content: JSON.stringify({ check: { run: "exit 1" } }) },
8283 ]);
8384 for (const branch of ["open", "closed"]) {
8485 await commit(branch, [{ path: `${branch}.txt`, content: branch }]);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs