Skip to content

Commit 9dea54e

Browse files
author
easonLiangWorldedtech
committed
fix(gate): align selection, source reads, and mutation to one tree; reject a partial stacked map
Two findings from the review at head: 1. Functional Correctness (major). The gate derived selectors from the pull request head tree while Stryker mutated the checkout, which is GitHub's merge commit. When main advanced a file the unit also changed, the two trees disagree on line numbers, so selectors could target the wrong code or miss the unit's changed lines. The ci command now aligns the working tree to the diff head before mutation runs, so selection, source reads, and mutation all see one tree. The new test advances a file on the base, merges, and asserts the tree used for mutation is the unit tree. 2. Functional Correctness (minor). parseStackedMap matched bracket groups and ignored trailing garbage, so a partially readable map could still select a parent base instead of the event-base fallback. It now consumes the whole stream of page arrays and returns [] when any part cannot be parsed. Also dropped the duplicated comment block above resolveCiInvocation. Local run: 51 tests pass.
1 parent a1a5fe9 commit 9dea54e

2 files changed

Lines changed: 84 additions & 9 deletions

File tree

‎scripts/stryker-diff.mjs‎

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,19 @@ export function resolveCiInvocation(repoRoot, eventBaseSha, mergeCommitSha, prHe
309309
return { baseSha: resolved.baseSha, diffHead: resolved.stackedOn ? prHeadSha : mergeCommitSha, stackedOn: resolved.stackedOn }
310310
}
311311

