From 3cff6a47f619f6ba24c829ccdc724ff418ef55dd Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 03:45:47 -0800 Subject: [PATCH] Review keeps a file that a branch swaps from our own code to upstream bytes (GST-3298) (#4690) A branch that replaces your own file, or drops a local patch, so the file now matches an upstream copy byte for byte no longer leaves review: a changed file counts as vendored only if it was already vendored and verified at the merge base, or is new on the branch. This closes the gap the second-model review of #4665 found, so readers always see your own lines leave. Nothing to do for repos without `review_vendored`, which is every repo today. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p1/outside-voice#2 reader=outside-voice Review-Finding: p1/red-team#1 reader=red-team --- bin/gstack-vendored-verify | 33 ++++--- ...vendored-review-keeps-replaced-own-code.md | 1 + docs/vendored-code.md | 26 ++++-- lib/review-exclude.ts | 7 +- lib/review-vendored.ts | 73 ++++++++++++---- test/review-exclude-vendored.test.ts | 55 +++++++++++- test/review-vendored.test.ts | 87 ++++++++++++++++++- 7 files changed, 239 insertions(+), 43 deletions(-) create mode 100644 changelog.d/vendored-review-keeps-replaced-own-code.md diff --git a/bin/gstack-vendored-verify b/bin/gstack-vendored-verify index 6220f9403..95d063d61 100755 --- a/bin/gstack-vendored-verify +++ b/bin/gstack-vendored-verify @@ -8,7 +8,9 @@ * The allowlist and the manifest list come from the base branch's .gstack/ship-policy.json (review_vendored), never * from the head; the manifests themselves are read at HEAD. By default it checks the entries this branch changes * (files added, modified or deleted since the merge base, and entries whose pin the manifest diff changes); --all checks every - * entry. --offline answers from the cache an earlier run filled, without the network. A repo makes it a required CI + * entry. --offline answers from the cache an earlier run filled, without the network. It also checks the merge base's + * pins for the files this branch changes or deletes (VENDORED_BASE), so the review plan can answer offline for a modified + * or re-pinned file; that line never fails the run. A repo makes it a required CI * check: exit 1 means a manifest says something that is not true. Logic: lib/review-vendored.ts. */ import { spawnSync } from '../lib/spawn-sync'; @@ -62,6 +64,7 @@ if (!policy) { process.stdout.write(json ? JSON.stringify({ state: 'none' }) + ' const problems: string[] = []; const entries: VendoredEntry[] = []; const before = new Map(); +const prior: VendoredEntry[] = []; for (const m of policy.manifests) { const text = git(['show', `${head}:${m}`]); if (text === null) { problems.push(`${m} is not in HEAD`); continue; } @@ -69,30 +72,38 @@ for (const m of policy.manifests) { problems.push(...parsed.errors); entries.push(...parsed.entries); const old = git(['show', `${mergeBase}:${m}`]); - if (old !== null) for (const e of parseManifest(old, m).entries) before.set(e.path, `${e.upstream}@${e.commit}:${e.upstream_path}`); + if (old !== null) for (const e of parseManifest(old, m).entries) { before.set(e.path, `${e.upstream}@${e.commit}:${e.upstream_path}`); prior.push(e); } } const seen = new Map(); entries.forEach(e => seen.set(e.path.toLowerCase(), (seen.get(e.path.toLowerCase()) ?? 0) + 1)); for (const [p, n] of seen) if (n > 1) problems.push(`${p} is pinned by more than one manifest`); -let selected = entries; -if (!argv.includes('--all')) { - const diff = git(['diff', '--name-only', '-z', '--no-renames', '--diff-filter=ADMT', mergeBase, head]); - if (diff === null) { process.stderr.write(`${CTX}: git could not list the files this branch changes; fix: rerun once, then check the checkout (git status)\n`); process.exit(EXIT.refused); } - const changed = new Set(diff.split('\0').filter(Boolean)); - selected = entries.filter(e => changed.has(e.path) || before.get(e.path) !== `${e.upstream}@${e.commit}:${e.upstream_path}`); -} -const res = problems.length ? null : resolveVendored({ root, rev: head, policy, entries: selected, fetch: !argv.includes('--offline'), cacheRoot: vendoredCacheRoot(resolveStateRoot()) }); +const diff = git(['diff', '--name-only', '-z', '--no-renames', '--diff-filter=ADMT', mergeBase, head]); +if (diff === null) { process.stderr.write(`${CTX}: git could not list the files this branch changes; fix: rerun once, then check the checkout (git status)\n`); process.exit(EXIT.refused); } +const changed = new Set(diff.split('\0').filter(Boolean)); +const selected = argv.includes('--all') ? entries : entries.filter(e => changed.has(e.path) || before.get(e.path) !== `${e.upstream}@${e.commit}:${e.upstream_path}`); +const resolve = (rev: string, list: VendoredEntry[]) => resolveVendored({ root, rev, policy, entries: list, fetch: !argv.includes('--offline'), cacheRoot: vendoredCacheRoot(resolveStateRoot()), keepGood: true }); +const res = problems.length ? null : resolve(head, selected); +const baseList = prior.filter(e => changed.has(e.path)); +const baseSummary = ((): { checked: number; verified: number } | { error: string } | null => { + if (!res || !baseList.length) return null; + try { + const b = resolve(mergeBase, baseList); + return b ? { checked: b.entries.length, verified: b.entries.filter(e => e.verdict === 'verified').length } : null; + } catch (err) { return { error: (err instanceof Error ? err.message : String(err)).split('\n')[0]! }; } +})(); if (!problems.length && !res) { process.stderr.write(`${CTX}: git could not list HEAD's files; fix: rerun once, then check the checkout (git status)\n`); process.exit(EXIT.refused); } const failed = res?.entries.filter(e => e.verdict !== 'verified') ?? []; const summary = { scope: argv.includes('--all') ? 'all' : 'changed', manifests: policy.manifests.length, entries: entries.length, checked: res?.entries.length ?? 0, verified: (res?.entries.length ?? 0) - failed.length, failed: failed.length, pins: res?.pins.length ?? 0, digest: res?.digest ?? null }; if (json) { - process.stdout.write(JSON.stringify({ state: problems.length || failed.length ? 'failed' : 'verified', ...summary, manifest_errors: problems, pin_results: res?.pins ?? [], failures: failed }) + '\n'); + process.stdout.write(JSON.stringify({ state: problems.length || failed.length ? 'failed' : 'verified', ...summary, manifest_errors: problems, pin_results: res?.pins ?? [], failures: failed, ...(baseSummary ? { base: baseSummary } : {}) }) + '\n'); } else { for (const p of problems) process.stdout.write(resultLine(CTX, 'VENDORED_MANIFEST_INVALID', p) + '\n'); for (const p of res?.pins ?? []) process.stdout.write(`VENDORED_PIN: ${p.upstream}@${p.commit.slice(0, 12)} reachable_from=${p.reachable_from ?? 'none'} files=${p.files} verified=${p.verified}\n`); for (const f of failed.slice(0, 50)) process.stdout.write(resultLine(CTX, CODES[f.verdict as Exclude], `${f.path} <- ${f.upstream}@${f.commit.slice(0, 12)}:${f.upstream_path}${f.detail ? `; ${f.detail}` : ''}`) + '\n'); if (failed.length > 50) process.stdout.write(`VENDORED_VERIFY_FAILED: +${failed.length - 50} more (--json lists every one)\n`); + if (baseSummary && 'error' in baseSummary) process.stdout.write(`VENDORED_BASE: unavailable (${baseSummary.error}; this line never fails the run)\n`); + else if (baseSummary) process.stdout.write(`VENDORED_BASE: checked=${baseSummary.checked} verified=${baseSummary.verified} (the merge base's copies of the vendored files this branch changes or deletes; the review plan treats a modified file as vendored only when its base copy verified; this line never fails the run)\n`); process.stdout.write(problems.length ? `VENDORED_VERIFY: failed manifests=${policy.manifests.length} manifest_errors=${problems.length}\n` : `VENDORED_VERIFY: checked=${summary.checked} verified=${summary.verified} failed=${summary.failed} pins=${summary.pins} manifests=${summary.manifests} scope=${summary.scope} digest=${summary.digest}\n`); } diff --git a/changelog.d/vendored-review-keeps-replaced-own-code.md b/changelog.d/vendored-review-keeps-replaced-own-code.md new file mode 100644 index 000000000..7e89bd22c --- /dev/null +++ b/changelog.d/vendored-review-keeps-replaced-own-code.md @@ -0,0 +1 @@ +Review now keeps a file in view when a branch replaces your own code, or drops a local patch, so the file matches an upstream copy byte for byte. A changed file counts as vendored only if it was already vendored and verified at the merge base, or is new on the branch. `gstack-vendored-verify` also caches the merge base's pins for the files a branch changes or deletes, so later offline steps can answer, and a failed fetch no longer wipes earlier good answers from the cache (docs/vendored-code.md). diff --git a/docs/vendored-code.md b/docs/vendored-code.md index 889e01b07..f1b32561e 100644 --- a/docs/vendored-code.md +++ b/docs/vendored-code.md @@ -97,7 +97,9 @@ Every failure fails closed: the file is simply not vendored. - Paths are repo-relative, with no `..`, `.` or empty segment, no backslash, and no two entries that differ only in letter case. - A file listed here and edited locally fails the check. Remove it from the - manifest to have it reviewed as your own code instead. + manifest to have it reviewed as your own code instead. Putting the upstream + bytes back later passes the check, but review still reads that change, as + below. ## The command @@ -159,8 +161,12 @@ gate-tagged file is excerpted only off the gate floor, so a gate-tagged upstream test file (anything under `tests/`, `test/` or `spec/`) stays in review whole. When a re-pin deletes files, a deleted file that verifies at the base's pin can be left out too; a file the branch drops from the manifest but -keeps stays in review. A file that does not verify keeps the reason it had -before. Keep the manifest outside every `review_exclude_paths` pattern: when a +keeps stays in review. A file the branch modifies counts as vendored only when +the merge base's manifests already pinned it and its base copy verified too. +So a branch that replaces your own file with upstream bytes, or drops a local +patch from a vendored file, keeps that file in review as your code, and +readers see your lines leave. A file new on the branch needs only its own +check. A file that does not verify keeps the reason it had before. Keep the manifest outside every `review_exclude_paths` pattern: when a pattern matches it, nothing counts as verified and the plan prints `REVIEW_VENDORED: unavailable`. @@ -177,10 +183,16 @@ Every later step (the review dispatch, the receipt write and carry) reads the same cache without the network, and the verified list is part of the selection digest the receipt binds. A machine with an empty cache verifies nothing, so its selection differs and the receipt says so; run -`gstack-vendored-verify --base ` there first. Reviewers still read the -manifest, every pin change and all of the repo's own code. When unverified -vendored files make a pattern keep too many files, the refusal names them as -`REVIEW_VENDORED_KEPT` and points at `gstack-vendored-verify`. +`gstack-vendored-verify --base ` there first. It also caches the merge +base's pins for the files the branch changes or deletes (its `VENDORED_BASE:` +line, which never fails the run), since a modified or re-pinned file needs +them. A fetch that fails fails its own run but leaves the cache's earlier good +answers in place, so a later `gstack-vendored-verify --offline` still answers. +Review keeps those files until a fetch succeeds, so the plan and the receipt's +offline check select the same files. Reviewers still read +the manifest, every pin change and all of the repo's own code. When manifest +entries that don't count as vendored make a pattern keep too many files, the +refusal counts them and points at `gstack-vendored-verify`. How much this saves depends on the gate tags. On harness-evals#504 (1,056 upstream test files), 877 files and 4.47 MB leave review, but 161 gate-tagged diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index 7c893e0e5..d22128981 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -521,8 +521,9 @@ export function reviewExclude(i: ExcludeInput): Exclusion { const why = new Map(); for (const f of kept) why.set(reasons.get(f)!, (why.get(reasons.get(f)!) ?? 0) + 1); const top = [...why].sort((a, b) => b[1] - a[1]).map(([r, n]) => `${r}:${n}`).join(','); - const unverified = vsel ? ('error' in vsel ? kept.length : vsel.failed.filter(e => kept.includes(e.path)).length) : 0; - const vfix = unverified ? `${unverified} of them are vendored files that did not verify (gstack-review-plan lists them as REVIEW_VENDORED_KEPT); run gstack-vendored-verify --base ${base} and fix what it names, then rerun once; ` : ''; + const unverified = vsel && !('error' in vsel) ? vsel.failed.filter(e => kept.includes(e.path)).length : 0; + const vfix = vsel && 'error' in vsel ? `the vendored check could not run (${vsel.error}), so no matched file counts as vendored; run gstack-vendored-verify --base ${base} and fix what it names, then rerun once; ` + : unverified ? `${unverified} of them are manifest entries that do not count as vendored (they did not verify, or the merge base has them as our own code); run gstack-vendored-verify --base ${base} and fix what it names, then rerun once; ` : ''; return { state: 'refused', code: 'REVIEW_EXCLUDE_KEEP_TOO_LARGE', lines: [`${i.context}: review_exclude_paths pattern ${p} on ${source} keeps ${kept.length} matched files in review (${top}), and the command readers run to read them would need ${bytes} argument bytes (more than ${KEEP_ARG_MAX_BYTES}), so the pattern cannot be applied and is not dropped either; fix: ${vfix}when those files are published data, add a review_content_patterns entry for them beside the pattern on ${base} as its own PR (docs/ship-policy.md#review-content-patterns), else narrow the pattern or split the PR; nothing was planned (REVIEW_EXCLUDE_KEEP_TOO_LARGE)`] }; } applied.push(p); @@ -589,7 +590,7 @@ export function excludeLines(x: Exclusion, base: string): string[] { /** The one line every brief gets under an active exclusion; it names the selection digest the receipt binds (verify's REVIEW_EXCLUDE_RECORD). */ export function disclosureLine(r: Pick): string { - return `Excluded by base policy ${r.source} (selection ${r.digest}): ${r.excluded} files, ${r.excluded_bytes} bytes on this branch matching ${r.applied.join(' ') || 'no applied pattern'}. They are not in your diff; do not report on their absence. Kept despite a match: ${r.kept} files (listed in the plan).${r.vendored ? ` ${r.vendored} of the excluded files are vendored upstream files gstack verified byte for byte against the pins the base allowlists; the manifest that pins them is in your diff.` : ''}`; + return `Excluded by base policy ${r.source} (selection ${r.digest}): ${r.excluded} files, ${r.excluded_bytes} bytes on this branch matching ${r.applied.join(' ') || 'no applied pattern'}. They are not in your diff; do not report on their absence. Kept despite a match: ${r.kept} files (listed in the plan).${r.vendored ? ` ${r.vendored} of the excluded files are vendored upstream files gstack verified byte for byte against the pins the base allowlists, each one new on this branch or already vendored at the merge base; the plan's REVIEW_VENDORED_PIN lines name the pins.` : ''}`; } /** The selection digest a disclosure line names, or undefined. */ export const disclosureDigest = (line: string | undefined) => line?.match(/^Excluded by base policy \S+ \(selection ([0-9a-f]{64})\)/)?.[1]; diff --git a/lib/review-vendored.ts b/lib/review-vendored.ts index 0a6390d9a..ac067ff1f 100644 --- a/lib/review-vendored.ts +++ b/lib/review-vendored.ts @@ -163,7 +163,7 @@ function withLock(dir: string, fn: () => T): T { try { return fn(); } finally { fs.rmSync(lock, { force: true }); } } -interface PinCache { reachable_from: string | null; default_branch?: string; checked_at: number; tree: Record; error?: string } +interface PinCache { reachable_from: string | null; default_branch?: string; checked_at: number; tree: Record; error?: string; failed?: string } /** Whether a cached ref the commit sits on is one the current policy trusts: a tag, the default branch, or a branch the base names, never a merge-queue branch. */ function trustedHolder(ref: string, def: string | undefined, up: VendoredUpstream): boolean { @@ -185,11 +185,20 @@ function writePin(dir: string, commit: string, p: PinCache): void { /** * Fetch one upstream's reachability refs and each pin's trees into its cache and record, per pin, the ref that holds - * the commit and the mode and blob id of every upstream path asked for. A failed fetch is recorded as the pin's error. + * the commit and the mode and blob id of every upstream path asked for. A failed fetch is this run's error for each pin it + * covers. It is recorded as the pin's error when the cache holds no good record for it; a good record stays, marked with + * the failure (`failed`) until a later fetch succeeds, so gstack-vendored-verify --offline keeps answering from it while + * review selection keeps the pin's files, as the run that failed did. */ -function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map>, env: NodeJS.ProcessEnv): void { +function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map>, env: NodeJS.ProcessEnv): Map { const dir = path.join(cacheRoot, key(up.url)); fs.mkdirSync(dir, { recursive: true }); + const errors = new Map(); + const failPin = (commit: string, error: string, rec: PinCache) => { + errors.set(commit, error); + const prev = readPin(dir, commit); + writePin(dir, commit, prev?.reachable_from && !prev.error ? { ...prev, failed: error } : { ...rec, error }); + }; withLock(dir, () => { const genv = gitEnv(dir); const flags = remoteFlags(env); @@ -198,7 +207,7 @@ function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map { for (const c of pins.keys()) writePin(dir, c, { reachable_from: null, checked_at: Date.now(), tree: {}, error }); }; + const fail = (error: string) => { for (const c of pins.keys()) failPin(c, error, { reachable_from: null, checked_at: Date.now(), tree: {} }); }; const head = git(refs, [...flags, 'ls-remote', '--symref', url, 'HEAD', 'refs/heads/*'], genv, t); const def = /^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(head.out)?.[1]; if (!head.ok || !def) { fail(`could not read the default branch (${head.err.split('\n').pop() || 'no HEAD'})`); return; } @@ -214,9 +223,9 @@ function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map r && trustedHolder(r, def, up)) ?? null; if (!reachable_from) { writePin(dir, commit, { reachable_from: null, default_branch: def, checked_at: Date.now(), tree: {} }); continue; } const tf = git(trees, [...flags, 'fetch', '--quiet', '--no-tags', '--depth=1', '--filter=blob:none', url, commit], genv, t); - if (!tf.ok) { writePin(dir, commit, { reachable_from, default_branch: def, checked_at: Date.now(), tree: {}, error: `could not fetch the commit's trees (${tf.err.split('\n').pop()})` }); continue; } + if (!tf.ok) { failPin(commit, `could not fetch the commit's trees (${tf.err.split('\n').pop()})`, { reachable_from, default_branch: def, checked_at: Date.now(), tree: {} }); continue; } const ls = git(trees, ['ls-tree', '-r', '-z', '--full-tree', commit], genv); - if (!ls.ok) { writePin(dir, commit, { reachable_from, default_branch: def, checked_at: Date.now(), tree: {}, error: 'could not list the commit\'s tree' }); continue; } + if (!ls.ok) { failPin(commit, 'could not list the commit\'s tree', { reachable_from, default_branch: def, checked_at: Date.now(), tree: {} }); continue; } const all = new Map(); for (const rec of ls.out.split('\0')) { const m = /^(\d{6}) (?:blob|commit) ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(rec); if (m) all.set(m[3]!, [m[1]!, m[2]!]); } const prev = readPin(dir, commit); @@ -225,6 +234,7 @@ function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map(); + if (i.fetch) for (const [url, pins] of byUpstream) for (const [commit, error] of fetchUpstream(i.cacheRoot, allowed.get(url)!, pins, env)) fetchErrors.set(`${url}@${commit}`, error); const head = headBlobs(i.root, i.rev, i.entries); if (!head) return null; const results: EntryResult[] = i.entries.map(e => { const local = head.get(e.path); if (!allowed.has(e.upstream)) return { ...e, verdict: 'not-allowlisted' }; if (!local) return { ...e, verdict: 'absent-local' }; + const fetchError = fetchErrors.get(`${e.upstream}@${e.commit}`); + if (fetchError) return { ...e, verdict: 'fetch-failed', detail: fetchError }; const pin = readPin(path.join(i.cacheRoot, key(e.upstream)), e.commit); + if (pin?.failed && !i.keepGood) return { ...e, verdict: 'fetch-failed', detail: `the latest fetch failed (${pin.failed}); review keeps the file until a fetch succeeds` }; if (!pin || !(e.upstream_path in pin.tree) && !pin.error && pin.reachable_from) return { ...e, verdict: 'fetch-failed', detail: 'not in the cache; run gstack-vendored-verify' }; if (pin.error) return { ...e, verdict: 'fetch-failed', detail: pin.error }; if (!pin.reachable_from) return { ...e, verdict: 'unreachable' }; @@ -296,9 +312,12 @@ export interface VendoredSelection { verified: string[]; failed: EntryResult[]; /** * The verified vendored files among `changed`: entries of the head's manifests, checked at the head, and files the range - * deletes that the merge base's manifests list, checked at the merge base (a re-pin's old files). With no head (a live - * tree) the manifests and blobs come from HEAD, and a file the working tree or index changes is not verified. A manifest - * that is missing at the head, does not parse, or pins one path twice gives { error } and nothing is verified. + * deletes that the merge base's manifests list, checked at the merge base (a re-pin's old files). A head entry the merge + * base already has counts only when the base manifests pinned it there too and its base copy verifies, so a branch that + * swaps our own code (or a local patch) for upstream bytes keeps that removal in review; a file new on the branch needs + * only its head check. With no head (a live tree) the manifests and blobs come from HEAD, and a file the working tree or + * index changes is not verified. A manifest that is missing at the head, does not parse, or pins one path twice gives + * { error } and nothing is verified. */ export function vendoredSelection(i: { root: string; policy: VendoredPolicy; head?: string; mergeBase: string; changed: ReadonlySet; fetch: boolean; cacheRoot: string; env?: NodeJS.ProcessEnv }): VendoredSelection | { error: string } { const show = (rev: string, f: string) => { const r = spawnSync('git', ['show', `${rev}:${f}`], { cwd: i.root, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); return r.status === 0 ? r.stdout ?? '' : null; }; @@ -317,23 +336,41 @@ export function vendoredSelection(i: { root: string; policy: VendoredPolicy; hea const lower = new Set(); for (const e of now) { if (lower.has(e.path.toLowerCase())) return { error: `${e.path} is pinned more than once` }; lower.add(e.path.toLowerCase()); } const atHead = now.filter(e => i.changed.has(e.path)); + const missing = (at: string, paths: string[]): Set | null => { + if (!paths.length) return new Set(); + const r = spawnSync('git', ['cat-file', '--batch-check=%(objectname)'], { cwd: i.root, input: paths.map(p => `${at}:${p}\n`).join(''), encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); + if (r.status !== 0) return null; + const lines = (r.stdout ?? '').split('\n'); + return new Set(paths.filter((p, k) => lines[k] === `${at}:${p} missing`)); + }; const dropped = old.filter(e => i.changed.has(e.path) && !lower.has(e.path.toLowerCase()) && !e.path.includes('\n')); - const probe = dropped.length ? spawnSync('git', ['cat-file', '--batch-check=%(objectname)'], { cwd: i.root, input: dropped.map(e => `${rev}:${e.path}\n`).join(''), encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }) : null; - if (probe && probe.status !== 0) return { error: 'git could not check which vendored files the range deletes' }; - const probed = (probe?.stdout ?? '').split('\n'); - const gone = dropped.filter((e, k) => probed[k] === `${rev}:${e.path} missing` && (i.head || !fs.existsSync(path.join(i.root, e.path)))); + const deleted = missing(rev, dropped.map(e => e.path)); + const added = missing(i.mergeBase, atHead.filter(e => !e.path.includes('\n')).map(e => e.path)); + if (!deleted || !added) return { error: 'git could not check which vendored files the range adds or deletes' }; + const gone = dropped.filter(e => deleted.has(e.path) && (i.head || !fs.existsSync(path.join(i.root, e.path)))); + const oldByPath = new Map(old.map(e => [e.path, e])); + const modified = new Set(atHead.filter(e => !added.has(e.path)).map(e => e.path)); + const prior = [...modified].flatMap(p => oldByPath.get(p) ?? []); const head = resolveVendored({ root: i.root, rev, policy: i.policy, entries: atHead, fetch: i.fetch, cacheRoot: i.cacheRoot, env: i.env }); - const base = gone.length ? resolveVendored({ root: i.root, rev: i.mergeBase, policy: i.policy, entries: gone, fetch: i.fetch, cacheRoot: i.cacheRoot, env: i.env }) : { entries: [], pins: [], digest: '' }; + const base = gone.length || prior.length ? resolveVendored({ root: i.root, rev: i.mergeBase, policy: i.policy, entries: [...gone, ...prior], fetch: i.fetch, cacheRoot: i.cacheRoot, env: i.env }) : { entries: [], pins: [], digest: '' }; if (!head || !base) return { error: 'git could not list the vendored files' }; + const atBase = new Map(base.entries.filter(e => modified.has(e.path)).map(e => [e.path, e])); + const ours = (p: string): string | null => { + if (!modified.has(p)) return null; + const b = atBase.get(p); + if (!b) return 'the merge base has this file but its manifests do not pin it, so the branch replaces our own code; it stays in review'; + return b.verdict === 'verified' ? null : `its merge-base copy is not the upstream's file (${b.verdict}${b.detail ? `: ${b.detail}` : ''}), so the branch replaces our own code; it stays in review`; + }; const dirty = new Set(); if (!i.head) { const d = spawnSync('git', ['-c', 'core.quotePath=false', 'diff', '--name-only', '-z', '--no-renames', 'HEAD'], { cwd: i.root, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); if (d.status !== 0) return { error: 'git could not list the working tree changes' }; for (const f of (d.stdout ?? '').split('\0')) if (f) dirty.add(f); } - const all = [...head.entries, ...base.entries]; - const verified = all.filter(e => e.verdict === 'verified' && !dirty.has(e.path)).map(e => e.path).sort(); - const failed = all.filter(e => e.verdict !== 'verified' || dirty.has(e.path)).map(e => (e.verdict === 'verified' ? { ...e, verdict: 'mismatched' as const, detail: 'changed in the working tree' } : e)); + const all = [...head.entries, ...base.entries.filter(e => !modified.has(e.path))]; + const why = (e: EntryResult) => (e.verdict !== 'verified' ? null : dirty.has(e.path) ? 'changed in the working tree' : ours(e.path)); + const verified = all.filter(e => e.verdict === 'verified' && why(e) === null).map(e => e.path).sort(); + const failed = all.filter(e => e.verdict !== 'verified' || why(e) !== null).map(e => (e.verdict === 'verified' ? { ...e, verdict: 'mismatched' as const, detail: why(e)! } : e)); return { verified, failed, pins: [...head.pins, ...base.pins], digest: createHash('sha256').update(JSON.stringify(verified)).digest('hex') }; } diff --git a/test/review-exclude-vendored.test.ts b/test/review-exclude-vendored.test.ts index 5261874d0..da77adc36 100644 --- a/test/review-exclude-vendored.test.ts +++ b/test/review-exclude-vendored.test.ts @@ -10,6 +10,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { disclosureLine } from '../lib/review-exclude'; +import { vendoredCacheRoot, vendoredPolicy, vendoredSelection } from '../lib/review-vendored'; import { receiptReviewAtHead } from '../lib/ship-receipt-depth'; import { REVIEW_VENDORED_KEY_VERSION } from '../lib/ship-policy'; import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; @@ -149,6 +150,46 @@ describe('review_exclude_paths with review_vendored', () => { expect(x.vendored_selection.verified).toEqual([]); }); + // Value: protects=a branch that replaces our own file, or a locally patched vendored file, with verified upstream bytes + // keeps that file in review as code, so readers see our lines leave; a file new on the branch, or vendored at the merge + // base too (the re-pin test above), still leaves the diff; fails_when=a modified file is checked at the head only; + // why_new=/ship review of #4665 (outside-voice finding lib/review-vendored.ts:319), GST-3298 PR 3 + test('a branch that swaps our own file or a local patch for upstream bytes keeps it in review', () => { + const ours = fixture(); + ours.repo.git('checkout', '-q', 'main'); + commit(ours.repo, local({ 'tests/a.py': 'def test_a():\n assert check_signature()\n' }), 'our own test'); + ours.repo.git('push', '-q', 'origin', 'main'); + ours.repo.git('checkout', '-q', '-B', 'feat'); + commit(ours.repo, { ...local({ 'tests/a.py': A, 'tests/c.py': C }), 'VENDORED.json': manifest(ours.up.c2, ['tests/a.py', 'tests/c.py']) }, 'vendor lib over our test'); + expect(ours.plan(false).out).toContain('REVIEW_VENDORED_KEPT: mismatched up/lib/tests/a.py (the merge base has this file but its manifests do not pin it'); + const x = JSON.parse(ours.plan(true).out).review_exclude; + expect({ kept: x.kept_files, verified: x.vendored_selection.verified }).toEqual({ kept: [{ path: 'up/lib/tests/a.py', reason: 'code' }], verified: ['up/lib/tests/c.py'] }); + const patched = fixture(); + patched.repo.git('checkout', '-q', 'main'); + commit(patched.repo, { ...local({ 'tests/b.py': B1 + 'assert local_patch()\n' }), 'VENDORED.json': manifest(patched.up.c1, ['tests/b.py']) }, 'vendor lib with a local patch'); + patched.repo.git('push', '-q', 'origin', 'main'); + patched.repo.git('checkout', '-q', '-B', 'feat'); + commit(patched.repo, local({ 'tests/b.py': B1 }), 'drop the local patch'); + expect(patched.plan(false).out).toContain("REVIEW_VENDORED_KEPT: mismatched up/lib/tests/b.py (its merge-base copy is not the upstream's file (mismatched"); + expect(keptOf(patched.plan(true).out)).toEqual([{ path: 'up/lib/tests/b.py', reason: 'code' }]); + }); + + // Value: protects=a working-tree edit to a verified vendored file keeps it in review on a live-tree plan; fails_when=the + // committed blob's verdict covers uncommitted bytes; why_new=/ship review of #4665 (test gap lib/review-vendored.ts:330) + test('a working-tree edit to a verified vendored file keeps it in review', () => { + const f = fixture(); + commit(f.repo, { ...local({ 'tests/a.py': A, 'tests/b.py': B1 }), 'VENDORED.json': manifest(f.up.c1, ['tests/a.py', 'tests/b.py']) }, 'vendor lib'); + fs.writeFileSync(path.join(f.repo.work, 'up/lib/tests/b.py'), B1 + 'assert edited()\n'); + const mergeBase = f.repo.git('merge-base', 'origin/main', 'HEAD').trim(); + const sel = vendoredSelection({ + root: f.repo.work, policy: vendoredPolicy(JSON.parse(policy()))!, mergeBase, changed: new Set(['up/lib/tests/a.py', 'up/lib/tests/b.py', 'VENDORED.json']), fetch: true, + cacheRoot: vendoredCacheRoot(f.repo.env.GSTACK_STATE_ROOT), env: { ...process.env, ...f.repo.env, GSTACK_VENDORED_FETCH_ROOT: f.up.fetchRoot }, + }); + if ('error' in sel) throw new Error(sel.error); + expect(sel.verified).toEqual(['up/lib/tests/a.py']); + expect(sel.failed.map(e => [e.path, e.verdict, e.detail])).toEqual([['up/lib/tests/b.py', 'mismatched', 'changed in the working tree']]); + }); + // Value: protects=a manifest under an applied pattern turns the vendored check off, so the files it pins stay in review // whole and a hidden re-pin cannot hide them too; fails_when=files verify against a manifest readers cannot see; // why_new=/ship review of #4665 (red-team finding lib/review-exclude.ts:483) @@ -169,6 +210,7 @@ describe('review_exclude_paths with review_vendored', () => { expect(x.kept_files).toEqual([{ path: 'up/lib/tests/data.json', reason: 'named-by-code' }]); expect(x.vendored).toBe(1); expect(disclosureLine(x)).toContain(' 1 of the excluded files are vendored upstream files'); + expect(disclosureLine(x)).not.toContain('is in your diff'); }); // Value: protects=a repo without review_vendored plans exactly as before: the same files kept as code, no vendored line and @@ -184,8 +226,9 @@ describe('review_exclude_paths with review_vendored', () => { expect(x.vendored_selection).toBeUndefined(); }); - // Value: protects=too many unverified vendored files refuse with a fix that names REVIEW_VENDORED_KEPT and the verify - // command instead of the review_content_patterns fix; fails_when=the old fix is printed; why_new=GST-3298 plan F1 + // Value: protects=too many unverified vendored files refuse with a fix that names the verify command, never lines a + // refused plan does not print, and a vendored check that could not run says so instead of counting every kept file as + // vendored; fails_when=the old fix is printed; why_new=GST-3298 plan F1, /ship review of #4665 (lib/review-exclude.ts:524) test('a keep-too-large refusal over unverified vendored files names the verify command', () => { const f = fixture(); const many: Record = {}; @@ -194,6 +237,12 @@ describe('review_exclude_paths with review_vendored', () => { commit(f.repo, { ...local({ ...many, 'tests/a.py': A }), 'VENDORED.json': manifest(f.up.c1, [...names, 'tests/a.py']) }, 'vendor lib'); const r = f.plan(false); expect(r.out + r.err).toContain('REVIEW_EXCLUDE_KEEP_TOO_LARGE'); - expect(r.out + r.err).toContain('330 of them are vendored files that did not verify (gstack-review-plan lists them as REVIEW_VENDORED_KEPT); run gstack-vendored-verify --base main'); + expect(r.out + r.err).toContain('330 of them are manifest entries that do not count as vendored (they did not verify, or the merge base has them as our own code); run gstack-vendored-verify --base main'); + expect(r.out + r.err).not.toContain('REVIEW_VENDORED_KEPT'); + const hidden = fixture(true, 'up/VENDORED.json'); + commit(hidden.repo, { ...local(many), 'up/VENDORED.json': manifest(hidden.up.c1, names) }, 'vendor lib'); + const h = hidden.plan(false); + expect(h.out + h.err).toContain('the vendored check could not run (up/VENDORED.json matches review_exclude_paths'); + expect(h.out + h.err).not.toContain('of them are manifest entries'); }); }); diff --git a/test/review-vendored.test.ts b/test/review-vendored.test.ts index c100ca49e..e8e410600 100644 --- a/test/review-vendored.test.ts +++ b/test/review-vendored.test.ts @@ -11,7 +11,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { bunIsolationArgs } from '../lib/bun-isolation'; import { REVIEW_VENDORED_KEY_VERSION, finish } from '../lib/ship-policy'; -import { parseManifest, pathProblem, vendoredErrors } from '../lib/review-vendored'; +import { parseManifest, pathProblem, vendoredCacheRoot, vendoredErrors, vendoredPolicy, vendoredSelection } from '../lib/review-vendored'; import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; setDefaultTimeout(60_000); @@ -268,6 +268,91 @@ describe('branch globs, missing branches, gitlinks and --json', () => { expect(outOf(m)).toContain('reachable_from=heads/release/2'); expect(m.status).toBe(0); }); + // Value: protects=a branch the upstream deletes stops vouching for its commits: the cached ref goes, online and then + // offline; fails_when=a stale cached branch keeps a commit reachable; why_new=/ship review of #4665 (test gap + // lib/review-vendored.ts:207 for the update-ref -d cleanup) + test('a named branch the upstream deletes drops its cached ref, online and offline', () => { + const c = consumer({ policy: policy([{ url: UP, branches: ['release/2'] }]) }); + commit(c.repo, { 'vendor/lib/tests/a.py': A + '# rel\n', 'vendor/MANIFEST.json': manifest([{ commit: c.up.release, files: ['tests/a.py'] }]) }, 'pin'); + expect(outOf(c.verify())).toContain('reachable_from=heads/release/2'); + run(c.up.work, ['push', '-q', c.up.bare, ':refs/heads/release/2'], c.upEnv); + for (const args of [['--base', 'main'], ['--base', 'main', '--offline']]) { + const r = c.verify(args); + expect(outOf(r)).toContain('(VENDORED_UNREACHABLE)'); + expect(r.status).toBe(1); + } + }); + // Value: protects=a fetch that fails after a good one fails this run but leaves the good cached pins, so a later offline + // check still answers; fails_when=the failure overwrites the cache; why_new=/ship review of #4665 (deferred finding + // lib/review-vendored.ts:201) + test('a failed fetch fails its own run and keeps the good cached pins', () => { + const c = consumer(); + expect(c.verify().status).toBe(0); + fs.renameSync(c.up.bare, `${c.up.bare}.away`); + const down = c.verify(); + expect(outOf(down)).toContain('(VENDORED_FETCH_FAILED)'); + expect(down.status).toBe(1); + const offline = c.verify(['--base', 'main', '--offline']); + expect(outOf(offline)).toMatch(/checked=2 verified=2 failed=0/); + expect(offline.status).toBe(0); + }); + // Value: protects=after a failed fetch the review plan and every later offline step select the same files, so the + // receipt's offline recompute matches the plan's digest, while gstack-vendored-verify --offline still answers from the + // good pins; fails_when=the offline selection counts a file the plan kept; why_new=/ship review of #4690 + // (lib/review-vendored.ts:278) + test('after a failed fetch the online and offline selections agree until a fetch succeeds', () => { + const c = consumer(); + expect(c.verify().status).toBe(0); + const both = ['vendor/lib/tests/a.py', 'vendor/lib/tests/b.py']; + const select = (fetch: boolean) => { + const sel = vendoredSelection({ root: c.repo.work, policy: vendoredPolicy(JSON.parse(policy()))!, head: c.repo.git('rev-parse', 'HEAD').trim(), mergeBase: c.repo.git('merge-base', 'origin/main', 'HEAD').trim(), changed: new Set(both), fetch, cacheRoot: vendoredCacheRoot(c.repo.env.GSTACK_STATE_ROOT), env: { ...process.env, ...c.repo.env, GSTACK_VENDORED_FETCH_ROOT: c.fetchRoot } }); + return 'error' in sel ? sel.error : sel.verified; + }; + fs.renameSync(c.up.bare, `${c.up.bare}.away`); + expect(select(true)).toEqual([]); + expect(select(false)).toEqual([]); + expect(c.verify(['--base', 'main', '--offline']).status).toBe(0); + fs.renameSync(`${c.up.bare}.away`, c.up.bare); + expect(select(true)).toEqual(both); + expect(select(false)).toEqual(both); + }); + // Value: protects=the merge-base pin check never fails verify, even when it throws: a deletion-only re-pin whose old pin + // cannot be cached still passes on its head result; fails_when=the base check's error exits nonzero; why_new=/ship review + // of #4690 (bin/gstack-vendored-verify:88) + test('a merge-base check that cannot run reports itself and leaves the head verdict alone', () => { + const c = consumer(); + c.repo.git('checkout', '-q', 'main'); + c.repo.git('merge', '-q', '--ff-only', 'feat'); + c.repo.git('push', '-q', 'origin', 'main'); + c.repo.git('checkout', '-q', 'feat'); + commit(c.repo, { 'vendor/lib/tests/b.py': null, 'vendor/MANIFEST.json': manifest([{ commit: c.up.c1, files: ['tests/a.py'] }]) }, 'drop b'); + const blocked = path.join(c.repo.root, 'blocked'); + fs.mkdirSync(blocked); + fs.writeFileSync(path.join(blocked, 'vendored-cache'), 'not a directory\n'); + const r = c.verify(['--base', 'main'], { GSTACK_STATE_ROOT: blocked, GSTACK_HOME: blocked, GSTACK_STATE_DIR: blocked }); + expect(outOf(r)).toContain('VENDORED_BASE: unavailable ('); + expect(outOf(r)).toContain('VENDORED_VERIFY: checked=0 verified=0 failed=0'); + expect(r.status).toBe(0); + }); + // Value: protects=verify also caches the merge base's pin for a re-pinned file, so the review plan answers offline on a + // clean machine and keeps treating the file as vendored; fails_when=the old pin stays cold and the offline selection + // keeps the file; why_new=GST-3298 PR 3 (a modified file counts only when its base copy verified) + test('verify caches the merge base pins a re-pin needs for an offline selection', () => { + const c = consumer(); + c.repo.git('checkout', '-q', 'main'); + c.repo.git('merge', '-q', '--ff-only', 'feat'); + c.repo.git('push', '-q', 'origin', 'main'); + c.repo.git('checkout', '-q', 'feat'); + commit(c.repo, { 'vendor/lib/tests/b.py': B2, 'vendor/MANIFEST.json': manifest([{ commit: c.up.c2, files: ['tests/a.py', 'tests/b.py'] }]) }, 'repin'); + const cold = path.join(c.repo.root, 'cold'); + const coldEnv = { GSTACK_STATE_ROOT: cold, GSTACK_HOME: cold, GSTACK_STATE_DIR: cold }; + const r = c.verify(['--base', 'main'], coldEnv); + expect(outOf(r)).toContain('VENDORED_BASE: checked=1 verified=1'); + expect(r.status).toBe(0); + const mergeBase = c.repo.git('merge-base', 'origin/main', 'HEAD').trim(); + const sel = vendoredSelection({ root: c.repo.work, policy: vendoredPolicy(JSON.parse(policy()))!, head: c.repo.git('rev-parse', 'HEAD').trim(), mergeBase, changed: new Set(['vendor/lib/tests/b.py']), fetch: false, cacheRoot: vendoredCacheRoot(cold) }); + expect('error' in sel ? sel.error : sel.verified).toEqual(['vendor/lib/tests/b.py']); + }); test('an upstream gitlink is VENDORED_MODE, and --json keeps the pin count beside the pin rows', () => { const c = consumer(); run(c.up.work, ['update-index', '--add', '--cacheinfo', `160000,${c.up.c1},tests/sub`], c.upEnv);