From 44e244d603036a46833ce14e9fd319276ee73e33 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 05:19:58 -0800 Subject: [PATCH] Review exclusions stay in place when the repo's own policy test pins an excluded path (GST-3512) (#4699) An excluded data file no longer comes back into review just because the repo's own test for `review_exclude_paths` pins that exact path in its pattern list. Results PRs that exclude a single data file and pin the list in a test now stay under the reader limit; code that reads the file, and example paths the test checks against the patterns, still keep it in review. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p1/specialist-batched#2 reader=testing Review-Finding: p2/outside-voice#1 reader=outside-voice Review-Finding: p2/outside-voice#2 reader=outside-voice --- ...view-exclude-keeps-names-from-real-code.md | 1 + docs/ship-policy.md | 2 +- lib/review-exclude.ts | 53 +++++++++- test/review-exclude-contract-test.test.ts | 99 +++++++++++++++++++ 4 files changed, 149 insertions(+), 6 deletions(-) create mode 100644 changelog.d/review-exclude-keeps-names-from-real-code.md create mode 100644 test/review-exclude-contract-test.test.ts diff --git a/changelog.d/review-exclude-keeps-names-from-real-code.md b/changelog.d/review-exclude-keeps-names-from-real-code.md new file mode 100644 index 000000000..b4400aed8 --- /dev/null +++ b/changelog.d/review-exclude-keeps-names-from-real-code.md @@ -0,0 +1 @@ +A repository's own test for `review_exclude_paths` no longer pulls excluded files back into review. When a test file that names `review_exclude_paths` pins the pattern list as quoted array entries, a pattern that names one file (such as `wiki/b2/sessions.jsonl`) stays excluded. Example paths the test expects the patterns to match, code that reads the file, other tests that name it, a quoted path passed to a call, and any joined or prefixed form of the path still keep it in review (docs/ship-policy.md). diff --git a/docs/ship-policy.md b/docs/ship-policy.md index a947f57b0..f128f6b28 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1522,7 +1522,7 @@ Everything else stays in every reader's diff with one reason code: | `gate-tagged` | the gate scan tagged one of its hunks | | `code` | it is code or a test, not content; a binary file outside the content extensions above, or one with executable magic, counts as code | | `secret-line` | an added line names a credential (the targeted pass's secret rule, or a key name given a value such as `OPENAI_API_KEY=`) and carries a value: the credential scan finds a secret on the line, or a run of 20 or more base64 or token characters mixing upper case, lower case and digits follows a name within 200 characters. A line that only names a variable or a credential store (`${OPENAI_API_KEY}`, `$GH_TOKEN`, `process.env.X`, `os.environ["X"]`, a keychain command) keeps nothing (GST-1967: harness-evals #333's captured prompts kept 2,610 files that way). For a file git calls binary only because of its attributes, the added lines come from `git diff --text`, which `.gitattributes` cannot change (readers' own diffs still follow the attributes and show the kept file as binary). When this is the only reason, pass readers get an excerpt, not the whole file ([secret-line excerpts](#secret-line-excerpts)) | -| `named-by-code` | a code or test file that stays in review (not docs, a data file, a `.log` or binary, and not itself excluded), or a [declared content](#review-content-patterns) file that stays in review, names its full repository path, at the head or the merge base | +| `named-by-code` | a code or test file that stays in review (not docs, a data file, a `.log` or binary, and not itself excluded), or a [declared content](#review-content-patterns) file that stays in review, names its full repository path, at the head or the merge base. A test file that names `review_exclude_paths` and holds the path only as whole quoted strings (`'p'`, `"p"` or `` `p` ``) inside array literals, where the path is itself one of the base policy's `review_exclude_paths` patterns, is the exclusion's own contract test pinning its list, so it keeps nothing (the scan skips other strings and comments). A path that is not a literal pattern, such as a hit or near-miss example, still counts, and so does a quoted path passed to a call, held in an object or a plain constant, joined or prefixed | | `consumer-scan-unavailable` | the `git grep` for those names failed, so every candidate is kept; also a live binary file whose bytes could not be read, and a text file with changed lines the collector read no lines for | | `gate-scan-unavailable` | the gate scan failed or did not run at the head, so no hunk's tag is known and every candidate is kept | diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index 1c58c8485..ccebb25ed 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -386,6 +386,47 @@ const consumer = (i: Scope, f: string, candidates: ReadonlySet, mode?: s return !candidates.has(f) && (kind === null || (!!i.declared?.has(f) && (!!i.keptDeclared?.has(f) || mode === '100755' || mode === '120000'))); }; +/** A test file by name: `*.test.*`, `*.spec.*`, `*_test.go`, `*_test.py` or `test_*.py`. */ +const TEST_FILE = /\.(test|spec)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$/; + +/** The quoted strings that are array entries (innermost open bracket [), by opening-quote offset; a forward scan that skips strings and comments. */ +function arrayEntries(body: string, hashComments: boolean): Map { + const out = new Map(); + const open: string[] = []; + for (let k = 0; k < body.length; k++) { + const c = body[k]!; + if ((c === '/' && body[k + 1] === '/') || (hashComments && c === '#')) { const e = body.indexOf('\n', k); if (e < 0) break; k = e; continue; } + if (c === '/' && body[k + 1] === '*') { const e = body.indexOf('*/', k + 2); if (e < 0) break; k = e + 1; continue; } + if (c === "'" || c === '"' || c === '`') { + let e = k + 1; + for (; e < body.length && body[e] !== c; e++) { if (body[e] === '\\') e++; else if (body[e] === '\n' && c !== '`') break; } + if (open[open.length - 1] === '[') out.set(k, body.slice(k + 1, e)); + k = e; + continue; + } + if (c === '(' || c === '[' || c === '{') open.push(c); + else if (c === ')' || c === ']' || c === '}') open.pop(); + } + return out; +} +let lastEntries: { body: string; py: boolean; entries: Map } | null = null; + +/** + * Whether a hit is the repo's own contract test for the exclusion pinning its pattern list and nothing more (GST-3512): + * the path is itself one of the base policy's review_exclude_paths patterns, and the test file names + * review_exclude_paths and holds the path only as whole quoted array entries ('p', "p" or `p`; the scan skips other + * strings and comments). Such a test pins the list, so it keeps nothing. A path that is not a literal pattern (a hit or + * near-miss example), a quoted call argument (readFileSync('p')), an object value, a plain constant, a joined or prefixed + * path, or a mention in a comment still counts, and so does every non-test file. + */ +function contractExample(patterns: ReadonlySet, s: string, file: string, body: string): boolean { + if (!patterns.has(s) || !TEST_FILE.test(file) || !body.includes('review_exclude_paths')) return false; + const py = file.endsWith('.py'); + if (lastEntries?.body !== body || lastEntries.py !== py) lastEntries = { body, py, entries: arrayEntries(body, py) }; + for (let at = body.indexOf(s); at >= 0; at = body.indexOf(s, at + 1)) if (lastEntries.entries.get(at - 1) !== s) return false; + return true; +} + /** * An uncapped search for fixed strings at the head (or the working tree) and `revs`: string -> the consumer files * holding it; null when git could not list a tree, a consumer's name did not survive UTF-8 decoding, or git could not build @@ -398,7 +439,7 @@ const consumer = (i: Scope, f: string, candidates: ReadonlySet, mode?: s * manifest (every line a digest and a path, lib/review-risk.ts) names files without reading them, so it keeps none. On a live tree, an entry git reads from its blob * (skip-worktree or assume-unchanged) goes into a second index grepped with --cached, as git grep itself would read it. */ -function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet, revs: readonly string[]): Map> | null { +function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet, revs: readonly string[], skip?: (s: string, file: string, body: string) => boolean): Map> | null { const found = new Map>(); if (!strings.length) return found; const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-exclude-')); @@ -446,7 +487,7 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet } else for (const f of files) try { bodies.set(f, fs.readFileSync(path.join(i.root, f), 'utf8')); } catch { return null; } for (const [file, body] of bodies) { if (hashManifest(body.split('\n'))) continue; - for (const s of strings) if (body.includes(s)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file); + for (const s of strings) if (body.includes(s) && !skip?.(s, file, body)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file); } } } @@ -459,7 +500,7 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet * nothing); `head-only` when only the head does (a notice, never applied); `fallback` when the base policy fails only on its * exclusion keys, which finish (lib/ship-policy.ts) then sets aside so every file is reviewed; `refused` when the base policy cannot be read or * does not validate, or git cannot list the matches; `active` otherwise. Named-by-code keeps a file only when a kept code - * file names its full repository path (never its basename: receipt trees reuse result.json thousands of times); a git grep + * file names its full repository path (not the exclusion's own contract test pinning it as a pattern, contractExample) (never its basename: receipt trees reuse result.json thousands of times); a git grep * failure keeps every candidate (consumer-scan-unavailable), and so does an unknown gate scan (gate-scan-unavailable) or a * matched text file with changed lines the collector holds no added lines for (GST-1451: it is unread, so it fails closed). */ @@ -473,6 +514,8 @@ export function reviewExclude(i: ExcludeInput): Exclusion { } if (load.setAside) return { state: 'fallback', source, errors: load.setAside.map(e => `${e.path}: ${e.message}`) }; const patterns = load.policy.review_exclude_paths; + const patternSet = new Set(patterns); + const example = (s: string, f: string, body: string) => contractExample(patternSet, s, f, body); if (!patterns.length) { const head = headPatterns(i); return head.length ? { state: 'head-only', patterns: head, source } : { state: 'none' }; } const sel = select(i, patterns); if ('error' in sel) return { state: 'refused', code: 'REVIEW_DIFF_UNREADABLE', lines: [`${i.context}: git could not list the files review_exclude_paths matches (${sel.error}); fix: git fetch origin ${base}, then rerun once; nothing was planned (REVIEW_DIFF_UNREADABLE)`] }; @@ -501,8 +544,8 @@ export function reviewExclude(i: ExcludeInput): Exclusion { const floorCtx = { project: parseGateIntegrityBlock(readClaudeMd(i.root)), specIsTestPath: true }; const gateData = renamed ? tagOnly.filter(p => !renamed.has(p) && gateFloor(p, floorCtx) === null && singleLineTags(p, text.added[p] ?? [])) : []; const y: Scope = { ...x, keptDeclared: new Set([...reasons].filter(([p, r]) => r !== null && declared.has(p)).map(([p]) => p)) }; - const named = grepFixed(y, [...candidates, ...secretOnly].filter(p => !p.includes('\n')), new Set([...candidates, ...secretOnly]), [i.mergeBase]); - const gateNamed = gateData.length ? grepFixed(y, gateData, new Set([...candidates, ...secretOnly]), [i.mergeBase]) : new Map>(); + const named = grepFixed(y, [...candidates, ...secretOnly].filter(p => !p.includes('\n')), new Set([...candidates, ...secretOnly]), [i.mergeBase], example); + const gateNamed = gateData.length ? grepFixed(y, gateData, new Set([...candidates, ...secretOnly]), [i.mergeBase], example) : new Map>(); for (const p of candidates) { if (i.gateTagged === null) reasons.set(p, 'gate-scan-unavailable'); else if (named === null || p.includes('\n')) reasons.set(p, 'consumer-scan-unavailable'); diff --git a/test/review-exclude-contract-test.test.ts b/test/review-exclude-contract-test.test.ts new file mode 100644 index 000000000..ff3f900f1 --- /dev/null +++ b/test/review-exclude-contract-test.test.ts @@ -0,0 +1,99 @@ +/** + * review_exclude_paths and the repo's own contract test (GST-3512): a test that pins the exclusion's pattern list, or quotes + * paths it expects the patterns to match, names those paths without reading them, so it does not keep them in review as + * named-by-code. Code that reads a path, a test that is not about the exclusion, and any unquoted or joined form still keep it. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { REVIEW_EXCLUDE_KEY_VERSION } from '../lib/ship-policy'; +import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); +const PATTERNS = ['results/**', 'wiki/b2/sessions.jsonl']; +const CONTRACT = 'tests/ci/review-exclude-policy.test.ts'; +const contract = (extra = '') => [ + "import policy from '../../.gstack/ship-policy.json';", + "const PATTERNS = ['results/**', 'wiki/b2/sessions.jsonl'];", + "const HITS = [\"results/b2/run.json\", `wiki/b2/sessions.jsonl`];", + "test('pins the list', () => expect(policy.review_exclude_paths).toEqual(PATTERNS));", + extra, +].join('\n') + '\n'; + +function repo(files: Record) { + const r = makeFixtureRepo({ prefix: 'gstack-exclude-contract-', baseFiles: { '.gstack/ship-policy.json': JSON.stringify({ review_exclude_paths: PATTERNS, min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n' } }); + repos.push(r); + commit(r, { 'results/b2/run.json': '{"pass": 1}\n', 'results/b2/other.json': '{"pass": 2}\n', 'results/b2/third.json': '{"pass": 3}\n', 'wiki/b2/sessions.jsonl': '{"s": 1}\n', ...files }); + const x = JSON.parse(runBin(r, 'gstack-review-plan', ['--base', 'main', '--gate-tagged', '0', '--json']).out).review_exclude; + return { kept: x.kept_files as Array<{ path: string; reason: string }>, excluded: x.excluded as number }; +} + +describe('review_exclude_paths and its contract test', () => { + // Value: protects=a test that pins review_exclude_paths and quotes the paths it expects to match leaves those files + // excluded; fails_when=the contract test's quoted examples keep them as named-by-code, undoing the exclusion; + // why_new=GST-3512 (GEVA-569: a B2 results PR stayed at about 4.8 MB because its contract test named sessions.jsonl) + test('the exclusion\'s own contract test pinning a pattern keeps nothing, and its hit examples still keep theirs', () => { + expect(repo({ [CONTRACT]: contract() })).toEqual({ kept: [{ path: 'results/b2/run.json', reason: 'named-by-code' }], excluded: 3 }); + }, 120_000); + + // Value: protects=named-by-code still keeps a file that code reads, that a test outside the exclusion's contract names, + // or that the contract test names in any form but a quoted array element (a joined path, a './' prefix, a call + // argument, an object value); fails_when=the exemption reaches past the contract test's listed examples; + // why_new=GST-3512 negative control, /ship review of #4699 (lib/review-exclude.ts:398, test:38) + test('code, other tests, call arguments and joined paths still keep the files they name', () => { + const r = repo({ + [CONTRACT]: contract([ + "const local = `${ROOT}/results/b2/other.json`;", + "const raw = require('fs').readFileSync('results/b2/fourth.json', 'utf8');", + "const dotted = ['./results/b2/fifth.json'];", + "const cfg = { file: 'results/b2/sixth.json' };", + ].join('\n')), + 'results/b2/fourth.json': '{"pass": 4}\n', 'results/b2/fifth.json': '{"pass": 5}\n', 'results/b2/sixth.json': '{"pass": 6}\n', + 'lib/load.js': "module.exports = () => require('fs').readFileSync('wiki/b2/sessions.jsonl', 'utf8');\n", + 'test/reader.test.js': "const fixture = 'results/b2/third.json';\n", + }); + expect(r.kept.filter(k => k.path !== 'results/b2/run.json')).toEqual([ + { path: 'results/b2/fifth.json', reason: 'named-by-code' }, + { path: 'results/b2/fourth.json', reason: 'named-by-code' }, + { path: 'results/b2/other.json', reason: 'named-by-code' }, + { path: 'results/b2/sixth.json', reason: 'named-by-code' }, + { path: 'results/b2/third.json', reason: 'named-by-code' }, + { path: 'wiki/b2/sessions.jsonl', reason: 'named-by-code' }, + ]); + }, 120_000); + + // Value: protects=an array the contract test iterates (for-of, test.each) is examples, not the pinned list, and a bracket + // inside a comment does not make a call argument look like an array entry; fails_when=those paths are exempted and + // drop out of review; why_new=GST-3512 /ship second-model review of #4699 (lib/review-exclude.ts:412 and :409) + test('iterated example arrays and brackets in comments still keep the files they name', () => { + const r = repo({ + [CONTRACT]: [ + "import policy from '../../.gstack/ship-policy.json';", + "test('pins the list', () => expect(policy.review_exclude_paths).toEqual(['results/**', 'wiki/b2/sessions.jsonl']));", + "for (const p of ['results/b2/third.json']) test(p, () => {});", + "test.each([['results/b2/other.json']])('%s', () => {});", + "const raw = require('fs').readFileSync(/* [ */ 'wiki/b2/sessions.jsonl', 'utf8');", + ].join('\n') + '\n', + }); + expect(r).toEqual({ kept: [ + { path: 'results/b2/other.json', reason: 'named-by-code' }, + { path: 'results/b2/third.json', reason: 'named-by-code' }, + { path: 'wiki/b2/sessions.jsonl', reason: 'named-by-code' }, + ], excluded: 1 }); + }, 120_000); + + // Value: protects=a comment holding an unpaired '(' inside the pinned list does not hide that the entries are array + // entries; fails_when=the pin keeps its own excluded file; why_new=GST-3512 /ship second-model review of #4699 + // (lib/review-exclude.ts:409) + test('a comment inside the pinned list does not keep the pinned path', () => { + const r = repo({ + [CONTRACT]: [ + "import policy from '../../.gstack/ship-policy.json';", + "const PATTERNS = [ // pinned (see GST-3512", + " 'results/**', 'wiki/b2/sessions.jsonl',", + "];", + "test('pins the list', () => expect(policy.review_exclude_paths).toEqual(PATTERNS));", + ].join('\n') + '\n', + }); + expect(r).toEqual({ kept: [], excluded: 4 }); + }, 120_000); +});