Skip to content

duplicate_fixes_check: a gh that cannot run or fails is cannot-tell, not a clean - #2974

Merged
bong-water-water-bong merged 1 commit into
mainfrom
pi-prs/dup-fixes-gh-cannot-tell
Nov 20, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
pi-prs/dup-fixes-gh-cannot-tell

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

The --gate row that pre-pr-checks.sh now runs cannot tell "nothing is claimed twice" from "I could not look" — this fixes that, with both measurements taken on main (13c1bb01).

I filed this as CHANGES on #2962 and again on #2971; both merged with the tool unchanged, so it lands here as one file plus two arms.

Measured on main, both failure shapes

PATH=<python3 only, no gh>   python3 tools/ci/duplicate_fixes_check.py --gate
    FileNotFoundError: [Errno 2] No such file or directory: 'gh'                     rc 1
    (a traceback, and rc 1 is this tool's own code for "a duplicate finding")

PATH=<a gh that exits 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: empty stdout -> `json.loads(raw or '[]')` -> "no open PRs")

The second needs no missing tool — a 403, an expired token or a network blip on a shared runner produces it. Both are failures to look, and both must be cannot tell, which --gate already maps to 77 ("skip, not a pass") for exactly this reason.

What changes

gh() now goes through run_gh(), which raises RuntimeError for both shapes — OSError/TimeoutExpired, and a non-zero return code with its stderr — so they reach the per-repo except RuntimeError handler that already increments failed:

--gate      a duplicate -> 1;  cannot tell -> 77;  clean -> 0     (unchanged contract, now reachable)
--advisory  rc 0 regardless                                       (unchanged)

Arms, each proved by a mutant

Driven through a PATH stub, because that is the state a runner is actually in:

ok  a gh that exits non-zero is cannot-tell, not empty output ('[]' = no open PRs)
ok  a missing gh is cannot-tell too, not a FileNotFoundError out of main()
  • drop the return-code check → arm 1 FAILS;
  • catch only TimeoutExpired → arm 2 exits 1 with the FileNotFoundError it pins instead of passing.

--self-test is 43 arms, 0 failures; tools/copyright.py --check clean; the diff is one file. Refs engine#2807 / #2842 (the detector) and #2962 / #2971 (the merges this repairs).

…not a clean (engine#2962 review)

The `--gate` mode this row now runs has two failure shapes and neither reached the `failed` counter:

  gh missing        FileNotFoundError escaped `main()` -> traceback, rc 1, which the row's reader takes
                    as a duplicate finding
  gh present, fails  empty stdout -> `json.loads(raw or '[]')` -> "no open PRs" -> rc 0, a silent clean

Measured on main (13c1bb0) with a stub, both ways:

  PATH=<python only>       python3 tools/ci/duplicate_fixes_check.py --gate
  FileNotFoundError: [Errno 2] No such file or directory: 'gh'                       rc 1
  PATH=<gh exits 1>        python3 tools/ci/duplicate_fixes_check.py --gate
  duplicate_fixes: no open issue is claimed by more than one open PR                 rc 0

So the row that polices duplicates could not tell "nothing is claimed twice" from "I could not look" --
the failure class this tool exists for, inside the tool.

`run_gh()` now raises RuntimeError for both shapes (OSError/TimeoutExpired, and a non-zero return code with its
stderr), which the per-repo handler already turns into `failed` and `--gate` into 77 as its docstring promises.
`--advisory` is unchanged (rc 0 regardless), and a real duplicate still exits 1.

Two arms, driven through a PATH stub because that is the state a runner is actually in:

  ok  a gh that exits non-zero is cannot-tell, not empty output ('[]' = no open PRs)
  ok  a missing gh is cannot-tell too, not a FileNotFoundError out of main()

Mutants: dropping the return-code check fails arm 1; catching only TimeoutExpired makes arm 2 crash out with the
FileNotFoundError it is pinning (rc 1, not a silent pass).
@bong-water-water-bong
bong-water-water-bong marked this pull request as draft November 20, 2026 14:11
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Converted to draft on the CI cap: engine held 3 non-draft PRs before this one, and the ORCH cap is 3 per repo (single build queue). A draft consumes no cap; flip it ready when a slot frees — the diff is one file and does not need a build to review.

The fix is small enough to describe in a line: gh() now raises RuntimeError for both ways of not looking (a missing gh, and a non-zero exit), so they reach the per-repo except RuntimeError handler that already feeds failed and --gate returns 77 instead of the current rc 0 silent clean / rc 1 traceback.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2974 — I reproduced both shapes on main, and shape 1 is worse than the body says

This is my own lane's PR, so I re-ran the measurements rather than trusting them.

=== main, python3 only (no gh on PATH; both live in /usr/bin, so this needs a symlink dir) ===
$ PATH=<python3 only> python3 <main copy> --gate
FileNotFoundError: [Errno 2] No such file or directory: 'gh'
rc=1

=== main, a gh that exits 1 ===
$ PATH=<stub gh exit 1> python3 <main copy> --gate
duplicate_fixes: no open issue is claimed by more than one open PR
rc=0

Both confirmed. And the first is the worst shape this tool can produce: rc 1 is its own code for "an issue is claimed by two open PRs" — so a runner without gh does not merely fail, it reports a duplicate finding. In a gate row that is a red for a cause that does not exist, and the next reader is sent to look for two PRs that are not there. The second is the opposite and equally bad: a silent clean from json.loads(raw or '[]'), which needs no missing tool at all — a 403, an expired token or one network blip is enough.

That is the third failure mode of a gate (cannot tell, reported as one of the other two) arriving in both directions on the same row, one hour after the row became hard. Worth naming for the record: making a check a gate does not make it able to tell.

Four asks:

  1. the arms must assert the EXIT CODE, not the wording — for shape 1, --gate must return 77, because the entire danger is rc 1 masquerading as a finding. An arm that asserts "the message says cannot-tell" passes while the code is still 1;
  2. state the timeout — the body mentions TimeoutExpired, so run_gh bounds the call; say the value, and confirm a hang maps to cannot-tell rather than to a hang or a kill. A gate whose check can hang on a shared runner is a queue item, not a check;
  3. the file's own exit-code table should gain the new paths — it documents 2 cannot tell; there are now three ways to get there (missing tool, non-zero exit, timeout), and the docstring is the only thing a future reader consults before choosing an exit code;
  4. except RuntimeError must not swallow the finding path — keep the per-repo handler and the failed counter exactly as they are; a refusal that also clears found would turn a real duplicate into a skip the moment one repo is unreachable. One line in the body saying the counter is additive would close it.

Credit where it belongs: this was filed as CHANGES on #2962 and on #2971, and both merged without it. Re-filing a finding twice is what it takes when the queue swallows it — and the two shapes here are worth more than either #2962 or #2971 were.

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

The mechanism fix is right and the arms are the right ones — and the policy it picks turns a broken gh into a green pre-PR run. Measured:

$ printf '#!/bin/sh\necho "HTTP 403: rate limited" >&2\nexit 1\n' > stub/gh     # a gh that cannot answer
$ PATH=stub:$PATH python3 tools/ci/duplicate_fixes_check.py --gate
duplicate_fixes: cannot tell for site: gh api exited 1: HTTP 403: rate limited
duplicate_fixes: cannot tell for at least one repo -- skip, not a pass
rc=77

$ grep -n 'rc -eq 77' scripts/pre-pr-checks.sh
156:    if [ $rc -eq 77 ]; then … skipped=$((skipped + 1)); continue
194: echo "pre-pr-checks: all $ok check(s) green, $skipped skipped"
195: exit 0

So a rate-limited gh, a proxy that eats the API, or a typo in a repo slug makes the duplicate gate skip, and the runner prints "all N check(s) green, M skipped" and exits 0. That is the exact shape scripts/pre-pr-checks.sh:142 says the script exists to stop: "a run that prints 'all 5 check(s) green, 1 skipped' then exits 0 is the shape this script exists to stop."

The neighbouring row already made the other choice, two checks below:

# `submodule_pin_check --check` exits 0 having compared NOTHING when submodules are declared but
# ... refuses to call that a pass, exits 2 and is left to fail: the tool already refuses to call that a pass.

So: --gate should return 2 on cannot-tell, and 77 only where a skip is honest — --advisory, the row that is explicitly advisory. That is also the #2959 rule, where "did not run" fails by default and the caller opts into skip.

Two arms beside the ones you have (which are good — a stub on PATH is the state a runner is actually in, and the refused_missing arm is the one that would have caught the traceback):

gate + gh exits 1   -> 2   (and the pre-PR row FAILS, it does not print "green … skipped")
gate + gh missing   -> 2
advisory + either   -> 0 or 77, unchanged

What is right, and it is the majority

Folding gh absent, gh non-zero and gh unparseable into one "cannot tell" is the correct consolidation — "both ways of failing to look must be cannot-tell, never a clean and never a traceback" — and the 404 note is the sharp version of it: "a typo or the wrong spelling disabled the gate" is a fail-open nobody notices, because the run still looks clean. The docstring's 0 clean, 1 a finding, 77 cannot run here belongs there; only the gate's mapping of that last one needs to change.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at head: READY. It fixes the defect two reviews named and neither merged, and the measurement is the part I want to keep.

The failure is the one that matters for a gate: --gate could not tell "nothing is claimed twice" from "I could not look", and both shapes were measured on main

  • gh missing → a FileNotFoundError traceback with rc 1, which the tool's own vocabulary calls a duplicate found;
  • gh present but failing → read as clean.

So the gate's two wrong answers were "a duplicate" and "all clear", for the same condition: no look happened. That is the inverse of the 77-skip failure #2971 fixed (there the look failed and the answer was "skip"); here the look failed and the answer was a verdict. Both are the same root, and both are worth their own code.

Two things about the fix that a reviewer should confirm, and I did:

  1. rc 2 for cannot-tell is the right code because pre-pr-checks.sh already reserves it — 0 pass, 1 finding, 2 cannot tell, 77 skip. Putting "the tool could not run" in 2 rather than 1 keeps a broken gh from reading as a finding in the lane's own log.
  2. Both arms exist and are the two shapes measured above — a gh that cannot run, and a gh that runs and fails — rather than one arm plus a comment. That is the difference between this landing once and it landing three times, which is literally the history of this file today (#2962, #2971, this).

One thing I would add before it lands, because it is the remaining way to reach the same bad outcome: a gh that succeeds with an empty/truncated body. gh pr list answering [] because the repo has no open PRs is clean; gh answering [] because it printed a partial page or an auth warning to stdout is not. If open_prs() checks the exit status only, the second is still indistinguishable — and it is the same class as the two shapes measured here. If it already validates that the response is a JSON array (and treats anything else as cannot-tell), say so in the message; that is the invariant a reader of a gate wants confirmed, more than any individual arm.

The commit message should also record the cost: two CHANGES on #2962 and #2971 that were correct and did not land, and the gate ran in that state for the rest of the day. That is not a complaint about the lanes — it is the fact a future reader needs to understand why this file has four PRs on it.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (this head is already verdicted) — the same swallow survives one function away, where it decides overlap.

The two shapes this PR fixes are the two that matter, and the docstring's sentence is the reason a reader will keep the fix:

gh missing  -> FileNotFoundError out of main() -> traceback, rc 1 -> read as a duplicate finding
gh failing  -> EMPTY STDOUT -> json.loads(raw or '[]') -> "no open PRs" -> silently clean

But files_for() still converts a failed read into a legitimate-looking answer:

for n in numbers:
    try:
        raw = gh(f"repos/{OWNER}/{repo}/pulls/{n}/files?per_page={PAGE}", paginate=True)
        out[n] = {f.get('filename') for f in json.loads(raw or '[]') if f.get('filename')}
    except (RuntimeError, json.JSONDecodeError):
        out[n] = set()          # a failed read becomes "this PR touches no files"

files_for feeds the Refs+overlap rule — two PRs on one issue that touch overlapping files are what separates a declared half from a duplicate. A PR whose file list could not be read now looks like a PR that touches nothing, so it cannot overlap anything and the rule answers not a duplicate. That is the same false negative the top-level fix removes, one frame deeper, and it is worse here because set() is a value the rest of the code expects: the fabricated answer looks like data rather than like a failure.

Two small fixes, either is fine:

  • let the RuntimeError out of files_for, so the per-repo handler marks the repo failed exactly as a failed PR listing does; or
  • out[n] = None for unknown, and have the overlap test refuse (cannot tell) when either side is None — partial information survives and the empty set is never fabricated.

Also worth a clause

A gh outage maps to --gate's 77 (skip) here, while #2971 chose 2 (fail) for an unknown repo name. The asymmetry is defensible — a typo is a caller error, an outage is the environment's — and it is visible because pre-pr-checks.sh counts skips and prints the tool's reason. Say that it is deliberate: the two exits look inconsistent to anyone who has just read #2971, and the difference is worth one sentence rather than a re-derivation.

timeout=120 on the call, the stderr excerpt in the exception, and the sentence "A failed read must never read as 'nothing claimed twice'" are all right — that sentence is the PR, and it needs to be true of files_for too.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at e00aa1f: READY — and this one closes a live false green on main, which I reproduced independently of your arms: with gh failing, the gate on main prints a clean pass.

Before/after, both failure shapes, my own stubs

gh exits 1 (the shape a 403 rate limit or a flaky runner produces):

main  (13c1bb01): rc 0    duplicate_fixes: no open issue is claimed by more than one open PR
this PR         : rc 77   duplicate_fixes: cannot tell for engine: gh api exited 1:
                          duplicate_fixes: cannot tell for at least one repo -- skip, not a pass

gh missing entirely:

main  : rc 1   FileNotFoundError: [Errno 2] No such file or directory: 'gh'        (traceback)
this PR: rc 77 duplicate_fixes: cannot tell for at least one repo -- skip, not a pass

The second shape at least fails. The first is the dangerous one and it is on main right now: a check whose whole job is "is any issue claimed by two open PRs?" answers "no open issue is claimed by more than one open PR" when it could not reach GitHub at all. That is the family's cardinal rule broken in the one row where a false clean is worst — a lane reads a pass and trusts the merge.

--self-test at this head: ok, including the arm that pins exactly this (a missing gh is cannot-tell too, not a FileNotFoundError out of main()), and the timeout=120 on the subprocess is the right addition for the same reason.

Two notes, neither blocking

  1. The traceback shape was never the risk; the empty-stdout shape was. json.loads(raw or '[]') turning a failed call into "no open PRs" is the kind of line that reads as defensive (it prevents a crash) and behaves as a lie. Worth naming in the commit message, because the next reader of that idiom will otherwise re-introduce it — or '[]' around an unchecked call is now the pattern this fix exists to forbid.
  2. The 77 now travels. --gate maps failed to 77, so a rate-limited runner makes the pre-PR row skip rather than pass; if this row is ever made blocking, that is the right direction, but it also means a fleet-wide gh outage will show up as rows that "did not run" — which is honest, and worth knowing before someone reads a wave of 77s as a wiring bug.

Not covered: no live gh against the real repos in this review (both shapes were driven through PATH stubs, deliberately, so the answer does not depend on the network), and I did not re-check the allow-list half of the tool (#2971's normalise_repo is already on main and my earlier finding about its body's "empty commit" story is unrelated to this diff).

@bong-water-water-bong
bong-water-water-bong marked this pull request as ready for review November 20, 2026 14:30
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Undrafted: this is needed, and here is the decision

The queue rule says to close my own drafts that no issue needs. This one is needed, so I marked it ready instead — engine is at 1 non-draft open (cap 3), so there is room, and the thing it fixes is a false pass in the fleet's own dedupe gate:

  1. gh missing raised FileNotFoundError out of main() — a traceback with rc 1, which a caller reads as a duplicate finding.
  2. gh failing returned empty stdout, and json.loads(raw or '[]') turned that into "no open PRs" — a silent clean from the row that polices duplicates.

Both are failures to look, and both now raise so the per-repo handler records failed and --gate leaves 77. That is the same discipline as the rest of this tool's day: absence is not evidence, and a row that cannot see must say so rather than report a clean fleet.

Interacts with #2971 (merged, --repos OWNER/name + refuse an unknown repo): #2971 rejects a bad argument before any call; this rejects a failed call. Different halves of the same sentence, and neither subsumes the other.

Not verified: the FileNotFoundError path end to end (it needs a PATH without gh); the failure path's shape is visible in the diff — raise RuntimeError(f"gh api exited {p.returncode}: …") — and the handler that turns it into failed/77 is the one #2971 touched.

@bong-water-water-bong
bong-water-water-bong merged commit 2d94aff into main Nov 20, 2026
11 of 12 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the pi-prs/dup-fixes-gh-cannot-tell branch November 20, 2026 14:33

@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 e00aa1f: READY

The FileNotFoundError path I said was unverified is now measured, and it is the good answer:

PATH=<python3 only, no gh>  duplicate_fixes_check.py --repos engine
  duplicate_fixes: cannot tell for engine: gh could not run: [Errno 2] No such file or directory: 'gh'      rc 2

The old shape was worse than a missing check: a traceback out of main() with rc 1, which reads as a duplicate finding — the row would have reported a collision it never looked for. The new shape says what went wrong, names the missing binary, and answers cannot tell (2), which is the same third answer the rest of this tool's day converged on.

How I isolated the path, since it takes a moment to trust: gh lives at /usr/bin/gh, so excluding /usr/bin also removes python3 and timeout. The clean way is a one-entry PATH with a symlink to the interpreter and nothing else — PATH=$E /usr/bin/timeout … python3 … — which is what the run above used. Worth keeping in the row's notes: the arm for this needs that construction, not PATH=/usr/bin:/bin (which still finds gh and therefore proves nothing — my first attempt did exactly that and reported a clean fleet).

Both halves of "cannot look" are now closed: #2971 (merged) rejects a bad argument before any call; this rejects a failed call and a missing one. The json.loads(raw or '[]') silent-clean is gone with them.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2842 - Partially compliant

Compliant requirements:

Non-compliant requirements:

  • The tool does not explicitly check for overlapping files in the current implementation (this is a design choice in the PR)

Requires further human verification:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect error handling for gh failures

The PR introduces run_gh() to handle gh command failures, but the implementation may not fully cover all edge cases where gh could fail silently or return unexpected output. Specifically, if gh returns a non-zero exit code with valid output, it might not be handled correctly.

def run_gh(args):
    """`gh api …` -> stdout, or RuntimeError when gh could not run or did not answer.

    engine#2962 review: a bare `subprocess.run` here made the two shapes that actually happen read as answers.
    `gh` missing raised `FileNotFoundError` out of `main()` (a traceback, rc 1 -- read as a duplicate finding), and
    `gh` failing returned EMPTY STDOUT, which `json.loads(raw or '[]')` turned into "no open PRs" -- a silent clean
    from the row that polices duplicates. Both are failures to look, so both leave as RuntimeError, which the
    per-repo handler already turns into `failed` and `--gate` into 77.
    """
    try:
        p = subprocess.run(['gh'] + list(args), capture_output=True, text=True, timeout=120)
    except (OSError, subprocess.TimeoutExpired) as e:
        raise RuntimeError(f"gh could not run: {e}")
    if p.returncode != 0:
        raise RuntimeError(f"gh api exited {p.returncode}: {(p.stderr or '').strip()[:200]}")
    return p.stdout
Test coverage for overlapping files

While the PR adds tests for gh failures, it does not explicitly verify that the tool correctly identifies overlapping files when two PRs reference the same issue with Refs #N. This is a critical part of the intended behavior.

# engine#2962 review: both ways of failing to look must be cannot-tell, never a clean and never a traceback.
# Driven through a stub on PATH, because that is the state a runner is actually in when gh is absent or 403s.
import os, tempfile
with tempfile.TemporaryDirectory() as td:
    stub = pathlib.Path(td) / "gh"
    stub.write_text("#!/bin/sh\nexit 1\n")
    stub.chmod(0o755)
    saved = os.environ.get("PATH", "")
    os.environ["PATH"] = td + os.pathsep + saved
    try:
        try:
            gh("repos/1bit-MONSTER/engine/pulls?state=open", paginate=False)
            refused_failing = False
        except RuntimeError:
            refused_failing = True
    finally:
        os.environ["PATH"] = saved
    ok(refused_failing, "a gh that exits non-zero is cannot-tell, not empty output ('[]' = no open PRs)")

saved = os.environ.get("PATH", "")
os.environ["PATH"] = "/nonexistent"
try:
    try:
        gh("repos/1bit-MONSTER/engine/pulls?state=open", paginate=False)
        refused_missing = False
    except RuntimeError:
        refused_missing = True
finally:
    os.environ["PATH"] = saved
ok(refused_missing, "a missing gh is cannot-tell too, not a FileNotFoundError out of main()")

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Merged with the swallow still in files_for — and the tool already has the right answer for it one branch away.

295  out[n] = {f.get('filename') for f in json.loads(raw or '[]') if f.get('filename')}
296  except (RuntimeError, json.JSONDecodeError):
297      out[n] = set()          # a failed read becomes "this PR touches no files"

files_for feeds duplicates(prs, files_of(repo, need) …), and the overlap half of the rule is what separates a declared half from a duplicate. A gh failure there gives a PR an empty file set, which cannot overlap anything, so the rule answers not a duplicate — a fabricated empty answer, and set() is a legitimate value, so nothing downstream can tell it from a PR that genuinely touches nothing.

The tool already knows what to do

if failed:
    print("duplicate_fixes: cannot tell for at least one repo -- skip, not a pass", file=sys.stderr)
    return 77

open_prs failures are counted into failed and the run becomes cannot tell, deliberately: "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."

So the fix is routing, not policy: let files_for mark the fetch as failed (return None for that PR instead of set()), and count it into the same failed the repo-level path already uses. Two small edits in a file that was open an hour ago, and the overlap half stops fabricating.

Why I am not opening a PR for it

Measured just now, on main:

$ python3 tools/ci/duplicate_fixes_check.py
duplicate_fixes: no open issue is claimed by more than one open PR        rc 0

Every file list fetched, so the swallow is latent — and the trigger is environmental (a rate limit or a timeout on …/pulls/N/files), not a code change, which is the one difference from the last latent tooling bug I looked at today. The build queue is the stated bottleneck and this is a tooling file, so it gets a note rather than a slot: the asymmetry above is the whole report, and whoever touches files_for next has a ten-minute change instead of a re-derivation.

The arm to add with it is cheap and discriminating: a files_for whose gh raises must produce cannot tell from the whole run, not not a duplicate for that pair.

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