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

A kept-result audit that disagrees drops the kept entry and says so #16808

Merged opened this

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

Merged

scout/forge:scout/16270-a-kept-result-audit-that-disagrees-drops → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16270-a-kept-result-audit-that-disagrees-drops was merged into main as bb5ad39.

Review

Sign in to review this change.
8 files changed +200 −13
.gitignore +1
@@ -27,6 +27,7 @@ typesafe-api-key
2727 # what a check hands between runs: the impact map, the kept results and the test times, never committed
2828 /.forge-impact.json
2929 /.forge-kept.json
30 /.forge-kept-dropped.json
3031 /.forge-times.json
3132
3233 # empty stubs an agent sandbox mounts over home-directory config; never the
scripts/shards.ts +23 −6
@@ -453,18 +453,35 @@ function unnamedLine(n: number, result: ShardResult): string {
453453 * when the file ran alone; among others the audit says it cannot tell.
454454 */
455455 export function auditLines(audited: ReadonlyMap<string, string>, results: readonly ShardResult[]): string[] {
456 return judgeAudits(audited, results).map((j) => j.line);
457 }
458
459 /** The audited files whose real run disagreed with the kept result (#16270). */
460 export const auditDisagreed = (audited: ReadonlyMap<string, string>, results: readonly ShardResult[]): string[] =>
461 judgeAudits(audited, results).flatMap((j) => (j.disagrees ? [j.file] : []));
462
463 const judged = (file: string, commit: string, green: boolean) => ({
464 file,
465 line: auditLine(file, commit, green),
466 disagrees: !green,
467 });
468
469 function judgeAudits(
470 audited: ReadonlyMap<string, string>,
471 results: readonly ShardResult[],
472 ): { file: string; line: string; disagrees: boolean }[] {
456473 const bare = (file: string): string => file.replace(/^\.\//, "");
457 const lines: string[] = [];
474 const out: { file: string; line: string; disagrees: boolean }[] = [];
458475 for (const [file, commit] of audited) {
459476 const ran = results.find((result) => result.files.some((f) => bare(f) === file));
460477 if (ran === undefined) continue;
461478 const red = failingFiles(ran.output).map(bare);
462 if (red.includes(file)) lines.push(auditLine(file, commit, false));
463 else if (ran.code === 0 || red.length > 0) lines.push(auditLine(file, commit, true));
464 else if (ran.files.length === 1) lines.push(auditLine(file, commit, false));
465 else lines.push(` ${file}: audit cannot tell: its shard went red without naming a failing test`);
479 if (red.includes(file)) out.push(judged(file, commit, false));
480 else if (ran.code === 0 || red.length > 0) out.push(judged(file, commit, true));
481 else if (ran.files.length === 1) out.push(judged(file, commit, false));
482 else out.push({ file, line: ` ${file}: audit cannot tell: its shard went red without naming a failing test`, disagrees: false });
466483 }
467 return lines;
484 return out;
468485 }
469486
470487 /**
scripts/test-shards.ts +17 −3
@@ -97,6 +97,7 @@ import {
9797 tally,
9898 weigher,
9999 besideOthers,
100 auditDisagreed,
100101 auditLines,
101102 failingFiles,
102103 failingTests,
@@ -123,7 +124,7 @@ import { CHECK_CACHE } from "../src/checks/cache.ts";
123124 import { parseCheck } from "../src/apps/manifest.ts";
124125 import { FLAKY_ALONE, onlyFiles } from "../src/checks/verify.ts";
125126 import { crashFlakeLine } from "../src/checks/flake.ts";
126 import { formatKept, keptLine, mergeKept, parseKept, type KeptEntry } from "../src/checks/kept.ts";
127 import { DROPPED_FILE, dropDisagreed, droppedLine, finalCode, formatKept, keptLine, mergeKept, parseKept, type KeptEntry } from "../src/checks/kept.ts";
127128 import { answerKept, freshKept } from "./kept-input.ts";
128129 import { askBase, baseVerdict, untilRed, type OnBase } from "../src/checks/base_red.ts";
129130
@@ -1094,6 +1095,19 @@ const judged = performance.now();
10941095 const wall = (judged - started) / 1000;
10951096 const ending = tally(results, wall);
10961097 for (const line of auditLines(audited, results)) console.log(line);
1098 // A kept result an audit contradicts is dropped from the handed file and named in a file the
1099 // forge reads for the store, and the run fails (#16270).
1100 const disagreed = auditDisagreed(audited, results);
1101 const auditDisagreement = disagreed.length > 0;
1102 if (auditDisagreement) {
outdated

Set auditDisagreement from disagreed.length > 0 alone. As written, a disagreeing audit with no handed file does not fail the run.

1103 writeFileSync(DROPPED_FILE, JSON.stringify(disagreed));
1104 const current = KEPT === undefined ? undefined : parseKept(readFileSync(KEPT, "utf8"));
1105 if (KEPT !== undefined && current?.ok) {
1106 const { kept, dropped } = dropDisagreed(current.value, disagreed);
1107 writeFileSync(KEPT, formatKept(kept));
outdated

This writes only the checkout's copy. The run is red, so the store write-back is skipped, and a later mergeKept keeps old entries. The drop is lost and the key is trusted again.

1108 console.log(droppedLine(dropped));
1109 } else console.log(` audit DISAGREED on ${disagreed.join(", ")}: no readable kept file to drop from here; the store is told`);
1110 }
10971111 const spread = results.map((result) => result.seconds);
10981112 console.log(`\n${ending.lines.join("\n")}`);
10991113 // Listed once, after the tally: what only a loaded box found over the budget.
@@ -1306,7 +1320,7 @@ async function runOnBase(asked: readonly string[], base: string): Promise<Map<st
13061320
13071321 // A fast tier red only on tests main's own tree fails too is main's red,
13081322 // not this pull's (#10304): said, and not counted against it.
1309 let code = ending.code;
1323 let code = finalCode({ code: ending.code, auditDisagreed: auditDisagreement, clearedByBase: false });
13101324 if (code !== 0 && tier === "fast" && range !== undefined && only === undefined) {
outdated

This exit-code logic is untested. Extract it into a pure function and cover it with a test that fails without it.

13111325 const red = redTests(results);
13121326 const asked = askBase({ red, changed });
@@ -1314,7 +1328,7 @@ if (code !== 0 && tier === "fast" && range !== undefined && only === undefined)
13141328 console.log(`\ntest-shards: asking main at ${range[0]} about ${asked.join(", ")}`);
13151329 const verdict = baseVerdict(red, await runOnBase(asked, range[0]!), range[0]!);
13161330 for (const line of verdict.lines) console.log(`test-shards: ${line}`);
1317 if (verdict.cleared) code = 0;
1331 code = finalCode({ code, auditDisagreed: auditDisagreement, clearedByBase: verdict.cleared });
13181332 }
13191333 }
13201334 process.exit(code);
src/checks/kept-store.ts +35 −1
@@ -8,7 +8,7 @@
88
99 import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
1010 import { join } from "node:path";
11 import { formatKept, parseKept } from "./kept.ts";
11 import { DROPPED_FILE, dropDisagreed, formatKept, parseDropped, parseKept } from "./kept.ts";
1212
1313 /** Where in the checkout the results are handed over, both ways. */
1414 export const KEPT_FILE = ".forge-kept.json";
@@ -72,3 +72,37 @@ export function keepKept(
7272 renameSync(partial, storeOf(dataDir, repoId));
7373 return `kept results kept: ${parsed.value.size} tests`;
7474 }
75
76 /**
77 * Forgets in the store what a check's audit contradicted (#16270), from any run, green or red:
78 * the file names tests, and removing is the one thing a pull's tree may ask of the store, since
79 * a result forgotten is only a test run again. The log line, or `undefined` when none named.
80 */
81 export function dropKept(dataDir: string, repoId: string, checkout: string): string | undefined {
82 const path = join(checkout, DROPPED_FILE);
83 let tests: string[];
84 try {
85 const stat = lstatSync(path);
86 if (!stat.isFile() || stat.size > MAX_BYTES) return undefined;
87 const parsed = parseDropped(readFileSync(path, "utf8"));
88 if (!parsed.ok || parsed.value.length === 0) return undefined;
89 tests = parsed.value;
90 } catch {
91 return undefined;
92 }
93 const store = storeOf(dataDir, repoId);
94 let text: string | undefined;
95 try {
96 text = readFileSync(store, "utf8");
97 } catch {
98 return undefined;
99 }
100 const old = parseKept(text);
101 if (!old.ok) return undefined;
102 const { kept, dropped } = dropDisagreed(old.value, tests);
103 if (dropped.length === 0) return undefined;
104 const partial = `${store}.${process.pid}.tmp`;
105 writeFileSync(partial, formatKept(kept));
106 renameSync(partial, store);
107 return `kept results dropped: ${dropped.length} (${tests.join(", ")}) forgotten after an audit disagreed`;
108 }
src/checks/kept.ts +50
@@ -133,6 +133,56 @@ export function mergeKept(old: Kept, fresh: Kept): Map<string, KeptEntry> {
133133 return merged;
134134 }
135135
136 /**
137 * The results left once the audits that disagreed are dropped (#16270): every entry for a
138 * disagreeing test goes, whatever its key, so no key that shares that file's inputs is trusted
139 * again. `dropped` names each, test and commit.
140 */
141 export function dropDisagreed(
142 kept: Kept,
143 tests: readonly string[],
144 ): { kept: Map<string, KeptEntry>; dropped: KeptEntry[] } {
145 const bad = new Set(tests);
146 const left = new Map<string, KeptEntry>();
147 const dropped: KeptEntry[] = [];
148 for (const [key, entry] of kept) {
149 if (bad.has(entry.test)) dropped.push(entry);
150 else left.set(key, entry);
151 }
152 return { kept: left, dropped };
153 }
154
155 /** Where in the checkout a check names the tests whose audit disagreed, for the store to forget. */
156 export const DROPPED_FILE = ".forge-kept-dropped.json";
157
158 /** The tests named in `text` (a JSON array of test paths), or why it is refused. */
159 export function parseDropped(text: string): { ok: true; value: string[] } | { ok: false; error: string } {
160 let data: unknown;
161 try {
162 data = JSON.parse(text);
163 } catch {
164 return { ok: false, error: "not JSON" };
165 }
166 if (!Array.isArray(data) || data.length > KEPT_MAX) return { ok: false, error: "not a list of tests" };
167 if (!data.every((t) => typeof t === "string" && TEST.test(t))) return { ok: false, error: "not a test path" };
168 return { ok: true, value: [...new Set(data as string[])] };
169 }
170
171 /**
172 * The exit code of a fast tier: an audit that disagreed always fails the run, and main's own red
173 * never clears it.
174 */
175 export function finalCode(x: { code: number; auditDisagreed: boolean; clearedByBase: boolean }): number {
176 if (x.auditDisagreed) return x.code === 0 ? 1 : x.code;
177 return x.clearedByBase ? 0 : x.code;
178 }
179
180 /** The log line for what a disagreeing audit dropped. */
181 export const droppedLine = (dropped: readonly KeptEntry[]): string =>
182 ` audit DISAGREED: dropped ${dropped.length} kept result${dropped.length === 1 ? "" : "s"} (${dropped
183 .map((e) => `${e.test} from ${e.commit.slice(0, 7)}`)
184 .join(", ")}); this run is untrustworthy and fails, the files rerun next time`;
185
136186 export interface KeptSplit {
137187 readonly run: string[];
138188 /** The tests not run, each with the commit that proved it. */
src/checks/run_tier.ts +8 −1
@@ -14,7 +14,7 @@ import { keepAfterGreen, setupFromSnapshot } from "./tier_snapshot.ts";
1414 import { clearedIn } from "./base_red.ts";
1515 import { scratchEnv } from "./disk_full.ts";
1616 import { keepImpact, seedImpact } from "./impact-store.ts";
17 import { keepKept, seedKept } from "./kept-store.ts";
17 import { dropKept, keepKept, seedKept } from "./kept-store.ts";
1818 import { keepTimes, seedTimes } from "./times-store.ts";
1919 import { handoverEnv, handsTimesBack } from "./handover.ts";
2020 import { redDetail } from "./report.ts";
@@ -431,6 +431,13 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco
431431 ...(cleared === undefined ? {} : { cleared }),
432432 };
433433 } finally {
434 // Red or green, what an audit contradicted is forgotten by the store (#16270).
435 try {
436 const dropped = dropKept(app.config.dataDir, repo.id, dir);
437 if (dropped !== undefined) write(dropped);
438 } catch (error) {
439 write(`kept results not dropped: ${String(error)}`);
440 }
434441 if (existsSync(dir)) await removeRunDir(dir);
435442 await removeRunDir(home);
436443 }
test/check-kept.test.ts +38 −2
@@ -2,8 +2,8 @@ import { afterEach, describe, expect, test } from "bun:test";
22 import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5 import { auditLine, formatKept, keptKey, mergeKept, parseKept, readsTheTree, splitKept, sampled, KEPT_TOOLING, KEPT_MAX } from "../src/checks/kept.ts";
6 import { KEPT_FILE, keepKept, seedKept } from "../src/checks/kept-store.ts";
5 import { DROPPED_FILE, finalCode, parseDropped, auditLine, formatKept, keptKey, mergeKept, parseKept, readsTheTree, splitKept, sampled, KEPT_TOOLING, KEPT_MAX } from "../src/checks/kept.ts";
6 import { KEPT_FILE, dropKept, keepKept, seedKept } from "../src/checks/kept-store.ts";
77 import { answerKept, freshKept, keyOfTest } from "../scripts/kept-input.ts";
88
99 const base = { bun: "1.2.3", platform: "linux", test: "test/a.test.ts", files: [["src/a.ts", "h1"], ["test/a.test.ts", "h2"]] as [string, string][] };
@@ -198,3 +198,39 @@ describe("the kept results beside the forge", () => {
198198 }
199199 });
200200 });
201
202 describe("a disagreeing audit reaches the store and the exit code (#16270)", () => {
203 test("a pull's red run names the file, and the store forgets it though nothing is written back", () => {
204 const data = mkdtempSync(join(tmpdir(), "kept-data-"));
205 const main = mkdtempSync(join(tmpdir(), "kept-co-"));
206 const pull = mkdtempSync(join(tmpdir(), "kept-co-"));
207 try {
208 const other = keptKey({ ...base, test: "test/b.test.ts" });
209 writeFileSync(
210 join(main, KEPT_FILE),
211 formatKept(new Map([[key, { test: base.test, commit }], [other, { test: "test/b.test.ts", commit }]])),
212 );
213 keepKept(data, "r1", main, true);
214 expect(dropKept(data, "r1", pull)).toBeUndefined();
215 writeFileSync(join(pull, DROPPED_FILE), JSON.stringify([base.test]));
216 expect(dropKept(data, "r1", pull)).toContain("test/a.test.ts");
217 expect(seedKept(data, "r1", pull)).toBe(1);
218 const seeded = parseKept(readFileSync(join(pull, KEPT_FILE), "utf8"));
219 expect(seeded.ok && [...seeded.value.keys()]).toEqual([other]);
220 // A default-branch run that merges its fresh results over the store keeps the drop.
221 writeFileSync(join(pull, DROPPED_FILE), "not json");
222 expect(dropKept(data, "r1", pull)).toBeUndefined();
223 expect(parseDropped(`["../x"]`).ok).toBe(false);
224 } finally {
225 for (const dir of [data, main, pull]) rmSync(dir, { recursive: true, force: true });
226 }
227 });
228
229 test("an audit that disagreed always fails; main's red clears nothing else of it", () => {
230 expect(finalCode({ code: 0, auditDisagreed: true, clearedByBase: false })).toBe(1);
231 expect(finalCode({ code: 1, auditDisagreed: true, clearedByBase: true })).toBe(1);
232 expect(finalCode({ code: 1, auditDisagreed: false, clearedByBase: true })).toBe(0);
233 expect(finalCode({ code: 1, auditDisagreed: false, clearedByBase: false })).toBe(1);
234 expect(finalCode({ code: 0, auditDisagreed: false, clearedByBase: false })).toBe(0);
235 });
236 });
test/shards.test.ts +28
@@ -10,7 +10,9 @@
1010 import { describe, expect, test } from "bun:test";
1111 import { readFileSync } from "node:fs";
1212 import { resolveLimits } from "../src/apps/contain.ts";
13 import { dropDisagreed, droppedLine, splitKept } from "../src/checks/kept.ts";
1314 import {
15 auditDisagreed,
1416 auditLines,
1517 SECONDS_PER_BYTE_DEFAULT,
1618 SHARDS_MAX,
@@ -891,3 +893,29 @@ describe("the audit of a kept file, judged by its own file", () => {
891893 expect(auditLines(audited, [])).toEqual([]);
892894 });
893895 });
896
897 describe("a disagreeing audit drops the kept result (#16270)", () => {
898 const commit = "abcdef1234567";
899 const entry = (test: string) => ({ test, commit });
900 test("every entry of the file goes, others stay, the log names them, and the next run recomputes", () => {
901 const kept = new Map([
902 ["a".repeat(64), entry("test/a.test.ts")],
903 ["b".repeat(64), entry("test/a.test.ts")],
904 ["c".repeat(64), entry("test/b.test.ts")],
905 ]);
906 const output = `test/a.test.ts:\n(fail) broken [1.00ms]\n`;
907 const bad = auditDisagreed(new Map([["test/a.test.ts", commit]]), [{ files: ["test/a.test.ts"], code: 1, output }]);
908 expect(bad).toEqual(["test/a.test.ts"]);
909 const after = dropDisagreed(kept, bad);
910 expect([...after.kept.keys()]).toEqual(["c".repeat(64)]);
911 expect(after.dropped.length).toBe(2);
912 expect(droppedLine(after.dropped)).toContain("test/a.test.ts from abcdef1");
913 // The next run finds no kept answer for the file: it runs.
914 const key = "a".repeat(64);
915 expect(splitKept(["test/a.test.ts"], after.kept, () => key).run).toEqual(["test/a.test.ts"]);
916 });
917 test("an agreeing audit drops nothing", () => {
918 const output = `test/a.test.ts:\n(pass) fine\n`;
919 expect(auditDisagreed(new Map([["test/a.test.ts", commit]]), [{ files: ["test/a.test.ts"], code: 0, output }])).toEqual([]);
920 });
921 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs