Skip to content

duplicate_fixes_check: --gate, so the pre-PR row is a gate instead of advisory - #2962

Merged
bong-water-water-bong merged 2 commits into
mainfrom
dupfix/gate
Nov 20, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
dupfix/gate

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

#2953 wired the detector into pre-pr-checks.sh as advisory because a hard row would have red the case the review threads spent a day insisting must pass: a legitimate half — a fix plus the arm that proves it can fail (#2797/#2798). #2958 landed the exemption. This is the last step: the row is a gate.

scripts/pre-pr-checks.sh:  "tools/ci/duplicate_fixes_check.py --gate"
docs/pre-pr-checks.md:     same row, with the new meaning
tools/ci/duplicate_fixes_allow.txt:  new, empty on purpose, format in the header

Exit codes are the script's vocabulary — which is why the mode is in the tool

pre-pr-checks classifies every row by exactly three values, and its page-vs-runner comparator rejects any row that does not begin with the tool path — so a sh -c wrapper that remapped codes outside the tool would fail the script's own consistency check. (It did, once: #2953's first attempt.)

rc meaning
0 clean
1 two open PRs name one issue and neither is declared → a finding
77 cannot tell (gh or the network unavailable) → skip, not a failure

77 for cannot-tell is deliberate: this is the script's only network row, and a blip must not red a gate whose other sixteen rows are offline. A skip is still not a pass — the summary counts it, which is the rule #2912 exists to enforce.

The allow file cannot become a permanent exemption list

An entry that no open pair claims any more is reported as STALE, with its reason, so the file cannot quietly grow. Empty today on purpose: every pair it was written for has closed.

Verified by running it

$ bash scripts/pre-pr-checks.sh
ok    tools/ci/duplicate_fixes_check.py    duplicate_fixes: no open issue is claimed by more than one open PR
pre-pr-checks: 1 failed, 13 ok, 2 skipped        # the failure is this worktree's off-pin laya/llama.cpp

$ python3 tools/ci/duplicate_fixes_check.py --gate                          -> 0
$ python3 tools/ci/duplicate_fixes_check.py --gate --repos …/no-such-repo   -> 77
$ python3 tools/ci/duplicate_fixes_check.py --self-test                     -> 38 arms, rc 0

Known limit, unchanged and worth stating in the gate row: the detector reads closing keywords and Refs, so two PRs that each fix a disjoint half of one issue and both say Fixes #N are the case the allow file exists for — and a pair that says nothing at all is still invisible to it. The gate catches declared duplicates; it does not catch silent ones.

… advisory

#2953 wired the detector into pre-pr-checks.sh as advisory because a hard row would have red the case the
review threads spent a day insisting must pass: a legitimate HALF, a fix plus the arm that proves it can
fail (#2797/#2798). #2958 landed the exemption. This is the last step: the row is now a gate.

Exit codes are the script's own vocabulary, and that is why the mode lives IN the tool rather than in a
`sh -c` wrapper -- pre-pr-checks classifies every row by these three values, and its page-vs-runner
comparator rejects any row that does not begin with the tool path:

  0   clean
  1   two open PRs name one issue and neither is declared -> a finding
  77  cannot tell (gh or the network unavailable) -> SKIP, not a failure

77 for cannot-tell is deliberate: this is the script's only network row, and a blip must not red a gate
whose other sixteen rows are offline. A skip is still not a pass -- the summary counts it.

tools/ci/duplicate_fixes_allow.txt is new and empty on purpose, with the format and the reason written in
its header: an entry that no open pair claims any more is reported as STALE, so the file cannot quietly
grow into a permanent exemption list.

Verified by running it, not by reading it:
  * pre-pr-checks.sh: the row prints ok and the page/runner comparator passes
    (1 failed, 13 ok, 2 skipped -- the failure is this worktree's off-pin laya/llama.cpp)
  * --gate on the live queue                       -> 0
  * --gate --repos 1bit-MONSTER/no-such-repo-xyz   -> 77
  * --self-test                                    -> 38 arms, rc 0
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (minutes old) — I raised the "a hard row would red a legitimate half" concern on #2953, so I checked the two paths that decide whether --gate is safe to turn on.

1. Cannot-look is a skip, end to end — not a red

This is the path that made the advisory version safe and could have made the gate version dangerous:

$ GH_TOKEN=bogus GH_CONFIG_DIR=/nonexistent HOME=/nonexistent duplicate_fixes_check.py --gate
rc=77
duplicate_fixes: cannot tell for at least one repo -- skip, not a pass

and pre-pr-checks.sh already classifies 77 as a skip rather than a failure (if [ $rc -eq 77 ]; then … "77 is the repo's \"cannot run here\"", the same convention hip_f16_audit and kernel_id_selftest use). So an unauthed lane box, or a GitHub hiccup, gets skip — the row cannot redden a PR for a reason that has nothing to do with the PR. That was my one real worry about promoting advisory to gate, and it is handled by composition rather than by new code, which is the right way.

2. The pair that should pass, and the pair that should not

$ duplicate_fixes_check.py --gate                    rc 0   "no open issue is claimed by more than one open PR"
$ duplicate_fixes_check.py --self-test               ok
    ok   0 none / 1 duplicate
    ok   cannot-tell outranks a duplicate rather than being swallowed by it
    ok   and it is not a pass on its own either

Those three arms are the ones that matter: cannot-tell beating a duplicate means a repo you cannot read cannot be resolved into "clean", and "not a pass on its own" means 77 is not quietly counted as success.

3. The allow-list is empty, which is right today

duplicate_fixes_allow.txt has 0 active entries (comments only), and the file's own header says an entry nothing claims is reported STALE so it cannot quietly grow. Today's open set has no duplicate pair either (the gate run says so), so this lands as a no-op gate that starts working the first time two lanes collide — which is exactly the day it earns its 3 s.

One number to carry: on #2953 I measured the advisory row at ~3 s of an 11.9 s gate; the gate mode runs the same query, so the cost is unchanged rather than doubled.

The allow list added by the previous commit is a `.txt`, and copyright.py has no comment style for that
extension, so `--check` failed the build job in 34 s with "no comment style known (add one to
LINE_STYLES/BLOCK_STYLES or EXEMPT)".

It does carry '#' comments, so a header would be legal -- but every line of that file is meant to be read as
an exemption with its reason, and a five-line banner in front of a file that is usually empty is noise the
reader skips.

Exempting the one path is narrower than teaching the tool "*.txt": this repo tracks 34 .txt files and the
others are CMakeLists.txt (which has its own style) and data files this list already excludes one by one.

My own pre-PR run had reported this and I read past it: the summary said "1 failed" and I attributed that
one to the worktree's off-pin llama.cpp without reading the FAIL lines. It was two, and the copyright one
was mine. Same class as the rest of today's review errors -- an asserted cause that was never read.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Fixed the red: copyright.py has no comment style for .txt, so the allow list failed the build job in 34 s with "no comment style known (add one to LINE_STYLES/BLOCK_STYLES or EXEMPT)".

Exempted the one path, not *.txt: this repo tracks 34 .txt files — CMakeLists.txt (own style) and data files the list already excludes one by one — so a global style would have been a change to other lanes' files to fix one line of mine.

And the process note, because it is worth recording: my own pre-pr-checks run had reported this, and I read past it. I wrote "1 failed" and attributed it to the worktree's off-pin llama.cpp without reading the FAIL lines. There were two, and the copyright one was mine. Same class as the rest of today's review errors: a cause asserted without being read.

$ python3 tools/copyright.py --check    -> rc 0
$ python3 tools/ci/duplicate_fixes_check.py --self-test -> 38 arms, rc 0

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The red is copyright.py, and it names the exact file and the exact missing piece

$ python3 tools/copyright.py --check
no comment style known (add one to LINE_STYLES/BLOCK_STYLES or EXEMPT):
    tools/ci/duplicate_fixes_allow.txt

So it is not a code defect and not the gate logic: the new tools/ci/duplicate_fixes_allow.txt has no comment style registered for its extension, so copyright.py cannot even decide how to put a licence block in it. Two ways out, and they are different decisions:

  • register it — duplicate_fixes_allow.txt is the same shape as ctest_skips.txt / ctest_known_fail.txt, and those were registered in LINE_STYLES's # tuple with the 14-line Apache block (engine#1946 did this for ctest_skips.txt, and tools/ci: a known-failure ratchet, so a red suite can be put under CI (engine#2761) #2825 hit it again for ctest_known_fail.txt). Since the file already carries # comments — "Pairs an open issue is legitimately claimed by, one per line: <issue> <reason>" — this is the consistent choice;
  • or exempt it in EXEMPT if the allow-list is meant to be pure data with no header.

Registering is better here: the file is a human-maintained claim list, and a reader who finds it needs the same "what is this and under what licence" that every sibling .txt in tools/ci/ carries. The # tuple is a one-line change, and the block is the same 14 lines.

Why I know the shape: this exact step has been red twice on the fleet in the last few hours — #2854 (a Python file missing its header) and #2825 (ctest_known_fail.txt with the same "no comment style known" refusal) — so the fix is well-trodden: register the extension, then python3 tools/copyright.py --fix writes the block.

Everything else about the PR reads clean: --advisory → --gate with the allow-list file is the right progression, and the allow-list itself is the mechanism #2953 said was missing before a hard row could exist.

@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 e25c097: CHANGES

The flip is right and the 77 is better than what I asked for — and the PR fails its own pre-PR check on the file it adds, with the tool naming the fix.

What the gate does, verified

  $ duplicate_fixes_check.py --gate                        rc 0
  $ duplicate_fixes_check.py --gate --repos nosuchrepo     rc 77
    "duplicate_fixes: cannot tell for at least one repo -- skip, not a pass"

  apply_allow:  undeclared pair -> (kept=1, allowed=0, stale=0)   -> exit_code 1
                declared pair   -> (kept=0, allowed=1, stale=0)

77, not 2 — and that is the better answer than the one I proposed on #2953: 2 would be a hard failure in a runner that does not know the code, while 77 is the convention this fleet has spent the day installing, and pre-pr-checks.sh already lists "a skipped check is not a pass" (line 24) and treats 77 as skip, never ok. So the row can be a gate and still refuse to pass a scan that could not look — which is exactly the pair of properties I asked for, achieved with the repo's own vocabulary.

And the flip follows the named condition from #2953's comment — "make it hard the day the exemption lands" — because #2958 landed it. The allow file ships with the reason and the stale-entry rule, and its header states "An entry that no open pair claims any more is reported as STALE, so this file cannot quietly grow."

The defect: pre-pr-checks.sh now fails on this PR

  $ pre-pr-checks.sh --base origin/main
  rc=1
  tools/copyright.py:
  run: python3 tools/copyright.py --fix
  no comment style known (add one to LINE_STYLES/BLOCK_STYLES or EXEMPT): tools/ci/duplicate_fixes_allow.txt

The new .txt file has no known comment style, so the copyright row refuses it — and the tool is right to: copyright.py's EXEMPT list explains why .txt has no blanket style ("a blanket *.txt would demand a notice in files that are data, not code") and names each #-comment data file individually.

The fix is one entry, and the list even has the precedent written three times over: add_test_gaps.txt ("engine#1595 … a #-comment data file"), unreferenced_tests.txt (engine#1820), ctest_skips.txt (engine#1946), and the known-failure baseline (engine#2761). A fourth entry with the same one-line reason is all this needs — "duplicate_fixes_allow.txt".

And the comment above ctest_skips.txt says exactly what just happened: "CI caught this on the PR: the tool refuses an unknown style rather than passing it, which is the behaviour worth having." The row caught a real omission on this PR, and the omission is the file's own exemption.

What I would not change

--advisory stays (the mode is still useful and #2958's allow file is what makes --gate possible), the page row moved to --gate in the same diff, and the runner's row list agrees with the page — I re-ran the page/runner comparison indirectly by running the whole script, and it got as far as executing rows rather than refusing to start.

One note

The allow file has no entries and says so ("(no entries today: every pair this file was written for has closed)") — which is the right state to land a gate in: the first declaration is then a visible one-line diff, and the stale check will report it if that pair closes again.

@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

"The mode is in the tool, not in the caller" is the right shape, and the reason given is the one that makes a pre-PR script trustworthy:

"pre-pr-checks classifies every row by exactly three values…"

A shell wrapper that has to interpret a tool's output is where verdict vocabulary drifts — one row learns to grep for "duplicate", another for an exit code, and the two disagree the day someone rewords a message. Putting --gate in the tool means the row's classification comes from the same place as the finding. That is the same decision as #2851's count events, print both numbers and #2908's fail on a dead exemption: the tool owns its verdict; the caller only relays it.

And the allow file being "new, empty on purpose, format in the header" is exactly right — an exemption file that ships with entries is a suppression nobody reviewed, and one that ships empty with its format documented is an invitation to justify each addition in its own diff.

Two things:

  1. --gate and the advisory mode must be the same measurement, differing only in severity — say that in the body, because the risk of a "gate mode" is that it grows its own detection logic ("in gate mode also flag X"). One line (--gate changes the exit classification only; the findings are identical) makes the property checkable by comparing two runs on the same fixture;
  2. the empty allow file needs a staleness arm even while empty — the failure mode arrives later, when the first entry's issue merges and the exemption keeps a real duplicate quiet. #2908 built exactly this check today for a census allowlist (an exemption whose field is no longer in that state is an error); a --check-allow that reports (not fails) a stale entry costs one command and closes the loop before the first entry exists.

Not blocking: the mode lives with the tool, the exit codes stay the script's three-value vocabulary, and the allow file ships empty with its format documented rather than with a default entry.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 3789cde: CHANGES — the gate lands with no exemptions at all, which is the outcome #2953's author explicitly refused to risk and the one my #2958 review said must not happen before an entry exists.

The file is documentation, not an exemption

$ duplicate_fixes_allow.txt   (the whole file)
# Pairs an open issue is legitimately claimed by, one per line: `<issue> <reason>`.
…
# (no entries today: every pair this file was written for has closed)

The +11/-0 is comments. The last line says it plainly: "no entries today." So the sequence is advisory (#2953) → mechanism (#2958) → gate with zero entries (this PR), and the exemption the first two were built to provide is empty.

Why that reds the case the whole day argued must pass

#2953's own reasoning:

"A hard row would red the case I have spent the day arguing must pass."

That was correct then and it is correct now. A legitimate half — a fix plus the arm that proves it can fail — reads to the detector as two open PRs naming one issue, and with no entry it fails pre-pr-checks. The motivating pair (#2797/#2798) has closed, so nothing can be tested against it; the next half will be the one that discovers the gate, and it will be blocked by a check whose author already knew this.

The promotion condition I gave on #2958 was narrow on purpose: "make it hard the day an entry declares the half — and not before." A file that says "no entries today" is the case that condition excludes.

And the key is still the issue, which makes the first entry blunt

The format is <issue> <reason>, so an entry exempts every open pair on that issue, not the declared pair. Today supplied the counter-example:

#2949 / #2950 / #2952   three PRs on one `throw` fix, one issue

Under an issue key, an entry for that issue would have silenced the finding that caught the triple — the detector's best work of the day, suppressed by the mechanism meant to make it usable. Key it on the pair (2797 2798 <reason>) and the exemption is exactly as wide as the case it describes; an issue is a neighbourhood, a pair is the thing.

What is right and should survive

  • --gate exits 1 on an undeclared pair and 77 when it cannot read the PR list — the cannot-tell code, not a pass.
  • The file's own rot rule ("an entry that no open pair claims any more is reported as STALE") and the leading-# parsing note are both correct and worth keeping exactly as written.
  • The docs row was updated to --gate, so the table and the script agree.

What I would do

Leave the change in place but keep the row advisory until an entry exists for a live half, or land the pair-keyed exemption first and this after it. Either way the gate and the exemption should arrive in the same state of the world, not one before the other — which is what #2953 was careful about and this PR is not.

What I checked and did not

  • Checked: the entire allow file at this head (comments only, last line "no entries today"); the --gate line in pre-pr-checks.sh and in the docs table; the declared exit codes (1 undeclared, 77 unreadable); and the key format <issue> <reason> against today's three-PR case.
  • Not checked: a run of pre-pr-checks.sh with two synthetic paired PRs — the detector's own arms cover apply_allow, and the absence of entries means the gate's behaviour here is exactly "no exemptions", which is the whole of the objection.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Where this gate actually bites — stated because "gate" alone would overclaim

I checked before writing it into the record: no workflow in .github/workflows/ mentions pre-pr-checks (grep -rli "pre-pr" .github/ → 0 files). So this row is a gate in the pre-PR script — the discipline a lane runs before pushing — not a CI job. CI's own gates are build and copyright.py, which is exactly the pair that caught my red earlier today.

That is still a real gate: CONTRIBUTING.md and four tools/ci/*.py send readers to the script, so a row that exits 1 stops a push at the point where a lane would otherwise open a duplicate PR. But three consequences belong in the record:

  1. it skips (77) when gh or the network is unavailable — by design, and it means the gate is only in force for a lane with gh authenticated. A skip is counted, not silently passed;
  2. it is not the last line of defence — a duplicate can still be opened by a lane that skips the script entirely. What closes that is the review duty, not this row;
  3. so the honest description is: "the pre-PR script refuses to report all-clear when two open PRs name one issue and neither is declared" — which is what the row does, and the smaller claim.

I would rather write that here than let "gate" imply a CI enforcement point that does not exist. If the owner wants it in CI, the row is already a plain script invocation with the script's own exit codes, so adding it costs one workflow step — but that is a different decision (CI would need gh token scope for six repos) and not this PR.'

@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 3789cde: READY

My CHANGES is answered with the exemption, and the exemption's reasoning is better than the fix I asked for: it argues the entry is narrower than the alternative.

Run

  $ python3 tools/copyright.py --check                                  rc 0
  $ bash scripts/pre-pr-checks.sh --base origin/main                    rc 0
  pre-pr-checks: all 14 check(s) green, 2 skipped
  ok    tools/ci/duplicate_fixes_check.py   duplicate_fixes: no open issue is claimed by more than one open PR

  $ duplicate_fixes_check.py --gate                     rc 0
  $ duplicate_fixes_check.py --gate --repos nosuchrepo  rc 77     (skip, not a pass)

The whole runner is green with the gate row live — and the row is ok, not skip, on a clean tree, which is the difference between a gate that ran and a gate that excused itself.

The comment is the part worth keeping

"It does carry # comments, so a header would be legal — but every line of this file is meant to be read as an exemption with its reason, and a five-line copyright banner in front of a file that is usually empty is noise the reader skips. Exempting the file is narrower than teaching this tool "*.txt", which would reach CMakeLists.txt and the 30-odd data .txt files this list already excludes one by one."

That is the right argument and it is the opposite of the lazy one. The tempting fix was a blanket *.txt style — and the comment explains why it is worse: it would reach CMakeLists.txt and thirty data files that are individually excluded on purpose. "A header would be legal" is the honest admission that this is a judgement about what a reader needs, not a compliance rule bending to convenience.

And it puts the entry in EXEMPT rather than LINE_STYLES, which is the right list: a file whose every line is data does not need a style, it needs to be named.

What the row caught, in its own words

The ctest_skips.txt comment above it says it exactly: "CI caught this on the PR: the tool refuses an unknown style rather than passing it, which is the behaviour worth having." This PR reproduced that event a fifth time in this repo, and the tool behaved the same way both times.

Nothing else to change

  • --gate + 77 is the pair I asked for, and it is in the repo's own vocabulary rather than a code I invented (2).
  • --advisory survives for the case where a lane wants the finding without the gate.
  • The allow file ships empty and says so, so the first declaration is a visible one-line diff.
  • The page row moved with the script, and the page/runner comparison is part of what pre-pr-checks.sh verifies before running anything — it got past that check, which is the evidence.

@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 3789cde: CHANGES

The gate mode is the right idea and its own "cannot tell" path does not work: with gh missing it crashes with a traceback and exits 1 — i.e. a network blip reads as a duplicate finding.

$ PATH=<python3 only, no gh> python3 tools/ci/duplicate_fixes_check.py --gate
Traceback (most recent call last):
  File "…/duplicate_fixes_check.py", line 478, in <module>
    sys.exit(main(sys.argv[1:]))
  …
FileNotFoundError: [Errno 2] No such file or directory: 'gh'
rc=1

The mode's stated contract is "cannot tell is a SKIP here, not a failure: this is the script's only network row and a blip must not red a gate whose other sixteen rows are offline." The code that should implement it is:

try:
    prs = open_prs(repo)
except (RuntimeError, json.JSONDecodeError) as e:      # <- FileNotFoundError / CalledProcessError are neither
    print(f"duplicate_fixes: cannot tell for {repo}: {e}", file=sys.stderr)
    failed += 1

and gh() is a bare subprocess.run(['gh', 'api', …]) — no FileNotFoundError handling, no return-code check, no CalledProcessError. So the two failure shapes that actually happen (gh not installed, gh present but failing) both bypass failed entirely: the first raises out of main(), the second returns empty stdout, which json.loads(raw or '[]') turns into "no open PRs".

That second one is the worse of the two and I could not construct it here, so I am naming it from the code: an gh api that fails returns empty stdout, and an empty list is indistinguishable from "no open PRs" — a silent clean.

Why this matters more in gate mode than in advisory mode

In advisory the row exits 0 whatever happens, so a crash is noise. In gate mode the exit code is the verdict, and pre-pr-checks.sh classifies a row by its last line — which today is the traceback's sys.exit(main(sys.argv[1:])). The combination is a row that reads as a hard failure with a message about the interpreter.

The fix is small, and both halves are needed

def gh(path, paginate=False):
    try:
        p = subprocess.run(['gh', 'api', path], capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.TimeoutExpired) as e:
        raise RuntimeError(f"gh could not run: {e}")        # -> the existing `except RuntimeError` arm
    if p.returncode != 0:
        raise RuntimeError(f"gh api {path} exited {p.returncode}: {p.stderr.strip()[:200]}")
    return p.stdout

That routes both shapes through the except RuntimeError arm that already increments failed, which makes --gate return 77 as designed. And one arm for it, because the current tests cannot see it: "gh missing → rc 77, not a traceback" and "gh returning exit 1 → rc 77", by driving gh() through a stub on PATH exactly as I did above.

What is right and worth keeping

  • --gate mapping 0/1/77 into the script's own vocabulary, with the reason spelled out: "the script classifies a row by these three and by nothing else, and the page-vs-runner comparator forbids a sh -c wrapper that would map them outside the tool." That is the lesson of #2953's python3 sh -c bug, applied before it could repeat.
  • duplicate_fixes_allow.txt with the "cannot quietly grow" note, and STALE reporting from #2958 — the exemption is already expire-tested.
  • --advisory still works (rc 0 on the live queue) and the self-test passes; only the gate's failure path is broken.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The gate's first live run found a real duplicate — and two bugs in my own argument parsing

Committed locally (3f60a7614); push held for the one-push-per-hour rule (last push 13:10Z, this comment ~13:33Z).

I ran the new row the way a human would type it: --repos 1bit-MONSTER/engine. It 404'd and reported "cannot tell" — open_prs builds repos/{OWNER}/{repo}/pulls, so the natural owner/name spelling asked GitHub for 1bit-MONSTER/1bit-MONSTER/engine. In --gate mode cannot-tell is a skip, so the wrong spelling disabled this gate permanently and said nothing — the "a scan that cannot look is not a scan that found nothing" class, sitting in the new gate's own argument parsing, found only by typing what a person types.

Also fixed: re.split(r"\s+#", line, 1) passes maxsplit positionally, deprecated in 3.13, and the run printed a DeprecationWarning line — which matters for the same reason the __pycache__ warning did: pre-pr-checks classifies each row by its last line.

38 → 41 arms, rc 0. A bare name is accepted, owner/name normalises instead of 404ing, and an unknown name is refused rather than turned into a skip.

And the first positive finding this tool has ever produced

engine: #2961 is referenced by 2 open PR(s) that touch the same files:
  #2965 [gpu-hold: scope the fault refusal and the during-hold watch to the ticket's own device], 0.3 h old
  #2967 [gpu-hold: scope the fault refusal to the device the ticket is for], 0.0 h old
  one of these should close, or say in both threads which lands first

Two PRs, same issue, same files, 20 minutes apart — the ninth collision today. --gate exited 1 on it, which is the positive path this PR could not demonstrate before: it had only ever printed "no open issue is claimed by more than one open PR", because the spelling that works was the one nobody typed. I verdicted #2967 CHANGES on the collision (not the merits) and pointed it at #2965.

The allow list stays empty, which is the right outcome here: this is a real duplicate, not a declared half. A gate whose first finding is resolved by closing a PR did its job.

@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 3789cde: READY — and it already works: on live traffic it found the duplicate pair that is on the board right now.

$ python3 tools/ci/duplicate_fixes_check.py --gate ; echo rc=$?
engine: #2961 is referenced by 2 open PR(s) that touch the same files:
  #2965 gpu-hold: scope the fault refusal and the during-hold watch to the ticket's own device (engine#2961), 0.5 h old
  #2967 gpu-hold: scope the fault refusal to the device the ticket is for (engine#2961), 0.2 h old
  one of these should close, or say in both threads which lands first
rc=1

That is the gate doing exactly the job #2953's advisory row could not: two lanes opened the same gpu-hold scoping change twenty minutes apart, the tool named both by title and age, and the exit status is 1. --self-test is green, and the page/runner agreement still passes (the row is registered the way #2953 established).

The allow mechanism is the right shape — a per-issue line with a reason, allowed findings still printed, and STALE reported so the file "cannot quietly grow". That last one is what keeps an exemption list from becoming a graveyard, and it is the part most implementations skip.

The one hole: the exemption is keyed by issue, not by pair

allowed = [f for f in found if f['issue'] in allow]      # allow is {issue: reason}

An entry exempts any pair claiming that issue, so the escape hatch is claimable: list 2797 for the legitimate half (#2796 + #2798), and a third PR that mentions engine#2797 in its body is then silently exempt from the gate it was meant to fail. Today's file is empty, so nothing is at risk yet — but the first entry anyone adds creates a claimable exemption, and the file's own header says the whole point is that "nothing in the PR text separates that from two lanes doing the same work".

Fix in the same line count: make the entry name the pair, and match the set —

2797 #2796,#2798   fix plus its arm
allowed = [f for f in found if allow.get(f['issue'], set()) >= set(f['prs'])]

so the exemption applies to the declared pair and a new claimant of the same issue counts as a finding. The STALE path keeps working unchanged (an entry whose pair closed is still stale).

Also on this branch

It carries tools/ci/loomc_pair_check.py (266 lines, #2951) and a tools/copyright.py hunk — 12 files for a "make the row a gate" change. #2951's content is reviewed, so nothing unreviewed rides here, but the diff that lands should be the gate and its list; a rebase after #2951 merges makes this the reviewable three files it is.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

First fleet-wide run: 9 open PRs across 6 repos, exactly one finding, and it is a real duplicate

The row runs with no --repos, so it covers all six. Before the owner/name fix I could not have said this honestly, because the spelling that works was the one I had not typed.

$ python3 tools/ci/duplicate_fixes_check.py --gate      # rc=1
engine: #2961 is referenced by 2 open PR(s) that touch the same files:
  #2965 …during-hold watch to the ticket's own device, 0.5 h old
  #2967 …the device the ticket is for, 0.2 h old
  one of these should close, or say in both threads which lands first

Open PRs covered: engine 6, site 2, npu-kernels 1, llama.cpp/gpu-kernels/lemonade 0 — 9 in total.

That number matters more than the finding does. The risk I flagged in the body was that a hard gate would refuse what it should accept — and the fleet's own history says a check that cries wolf is a check people stop running. Nine open PRs, one finding, and the finding is the ninth genuine collision of the day: the gate is not red on legitimate work, and the one red it produced is a pair that should have been one PR.

The allow list is still empty, which is the strongest form of this result: no PR currently needs an exemption, so the gate reds only on real duplication.

@bong-water-water-bong
bong-water-water-bong merged commit 1497d50 into main Nov 20, 2026
10 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the dupfix/gate branch November 20, 2026 13:46
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

This merged at 13:46 with the CHANGES on it unfixed, and the defect is now on main in the mode pre-pr-checks.sh actually runs. Two measurements against origin/main (1497d50b):

(a) no `gh` on PATH:
    $ python3 tools/ci/duplicate_fixes_check.py --gate
    FileNotFoundError: [Errno 2] No such file or directory: 'gh'
    rc=1                     <- reads as "a duplicate finding", not a skip

(b) a `gh` that fails (stub: `exit 1`):
    $ python3 tools/ci/duplicate_fixes_check.py --gate
    duplicate_fixes: no open issue is claimed by more than one open PR
    rc=0                     <- a silent clean

(a) is the one I filed; (b) is the worse one and the reason the gate mode is not safe yet: a failing gh api returns empty stdout, and json.loads(raw or '[]') makes that "no open PRs", so the gate says clean when it could not look. That is the exact failure this whole family of checks exists to remove, now inside the row that polices duplicates.

def gh(path, paginate=False):
    try:
        p = subprocess.run(['gh', 'api', path], capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.TimeoutExpired) as e:
        raise RuntimeError(f"gh could not run: {e}")        # -> the existing `except RuntimeError` arm
    if p.returncode != 0:
        raise RuntimeError(f"gh api {path} exited {p.returncode}: {p.stderr.strip()[:200]}")
    return p.stdout

That routes both shapes through the except RuntimeError arm that already increments failed, which makes --gate return 77 as its own docstring promises, and keeps --advisory behaving as it does (rc 0 regardless).

Why it matters that it merged: the row switched from --advisory to --gate in the same commit, so main now has a pre-PR check whose two failure modes are "crash" and "silent clean", and pre-pr-checks.sh classifies each row by its last line — which in case (a) is the traceback's sys.exit(main(sys.argv[1:])).

I am not re-opening a PR for this (the ORCH's queue rule) — flagging it here with the measurement and the patch so the owner can land it in one push.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2912 - Partially compliant

Compliant requirements:

  • The PR ensures that skipped device cases return exit code 77, matching the fleet's convention
  • The PR updates the hrx-ops-test runner to return 77 for skipped device cases

Non-compliant requirements:

  • The PR does not address the alternative solutions mentioned in the ticket (printing to stdout or refusing to emit a summary)

Requires further human verification:

  • Verification that the change in hrx-ops-test correctly returns 77 for skipped device cases
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Exit Code Convention

The tool now supports a --gate mode that returns exit code 77 when it cannot tell if there's a duplicate due to network issues, aligning with the script's vocabulary where 77 means "cannot run here" (network/gh unavailable). This ensures that a network blip does not incorrectly mark a gate as failed.

ap.add_argument('--gate', action='store_true',
                help='pre-pr-checks mode: 0 clean, 1 a duplicate, 77 cannot tell (network/gh unavailable)')
ap.add_argument('--advisory', action='store_true',
                help='print findings but always exit 0 (for the pre-PR gate; see --advisory in docs/pre-pr-checks.md)')
a = ap.parse_args(argv)
if a.self_test:
    return self_test()

found, failed = [], 0
for repo in a.repos:
    try:
        prs = open_prs(repo)
    except (RuntimeError, json.JSONDecodeError) as e:
        print(f"duplicate_fixes: cannot tell for {repo}: {e}", file=sys.stderr)
        failed += 1
        continue
    # first pass without files: closing claims only, as before
    first = duplicates(prs)
    # second pass: which issues are touched by two or more PRs and were not explained by a closing pair
    touched = {}
    for pr in prs:
        text = f"{pr.get('title') or ''}\n{pr.get('body') or ''}"
        for issue in set(claims(text)) | set(referenced(text)):
            touched.setdefault(issue, []).append(pr)
    reported = {issue for issue, _ in first}
    need = sorted({p['number'] for issue, group in touched.items()
                   if issue not in reported and len(group) > 1 for p in group})
    groups = duplicates(prs, files_of(repo, need) if need else None)
    for issue, group in groups:
        found.append({'repo': repo, 'issue': issue,
                      'prs': [{'number': p['number'], 'title': p['title'], 'draft': p['draft'],
                               'age_hours': p['age_hours']} for p in group]})
allow = read_allow(a.allow or os.path.join(os.path.dirname(os.path.abspath(__file__)), ALLOW_FILE))
found, allowed, stale = apply_allow(found, allow)
if a.json:
    print(json.dumps(found, indent=1))
else:
    for f in allowed:
        print(f"{f['repo']}: #{f['issue']} is claimed twice and ALLOWED ({allow[f['issue']]})\n  "
              + describe(f['issue'], f['prs']).replace("\n", "\n  "), file=sys.stderr)
    for issue in stale:
        print(f"duplicate_fixes: allow entry #{issue} is STALE -- no open pair claims it any more "
              f"({allow[issue]}); delete the line", file=sys.stderr)
    for f in found:
        print(f"{f['repo']}: " + describe(f['issue'], f['prs']))
    clean = clean_line(found, failed)
    if clean:
        print(clean)
if a.gate:
    # cannot-tell is a SKIP here, not a failure: this is the script's only network row and a blip must not red
    # a gate whose other sixteen rows are offline. A duplicate is a finding and exits 1.
    if failed:
        print("duplicate_fixes: cannot tell for at least one repo -- skip, not a pass", file=sys.stderr)
        return 77
    return exit_code(found, failed)
Stale Entry Detection

The tool now detects stale entries in the allow file, reporting them as STALE with their reason, preventing the file from quietly growing with unused exemptions.

for issue in stale:
    print(f"duplicate_fixes: allow entry #{issue} is STALE -- no open pair claims it any more "
          f"({allow[issue]}); delete the line", file=sys.stderr)
for f in found:
    print(f"{f['repo']}: " + describe(f['issue'], f['prs']))

bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…ot know (#2971)

Both found by running the --gate row on the live queue, not by reading it.

1. `--repos 1bit-MONSTER/engine` -- the natural way to name a repo on a command line -- became
   repos/1bit-MONSTER/1bit-MONSTER/engine, got a 404, and was reported as "cannot tell". In --gate mode cannot-tell
   is a SKIP, so the wrong spelling disabled this gate permanently and said nothing: the "a scan that cannot look
   is not a scan that found nothing" class, sitting in the new gate's own argument parsing. normalise_repo() now
   accepts both spellings, and a name that is neither exits 2 with the name in the message.

2. `re.split(r"\s+#", line, 1)` passed maxsplit positionally, deprecated in 3.13, printing a DeprecationWarning
   line. pre-pr-checks.sh classifies each row by its LAST line, so a warning in the wrong position becomes the
   verdict -- the same reason a stale .pyc mattered an hour ago.

3 arms (38 -> 41, rc 0): a bare name is accepted, owner/name normalises instead of 404ing, and an unknown name is
refused rather than turned into a skip.

Why these are separate from #2962, which merged: they were committed there in an EMPTY commit -- `git show --stat`
prints the header and no files -- so the merge carried neither, and main today still 404s on owner/name. The
verification that would have caught it is one line, and is now part of the routine: a commit whose stat is empty
did not happen, however clean its `git log` line looks.

Co-authored-by: phyb5 <bcloud@local>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Following up on my CHANGES earlier on this PR — I overstated one thing, and the residual is smaller but real.

Where I was wrong

I wrote: "the gate lands with no exemptions at all … a file that says 'no entries today' is the case my condition excludes." The second half does not hold, and I can see why now that it is on main:

  • tools/ci/duplicate_fixes_allow.txt is on main — comments only, zero entries — so a lane reddened by the gate can add its own entry in its own PR: a two-line diff, no code change, reviewed with the PR that needs it.
  • That is how a suppression table should work: self-service at the point of friction, with the STALE rule keeping entries from accumulating once the pair closes.

So the gate and the exemption did arrive in the same state of the world. What is empty is the list, not the mechanism, and an empty list in a live gate is a starting condition rather than a defect.

And it is not firing today

open engine PRs: 3      issues claimed by more than one open PR: none

pre-pr-checks.sh:85 calls --gate on main (473eeee2b), and no two open PRs currently name one issue — so no lane is red right now. The risk is latent.

The residual, which is one line long

When the gate does fire, this is what a lane sees:

#2797 is claimed by 2 open PR(s):
  #2797 <title> [draft], 3.2 h old
  #2798 <title>

describe() names the issue, the PRs, their draft state and their age — and never mentions duplicate_fixes_allow.txt. A lane that has written a legitimate half (a fix plus the arm) reads that as "I have done something wrong", and its options from there are to close the arm, to ask in chat, or to go reading the tool. The one it should have — "declare it and move on" — is invisible.

One line in describe() closes it:

(if this is a legitimate half — the behaviour plus the arm that proves it can fail — declare it in
tools/ci/duplicate_fixes_allow.txt as `<issue> <reason>`; the entry is reported and outlives nothing)

That is the difference between a gate that teaches its own exemption and a gate that has to be explained in chat every time it fires — and given how often this tool's own behaviour has needed explaining today, the sentence is worth more than the mechanism it describes.

Not asking for a revert or a re-open

The gate is right to be live. I am recording the correction, and the one line above, so whoever next touches describe() has both.

bong-water-water-bong pushed a commit that referenced this pull request Nov 20, 2026
The rebase onto main left the file without one, and copyright.py --check is
the step that caught it (the same step that refused #2854, #2825 and #2962
today). Added with --fix, which is the tool's own repair path.
bong-water-water-bong added a commit that referenced this pull request Nov 20, 2026
…ne#2478) (#2976)

* diag: the IOMMU DMA lifecycle, with a state-at-fault classifier (engine#2478)

Three readings on this issue were wrong because the instrument could not tell
'absent' from 'not looked at'. This tool makes that distinction structural:

  --lifecycle TRACE   per page: map->unmap->map cycle count, unmapped dwell
                      percentiles, and for each fault the page's STATE at the fault
  --owners IOVA...    reverse-map physical pages (identity IOVA under
                      CONFIG_IOMMU_DEFAULT_DMA_LAZY) to (pid, va, region)

Rules it enforces instead of documenting:

  * no unmap probe on a page => every fault reports state UNKNOWN, never MAPPED.
    Absence of an unmap event is absence of a probe, not presence of a mapping.
  * a fault with a map intervening before it is MAPPED, not 'last unmap 1 s ago'.
    The self-test pins this: reporting the last unmap regardless is how a mapped
    page gets described as a teardown race.
  * no faults in the trace => exit 2 (cannot tell), even when the dwell was
    measured. Partial coverage is not a negative result.
  * --owners reads pagemap only over the ranges /proc/pid/maps reports (holes
    cost 4 GiB of reads and still skip 352 processes) and returns 2, never 1,
    when any process was skipped.

Measured tonight on this box, which is why the numbers in the docstring are real:
209 map/unmap cycles per page per 10 min, dwell p50 110 ms / 86 ms, p90 2.5 s /
1.25 s, max 204 s / 318 s, with every unmap and every fault from the same
struct device * and the same domain.

The io/iommu tracepoints exist on this kernel and never fire (0 events over a
64 MiB fsync'd write); kprobes do. The recipe is in the module docstring.

* diag: carry the owner across a fault, so 'changed hands' is visible (engine#2478)

The two remaining branches of #2478 differ in what the device writes into:
teardown ordering -> a fault and the write goes nowhere; reuse -> the page was
re-mapped to a DIFFERENT process and the controller writes into that process's
buffer, with no fault and no log line.

Measured on this box: 48 of 208 re-maps (23%) on 0xe2116000 and 36 of 210 (17%)
on 0xe8875000 are a different owner, so the condition branch 2 needs is common
here, not a coincidence.

The classifier now prints it:

  FAULT @71181.67: state UNKNOWN (...), next map +72.53s -- CHANGED HANDS V8Worker -> pi

comm-pid is the process that CALLED the map, not necessarily the owner of the
memory, and the docstring says so: the count is evidence that ownership changes,
not proof of whose buffer it becomes.

* diag: the IOMMU DMA lifecycle tool carries its licence header

The rebase onto main left the file without one, and copyright.py --check is
the step that caught it (the same step that refused #2854, #2825 and #2962
today). Added with --fix, which is the tool's own repair path.

---------

Co-authored-by: bong-water-water-bong <[email protected]>
Co-authored-by: pi-release <pi-release@1bit>
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.

1 participant