312+
// Selection, source reads, and Stryker must all see the same tree. The workflow checks out
313+
// GitHub's merge commit, which also carries whatever main advanced since the parent unit, so for
314+
// a stacked unit the working tree is moved to the unit head before mutation runs; otherwise the
315+
// selectors come from one tree and the mutated source comes from another.
316+
export function alignExecutionTree(repoRoot, diffHeadSha) {
317+
validateSha(diffHeadSha, "diff head SHA")
318+
const current = git(repoRoot, ["rev-parse", "HEAD"]).trim().toLowerCase()
319+
const wanted = String(diffHeadSha).toLowerCase()
320+
if (current === wanted) return false
321+
git(repoRoot, ["checkout", "--quiet", wanted])
322+
return true
323+
}
324+
312325
export function selectFromGit(repoRoot, baseSha, headSha, options = {}) {
313326
validateSha(baseSha, "base SHA")
314327
validateSha(headSha, "head SHA")
@@ -837,17 +850,44 @@ function argument(name) {
837850
// instead of throwing.
838851
export function parseStackedMap(value) {
839852
if (!value) return []
840-
const chunks = String(value).match(/\[[^\]]*\]/g) || [String(value)]
853+
// gh api --paginate emits one JSON array per page, so the input is a stream of arrays rather
854+
// than a single array. Consume the whole stream: if any part of it cannot be parsed, the map
855+
// is not trustworthy as a whole and the caller must fall back to the event base instead of
856+
// keeping a partial entry that could select a parent base.
857+
const text = String(value)
841858
const entries = []
842-
for (const chunk of chunks) {
859+
let index = 0
860+
while (index < text.length) {
861+
while (index < text.length && /[\s,]/.test(text[index])) index += 1
862+
if (index >= text.length) break
863+
if (text[index] !== "[") return []
864+
let depth = 0
865+
let inString = false
866+
let end = -1
867+
for (let i = index; i < text.length; i++) {
868+
const char = text[i]
869+
if (inString) {
870+
if (char === "\\") { i += 1; continue }
871+
if (char === "\"") inString = false
872+
continue
873+
}
874+
if (char === "\"") { inString = true; continue }
875+
if (char === "[") depth += 1
876+
else if (char === "]") {
877+
depth -= 1
878+
if (depth === 0) { end = i; break }
879+
}
880+
}
881+
if (depth !== 0 || end < 0) return []
843882
let parsed
844883
try {
845-
parsed = JSON.parse(chunk)
884+
parsed = JSON.parse(text.slice(index, end + 1))
846885
} catch {
847-
continue
886+
return []
848887
}
849-
if (!Array.isArray(parsed)) continue
888+
if (!Array.isArray(parsed)) return []
850889
entries.push(...parsed.filter((entry) => entry && entry.number && /^[0-9a-f]{40}$/i.test(String(entry.headSha))))
890+
index = end + 1
851891
}
852892
return entries
853893
}
@@ -867,10 +907,14 @@ function main() {
867907
const openPullRequests = parseStackedMap(argument("--stacked-map"))
868908
// --pr-head is the pull request head itself. The workflow runs on GitHub's merge commit, whose
869909
// first parent is the base tip, so the merge commit cannot identify the stacked unit; its second
870-
// parent can. The merge commit stays the diff head.
910+
// parent can. A plain pull request keeps the merge commit as the diff head; a stacked unit
911+
// uses its own head, and the working tree is aligned to that head below.
871912
const prHeadSha = argument("--pr-head") ?? headSha
872913
const invocation = resolveCiInvocation(repoRoot, baseSha, headSha, prHeadSha, openPullRequests)
873914
if (invocation.stackedOn) console.log(`Stacked unit: measured against the head of parent PR #${invocation.stackedOn}, not the event base.`)
915+
if (invocation.stackedOn && alignExecutionTree(repoRoot, invocation.diffHead)) {
916+
console.log(`Aligned the working tree to the diff head ${invocation.diffHead.slice(0, 12)} so selection, source reads, and mutation run on the same tree.`)
917+
}
874918

875919
const reportRoot = path.resolve(repoRoot, argument("--reports") ?? "reports/mutation")
876920
const manifest = {

‎scripts/stryker-diff.test.mjs‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
parseVitestTestFiles,
2727
preferDirectTestFiles,
2828
parseStackedMap,
29+
alignExecutionTree,
2930
resolveCiInvocation,
3031
resolveStackedUnitBase,
3132
resolveStrykerTempDir,
@@ -353,9 +354,10 @@ describe("stacked unit base resolution", () => {
353354
{ number: 2, headSha: "c".repeat(40) },
354355
],
355356
)
356-
assert.deepEqual(parseStackedMap("[{\"number\": 1, \"headSha\": \"" + "d".repeat(40) + "\"}]garbage"), [
357-
{ number: 1, headSha: "d".repeat(40) },
358-
])
357+
// Trailing content cannot be consumed as a page, so the whole map is rejected rather than
358+
// keeping a partial entry that could select a parent base.
359+
assert.deepEqual(parseStackedMap("[{\"number\": 1, \"headSha\": \"" + "d".repeat(40) + "\"}]garbage"), [])
360+
assert.deepEqual(parseStackedMap("[{\"number\": 1, \"headSha\": \"" + "d".repeat(40) + "\"}] [{\"number\": 2"), [])
359361
})
360362

361363
it("the ci command picks the diff head from the commit graph", () => {
@@ -405,6 +407,35 @@ describe("stacked unit base resolution", () => {
405407
fs.rmSync(repository, { recursive: true, force: true })
406408
}
407409
})
410+
411+
it("aligns the working tree to the diff head so selection and mutation see one tree", () => {
412+
const { repository, eventBaseSha, parentSha, childSha, run, write } = createSyntheticStack()
413+
414+
try {
415+
run("checkout", "--quiet", "-b", "merge-branch", eventBaseSha)
416+
// The base advance changes a file, so the merge tree differs from the unit tree. The
417+
// selectors are derived from the unit tree, so mutation has to run on that same tree.
418+
write("packages/core/src/unrelated.ts", "export const unrelated = () => 99\n")
419+
run("add", ".")
420+
run("commit", "--quiet", "-m", "base advance")
421+
const advancedBase = run("rev-parse", "HEAD")
422+
run("merge", "--no-ff", "--quiet", "-m", "merge", childSha)
423+
const mergeSha = run("rev-parse", "HEAD")
424+
425+
const invocation = resolveCiInvocation(repository, advancedBase, mergeSha, childSha, [{ number: 1, headSha: parentSha }])
426+
assert.equal(invocation.diffHead, childSha)
427+
assert.equal(run("rev-parse", "HEAD").toLowerCase(), mergeSha.toLowerCase())
428+
429+
assert.equal(alignExecutionTree(repository, invocation.diffHead), true)
430+
assert.equal(run("rev-parse", "HEAD").toLowerCase(), childSha.toLowerCase())
431+
// The tree Stryker would mutate is now the unit tree, not the merge tree.
432+
assert.equal(fs.readFileSync(path.join(repository, "packages/core/src/unit2.ts"), "utf8").replace(/\r/g, ""), "export const unit2 = () => 2\n")
433+
// Aligning again is a no-op.
434+
assert.equal(alignExecutionTree(repository, invocation.diffHead), false)
435+
} finally {
436+
fs.rmSync(repository, { recursive: true, force: true })
437+
}
438+
})
408439
})
409440

410441
describe("parseNameStatus", () => {

0 commit comments

Comments
 (0)