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

A forge revert is exempt from both doors and the test-with-change rule #16719

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

flow/revert-rules → main 0 commits 2 threads · 2 unresolved

  • Merged. flow/revert-rules was merged into main as 7eb9bda.

Review

Sign in to review this change.
6 files changed +259 −11
scripts/gate.ts +10 −2
@@ -822,12 +822,20 @@ export async function dupesNote(cwd: string = process.cwd()): Promise<string[]>
822822 return notes;
823823 }
824824
825 /**
outdated

This comment, "A pull that adds a page adds its terminal screen and how-to too", described bothDoorsRefusal. The new isForgeRevert block now sits between it and that function, so the old comment is stranded above an unrelated export and two doc blocks are stacked. Move this line back to directly above export async function bothDoorsRefusal.

826 * The pull is the forge's own revert of a landing (#6377), which the check proved line for line
827 * before it set `FORGE_CHECK_REVERTS` (`src/checks/revert_exact.ts`): it restores a tree that
828 * already passed "both doors" and "a test with the change", so those two stand down. Nothing else
829 * does, and the pull's own content cannot set it.
830 */
831 export const isForgeRevert = (): boolean => /^#\d+$/.test(process.env.FORGE_CHECK_REVERTS ?? "");
832
825833 /** A pull that adds a page adds its terminal screen and how-to too (#10628). */
826834 export async function bothDoorsRefusal(cwd: string = process.cwd()): Promise<string[]> {
827835 const { parseNameStatus } = await import("../src/kernel/pin_edits.ts");
828836 const { bothDoorsProblems } = await import("../src/kernel/both_doors.ts");
829837 const base = baseRef(cwd);
830 if (!base) return [];
838 if (!base || isForgeRevert()) return [];
831839 const diff = git(["diff", "--name-status", "-M", `${base}..${judgedHead(cwd)}`], cwd);
832840 const log = git(["log", "--format=%B%x00", `${base}..${judgedHead(cwd)}`], cwd);
833841 if (!diff.ok || !log.ok) return [];
@@ -844,7 +852,7 @@ export async function testsWithChangeRefusal(cwd: string = process.cwd()): Promi
844852 const { parseNameStatus } = await import("../src/kernel/pin_edits.ts");
845853 const { testsWithChangeProblems } = await import("../src/kernel/tests_with_change.ts");
846854 const base = baseRef(cwd);
847 if (!base) return [];
855 if (!base || isForgeRevert()) return [];
848856 const diff = git(["diff", "--name-status", "-M", `${base}..${judgedHead(cwd)}`], cwd);
849857 const log = git(["log", "--format=%B%x00", `${base}..${judgedHead(cwd)}`], cwd);
850858 if (!diff.ok || !log.ok) return [];
src/checks/revert_exact.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * A pull that only takes back a landed one (`revertsPullId`, the forge's own revert:
3 * `actions/revert.ts`, #6377) restores a tree that already passed the gate's "both doors" and "a
4 * test with the change" rules, and its inverse change cannot satisfy either: it removes a page or a
5 * test rather than adding one. So the check tells the gate, as `FORGE_CHECK_REVERTS=#<number>`, and
6 * those two rules stand down (`scripts/gate.ts`). The env is the forge's word, never the pull's: it
7 * is set only when the pull row says it reverts a merged pull and its change against the base is
8 * exactly the inverse of that landing, line for line. A revert branch with anything else pushed to
9 * it is judged whole.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { getIssueById } from "../core/issues.ts";
14 import { getPull, type Pull } from "../core/pulls.ts";
15 import { runGit } from "../git/env.ts";
16 import { isSafeOid } from "../git/guard.ts";
17
18 /** The variable the gate reads. */
19 export const REVERTS_ENV = "FORGE_CHECK_REVERTS";
20
21 /**
22 * What a check's step is told of the diff it judges, here and on a runner alike: the base and what
23 * was learned of it (`FORGE_CHECK_BASE`, `FORGE_CHECK_LEARNED`) when there is a base, and the
24 * revert mark `revertsEnv` gave. One function, so neither path can drop the mark alone.
25 */
26 export function diffEnv(base: string | undefined, learned: string, reverts: Readonly<Record<string, string>>): Record<string, string> {
27 return { ...(base === undefined ? {} : { FORGE_CHECK_BASE: base, FORGE_CHECK_LEARNED: learned }), ...reverts };
28 }
29
30 /**
31 * A zero-context diff without its index and hunk-position lines: what two equal changes share
32 * wherever they sit.
33 */
34 async function bareChange(bare: string, from: string, to: string): Promise<string | undefined> {
35 const diff = await runGit(["diff", "-U0", "--no-color", "--no-ext-diff", "--no-renames", from, to], { cwd: bare, timeoutMs: 60_000 });
36 if (!diff.ok) return undefined;
37 return diff.value
38 .split("\n")
39 .filter((line) => !line.startsWith("index ") && !line.startsWith("@@"))
40 .join("\n");
41 }
42
43 /**
44 * `{ FORGE_CHECK_REVERTS: "#<n>" }` when `pull` reverts merged pull #n and `base..commit` (the pull
45 * as it would land) is exactly the inverse of #n's landing; else nothing.
46 */
47 export async function revertsEnv(
48 db: Database,
49 bare: string,
50 pull: Pull | undefined,
51 base: string | undefined,
52 commit: string,
53 ): Promise<Record<string, string>> {
54 if (pull === undefined || pull.revertsPullId === null || base === undefined) return {};
55 const issue = getIssueById(db, pull.revertsPullId);
56 const taken = issue === undefined ? undefined : getPull(db, issue.repoId, issue.number);
57 const landed = taken?.mergedOid;
58 if (taken === undefined || landed == null || !isSafeOid(landed) || !isSafeOid(base) || !isSafeOid(commit)) return {};
59 const [undo, change] = await Promise.all([bareChange(bare, landed, `${landed}^1`), bareChange(bare, base, commit)]);
60 if (undo === undefined || change === undefined || undo.trim() === "" || undo !== change) return {};
61 return { [REVERTS_ENV]: `#${taken.number}` };
62 }
src/checks/run_tier.ts +5 −6
@@ -8,6 +8,7 @@ import { noteRunProgress } from "../core/runs.ts";
88 import { runGit } from "../git/env.ts";
99 import { checkKey, provenBy, recordProven } from "./proven.ts";
1010 import { giveHistory } from "./history.ts";
11 import { diffEnv, revertsEnv } from "./revert_exact.ts";
1112 import { readLearned } from "./learned.ts";
1213 import { keepCache, restoreCache } from "./cache.ts";
1314 import { keepAfterGreen, setupFromSnapshot } from "./tier_snapshot.ts";
@@ -85,6 +86,8 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco
8586 // the verdict, and nothing is checked out (#1795).
8687 const learned =
8788 base === undefined ? "" : readLearned(app.config.dataDir, x.pull!.id).join(",");
89 // The forge's own revert of a landing, proven line for line, is told to the gate (#6377).
90 const reverts = await revertsEnv(app.db, bare, x.pull, base, run.commitOid);
8891 const tree = await runGit(["rev-parse", `${run.commitOid}^{tree}`], { cwd: bare });
8992 // A bisection step runs a slice: its green proves nothing of the whole.
9093 const key = tree.ok && x.only === undefined
@@ -114,6 +117,7 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco
114117 base,
115118 builtOnBase,
116119 learned,
120 reverts,
117121 tree,
118122 key,
119123 outside,
@@ -247,12 +251,7 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco
247251 // The one place besides the checkout the cell can write on disk; its
248252 // own /tmp is a 256 MiB tmpfs the shards would fill (#8679).
249253 ...scratchEnv(cell === undefined ? undefined : home),
250 ...(base === undefined
251 ? {}
252 : {
253 FORGE_CHECK_BASE: base,
254 FORGE_CHECK_LEARNED: learned,
255 }),
254 ...diffEnv(base, learned, reverts),
256255 // A cell inside a cell is not a cell. This check's own cell is the
257256 // boundary; a forge the tests boot inside it would wrap its apps in
258257 // nested cells, and those never answer in time. Its children run as
src/checks/tier_runner.ts +8 −2
@@ -4,6 +4,7 @@ import { noteRunProgress } from "../core/runs.ts";
44 import { runGit } from "../git/env.ts";
55 import { recordProven } from "./proven.ts";
66 import { headDepth } from "./history.ts";
7 import { diffEnv } from "./revert_exact.ts";
78 import { clearedIn } from "./base_red.ts";
89 import { recordCrashFlakes } from "./flake.ts";
910 import { handoverEnv } from "./handover.ts";
@@ -27,6 +28,11 @@ export interface RunnerCheck {
2728 readonly base: string | undefined;
2829 readonly builtOnBase: string | undefined;
2930 readonly learned: string;
31 /**
32 * `FORGE_CHECK_REVERTS` when the pull is the forge's revert of a landing, proven
33 * (`revert_exact.ts`).
34 */
35 readonly reverts: Readonly<Record<string, string>>;
3036 readonly tree: Awaited<ReturnType<typeof runGit>>;
3137 readonly key: string | undefined;
3238 readonly outside: boolean;
@@ -46,7 +52,7 @@ export async function tryRunner(
4652 send: typeof runRunnerStep = runRunnerStep,
4753 ): Promise<CheckOutcome | undefined> {
4854 const { app, options } = lane;
49 const { run, repo, bare, manifest, command, base, builtOnBase, learned, tree, key, outside, write, signal } = c;
55 const { run, repo, bare, manifest, command, base, builtOnBase, learned, reverts, tree, key, outside, write, signal } = c;
5056 // A runner that joined takes the steps (`runner_step.ts`, #13652): only a check that hands
5157 // back nothing but its log and its verdict, and only while a runner is connected. Not taken,
5258 // or an answer that is not the check's own verdict, and it runs here as it always has.
@@ -88,7 +94,7 @@ export async function tryRunner(
8894 FORGE_CHECK: run.id,
8995 FORGE_COMMIT: x.commitOid,
9096 ...handoverEnv(),
91 ...(base === undefined ? {} : { FORGE_CHECK_BASE: base, FORGE_CHECK_LEARNED: learned }),
97 ...diffEnv(base, learned, reverts),
outdated

This spread is the whole hand-off to a runner and nothing tests it (test/check-runner-base-gate.test.ts only passes reverts: {}). Add a test that the job env carries FORGE_CHECK_REVERTS when reverts is set and does not carry it otherwise.

9298 FORGE_CELLS: "off",
9399 },
94100 limits: {
test/check-runner-base-gate.test.ts +17 −1
@@ -16,6 +16,7 @@ import { exportTree } from "../src/apps/checkout.ts";
1616 import type { CheckManifest } from "../src/apps/manifest.ts";
1717 import { BASE_GATE_FILE, BASE_GATE_MARK, withBaseGateFrom } from "../src/checks/base_gate.ts";
1818 import { giveHistory } from "../src/checks/history.ts";
19 import { diffEnv, REVERTS_ENV } from "../src/checks/revert_exact.ts";
1920 import type { LaneState } from "../src/checks/lane_state.ts";
2021 import type { Execution } from "../src/checks/local_runner.ts";
2122 import type { RunnerJob } from "../src/checks/runner_jobs.ts";
@@ -85,7 +86,7 @@ async function repoWith(name: string, base: string, head: string): Promise<{ rep
8586 }
8687
8788 /** Hand the check to a fake runner: the job it was given, and nothing taken. */
88 async function handOver(repo: Repo, base: string, head: string): Promise<{ job: Omit<RunnerJob, "id">; bare: string; log: string[] }> {
89 async function handOver(repo: Repo, base: string, head: string, reverts: Record<string, string> = {}): Promise<{ job: Omit<RunnerJob, "id">; bare: string; log: string[] }> {
8990 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
9091 const jobs: Omit<RunnerJob, "id">[] = [];
9192 const log: string[] = [];
@@ -107,6 +108,7 @@ async function handOver(repo: Repo, base: string, head: string): Promise<{ job:
107108 base,
108109 builtOnBase: base,
109110 learned: "",
111 reverts,
110112 tree: await runGit(["rev-parse", `${head}^{tree}`], { cwd: bare }),
111113 key: undefined,
112114 outside: false,
@@ -167,6 +169,20 @@ describe("a runner's check runs the base's gate first", () => {
167169 expect(job.steps.find((s) => s.name === "check")?.command).toBe("true");
168170 }, 30_000);
169171
172 test("the forge's revert mark reaches the runner's job, and no mark is invented without one", async () => {
173 const { repo, base, head } = await repoWith("spillway", BASE_SOURCE, PULL_SOURCE);
174 const marked = await handOver(repo, base, head, { [REVERTS_ENV]: "#12" });
175 expect(marked.job.env[REVERTS_ENV]).toBe("#12");
176 expect(marked.job.env["FORGE_CHECK_BASE"]).toBe(base);
177 const plain = await handOver(repo, base, head);
178 expect(plain.job.env[REVERTS_ENV]).toBeUndefined();
179 }, 30_000);
180
181 test("the step's diff env is one function, here and on a runner: base, learned and the mark", () => {
182 expect(diffEnv("b".repeat(40), "x,y", { [REVERTS_ENV]: "#7" })).toEqual({ FORGE_CHECK_BASE: "b".repeat(40), FORGE_CHECK_LEARNED: "x,y", [REVERTS_ENV]: "#7" });
183 expect(diffEnv(undefined, "", {})).toEqual({});
184 });
185
170186 test("ids that are not ids leave the command for the caller to keep off the runner", () => {
171187 expect(withBaseGateFrom("true", BASE_SOURCE, "main; rm -rf /", "a".repeat(40))).toBe("true");
172188 expect(withBaseGateFrom("true", BASE_SOURCE, "a".repeat(40), undefined)).toBe("true");
test/revert-gate.test.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * The forge's own revert of a landing (#6377) restores a tree that already passed "both doors" and
3 * "a test with the change", so the check tells the gate (`FORGE_CHECK_REVERTS`, set only when the
4 * pull row reverts a merged pull and its change is exactly that landing's inverse) and those two
5 * rules stand down. A pull that is not that revert is still held to both.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { bothDoorsRefusal, testsWithChangeRefusal } from "../scripts/gate.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { mergePull, openPull } from "../src/actions/pulls.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { revertPull } from "../src/actions/revert.ts";
16 import { REVERTS_ENV, revertsEnv } from "../src/checks/revert_exact.ts";
17 import { getPull, type Pull } from "../src/core/pulls.ts";
18 import type { Repo } from "../src/core/repos.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { resolveOid } from "../src/git/merge.ts";
21 import { repoDir } from "../src/git/repos.ts";
22
23 const PAGE = "src/web/pages/traffic.ts";
24
25 describe("the check marks the forge's own revert, and only that", () => {
26 let root: string;
27 let app: App;
28 let alice: User;
29 let repo: Repo;
30 let bare: string;
31 let shipped: Pull;
32 let revert: Pull;
33
34 const tip = async (ref: string) => (await resolveOid(bare, `refs/heads/${ref}`))!;
35
36 beforeAll(async () => {
37 root = mkdtempSync(join(tmpdir(), "forge-revert-gate-"));
38 app = createApp({ dataDir: root, port: 0 });
39 const made = await createUser(app.db, {
40 origin: "seed",
41 trusted: true,
42 username: "alice",
43 email: "[email protected]",
44 password: "a-good-passphrase",
45 adminIfFirst: true,
46 });
47 if (!made.ok) throw new Error(made.error);
48 alice = made.value;
49 const r = await createRepo(app, alice, { name: "app", visibility: "public" });
50 if (!r.ok) throw new Error(String(r.error));
51 repo = r.value;
52 bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
53 await commitToBranch(app, alice, repo, { branch: "main", message: "base", files: [{ path: "README.md", content: "x\n" }] });
54 // A web-only landing: a page and nothing else.
55 await commitToBranch(app, alice, repo, {
56 branch: "page",
57 base: "main",
58 message: "Add traffic",
59 files: [{ path: PAGE, content: "export const page = 1;\n" }],
60 });
61 const opened = await openPull(app, alice, repo, { title: "Add traffic", baseBranch: "main", headBranch: "page" });
62 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
63 const merged = await mergePull(app, alice, repo, opened.value, "squash");
64 if (!merged.ok) throw new Error(JSON.stringify(merged.error));
65 shipped = getPull(app.db, repo.id, opened.value.number)!;
66 const reverted = await revertPull(app, alice, repo, shipped);
67 if (!reverted.ok) throw new Error(JSON.stringify(reverted.error));
68 revert = reverted.value;
69 });
70
71 afterAll(() => {
72 app.close();
73 rmSync(root, { recursive: true, force: true });
74 });
75
76 test("the forge's revert, as it would land, is marked with the pull it takes back", async () => {
77 const env = await revertsEnv(app.db, bare, revert, await tip("main"), await tip(revert.headBranch));
78 expect(env).toEqual({ [REVERTS_ENV]: `#${shipped.number}` });
79 });
80
81 test("a pull with no revertsPullId is not, though its change is the same", async () => {
82 const plain = { ...revert, revertsPullId: null };
83 expect(await revertsEnv(app.db, bare, plain, await tip("main"), await tip(revert.headBranch))).toEqual({});
84 });
85
86 test("a revert branch with anything else pushed to it is judged whole", async () => {
87 await commitToBranch(app, alice, repo, {
88 branch: revert.headBranch,
89 message: "And a feature",
90 files: [{ path: "src/web/pages/other.ts", content: "x\n" }],
91 });
92 expect(await revertsEnv(app.db, bare, revert, await tip("main"), await tip(revert.headBranch))).toEqual({});
93 });
94 });
95
96 describe("the gate stands down two rules for a marked revert", () => {
97 const root = mkdtempSync(join(tmpdir(), "revert-gate-"));
98 afterAll(() => rmSync(root, { recursive: true, force: true }));
99 const run = (cwd: string, ...args: string[]) => {
100 const r = Bun.spawnSync(["git", "-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd });
101 if (r.exitCode !== 0) throw new Error(r.stderr.toString());
102 return r.stdout.toString().trim();
103 };
104 const put = (dir: string, file: string, text: string) => {
105 mkdirSync(join(dir, file, ".."), { recursive: true });
106 writeFileSync(join(dir, file), text);
107 };
108 const judged = async (env: Record<string, string | undefined>, f: () => Promise<string[]>) => {
109 const old = Object.fromEntries(Object.keys(env).map((k) => [k, process.env[k]]));
110 const set = (vars: Record<string, string | undefined>) => {
111 for (const [k, v] of Object.entries(vars)) {
112 if (v === undefined) delete process.env[k];
113 else process.env[k] = v;
114 }
115 };
116 set(env);
117 try {
118 return await f();
119 } finally {
120 set(old);
121 }
122 };
123
124 // Main holds a page landed with its doors waived; the pull under check takes it back.
125 const dir = join(root, "repo");
126 let landed = "";
127 beforeAll(() => {
128 mkdirSync(dir);
129 run(dir, "init", "-q", "-b", "main");
130 put(dir, "README.md", "x");
131 put(dir, "src/tui/screens/entries.ts", "export const ENTRIES = [];\n");
132 put(dir, PAGE, "export const page = 1;\nexport const more = 2;\n");
133 run(dir, "add", "-A");
134 run(dir, "commit", "-qm", "base");
135 put(dir, PAGE, "export const page = 1;\n");
136 run(dir, "commit", "-qam", "Trim traffic\n\nNo door: a line no terminal shows\nNo test: a constant removed");
137 landed = run(dir, "rev-parse", "HEAD");
138 run(dir, "revert", "--no-edit", "HEAD");
139 });
140
141 test("a non-revert with the same change still fails both rules", async () => {
142 const env = { FORGE_CHECK_BASE: landed, [REVERTS_ENV]: undefined };
143 expect((await judged(env, () => bothDoorsRefusal(dir))).length).toBeGreaterThan(0);
144 expect((await judged(env, () => testsWithChangeRefusal(dir))).length).toBeGreaterThan(0);
145 });
146
147 test("the forge's revert of a web-only commit passes both", async () => {
148 const env = { FORGE_CHECK_BASE: landed, [REVERTS_ENV]: "#12" };
149 expect(await judged(env, () => bothDoorsRefusal(dir))).toEqual([]);
150 expect(await judged(env, () => testsWithChangeRefusal(dir))).toEqual([]);
151 });
152
153 test("a mark that is not a pull number is no mark", async () => {
154 const env = { FORGE_CHECK_BASE: landed, [REVERTS_ENV]: "yes" };
155 expect((await judged(env, () => bothDoorsRefusal(dir))).length).toBeGreaterThan(0);
156 });
157 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs