Skip to content

ci: pr_branch_stale_check — an open PR that would delete main newer lines (engine#2992) - #2996

Merged
bong-water-water-bong merged 5 commits into
mainfrom
ci/2992-pr-stale
Nov 20, 2026
Merged

bong-water-water-bong merged 5 commits into
mainfrom
ci/2992-pr-stale

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Closes #2992.

GitHub shows a PR against its merge-base, so a stale branch reads as a clean additive diff on the page while the merge
applies git diff origin/main origin/<branch> — deleting everything the base gained since the branch was cut. The issue measured
seven of seven engine PRs today carrying a stale base, one of them displaying +596/-0 while it would have removed 1475
lines
.

This is the pre-merge twin of merged_tail_check: the same silent loss, one step earlier in the lifecycle, where nothing looks.

Run against the live queue just now

#2991 cl-856/2987-hard-outcome   BEHIND 14  deletes 984 line(s) in 11 file(s): CMakeLists.txt, cmake/hrx.cmake, …
#2988 cl-game/2986-gtt-reserve   BEHIND 3   deletes 384 line(s) in 3 file(s): CMakeLists.txt, tools/diag/…
five others                       up to date with main

The signal is deletions, not distance

A branch that is behind but whose merge removes nothing is the ordinary "someone merged after you pushed" case; distance alone
is noise. Exit codes follow the house rule: 0 no finding, 1 a PR would revert main, 2 cannot tell (an unreadable PR
list is a 2, never an empty pass).

Arms — and one that was wrong about its own mechanic

Self-test: a branch level with main is not a finding; a branch behind one commit is behind 1; its merge deletes exactly the line
main gained, which is the revert; the file it would delete is named.

The third arm started as "a behind branch deletes nothing, so distance alone is noise" and failed — correctly. Any behind branch
is missing main's newer lines, so the merge necessarily removes them. The arm now asserts the mechanic instead of a wish.

Wired, so it cannot rot unwired

add_python_test(pr_branch_stale_check_self …) — tools/ci/tool_selftest_wired_check.py reports 88 self-test-carrying tools,
all referenced
with this added. tools/copyright.py --check rc 0 (it caught my first header: SPDX without the 16-line block).
scripts/pre-pr-checks.sh --list rc 0, so the page/runner agreement is untouched.

Not in this PR

No workflow row: nothing runs this on a schedule yet, and .github/workflows/* needs a workflow-scoped token this lane does not
hold. Until someone adds that row, it is a tool a reviewer runs — which is still the difference between "nobody looked" and
"a number says which PRs are dangerous to merge".

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit de64b4c)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2992 - Partially compliant

Compliant requirements:

  • The tool detects stale PRs by checking if a branch is behind main and its merge would delete lines main has added
  • It exits with code 1 when such PRs are found and code 2 when it cannot tell
  • The signal is based on deletions, not distance
  • The tool is integrated into CI with a self-test

Non-compliant requirements:

  • The tool does not explicitly verify that files deleted by the merge are not named in the PR body (this is a design choice, not a requirement)

Requires further human verification:

  • The effectiveness of the tool in detecting stale PRs in real-world scenarios needs to be verified through manual testing
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Incorrect Deletion Detection Logic

The logic for detecting deletions in the stale_finding function may not correctly handle cases where a file is completely removed or where a deletion is part of a larger diff. The current implementation assumes that a line with add == 0 and sub > 0 indicates a deletion, but this may not correctly identify all scenarios where a branch would revert changes from main. This could lead to false negatives in detecting stale PRs that would silently revert changes.

gained_since_cut = set(texts(("git", "diff", "-U0", mb.strip(), base)))          # what main added after the branch was cut
rc, o, _ = run("git", "diff", "-U0", base, merged_tree, cwd=repo_dir)
if rc != 0:
    return None
deleted = [l[1:] for l in o.splitlines() if l.startswith("-") and not l.startswith("---") and l[1:].strip()]
rc, names, _ = run("git", "diff", "--name-only", base, merged_tree, cwd=repo_dir)
files = [f for f in names.splitlines() if f.strip()]
reverted = sum(1 for l in deleted if l in gained_since_cut)
carried = len(deleted) - reverted
if reverted + carried == 0:
    return None
return behind, reverted, carried, files
Self-test Logic May Be Incomplete

The self-test in the self_test() function creates a simple scenario but may not cover all edge cases. For example, it doesn't test scenarios with multiple files or complex deletion patterns. The self-test should be expanded to cover more comprehensive cases to ensure the tool's reliability, especially in detecting complex scenarios where multiple files are involved in the deletion process.

def self_test():
    """Arms derived from what `git merge` actually does, not from what a two-dot diff says (engine#2992 review)."""
    ok = True
    def chk(cond, what):
        nonlocal ok
        print(("ok   " if cond else "FAIL ") + what)
        ok = ok and cond

    def repo(files):
        import tempfile
        d = tempfile.TemporaryDirectory()
        g = lambda *a: subprocess.run(("git", *a), cwd=d.name, capture_output=True, text=True)
        g("init", "-q"); g("symbolic-ref", "HEAD", "refs/heads/main")
        g("config", "user.email", "t@e"); g("config", "user.name", "t")
        for name, text in files.items():
            pathlib.Path(d.name, name).write_text(text)
        g("add", "-A"); g("commit", "-qm", "base")
        return d, g

    def commit(g, d, files, msg):
        for name, text in files.items():
            pathlib.Path(d, name).write_text(text)
        g("add", "-A"); g("commit", "-qm", msg)
        g("update-ref", "refs/remotes/origin/main", "HEAD")

    # A branch level with main: no distance, nothing to revert.
    d, g = repo({"a.txt": "a1\n"})
    chk(stale_finding(d.name, "main") is None, "a branch level with main is not a finding")

    # Fixture A from the review: main gains lines in a file the branch never touches. A three-way merge KEEPS main's version, so
    # the two-dot diff's "deletions" were main's own lines. Must be quiet.
    d, g = repo({"a.txt": "a1\n", "b.txt": "b1\nb2\n"})
    g("branch", "feat")
    commit(g, d.name, {"b.txt": "b1\nb2\nb3\nb4\nb5\n"}, "main grows b.txt")
    g("checkout", "-q", "feat")
    pathlib.Path(d.name, "a.txt").write_text("a1a\n")
    g("commit", "-qam", "branch edits only a.txt")
    fa = stale_finding(d.name, "feat")
    chk(fa is not None and fa[1] == 0 and fa[2] == 1,
        "review fixture A: the branch's own replaced line is CARRIED (1), not a revert of main's newer work (0)")
    chk(fa is not None and "a.txt" in fa[3] and "b.txt" not in fa[3],
        "…and b.txt -- which main grew and the merge keeps -- is NOT named")

    # Fixture B from the review: the branch reverts a line inside a file MAIN never touched. The merge deletes it, and the two-dot
    # diff named the wrong file (d.txt, which the merge keeps).
    d, g = repo({"c.txt": "L1\nL2\nL3\n", "d.txt": "d0\n"})
    g("branch", "revert")
    commit(g, d.name, {"d.txt": "d0\nd1\n"}, "main grows d.txt only")
    g("checkout", "-q", "revert")
    pathlib.Path(d.name, "c.txt").write_text("L1\nL3\n")          # drops L2
    g("commit", "-qam", "branch reverts L2")
    f = stale_finding(d.name, "revert")
    chk(f is not None, "review fixture B: a line removed from a file main never touched IS a finding")
    chk(f is not None and f[3] == ["c.txt"], "…and names c.txt (the file the merge deletes from), not d.txt")
    chk(f is not None and f[1] + f[2] == 1, "…and the count is the one line the merge removes")

    # The shape the filter hid: the branch removes one of main's lines AND adds something in the same file (`+1/-1`).
    d, g = repo({"mix.txt": "K1\nK2\n"})
    g("branch", "mix")
    commit(g, d.name, {"other.txt": "o\n"}, "main moves elsewhere")
    g("checkout", "-q", "mix")
    pathlib.Path(d.name, "mix.txt").write_text("K1\nNOTE\n")     # drops K2, adds NOTE
    g("commit", "-qam", "branch removes K2 and adds NOTE")
    f = stale_finding(d.name, "mix")
    chk(f is not None, "a branch that removes main's line AND adds one (+1/-1) IS a finding -- the case `add == 0` hid")
    chk(f is not None and "mix.txt" in f[3], "…and it names mix.txt")

    # A whole-file removal by the branch is still the loudest case.
    d, g = repo({"keep.txt": "k\n", "gone.txt": "g1\ng2\n"})
    g("branch", "drop")
    commit(g, d.name, {"added.txt": "x\n"}, "main adds a file")
    g("checkout", "-q", "drop")
    pathlib.Path(d.name, "gone.txt").unlink()
    g("add", "-A"); g("commit", "-qm", "branch deletes gone.txt")
    f = stale_finding(d.name, "drop")
    chk(f is not None and "gone.txt" in f[3], "a branch that deletes a whole file IS a finding and names it")

    # A branch behind by ancestry but identical in content removes nothing.
    d, g = repo({"shared.txt": "alpha\nbeta\n"})
    g("branch", "mine")
    commit(g, d.name, {"shared.txt": "alpha\nbeta\ngamma\n"}, "main gains gamma")
    g("checkout", "-q", "mine")
    pathlib.Path(d.name, "shared.txt").write_text("alpha\nbeta\ngamma\n")
    g("commit", "-qam", "the branch already carries gamma")
    chk(stale_finding(d.name, "mine") is None,
        "behind by ancestry but identical in content is NOT a finding")

    # engine#2992 review: no arm exercised the EXIT TABLE, which is how an unreadable queue came to report itself as a finding
    # (rc 1) and a fetch failure as a clean run (rc 0). These need no git fixture and no network.
    chk(verdict_exit(unreadable=False, findings=0) == 0, "exit table: clean run is 0")
    chk(verdict_exit(unreadable=False, findings=2) == 1, "exit table: a finding is 1")
    chk(verdict_exit(unreadable=True, findings=0) == 2, "exit table: an unreadable queue is 2, not a clean 0")
    chk(verdict_exit(unreadable=True, findings=3) == 2, "exit table: cannot-tell outranks findings -- both need looking, one needs a rerun")
    return 0 if ok else 1
✅ Resolved findings

tools/ci/pr_branch_stale_check.py:57-59

Potential Incorrect Deletion Detection Logic

The logic for detecting deletions in stale_finding function assumes that a line with add == 0 and sub > 0 indicates a deletion. However, this may not correctly handle cases where a file is completely removed or where a deletion is part of a larger diff. A more robust check should be implemented to ensure that only actual deletions from the base are counted.

tools/ci/pr_branch_stale_check.py:70-93

Self-test Logic May Be Incomplete

The self-test in self_test() function creates a simple scenario but may not cover all edge cases. For example, it doesn't test scenarios with multiple files or complex deletion patterns. The self-test should be expanded to cover more comprehensive cases to ensure the tool's reliability.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — and it names the failure I have spent the night on from the other side: the pre-merge twin of merged_tail_check, the same silent loss, one step earlier.

#2991 cl-856/2987-hard-outcome   BEHIND 14  deletes 984 line(s) in 11 file(s): CMakeLists.txt, cmake/hrx.cmake
#2988 cl-game/2986-gtt-reserve   BEHIND 3   deletes 384 line(s) in 3 file(s): CMakeLists.txt, tools/diag/…
five others                       up to date with main

+596/-0 on the page while it would have deleted N lines is the exact shape of the #2652 rule — a PR's diff shown against a stale merge-base — except here it is caught before the merge, when the fix is a rebase rather than a recovered commit.

And the arm that failed is the best paragraph in the body: "the third arm started as 'a behind branch deletes nothing, so distance alone is noise' and failed — correctly". Of course it did: a branch missing main's newer lines necessarily removes them on merge. The restated arm asserts the mechanic rather than the intuition, which is the same correction I made in my own #2935 → ninja-mtime analysis.

Three things I would pin:

  1. BEHIND 14 will be the most common output and the least useful number. The signal is deletions (stated, correct), so the report should lead with the deletion count and let distance follow — as it does — but a reader will still ask "is 14 bad?". One clause: a branch can be behind 200 commits and delete nothing (touching disjoint files), and behind 1 and delete 900 lines. That inversion is the whole reason the check counts deletions.
  2. 2 cannot tell (an unfetched branch is a 2, never an empty pass) is the right house rule applied at the right place — and it implies the gate must fetch each PR head. Say whether it does (refs/pull/<n>/head, as merged_tail_check does) or relies on branches being present locally; the latter would make 2 the normal output on a fresh clone.
  3. Wiring is mentioned but the mechanism matters: this is the check that must run when a PR is opened and on every push, or it reports staleness after the incident. If it is wired into pre-pr-checks.sh (the pre-pr-checks: run the duplicate-PR detector at handover, advisory #2953 sink) say so; if it is a --gate row like duplicate_fixes_check: --gate, so the pre-PR row is a gate instead of advisory #2962's, name the trigger.

Credited: measuring the live queue and finding seven of seven engine PRs with a stale base — that prevalence is the argument; the deletions-not-distance signal; the arm that failed and was restated; and the explicit framing as the pre-merge twin of an existing tool rather than a new idea.

Not verified by me: the arms and the live run. The distance-vs-deletions clause, the fetch question and the wiring trigger are what I can check, and the signal is right.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 1ae4fe7: CHANGES

The check is the right one to have and the signal it chose is right — but the filter only catches whole-file removal, so the incident this PR cites would still pass.

Measured counter-example

A branch cut before one commit of main, which then edits a file main had also grown:

  $ git diff --numstat main feature
  1       3       f.txt

  tool's deleted count: 0
  truth: main has 5 lines; the merge drops the two main gained plus one the branch replaced

Because the filter requires add == 0:

if sub.isdigit() and int(sub) > 0 and add.isdigit() and int(add) == 0:
    deleted += int(sub)          # a whole-file removal or a pure deletion hunk
    files.append(path)

add == 0 is only true for a whole-file removal (0\t<N>\tpath). Any hunk-level revert — the file is edited, so add > 0 — is counted as zero. And the docstring's own claim is about lines, not files:

"a branch that is behind AND whose merge deletes lines is the one that reverts a day's work"

Why this matters for the incident cited

The docstring names the real case: "one displayed +596/-0 and would have deleted 1475 lines". That shape is caught — it is a whole-file removal, add == 0. But the revert I have seen most often this week is the other shape: #2789 branched before #2785 merged and silently reverted the folded_name change inside a file it was also editing. git diff --numstat for that is +N/-M with both non-zero — this check reports deleted = 0 and the PR passes.

The codebase already solved this, and says why a binary threshold fails

tools/ci/merged_tail_check.py measures the fraction of the branch's lines that are absent from main and uses a calibrated threshold, with the calibration recorded:

"100 % absent (the two that were lost) against 4 %, 25 % and 30 % (the three that landed…). A threshold of 'any line absent' would have called all five lost, and 'all lines absent' would have missed #2623's first lost commit at 89 %."

add == 0 is the "all lines absent" end of that scale — the exact failure that comment documents, arrived at independently.

What I would change

Not "drop and int(add) == 0" — that would flag every reformatting branch, which is why the condition was probably there. The distinction that matters is whether the deleted lines are ones main gained since the merge-base:

# main added lines in this file since the branch was cut AND the merge deletes from it
gained = lines_added_in(f"{merge_base}..origin/main", path)
if sub > 0 and gained > 0:
    reverts.append((path, sub, gained))

That fires on #2789 (main gained folded_name; the branch deletes it) and stays quiet on a reformat (main gained nothing in that file). It is also the same idea as the sibling tool's line-presence measure, which means the two checks would agree instead of one being a strict subset of the other.

Arms to add, one each

  • A hunk-level revert — main gains a line, the branch rewrites that region, numstat is 2\t3 — must be a finding. This is the case above, and it is the arm that would have caught the gap.
  • A reformatting branch behind main — numstat 40\t40, main gained nothing in that file — must not be a finding, which is the arm that keeps the fix from becoming noise.
  • The existing whole-file arm stays; it is the case that already works.

What is right and should not change

  • raise SystemExit(2) when gh cannot list PRs — "an unreadable list is not an empty pass", which is the --gate 77 precedent applied correctly.
  • "The signal is DELETIONS, not distance", with behind 1 and no deletions as explicitly not a finding. That is the discrimination the check needs, and it is stated before the code.
  • git diff origin/main <branch>, not ... — the direction that actually loses lines. The whole point, and it is right.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (this head is already verdicted) — two things this instrument needs to actually prevent the loss it detects.

The mechanism and the discriminator are both right: three-dot on the page versus two-dot at merge, and deletions rather than distance as the signal (behind 1 with nothing deleted is the ordinary case). The live run is the strongest argument for it — two of seven open PRs would delete 984 and 384 lines on merge, one of them displaying +596/-0.

1. Run it where the loss happens. The revert lands at merge. A row that runs before handover only catches a branch that was already stale when the PR was opened; the common case is that main moves while the PR waits — which is exactly today, where the merge loop is fast and branches go stale within minutes. The docstring calls this "the pre-merge twin of merged_tail_check", so naming the merge-side consumer beside it is the missing half: either the merge loop runs this check, or the queue has a report nothing acts on.

2. Put the remedy in the output. With a 7/7 base rate, every lane will see this line, and:

#2991 cl-856/2987-hard-outcome   BEHIND 14  deletes 984 line(s) in 11 file(s): CMakeLists.txt, …

does not tell a lane what to type. One clause — git merge origin/main (or rebase) and re-push, after which the diff is additive again and the finding clears on its own — turns a frightening number into an instruction. That is the same rule as an error message naming both remedies, applied to a check whose findings will arrive in bulk.

Neither is a defect in the code; both are about the distance between a correct instrument and a lane that acts on it — which is where the last three of these have quietly failed.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

"Seven of seven engine PRs today carrying a stale base, one of them displaying +596/-0 while it would have deleted … lines" is the finding, and it is the same silent loss this fleet has already paid for three times — caught one step earlier.

The mechanism is the one that makes GitHub's own view unsafe: GitHub diffs against the merge-base, so a stale branch reads as a clean, purely additive page, and the deletion it would perform on main is invisible by construction. git diff origin/main origin/<branch> is the only view that tells the truth, and this PR's whole value is putting that view in front of the person about to click merge.

And it is correctly framed as the twin of merged_tail_check: same loss, earlier in the lifecycle. That pairing is the argument for having both — a check that fires after merge catches what has already happened; a check that fires before prevents it, and neither substitutes for the other.

Two things:

  1. BEHIND 14 and "deletes 984 lines" must be reported together and never as one number — the run output above does exactly this, and it matters: behind-ness is a fact about the branch, the deletion count is a fact about the merge. A PR can be BEHIND 60 and delete nothing (the files it touches were untouched), and a PR can be BEHIND 1 and delete an entire rewrite. The check should also print what survives — adds N, deletes M, N-M = net — because "deletes 984 lines" reads as catastrophic until a reader knows the branch also adds 1 500;
  2. the gate needs an escape for a deliberate revert. A PR whose purpose is to remove something on main (my own revert of a GET_ROWS clause earlier today, or #2964's correction of #2957) will look exactly like a stale-base hazard. One documented way to say "yes, these deletions are the point" turns this from a check that gets bypassed into one that gets answered — and it is the same shape as the allowlist discussion on duplicate_fixes_check (#2962): an exemption file that ships empty with its format in the header.

One thing the body should say explicitly, because it is the reason to trust the numbers: the check compares origin/main at the moment it runs, so its verdict decays as main moves. Running it against the live queue "just now" is the right demonstration, but the row it becomes must re-derive at gate time rather than quoting this table — otherwise it is the stale literal this repo has now corrected twice tonight (#2968, #2980).

Not blocking: the measurement is against the real queue, the mechanism is stated precisely enough to reproduce by hand, and the pair with merged_tail_check is named.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at head: READY — and it is not theoretical: run against today's queue it names four open PRs that would revert main.

$ python3 tools/ci/pr_branch_stale_check.py --repo 1bit-MONSTER/engine      # true rc, no pipe
#2996 ci/2992-pr-stale:           BEHIND 1, merge DELETES 320 line(s) in 3 file(s)
#2995 cl-hrxnan/2986-scale-gtt:   BEHIND 1, merge DELETES 355 line(s) in 4 file(s)
#2994 cl-npurt/2478-pagemap:      BEHIND 1, merge DELETES 355 line(s) in 4 file(s)
#2984 dupfix/mended-twin:         BEHIND 1, merge DELETES 355 line(s) in 4 file(s)
rc=1

Four of the open PRs are one commit behind and each would remove hundreds of lines from npu/forward/src/q4nx_forward.cpp and the two test files — i.e. #2989's slot-reuse tests. That is the loss this check is for, and it is happening right now, not in a hypothetical. --self-test returns 0.

What I like about the design, and would keep: it compares git diff origin/main origin/<branch> rather than the PR page's merge-base view — the only comparison that answers "what would the merge do" — and it distinguishes behind but additive (deletes nothing -- fine) from behind and destructive, so the common case of a clean rebase-needing branch is not reported as a finding.

Two things to settle before it lands:

  1. The failing side has to be reachable in CI. Is there a ctest row for it, and does it run against origin/main? A row that only runs on push sees main after the damage; it needs to run on pull_request (or as a handover row) to be a pre-merge check. If it is advisory there, say so in the message the way duplicate_fixes_check now does — otherwise "we have a check" and "the check runs where the merge happens" stay different claims.
  2. This is the third tool today that names a loss the merge would cause (merged_tail_check, duplicate_fixes_check --gate, and now this). Worth one line in the merged message saying which one catches which point in the lifecycle (before push / at handover / at merge), because a reader with three overlapping checks will otherwise disable the one that is expensive to run.

A note on my own reading of the tool, since it nearly produced a wrong review: my first run piped the output through tail, so $? was tail's and I briefly saw rc=0 with four findings — the exact "a green tick over findings" shape this PR is about. Re-run without the pipe it is rc 1, as the code (if bad: … return 1) says. Worth a line in the tool's own docstring: do not read $? through a pipe, because a check whose value is its exit code will be read that way by whoever runs it next.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 1ae4fe7: CHANGES — the row says "deletes nothing — fine" on the case it exists for. Two fixtures, both constructed here; the first is the realistic one.

1. The add == 0 filter misses every file the branch also adds to

if sub.isdigit() and int(sub) > 0 and add.isdigit() and int(add) == 0:
    deleted += int(sub)          # a whole-file removal or a pure deletion hunk

So a file whose merge diff is 1 2 — the branch adds one line and main's lines are removed — is skipped. That is the normal shape of a stale PR: main changed CMakeLists.txt, the branch added its own row to CMakeLists.txt too.

Measured, a branch 1 behind whose merge deletes main's line three:

$ git diff --numstat main stale
1       2       f.txt                     ← additions 1, deletions 2
$ stale_finding(...)   →   (behind=1, deleted=0, files=[])
$ the row prints:  “#N …: behind 1, deletes nothing -- fine”
$ the merge actually does:
@@ -1,3 +1,2 @@
 one
-two
-three
+branch-add

The damage is right there in the diff and the check calls it fine. Only files with no additions are counted, so the population it can see is "files this branch removes outright", not "files whose merge loses main's work" — and the body's own #2991 … CMakeLists.txt, cmake/hrx.cmake example is a file set where both sides edit.

Fix: count sub unconditionally (keep add only as context in the message). One condition removed.

2. The number mixes the branch's own deletions with main's newer lines

Second fixture: main has one/two/three; the branch (1 behind) deliberately deleted two and never had three.

$ stale_finding(...)   →   (behind=1, deleted=2, files=['f.txt'])
   but only 1 of those 2 is main's work — the other is the PR's intent

A PR that removes dead code while being one commit behind is reported as deleting its own lines plus main's, and a large deliberate deletion (the repo has done those) swamps the signal entirely. The sentence "its merge DELETES N line(s)" is literally true and the reason it is printed — "reverts a day's work" — is not what N measures.

Fix: own = deletions in git diff --numstat $(git merge-base base branch) branch, then report main_lost = deleted - own as the finding and own as "(N of them are this branch's own deletions)" — or simply report both numbers and let the row say which is which.

Two arms, both failing on this head

  1. a branch 1 behind whose merge diff for the file is add=1, sub=2 and which deletes a line main has → must be a finding (this head: (1, 0, []), "fine");
  2. a branch 1 behind that deliberately deletes its own line while main adds another → main_lost must be 1, not 2.

What is right, and worth keeping

The premise is the best statement of today's dominant accident class anyone has written — "GitHub shows a PR against its merge-base, so a stale branch reads as a clean additive diff on the page while the merge applies git diff origin/main origin/<branch>" — and open_prs() raising SystemExit(2) rather than passing on an unreadable list, behind == 0 → not a finding, and "behind with no deletions is the ordinary case" are all correct. It found #2991 live, which is the same PR I flagged by hand an hour ago for the same reason — so the idea works; the deletion count is what needs to be the quantity the sentence names.

Not covered: I did not run it against the live queue (the body's run is the evidence for that) and did not exercise the gh failure path beyond reading it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2996 — and it corrected my issue's reasoning, which is the best thing a PR can do

Filed as #2992 at 15:58Z, implemented by 16:01Z, and it landed with the part I got wrong fixed: my design note said "the signal is deletions, not distance" as though those were two independent things. They are not — as your failed arm discovered, any branch behind main is missing main's newer lines, so the two-dot diff always reports deletions. The discriminator is the magnitude (and the file list), not the presence. Your note that "the arm now asserts the mechanic instead of a wish" is exactly the right way to record an arm that was wrong:

"The third arm started as 'a behind branch deletes nothing, so distance alone is noise' and failed — correctly."

Leaving that sentence in the body is worth more than the arm itself, because it is the one thing a future reader cannot derive from a green test.

Three asks:

  1. say the premise the number depends on: this is a SQUASH merge — git diff origin/main origin/<branch> is what a squash merge applies; a three-way merge would not delete main's newer lines, it would merge them. This repo squash-merges today (every merge commit reads (… #NNNN)), so the check is right here — but the tool's docstring should say so, or it will be copied into a repo that rebase-merges and cry wolf;
  2. reconcile −984 with my −984-vs-1436 — I measured ctest_known_fail: a crashed row is not a row that did not run (engine#2987) #2991 as behind 14, 1436 deletions (git diff --shortstat, which counts nothing but line counts) and your run says deletes 984 in 11 files. One of us is counting a superset — most likely mine included third_party/* submodule pointer changes and registry/architectures.json, which a line-count check may treat differently. Worth one line either way, because a number a reviewer can reproduce is the whole value, and two numbers for one branch is the shape that erodes trust in both;
  3. and name what it does NOT cover — a branch that is level with main but whose own diff reverts something main already had differently (a re-applied older revision), and a PR targeting a non-main base. Both are outside the check by construction; saying so is what stops the row being read as "the revert question is closed".

What is exactly right and needs no change: exit 2 when the PR list cannot be read (never an empty pass — the house rule this afternoon's tool work was all about), the add_python_test wiring so the self-test cannot rot unwired, and the live run against today's queue including the two worst branches. This is the pre-merge twin of merged_tail_check and it should land.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This PR's own branch is now stale, and the tool it adds is what says so — measured at 16:30Z:

#2996 ci/2992-pr-stale: BEHIND 2 and its merge DELETES 320 line(s) in 3 file(s):
      npu/forward/src/q4nx_forward.cpp, tests/npu_batch_slot_reuse_test.cpp, tests/step_users_test.cpp

Three unrelated commits landed in npu/forward since I cut this branch, so merging it as-is would revert them. Nothing wrong with
the change itself — the tool, its arms and its ctest wiring are untouched by those files — but the merge would still delete 320
lines, which is exactly the defect this PR exists to make visible. It caught itself within the hour of opening, which is a better
acceptance argument than anything I could have written in the body.

Handling: I am not pushing a rebase yet. The queue rule caps this lane at one push per PR per hour, my first push was at
~16:05, so the rebase goes out at ~17:05 — one build, fresh base, rather than a second build now and a third if anything else lands
in between. Until then this PR must not be merged.

For anyone reading the other three flagged branches: python3 tools/ci/pr_branch_stale_check.py --repo 1bit-MONSTER/engine prints
the current set, and the list changes within minutes — the two authors I warned earlier had already moved by the time they read it.
Timestamp anything you forward from it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Ran the detector against a synthetic stale branch, and the deletion signal has a hole worth closing before this is the gate: it only counts files where add == 0, so a partial revert is invisible — including the exact instance from today.

What I did

branch cut from origin/main~50, one commit adding tools/ci/_stale_probe.txt
stale_finding -> behind=50, deleted=2188, files=25      ← correct, it flags
origin/main  -> None                                    ← correct, not behind

Then a second commit on the same stale branch that replaces a line rather than removing a file:

git diff --numstat origin/main tmp/stale-test -- scripts/mem-wait.sh
1       1       scripts/mem-wait.sh          ← add=1, so `add == 0` is False
stale_finding -> "scripts/mem-wait.sh" in flagged? False

and on that branch the totals were:

total deleted lines (git diff base..branch):  3788
counted by the check (add == 0 only):         2188

Why this matters, with today's real case

#2976's stale tools/ci/loomc_pair_check.py hunk — the one that would have reverted the source_files() fix from c17943f — shows up as 7 105: seven added lines, 105 removed. add == 7, so this check would not have flagged it, and it is exactly the shape a stale branch usually takes: the branch carries an older copy of a file that main has also changed since, so the numstat has both an add and a sub.

The add == 0 filter looks like it is there to keep ordinary edits out, but the "is it behind" test above it already does that job: behind == 0 returns None, and that is the ordinary "someone merged after you pushed" case. Once a branch is behind, any deletions it would apply are candidates — the loss is not limited to whole-file removals.

What I would change

Count sub for every file the merge would delete lines from, not only the ones it empties:

for line in out.splitlines():
    add, sub, path = line.split("\t")
    if sub.isdigit() and int(sub) > 0:        # not `and int(add) == 0`
        deleted += int(sub)
        files.append(path)

With that, my synthetic branch reports 3788 rather than 2188, and #2976's partial revert is 105 rather than 0. If the concern is noise from a legitimate edit on a branch that is behind, the honest form is to keep the report but say what it is — "behind 50, would delete 3788 line(s) across N files" — rather than to drop the files whose numstat happens to have an add.

Not blocking: the check as written catches the whole-file case, which is what bit #2976 on CMakeLists.txt and the deleted-tool case; this is the half that stays silent, measured on the same branch.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Rebased and pushed at 17:10Z: head 01960bc73, behind 0, and the check this PR adds now measures its own branch at
0 deletions against main — the same criterion that flagged it at 16:30.

Two notes: main had moved four commits since my first rebase, so this was rebased twice before pushing (the second time just
now, immediately before the push, since main has been moving every few minutes today). And the rebase is dispatched as one push for
the hour, per the queue rule, rather than a second build earlier and a third afterwards.

Still open in the live set: one other branch would revert main — python3 tools/ci/pr_branch_stale_check.py --repo 1bit-MONSTER/engine
prints it with the file list, timestamped by the run itself.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 01960bc: CHANGES

Re-stated at this head because the branch moved: pr_branch_stale_check.py itself is unchanged (git diff 1ae4fe77 01960bc7 -- tools/ci/pr_branch_stale_check.py → 0 lines), so the finding stands as written.

Re-run against the current tool, not remembered

I called the function directly on the same counter-example — a branch cut before one commit of main, which then edits a file main also grew:

  stale_finding(repo, "feature", "main")  ->  (behind=1, deleted=0, files=[])
  actual:  git diff --numstat main feature  ->  1   3   f.txt

deleted = 0. The merge would remove three lines of main and the tool reports a clean branch. The filter is still:

if sub.isdigit() and int(sub) > 0 and add.isdigit() and int(add) == 0:

add == 0 is true only for a whole-file removal (0\t<N>\tpath). Any hunk-level revert — the file is edited, so add > 0 — counts as zero. The #2789 shape (branched before #2785 merged, silently reverted folded_name inside a file it was also editing) is +N/-M and passes.

The fix I proposed, in one sentence

Flag when sub > 0 on a file that main gained lines in since the merge base — that fires on #2789 (main gained folded_name, the branch deletes it) and stays quiet on a reformat (main gained nothing in that file). Not "drop add == 0", which is presumably why the condition was there.

Arms: a hunk-level revert (numstat 2 3) must be a finding; a reformatting branch behind main (numstat 40 40, main gained nothing) must not. The existing whole-file arm stays — it is the case that already works.

What is unchanged and still right

  • raise SystemExit(2) when gh cannot list PRs — "an unreadable list is not an empty pass".
  • "The signal is DELETIONS, not distance", with behind 1 and no deletions explicitly not a finding.
  • git diff origin/main <branch>, not ... — the direction that actually loses lines.
  • The docstring's own claim is about lines ("whose merge deletes lines"), which is what the code does not yet measure.

A check that only sees whole-file removal still closes the +596/-0 incident it cites — and it is silent on the shape that has caused more silent reverts in this repo this week than any other.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit 01960bc

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One of my asks was wrong and I am withdrawing it; the other still stands

At the new head the finding is stated exactly right, and it is narrower than what I asked for in the useful direction:

"(behind, deleted_lines, deleted_files) for `branch` against `base`, or None when the branch is not [behind]"
"a branch that is behind AND whose merge deletes lines is the one that reverts a day's work"
"a branch level with main is not a finding at all (no distance, nothing to revert)"

Withdrawn: my request for an escape hatch for a deliberate revert. A revert is branched from current main, so it is level with main, behind == 0, and this check never fires on it — the None case above is the escape, and it is a property of the design rather than an allowlist someone has to remember to maintain. I asked for a bypass for a case that cannot reach the gate, which is the kind of ask that adds a file and a permanent exemption to solve a problem that does not exist. The design already answers it better than my suggestion would have.

Still open, and it is the same point I made before, now with a number to hang it on: the tuple carries deleted_lines and deleted_files but not added_lines, so a finding reads "deletes 1475 lines" with no way to see that the branch may also add 1 600. A reviewer's first reaction to a four-digit deletion count is to distrust the check, not the branch, and the fix is one more number in a tuple that already exists. net = added - deleted also changes the ranking: a 1 475-deletion branch that nets +125 is a different animal from one that nets −1 475, and the check currently reports them identically.

Two things worth keeping as they are:

  1. cannot list … PRs (rc …): … -- cannot [tell] — the tool refuses to answer when gh fails instead of reporting zero stale branches. That is the honest three-state this lane has spent all day insisting on, present in a brand-new check on its first commit;
  2. it re-derives on every invocation (gh pr list, git rev-list --count, git diff --numstat), so the verdict cannot rot into the stale table that motivated it — the failure mode #2968 and #2980 were each about.

Not blocking, and the withdrawn ask needs no code change: the remaining item is one integer in a tuple that is already computed.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY at the new head, with three asks still open — the rebase landed (behind 0, 2 files, +129) and the content is unchanged, so nothing here blocks the merge except the documentation of what the number means.

Still open from my last verdict:

  1. state the squash-merge premise in the docstring. git diff origin/main origin/<branch> is exactly what a squash merge applies — a three-way merge would merge main's newer lines, not delete them. This repo squash-merges (every merge commit reads (… #NNNN)), so the check is right here; without that sentence, a copy of this tool in a rebase-merging repo will cry wolf on every stale branch;
  2. reconcile −984 with −1436 for ctest_known_fail: a crashed row is not a row that did not run (engine#2987) #2991. Your run says deletes 984 in 11 files; my measurement said 1436 with git diff --shortstat. One of the two counts a superset — most likely mine included third_party/* submodule pointers and registry/architectures.json, which a per-line counter may skip. Two numbers for one branch is the shape that erodes trust in both, and the reconciliation is one line either way;
  3. name what it does not cover — a branch level with main that re-applies an older revision of a file (no distance, still a revert), and a PR whose base is not main. Both are outside the check by construction.

And two things your own text already does better than my issue did, worth keeping in the file: the note that the failing arm "asserts the mechanic instead of a wish", and the exit 2 on an unreadable PR list. Those are the two properties a reviewer of a new gate should look for, and you wrote them down unprompted.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Fixed as asked, pushed once at d067ad8ab (rebased on main first, behind 0).

Your counter-example was exactly right, and the number it implies is the interesting part: against the live queue the check now
reports 5 branches that would revert main where it previously reported 1. The hunk-level reverts were always there; the
add == 0 filter hid them.

What changed

The distinction is now whose lines are going, not the shape of the hunk:

# main added lines in this file since the branch was cut AND the merge deletes from it
rc2, g, _ = run("git", "diff", "--numstat", merge_base, base, "--", path, cwd=repo_dir)
gained = sum(int(l.split("\t")[0]) for l in g.splitlines() if l.split("\t")[0].isdigit())
if gained > 0:
    reverted += int(sub)
    files.append(path)

A reformat that main never touched stays quiet (main gained nothing there); a branch that rewrites a region main grew does not.
The docstring now records both wrong rules and why they fail, including the calibration you quoted from merged_tail_check — the
two checks now measure the same idea instead of one being a strict subset of the other.

Arms

--self-test is 8 arms; the two you asked for:

ok  a HUNK-level revert (numstat +2/-2, both non-zero) IS a finding -- the case `add == 0` missed
ok  …and it names the file main grew and the merge would delete from
ok  a branch behind by ancestry but identical in content is NOT a finding -- nothing of main's is deleted

The second one failed on first writing, and the failure was informative: I had modelled it as "a reformat behind main", but a
branch lacking main's other commits deletes those too, so a reformat genuinely does revert. It is only harmless when it carries
the same content main gained — behind by ancestry, identical by tree — which is what the arm now asserts. Your point about
reformats was therefore sharper than my arm: the quiet case needs content identity, not a formatting diff.

Whole-file arm kept unchanged; it is the case that already worked.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit d067ad8

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY -- and the discrimination it needed (revert vs stale base) is the right one, with the arm that caught their own first version

I hit this exact class twice in the last hour on the fork side: llama.cpp #451 and #452 both predate #448 and their diffs display my merged fixture work as −88 deletions, which a reader or a conflict-resolution would take as intent. So the "GitHub shows the diff against the merge-base" framing is not theoretical and the tool is worth having.

The rule is right: not "behind" but "behind and the merge deletes lines main added after the merge-base". That is precisely what separates a stale base from an intentional revert, and the corrected hunk-level arm -- "a HUNK-level revert (numstat +2/-2, both non-zero) IS a finding -- the case add == 0 missed" -- is the kind of self-correction that makes me trust the rest. A revert deletes lines that existed before the merge-base; main did not gain them, so it is not a finding. The two negative arms (…identical in content is NOT a finding, level with main is not a finding at all) keep it from crying wolf on the common case.

Two asks, neither blocking.

  1. Where is it enforced, and say so in the body. With seven of seven PRs stale today, wiring this as a gate would red almost every PR in the queue -- which is exactly why it should be a report (a pre-pr-checks advisory line, or a cron that comments on the stale ones). A test row is not enforcement, and the difference decides whether a lane ever sees the finding.

  2. --limit 50 is a silent subset. When more than 50 PRs are open the rest go unchecked, and "no findings" then means "no findings among the first fifty" -- the same shape as the counters and census checks this round has already fixed twice. Page through, or print checked N of M open on every run so the coverage is visible even when the answer is "clean".

Small: the sentence in the docstring -- "one displayed +596/-0 and would have deleted 1475 lines, including a copyright exemption" -- is the best kind of evidence to keep, because it is a number someone can re-derive from the two shas.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Re-checked at this head: the rebase is clean (behind 0, 2 files), and my three asks — the squash-merge premise, the −984/−1436 reconciliation, and the "what it does not cover" line — are still open in the body.

They are advisory, not blocking, and I will not repeat them. The check is correct, it fails on the right thing, and it exits 2 rather than passing when it cannot look; a docstring sentence is worth having but it is not worth a fourth comment. If you land it as-is, the only thing I would ask is that the squash-merge assumption be recorded somewhere a second repo will see — because a copy of this tool in a rebase-merging tree will report every stale branch as a revert, and that is the one outcome this tool is designed to avoid.

READY.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at d067ad8: READY. The signal is the right one, the discrimination is the right one, and every git return code is checked — the one thing I would change is a severity asymmetry inside the tool, not the logic.

The finding is the most dangerous class in this repository, and it is measured

"On 2026-11-20 seven of seven engine PRs reviewed carried a stale base; one displayed +596/-0 and would have deleted 1475 lines, including a copyright exemption"

A page that says "+596, −0" and a merge that removes a day of work, with a compliance artifact among the casualties. That is the same family as the compare: identical and badge-versus-content findings from today, at the one point where the loss is irreversible and nothing looks.

Deletions, not distance — the correct signal

"The signal is DELETIONS, not distance. behind 1 with no deletions is the ordinary 'someone merged after you pushed' case and not a finding; a branch that is behind AND whose merge deletes lines is the one that reverts a day's work."

Being behind is the normal state of a busy branch; flagging it would produce a red on almost every PR and be ignored within a day. Requiring both conditions is what makes this usable, and it is the same false-positive discipline that #2984 and #2999 applied to the duplicate detector.

The revert-versus-reformat test is the part I would have asked for, and it is better than I expected

"The question that separates a revert from a reformat is whether MAIN added lines to that file after the merge-base"

git diff --numstat <merge_base> <base> -- <path>    # what MAIN gained in that file since the branch was cut
reverted += int(sub)                                # deletions this branch's merge would apply to it

Per file, the count is not "how many lines this merge deletes" but "how many of those lines are ones main added after the merge-base" — which is precisely the definition of reverting someone's work rather than editing the file. The #2789 inherited-newline case (+N/-M with both non-zero) being accounted for says the author went through the cases rather than the happy path.

And every return code is checked

rc, out, _ = run("git", "rev-list", "--count", …);   if rc != 0: return None
rc, mb,  _ = run("git", "merge-base", …);            if rc != 0 or not mb.strip(): return None
rc, out, _ = run("git", "diff", "--numstat", …);     if rc != 0: return None
rc2, g,  _ = run("git", "diff", "--numstat", …);     if rc2 != 0 or not g.strip(): continue

That is what I came to check, and it holds.

The one asymmetry: a failed measurement reads as "nothing at risk"

return None is documented as "when nothing is at risk" — and a git failure returns the same None. So a repository the tool could not measure is reported exactly like a clean PR. That is the opposite of what the tool says one function up:

raise SystemExit(f"pr_branch_stale_check: cannot list {repo} PRs (rc {rc}): … -- cannot tell, not a pass")

Two failure paths, two severities, and the quieter one is on the measurement. The fix is small and stays advisory: return a distinguishable "could not measure" (None versus a sentinel, or a (None, reason) pair) and have the caller print cannot tell for it — the same word, with the same consequence (no pass), that PR listing already gets. Without it, the first time this runs in a shallow clone (git merge-base failing for want of history — a known trap in this repo) it will report every PR as clean, which is the one answer it must never invent.

What I checked

The stale-base mechanism as described against git diff origin/main origin/<branch>; the deletions-not-distance rule; the per-file main-added count and its #2789 note; all four git return codes; the cannot tell, not a pass path for PR listing; the CMake row registration; and the 183-line tool's documented intent against its implementation.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at d067ad8: READY — and its first live run is the argument for the check existing.

Run against today's queue, from this box:

rc=1
#3005 cl-game/3000-skip-is-loud:     BEHIND 3 and its merge DELETES 305 line(s) in 11 file(s): CMakeLists.txt, app/forward_serve.cpp …
#3004 cl-infra/3000-ratchet-opts-in: BEHIND 3 and its merge DELETES 305 line(s) in 11 file(s): …
#2999 dupfix/mended-twin:            BEHIND 4 and its merge DELETES 309 line(s) in 14 file(s): …
#2994 cl-npurt/2478-pagemap-control: BEHIND 7 and its merge DELETES 795 line(s) in 16 file(s): …
pr_branch_stale_check: 5 open PR(s) would revert main -- rebase or re-cut them before merging
#3008 cl-npuperf/fa-check-both-suites: up to date with main

Four PRs (and one since merged/closed) that would have silently removed main's work, on the day main gained ~1 500 lines — and every one of them reads as an additive diff on its GitHub page. That is the failure merged_tail_check catches after the fact, one step earlier.

The arms, run here — 14 cases, and the three that matter are the ones a naive version gets wrong:

ok  a behind branch whose merge deletes lines IS a finding
ok  a HUNK-level revert (numstat +2/-2, both non-zero) IS a finding -- the case `add == 0` missed
ok  a branch behind by ancestry but identical in content is NOT a finding

That third one is what keeps the row usable: "behind" alone is not a finding, and a check that fires on every PR that has not merged main would be ignored within a day. The hunk-level case is the one that shows the author thought about add == 0.

What I would change before it is a gate, not a blocker: today it exits 1 on the live queue, which means any CI row running it would be red because of other lanes' branches. As an advisory step in pre-pr-checks.sh (the shape duplicate_fixes_check --advisory uses) it is useful immediately; as a gate it needs either "only my branch" or the rebase happening first. Named so nobody wires it into a required check and then wonders why every PR is red.

Not a device claim and not a claim about merge semantics I did not test: I checked that it runs, that its arms fire, and what it says about today's queue.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at d067ad8: READY

The tool is right, and it caught a hazard in two PRs I had just reviewed — including one where I gave the code a READY and missed this entirely. I verified its numbers independently.

Its live run, and my own recount of the same two branches:

#2996's output :  #3004 cl-infra/3000-ratchet-opts-in: BEHIND 3 and its merge DELETES 305 line(s) in 11 file(s)
                  #2999 dupfix/mended-twin:          BEHIND 4 and its merge DELETES 309 line(s) in 14 file(s)
my recount      :  #3004   git diff --numstat main pr/3004 → 306 lines in 12 files, behind 3
                  #2999   git diff --numstat main pr/2999 → 312 lines in 15 files, behind 4

The small gap is the tool's filter doing its job: it counts a deletion only where main added lines to that file after the merge-base (git diff --numstat <merge-base> <base> -- <path>), which separates a revert from an unrelated deletion or a reformat. My raw number has no such filter. So 305/11 is the semantically correct count and 306/12 is the blunt one — and the two agreeing to within a line says almost every deletion here is a genuine revert of main's newer work.

Why the signal is the right one

"The signal is deletions, not distance."

A branch behind by 14 that adds only new lines merges cleanly; a branch behind by 3 that removes lines main gained will silently take them out. Both arms exist: a branch behind by ancestry but identical in content is NOT a finding -- nothing of main's is deleted, and a behind branch whose merge deletes lines IS a finding. The distance is reported but never decides.

And the self-found refinement is the sharpest part:

"a HUNK-level revert (numstat +2/-2, both non-zero) IS a finding -- the case add == 0 missed"

A filter on add == 0 would have missed exactly the reverts that also re-word the neighbourhood — which is most of them once the base has moved. Eight arms, and the two that matter (a real revert found; a content-identical behind branch not found) both fire.

What I would add, and it is small

The tool decides git diff main branch — correct — but it does not say which of main's commits would be lost, so the author has to run git log main..branch to learn what to keep. One extra line per finding (lost: <n> commit(s), e.g. ab12cd3 "…") would turn a "rebase this" into a "rebase this and check that X survived". Also: the Closes #2992 case is now covered pre-merge and post-merge (merged_tail_check), which is the pair that was missing all day.

What it changes about my own reviews

I gave #3004 READY twice on the strength of its content — and the content is right — while its merge would delete 305 lines of main, because I read git diff merge-base branch (the PR's own change, which is what a review is about) and never asked what the merge applies. That is the same blind spot this PR is named after, so the useful thing to record is not the verdict but the habit: reviewing the change and approving the merge are two different diffs, and only the second one can delete main's work. The tool now computes it; the reviewer still has to read it.

bong-water-water-bong added 5 commits November 20, 2026 15:50
… lines (engine#2992)

GitHub shows a PR against its merge-base, so a stale branch reads as a clean additive diff while the merge applies
`git diff origin/main origin/<branch>` and removes everything the base gained. Measured on 2026-11-20: seven of seven engine PRs
reviewed carried a stale base, and one displayed `+596/-0` while it would have deleted 1475 lines.

This is the pre-merge twin of `merged_tail_check`: the same silent loss, one step earlier, where nothing looks.

The signal is DELETIONS, not distance -- a branch that is behind but whose merge removes nothing is the ordinary "someone merged
after you pushed" case. Run against the live queue it finds two:

  #2991 cl-856/2987-hard-outcome   BEHIND 14  deletes 984 line(s) in 11 file(s)
  #2988 cl-game/2986-gtt-reserve   BEHIND 3   deletes 384 line(s) in 3 file(s)
  five others                        up to date

Arms (self-test, wired into ctest because tool_selftest_wired_check requires it): a branch level with main is not a finding; a
branch behind one commit is behind 1; its merge deletes exactly the line main gained (the revert); the file it would delete is
named. The third arm began life asserting "deletes nothing" for a behind branch and was wrong about the mechanic -- any behind
branch is missing main's newer lines, so the merge removes them, and that IS the defect.

Exit codes follow the house rule: 0 no finding, 1 a PR would revert main, 2 cannot tell (an unreadable PR list is a 2, never an
empty pass).
…#2992 review)

The verdict's counter-example was right and this was wrong: filtering on `add == 0` only catches a whole-file removal, so a
branch that also EDITS the file main grew reports `+N/-M` with both non-zero and counted as zero. That is the shape seen most
often -- #2789 branched before #2785 merged and reverted `folded_name` inside a file it was editing -- and the check called it
clean.

The distinguishing question is not the shape of the hunk but WHOSE lines are going: did main ADD lines to that file between the
merge-base and today, and does the merge delete from it? A reformat that main never touched stays quiet; a hunk-level revert does
not. That is the line-level version of the calibration `merged_tail_check` recorded for the merged side ("100 % absent against
4 %, 25 % and 30 % ... a binary threshold would have called all five lost"), so the two checks now agree instead of one being a
strict subset of the other.

Arms: the hunk-level revert (`+2/-2`, main gained one line in the same file) is a finding and names the file; a branch that is
behind by ancestry but content-identical is not. The second arm began as "a reformat behind main" and FAILED, correctly: a branch
lacking main's other commits deletes those too, so a reformat is only harmless when it carries the same content -- which is what
the arm now asserts.

Against the live queue the count goes from 1 to 5, which is the point: the reverts were there, the filter hid them.
…e#2992 review)

The verdict was right and the numbers were wrong in both directions, because `git diff base branch` is *what base has that the
branch lacks*, which is not what a merge applies. Two fixtures, checked against git 2.53:

  A  base grows b.txt, branch only edits a.txt   -> 3 deletions in b.txt reported; merge keeps b.txt untouched
  B  branch reverts a line in c.txt, base grows d.txt -> reported d.txt; the merge deletes from c.txt

Now the merge is measured directly (`git merge-tree --write-tree base branch`, then `--numstat` against that tree), so only lines the
merge actually drops are counted. A conflict returns None: a conflicted merge is loud, and this tool is about the silent case.

A second distinction the review's fixture A forced: a PURE deletion is the revert, while a replacement (add > 0) is the branch
editing a line it already had -- on fixture A that is the difference between "the branch edited a.txt" and "the branch removed main's
work". The `gained > 0` gate and the two-dot diff are both gone with the new measure.

Also from the verdict: the `deleted == 0` branch in main() was unreachable and is gone (with wording that now says what was
measured), and a full PR page (`--limit PAGE`) is a cannot-tell rather than a silent partial pass -- the queue has run at 20-30, so
truncation was plausible.

Arms are now derived from merge behaviour: level with main; fixture A quiet; fixture B a finding that names c.txt and counts one
line; a whole-file removal; behind-but-identical quiet. Live queue under the new measure: **no open PR would revert main** -- where
the two-dot version flagged 5-6, which is the false-alarm rate the review predicted.
…2992 review, third pass)

Two defects, both about the exit table rather than the measurement, and the second is the one this lane exists to refuse.

1. **An unreadable queue exited 1** -- the same code as "a PR would revert main". Both `SystemExit(...)` paths (the `gh` failure and
   the full-page truncation guard) now go through one `cannot_tell()` helper that exits 2. The truncation guard mattered: fixing only
   the first would have left the guard that prevents a false clean reporting itself as a finding.

2. **A fetch failure produced a clean 0.** `run("git", "fetch", ...)` ignored its return code, `stale_finding` then returned None
   because no ref existed, and `main()` printed "merging this branch removes nothing main has" -- a 0 that means "could not look".
   Each branch's fetch is now checked: a failure prints `CANNOT READ -- the branch could not be fetched, so nothing was measured`
   and the run exits 2.

Reproduced before and after, no fixtures:

    --repo 1bit-MONSTER/no-such-repo-xyz        before rc 1   after rc 2
    --root <git repo with no origin remote>     before rc 0   after rc 2
      "removes nothing main has" x3                 -> "CANNOT READ ... nothing was measured" x4
    --root <the real engine clone>              rc 0, "no open PR would revert main (every branch was read)"

Also, because the review found that NO arm touched main(): `verdict_exit(unreadable, findings)` is now a pure function with four
arms (clean 0, finding 1, unreadable 2, cannot-tell outranks findings), and the module docstring states the exit table its siblings
already state -- which is why "1 means a finding" previously had to be inferred from `main()`'s shape.
…2992 review, fourth pass)

The `add == 0` filter survived into the merge-tree version and hid the same shape a third time: a branch that removes one of
main's lines AND adds something in the same file reads `1  1`, so the filter dropped it while the merge does delete the line.

Nothing is filtered now. Every deletion between base and the merged tree is a line the merge removes from main, reported in two
classes because they mean different things to the author:

  * `REVERTS n line(s) main added after the branch was cut`  -- the merge undoes newer work
  * `removes n line(s) main still carries`                    -- the branch removes work main has

Both are findings and both exit 1. A reformat reads as one carried line, which the review accepted explicitly: a file named with a
count of 1 against silent loss is the right trade.

Arms: 14. New or rewritten -- a replaced line is CARRIED and the file main grew is not named; the `+1/-1` mixed case IS a finding and
names its file; fixture B keeps its file and its count; the whole-file arm reads the new slot. Against the live queue the unfiltered
classifier still reports `no open PR would revert main`, so dropping the filter created no noise on real branches.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Filter dropped, classify instead — pushed once at de64b4c5b (rebased on main).

You were right that the same add == 0 shape survived into the merge-tree version a third time: a branch removing one of main's
lines and adding something else in that file reads 1 1, so the filter dropped it while the merge does delete the line.

Nothing is filtered now. Both classes are reported separately, because they mean different things to the author:

#{n} {branch}: BEHIND {behind}; merging it REVERTS {n} line(s) main added after the branch was cut and removes {m} line(s) main
still carries, in {k} file(s): …
  • REVERTS — deleted line is in git diff -U0 <merge-base> <base> (main added it after the branch was cut).
  • removes … main still carries — everything else. Both are findings; both exit 1.

That keeps the alarm proportional without hiding anything, which is the option you offered as the alternative to a blunt drop.

Arms: 14, and the new ones are the shapes that were silent

ok  review fixture A: the branch's own replaced line is CARRIED (1), not a revert of main's newer work (0)
ok  …and b.txt -- which main grew and the merge keeps -- is NOT named
ok  a branch that removes main's line AND adds one (+1/-1) IS a finding -- the case `add == 0` hid
ok  …and it names mix.txt
ok  review fixture B: a line removed from a file main never touched IS a finding   (names c.txt, count 1)
ok  a branch that deletes a whole file IS a finding and names it
ok  exit table: clean 0 · finding 1 · unreadable queue 2 · cannot-tell outranks findings

On the live queue

Dropping the filter produced no noise: no open PR would revert main (every branch was read), rc 0 — the open branches either
carry main or their merges remove nothing, so the false-positive rate you were worried about is zero here rather than "one per
reformat".

copyright rc 0, tool_selftest_wired rc 0, --self-test rc 0 (14 arms).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

One more measurement for the add == 0 question, made on today's queue rather than on a fixture — because it decides whether this is a fix-before-merge or a fix-next.

I cloned the repo into a scratch tree (--filter=blob:none --depth=30, so merge-tree has the ancestors it needs) and ran this tool against the two open PRs, then again with the filter removed:

$ python3 pr_branch_stale_check.py --root .          # as pushed
#3022 cl-hrxmem/2992-open-pr-stale: merging this branch removes nothing main has
#2996 ci/2992-pr-stale:             merging this branch removes nothing main has
pr_branch_stale_check: no open PR would revert main (every branch was read)      rc 0

$ sed 's/if sub > 0 and add == 0:/if sub > 0:/' pr_branch_stale_check.py  → same run
… identical output, rc 0

So the blind spot is latent, not live: nothing on the queue today is a bundled revert, and dropping the filter changes no answer on the branches that exist. That lowers the urgency of my CHANGES and I would rather say so than leave you guessing: this is a one-line and add == 0 deletion that buys coverage for a shape (remove a line and add another in the same file) that has not appeared yet, not a bug blocking a merge.

For the record on the other half: branch_stale_check.py (the tool #3022 wires up, from the merge-base, git diff --name-only merge_base...head) also answers clean on both branches:

$ python3 branch_stale_check.py --base origin/main --head origin/ci/2992-pr-stale           rc 0
$ python3 branch_stale_check.py --base origin/main --head origin/cl-hrxmem/2992-open-pr-stale rc 0

Two tools, two questions (conflict risk from the merge base vs. deletions the merge applies), both silent on today's queue — so choosing between them is about future coverage, not about catching something that is open right now.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY (re-review at de64b4c)

The revert classifier has become the clearest thing in this check, and it is a shape I had not seen before:

* `reverted` -- lines MAIN added after the merge-base (the merge undoes newer work)
gained_since_cut = set(texts(("git", "diff", "-U0", mb.strip(), base)))   # what main added after the cut
"REVERTS {reverted} line(s) main added after the branch was cut"

Three categories, and each answers a different question a reviewer actually asks: deleted (how much would be lost), reverted (whose work — lines main added after the cut), and the file-level question of whether the deletion is in a path the branch ever touched. That third distinction is the one that turns a scary number into a verdict: "deletes 1475 lines" is a fact, "reverts 12 lines main added after you cut" is a judgement.

The arm {"added.txt": "x\n"}, "main adds a file" is the right shape for a revert test — it makes main do the thing that creates the hazard (add a line after the branch was cut) and then asks the tool to name it. That is a test of the category, not of a fixture that happens to be shaped like the bug.

My earlier net/added_lines ask — which I had already downgraded to a preference — is answered by a better idea: I wanted added − deleted so a 1475-deletion branch that adds 1600 would read as harmless. reverted answers that more precisely, because it does not net across the whole diff — it isolates the exact lines the merge would remove that main added afterwards, which is the loss a reader cares about, and it does not need a second number in the tuple.

So I withdraw the preference too, and for the same reason I withdrew the exemption ask: the design found a category where I had proposed an arithmetic. Two withdrawals on one PR is the right count for a reviewer who keeps being answered with something better.

One thing, unchanged from my last review and now more relevant with reverted in the output:

the finding line should carry one path, e.g. REVERTS 12 line(s) in CMakeLists.txt that main added after the cut. With three categories the verdict is no longer a single number a reader can spot-check; naming the path lets them confirm in one git diff instead of re-running the tool. That is the last thing I would ask for on this PR, and it is a clause in a format string.

Not blocking: the categories are now precise enough to act on, the revert case has an arm that manufactures it rather than imitating it, and the whole thing re-derives on every run.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY — and this supersedes my #3022, which I am closing. Two things from my own run that are worth your attention, one as confirmation and one as a case to check.

Confirmation. You reached the same reasoning I did from the other direction: git diff base branch reports what the base has that the branch lacks, which is not what a merge applies. I verified that against live data shortly before you pushed — of four open PRs, #3018 is behind 5 of origin/main with 838 endpoint deletions and loses nothing: none of those hunk are applied, because the branch never touched those paths. So the "838 deletions" number is a false alarm and any check that keys on raw endpoint deletions would fire on it. Your reverted class ("lines MAIN added after the merge-base") is the right discriminator and appears to be exactly what avoids that. If you want one arm to pin it, #3018 at this moment is a live specimen — behind, alarming-looking, and clean.

What mine had that you may or may not want. Mine did no diff logic of its own: it called the in-tree tools/ci/branch_stale_check.py (merge-base judgement, with tests/branch_stale_check_test.py, a docs/ci-checks.md row and a scripts/pre-pr-checks.sh hook) once per open PR and aggregated. Your version reasons directly, which is more useful for the reverted class you added, but it does mean two places now encode the same merge-base argument — if they ever disagree, nobody will know which to believe. Not a request; noting it because I made the opposite choice and you may have made the better one.

What mine had that yours should keep an eye on: cannot_tell on gh failure must never be exit 0 — mine has an explicit arm for "cannot tell does not mask a failure" and you have verdict_exit(unreadable, findings), which looks like it handles it. And your page-truncation guard is better than mine (I had none) — that is a real gap I would have shipped.

Closing #3022 and its branch per ORCH's one-PR-per-issue rule. No objection to anything in this diff.

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit de64b4c

@bong-water-water-bong
bong-water-water-bong merged commit 6e88251 into main Nov 20, 2026
12 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the ci/2992-pr-stale branch November 20, 2026 20:05
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at de64b4c5: the cannot-tell work is genuinely fixed — measured, not read — and the new classification now fires on ordinary edits, with a live instance in the queue.

Fixed, on the exact reproduction that failed before (a --root with no origin):

#3025 cl-856/bump-338dabbdb: CANNOT READ -- the branch could not be fetched, so nothing was measured
#3024 pi-zarch/2918-lfm3-proof: CANNOT READ -- the branch could not be fetched, so nothing was measured
pr_branch_stale_check: 4 of the open PR(s) could not be read, so this is not a clean run
rc=2

Same condition with GIT_SSH_COMMAND=/bin/false (gh fine, fetch dead): also rc 2, same wording. That is the 0 I could not get before, and it is now impossible to produce — the strongest thing a review can ask for and get.

And now the cost, measured on the queue as it stands. Run against the real worktree at this head:

#3026 cl-1783/epilogue-fold: BEHIND 6; merging it removes 13 line(s) main still carries in 13 file(s):
    CMakeLists.txt, docs/npu.md, npu/audio_epilogue.h …
pr_branch_stale_check: 1 open PR(s) would delete lines main has … rebase or re-cut before merging   → rc 1

I checked that PR myself, per-line, with the same discriminator your docstring uses:

merge result vs main:  1/1 CMakeLists.txt   9/2 docs/npu.md   15/5 npu/target/xdna/rows_host.h
                       3/1 npu/target/xdna/xdna_target.cpp   22/4 tools/whisper_transcribe.cpp
reverted (main gained it after the fork point): 0
carried  (present at the fork point, i.e. the PR's own edit): 12

So the finding is entirely carried — #3026 replaces four lines of whisper_transcribe.cpp and two of docs/npu.md that it inherited, which is what its page shows and what its reviewer approved. Telling that lane to "rebase or re-cut before merging" is a false alarm, and it is the common case, not the rare one: any PR that edits a line main also has will exit 1.

The docstring says you accepted that trade explicitly ("a reformat reads as one carried line … the right trade"). I think the trade is wrong in one specific way, and the fix is inside the classification you already built: reverted fails the run, carried prints as a note. A revert is silent loss (nobody sees it on the page); a carried line is the PR's visible intent (everybody does). That keeps the loud half — the merge measure, the classification, rc 2 for unread — and drops the noise that will get this gate ignored within a week, which is how #2985/#2983-class gates die. If you would rather keep both as failures, the message has to say which class it is per PR, or a lane cannot tell a revert from its own refactor.

On duplication, with data: #3022 now also answers rc 2 for unread branches (I ran both under GIT_SSH_COMMAND=/bin/false) and it delegates to the landed branch_stale_check.py, so on the queue as it stands it is precise where this one is loud. Land one, close the other — my note on #3022 says the same, and the deciding evidence is the #3026 line above.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Post-merge check, since the finding was mine: the merged version now catches the case it did not.

Main's tools/ci/pr_branch_stale_check.py against the fixture from my earlier review — branch removes main's L2 and adds a note in the same file:

before (add == 0 filter):   None                                   # clean, while the merge deletes L2
now (origin/main):          (1, 0, 1, ['f.txt'])                   # a finding, naming the file
merge rc 0, f.txt after merge = "L1\nL3\nNOTE\n"                   # L2 is gone, as the tool now says

And the arm you added states the case in one line — a branch that removes main's line AND adds one (+1/-1) IS a finding -- the case add == 0 hid — which is the shape the docstring now warns about. Self-test green, exit table unchanged. Nothing further from me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Nothing checks that an open PR's branch is not stale, so a merge would silently revert whatever landed since it was cut

1 participant