fix(803,664): fence the HEAD alias on the PR timeline's pull_push count (#873)
Build ErsatzTV Image / CI toolchain image resolves (push) Successful in 15s
Build ErsatzTV Image / Delimiter ban (release path) (push) Successful in 26s
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 9m14s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 6m16s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (push) Successful in 6m39s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (push) Skipped
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (push) Skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m37s
Build ErsatzTV Image / CI toolchain image resolves (push) Successful in 15s
Build ErsatzTV Image / Delimiter ban (release path) (push) Successful in 26s
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 9m14s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 6m16s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (push) Successful in 6m39s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (push) Skipped
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (push) Skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 4m37s
A force-push H1 -> H2 -> H1 spanning `pr-changed-files.sh`'s paging leaves its final
`.head.sha` comparison equal while the middle pages came from H2, so a mixed file list
could produce a docs-only exemption `success` no single head ever justified. The base
alias had been fenced since #706 by a monotonic `change_target_branch` count; the head
axis had nothing, and three contracts asserted otherwise.
`count_retargets` becomes `count_pr_mutations`: one timeline walk, two tallies, one shared
trust flag, a separate fence arm and diagnostic per axis. The advisory hook re-reads
`.head.sha` at the same hoist and off the same response as the base re-read. All three
overclaiming contracts are corrected, plus four paraphrases the first sweep missed.
Measured, not assumed: Gitea 1.27.1 still serves no `files` on `compare/{base}...{head}`;
every push is a `pull_push` event and its count cannot alias; PR #761 really went
`8798a1d -> 830a407 -> 8798a1d`; and Gitea creates the push comment BEFORE emitting the
synchronize notification, so a run cannot abstain on its own trigger.
Two pre-existing fail-opens in the shared walk were found by review and fixed: an empty
ARRAY first page was trusted on any page while the `null` arm required `page > 1`, and no
row was validated before `.type` was selected on.
NOT closed, and documented rather than overclaimed: the walk's `null` terminator is
defeatable, because Gitea pages before it filters (#870). The fence closes the ABA on a
timeline with no truncating block, not the ABA outright.
fixes #803
fixes #664
Refs #870
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Timothy <timothy@noreply.gitea.tblindustries.be>
This commit was merged in pull request #873.
This commit is contained in:
+39
-10
@@ -10,7 +10,9 @@
|
||||
# drift; one cannot.
|
||||
#
|
||||
# SCOPE — mechanism, not policy. This script answers exactly one question: "what is the complete set of
|
||||
# paths this PR touches, at one head, or can we not tell?" It deliberately does NOT classify the PR.
|
||||
# paths this PR touches, with no head or base movement observable from in here, or can we not tell?"
|
||||
# ("at one head" until 2026-08-28 — the same overclaim as the CONTRACT below, in the paraphrase that
|
||||
# survived the first sweep for it.) It deliberately does NOT classify the PR.
|
||||
# The two callers' allow-lists differ ON PURPOSE and must stay separate:
|
||||
# * the hook's docs-only pattern also lets .claude/ .gitea/ .husky/ through, which is safe there only
|
||||
# because it falls through to a HUMAN PROMPT;
|
||||
@@ -20,8 +22,23 @@
|
||||
# CONTRACT
|
||||
# Usage: pr-changed-files.sh <owner> <repo> <pr> <expected-head-sha> <expected-base-ref>
|
||||
# stdout: newline-delimited paths, BOTH sides of every rename, no blank lines. May be empty.
|
||||
# exit 0 the enumeration is COMPLETE and bound to <expected-head-sha> AND <expected-base-ref>.
|
||||
# stdout is authoritative.
|
||||
# exit 0 the enumeration is COMPLETE, and both <expected-head-sha> and <expected-base-ref> were
|
||||
# observed unchanged at BOTH ends of it. stdout is authoritative.
|
||||
#
|
||||
# READ THAT AS THE ONE-WAY GUARANTEE IT IS (ersatztv#803/#664). This line said "bound to
|
||||
# <expected-head-sha>" until 2026-08-28, which claims more than the code can do. Every
|
||||
# binding below compares a value against ITSELF, so it detects movement that is still in
|
||||
# effect at the end and is blind to an ALIAS: `H1 -> H2 -> H1` across the paging round
|
||||
# trips, or `main -> S -> main`, restores the expected value while the middle pages were
|
||||
# enumerated against the other one. Exit 0 means "no movement was OBSERVABLE from here",
|
||||
# not "this list belongs to one head".
|
||||
#
|
||||
# A caller needing the stronger property must fence it with a MONOTONIC key, because a
|
||||
# count cannot alias where a value can. The ENFORCED caller
|
||||
# (`.gitea/workflows/review-verdict.yml`) does exactly that on both axes — it counts
|
||||
# `change_target_branch` and `pull_push` timeline events before and after, and writes
|
||||
# nothing if either moved (`ci.verdict-write-retarget-fence`). The advisory hook does not,
|
||||
# and does not need to: its failure mode is a human prompt, not a green status.
|
||||
# exit 1 the enumeration could NOT be completed or verified. stdout is meaningless — the caller
|
||||
# MUST fail closed (withhold any exemption). A diagnostic goes to stderr.
|
||||
# exit 2 usage error.
|
||||
@@ -45,8 +62,14 @@
|
||||
# {head}` returns `total_commits`/`commits` and NO `files` (measured on 1.25.4, re-confirmed on
|
||||
# 1.27.1 2026-08-28 ersatztv#747). Separately, and NOT re-probed since 1.25.4: a `--depth=1` fetch of
|
||||
# the two shas has no merge base, so a three-dot diff is impossible while a two-dot one over-reports
|
||||
# every commit `main` gained since the branch point (measured, #698). The remainder is covered one level up
|
||||
# instead, by the workflow reclassifying on `edited` rather than trusting a machine-written success.
|
||||
# every commit `main` gained since the branch point (measured, #698). Independently re-probed again on
|
||||
# 1.27.1, 2026-08-28 (ersatztv#803): still `total_commits`/`commits` only, over a 12-commit range.
|
||||
#
|
||||
# The remainder is covered one level up instead, and since ersatztv#803 that cover is explicit on BOTH
|
||||
# axes rather than the base alone: the enforced caller fences its WRITE on the monotonic count of
|
||||
# `change_target_branch` AND `pull_push` timeline events (`ci.verdict-write-retarget-fence`) — which
|
||||
# is the thing an ALIAS cannot defeat — in addition to reclassifying on `edited` rather than trusting
|
||||
# a machine-written success.
|
||||
#
|
||||
# AUTH/TRANSPORT is caller-supplied via env, because the two callers authenticate differently:
|
||||
# ETV_GITEA_TOKEN | GITEA_TOKEN -> `Authorization: token`
|
||||
@@ -240,10 +263,16 @@ if [ "$complete" != yes ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Bind the enumeration to ONE head. Paging is several round-trips; a force-push between them means
|
||||
# page 1 came from head A and page 2 from head B, so the assembled list belongs to no single commit —
|
||||
# B's code page can be skipped entirely while B's docs page reads as a clean short tail. Re-read the
|
||||
# head and refuse if it moved.
|
||||
# Re-read the head and refuse if it MOVED. Paging is several round-trips; a force-push between them
|
||||
# means page 1 came from head A and page 2 from head B, so the assembled list belongs to no single
|
||||
# commit — B's code page can be skipped entirely while B's docs page reads as a clean short tail.
|
||||
#
|
||||
# ONE-WAY ONLY. This said "Bind the enumeration to ONE head" until 2026-08-28, which is the overclaim
|
||||
# ersatztv#664 was filed against and ersatztv#803 carried: `H1 -> H2 -> H1` across the paging window
|
||||
# passes the comparison below, because the value re-read is the value expected, while pages 1 and 2
|
||||
# came from different trees. Nothing checkable HERE closes that — the check would have to compare
|
||||
# against something the API does not offer (see the `compare/` probe above) — so it lives at the
|
||||
# caller as a monotonic event count instead (`ci.verdict-write-retarget-fence`).
|
||||
prjson=$(gq "repos/$owner/$repo/pulls/$pr")
|
||||
if [ -z "${prjson//[[:space:]]/}" ]; then
|
||||
echo "pr-changed-files: could not re-read PR head to bind the enumeration — failing closed" >&2
|
||||
@@ -268,7 +297,7 @@ fi
|
||||
|
||||
# Same window, the tip-advance question this time (ersatztv#707; see the comment at
|
||||
# `base_sha_before` above for why this is a DIFFERENT check from `.base.ref`, not a duplicate of
|
||||
# it). `prjson` is already fetched above to bind the head sha, so this is the same re-read, not a
|
||||
# it). `prjson` is already fetched above to re-read the head sha, so this is the same read, not a
|
||||
# new round trip. `$expected_base`'s branch name can be unchanged across the whole enumeration
|
||||
# while its TIP moved partway through — the exact #707 window: no retarget, no head movement,
|
||||
# nothing the ref check or the head-sha check can see, yet later pages were diffed against a base
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Tests for the head re-read in `.claude/hooks/pretooluse-merge-consent.sh` (ersatztv#803).
|
||||
|
||||
`$sha` is captured once from the PR snapshot at the top of the hook, and every later check — the CI
|
||||
combined status, the `review-verdict/h10` status, and the verdict-comment classification — is
|
||||
addressed by it. Between the capture and those checks sits the docs-only enumeration, up to forty
|
||||
round trips. A push landing in that gap was therefore checked against the commit it had just
|
||||
replaced, and the hook would report "a positive Review-verdict references the current head" about a
|
||||
head that was no longer current.
|
||||
|
||||
The fix is deliberately the SAME one the base got in #778, at the SAME hoist and off the SAME
|
||||
response, so the two axes cannot describe two different instants. These tests pin that it fires, that
|
||||
it names both shas, that it does not fire on a quiet run, and that an unreadable head asks rather than
|
||||
denying.
|
||||
|
||||
WHAT IS NOT CLAIMED HERE. The hook cannot detect an ABA — a push away and back leaves `.head.sha`
|
||||
equal at both of its reads, exactly as it does inside `scripts/pr-changed-files.sh`. That case belongs
|
||||
to the monotonic `pull_push` count in `.gitea/workflows/review-verdict.yml`
|
||||
(`ci.verdict-write-retarget-fence`), and is covered in `test_pr_changed_files.py`. No test here
|
||||
implies the hook closes it.
|
||||
|
||||
Observable contract: the hook exits 0 with EMPTY stdout when it has no opinion (passthrough to normal
|
||||
permissioning), and emits a JSON `permissionDecision` otherwise.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
HOOK = REPO_ROOT / ".claude" / "hooks" / "pretooluse-merge-consent.sh"
|
||||
|
||||
SHA = "a9e3e23abf337980ca4c05854f5b1e210099d08b"
|
||||
MOVED = "b7c4d19ffe2210873bb9a0417c6e3f2280551ac4"
|
||||
|
||||
# NOT docs-only, on purpose: the docs-only exemption short-circuits the gate long before the hoist,
|
||||
# so a docs PR would never reach the head check and every test here would pass without exercising it.
|
||||
#
|
||||
# THE MOVE IS SERVED FROM THE SECOND `/pulls/{n}` READ ONWARD, not at a hardcoded read index. The
|
||||
# hook's own two reads are not adjacent — `scripts/pr-changed-files.sh` makes its own in between, in a
|
||||
# separate process sharing this shim — so counting to a specific read would pin an implementation
|
||||
# detail that any refactor of the enumerator would silently break. "Moved once, early, and stayed
|
||||
# moved" is both the realistic shape and the one that needs no such knowledge.
|
||||
CURL_SHIM = r"""#!/usr/bin/env python3
|
||||
import json, os, sys, pathlib, urllib.parse
|
||||
|
||||
state = pathlib.Path(os.environ["STUB_DIR"])
|
||||
args = sys.argv[1:]
|
||||
url = [a for a in args if a.startswith("http")][-1]
|
||||
|
||||
if "/pulls/" in url and "/files" in url:
|
||||
q = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
|
||||
page = int(q.get("page", ["1"])[0])
|
||||
if page == 1:
|
||||
print(json.dumps([{"filename": "ErsatzTV/Program.cs", "status": "modified"}]))
|
||||
else:
|
||||
print("[]")
|
||||
sys.exit(0)
|
||||
|
||||
if "/status" in url:
|
||||
print(json.dumps({"state": "success", "statuses": [
|
||||
{"context": "review-verdict/h10", "status": "success",
|
||||
"description": "Review-verdict: MERGEABLE @ a9e3e23 (base: main)"}]}))
|
||||
sys.exit(0)
|
||||
|
||||
if "/pulls/" in url:
|
||||
ctr = state / "pr_reads"
|
||||
seen = int(ctr.read_text()) if ctr.exists() else 0
|
||||
ctr.write_text(str(seen + 1))
|
||||
mode = (state / "head_mode").read_text().strip()
|
||||
sha = os.environ["STUB_SHA"]
|
||||
if seen >= 1:
|
||||
if mode == "moved":
|
||||
sha = os.environ["STUB_MOVED"]
|
||||
elif mode == "unreadable":
|
||||
sha = ""
|
||||
body = {"base": {"ref": "main"}, "body": "fixes #1"}
|
||||
if sha:
|
||||
body["head"] = {"sha": sha}
|
||||
print(json.dumps(body))
|
||||
sys.exit(0)
|
||||
|
||||
print("{}")
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hook(tmp_path):
|
||||
bindir = tmp_path / "bin"
|
||||
bindir.mkdir()
|
||||
curl = bindir / "curl"
|
||||
curl.write_text(CURL_SHIM)
|
||||
curl.chmod(0o755)
|
||||
state = tmp_path / "state"
|
||||
state.mkdir()
|
||||
(state / "head_mode").write_text("stable")
|
||||
|
||||
env = dict(os.environ)
|
||||
env["PATH"] = f"{bindir}{os.pathsep}{env['PATH']}"
|
||||
env["STUB_DIR"] = str(state)
|
||||
env["STUB_SHA"] = SHA
|
||||
env["STUB_MOVED"] = MOVED
|
||||
env["ETV_GITEA_TOKEN"] = "stub" # noqa: S105 - deliberately fake; the real credential comes from the environment
|
||||
env["ETV_GITEA_URL"] = "http://gitea.example"
|
||||
env.pop("ETV_GITEA_BASICAUTH", None)
|
||||
|
||||
class Handle:
|
||||
def set_head_mode(self, mode):
|
||||
"""'stable' | 'moved' | 'unreadable' — applied from the SECOND /pulls read onward."""
|
||||
(state / "head_mode").write_text(mode)
|
||||
|
||||
def decision(self, mwcs=False):
|
||||
payload = {"tool_input": {"method": "merge", "owner": "timothy", "repo": "ersatztv", "pull_number": 42}}
|
||||
if mwcs:
|
||||
payload["tool_input"]["merge_when_checks_succeed"] = True
|
||||
r = subprocess.run(["bash", str(HOOK)], input=json.dumps(payload), env=env, capture_output=True, text=True)
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout) if r.stdout.strip() else None
|
||||
|
||||
def reason(self, mwcs=False):
|
||||
d = self.decision(mwcs=mwcs)
|
||||
return "" if d is None else json.dumps(d)
|
||||
|
||||
return Handle()
|
||||
|
||||
|
||||
def test_a_head_that_MOVED_mid_run_denies(hook):
|
||||
hook.set_head_mode("moved")
|
||||
reason = hook.reason()
|
||||
assert "deny" in reason, "the hook kept its opinion about a head that was replaced while it was evaluating"
|
||||
assert SHA[:7] in reason and MOVED[:7] in reason, (
|
||||
"the deny must name BOTH shas; 'the head moved' is not something a reader can act on"
|
||||
)
|
||||
assert "803" in reason, "the deny should cite the issue that explains the window"
|
||||
|
||||
|
||||
def test_positive_control_a_QUIET_head_does_not_trigger_the_head_deny(hook):
|
||||
"""Without this, the test above passes against a hook that denies on every path.
|
||||
|
||||
It very nearly would: this PR is deliberately non-docs, so the gate runs to completion, and the
|
||||
assertion is not "no decision" but "not a decision caused by the HEAD arm".
|
||||
"""
|
||||
hook.set_head_mode("stable")
|
||||
reason = hook.reason()
|
||||
assert "head moved from" not in reason, f"the head arm fired on a run whose head never moved: {reason}"
|
||||
# Positively witness that the run got PAST the head arm rather than never reaching it — an
|
||||
# absence assertion alone is satisfied by a hook that exited before the check ever ran. This
|
||||
# fixture stops at the issue-body read, which is downstream of the hoist.
|
||||
assert "could not fetch linked issue" in reason, (
|
||||
"the run did not reach the checks downstream of the head re-read, so this control does not "
|
||||
f"show the head arm was exercised and stayed silent: {reason}"
|
||||
)
|
||||
|
||||
|
||||
def test_an_UNREADABLE_head_on_re_read_ASKS_rather_than_denying(hook):
|
||||
"""The two cases are not the same and must not collapse into one decision.
|
||||
|
||||
A head that MOVED is a state we positively established — the verdict covers an older commit,
|
||||
which is what the `stale` verdict class denies for. A head we could not READ is the absence of
|
||||
evidence, and this gate's standing rule is that uncertainty asks. Collapsing them would block
|
||||
merges on a transport blip; collapsing them the other way would grant on one.
|
||||
"""
|
||||
hook.set_head_mode("unreadable")
|
||||
reason = hook.reason()
|
||||
assert "deny" not in reason, f"an unreadable head was treated as a moved one: {reason}"
|
||||
# ASSERT WHICH ask, not merely that SOME ask happened. This fixture's issue endpoint returns
|
||||
# `{}`, so the hook asks later anyway for a completely unrelated reason — meaning a mutation
|
||||
# deleting this arm outright (empty `sha_now` -> fall through and keep using `$sha`) left the
|
||||
# test green. Naming the arm's own message is what makes the test measure the arm.
|
||||
assert "reports no head commit (.head.sha) on re-read" in reason, (
|
||||
f"the hook asked, but NOT via the unreadable-head arm: {reason}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mwcs", [False, True], ids=["immediate", "scheduled"])
|
||||
def test_the_head_deny_covers_BOTH_merge_paths(hook, mwcs):
|
||||
"""The twin-miss shape, tested because this exact hook has already been bitten by it.
|
||||
|
||||
The base re-read first landed INSIDE the scheduled-auto-merge branch only, and cold review
|
||||
found the consequence with this repo's own fixture: scheduled+retarget denied while
|
||||
immediate+retarget auto-GRANTED. The head check is placed at the same hoist precisely so it
|
||||
sits ABOVE the point where the two paths diverge — but "it is above the split" is a claim about
|
||||
the source, and the thing worth pinning is the OUTCOME on both paths.
|
||||
"""
|
||||
hook.set_head_mode("moved")
|
||||
reason = hook.reason(mwcs=mwcs)
|
||||
assert "deny" in reason, (
|
||||
f"a head that moved mid-run was not denied on the {'scheduled' if mwcs else 'immediate'} merge path: {reason}"
|
||||
)
|
||||
assert MOVED[:7] in reason, f"the deny does not name the new head: {reason}"
|
||||
@@ -15,7 +15,8 @@ loop could have silently flipped. Every failure-path test below therefore assert
|
||||
explicitly, so the behaviour is a contract rather than a coincidence.
|
||||
|
||||
Observable contract of the script:
|
||||
exit 0 -> enumeration complete and bound to the expected head; stdout is the authoritative path set
|
||||
exit 0 -> enumeration complete, with no head/base movement observable from inside it (ONE-WAY;
|
||||
an A->B->A alias passes — #664/#803); stdout is the authoritative path set
|
||||
exit 1 -> could not enumerate/verify; stdout meaningless, caller MUST withhold any exemption
|
||||
exit 2 -> usage error
|
||||
"""
|
||||
@@ -974,19 +975,64 @@ if "/timeline" in url:
|
||||
if mode == "unreadable":
|
||||
print("<html>502 Bad Gateway</html>")
|
||||
sys.exit(0)
|
||||
if mode == "trusted-then-unreadable":
|
||||
# The FIRST count succeeds, the SECOND cannot be established. `timeline_reads.txt` is
|
||||
# incremented only on the LAST-REAL-PAGE branch below, after the `page > pages` and
|
||||
# `page < pages` early exits — so it counts REAL PAGES SERVED, not requests: it holds 1
|
||||
# after the before-count, and `>= 2` first becomes true partway through the after-count.
|
||||
# (An earlier version of this comment said "requests 0-1 are the before-count", which is a
|
||||
# mechanism nobody measured; the arrangement is produced either way, but the description
|
||||
# was of a different program.)
|
||||
#
|
||||
# This is the only arrangement that separates the head arm from its trust guard: with both
|
||||
# counts trusted the guard is a no-op, and with both untrusted `pushes_before` is 0 too, so
|
||||
# the arm cannot fire either way. Only trusted-then-untrusted makes the two disagree.
|
||||
ctr0 = out / "timeline_reads.txt"
|
||||
seen0 = int(ctr0.read_text()) if ctr0.exists() else 0
|
||||
if seen0 >= 2:
|
||||
print("<html>502 Bad Gateway</html>")
|
||||
sys.exit(0)
|
||||
if mode == "untyped-rows":
|
||||
# Well-formed JSON, well-formed array, rows the walk cannot classify: no `.type` at all on
|
||||
# one row and a non-string one on another. Both are invisible to a `select(.type == ...)`.
|
||||
#
|
||||
# THIS MODE MUST STILL TERMINATE, and getting that wrong made the test measure nothing.
|
||||
# Serving these rows on EVERY page ran the walk into its 20-page cap, which withholds the
|
||||
# exemption on its own — so the test passed identically with the row validation deleted.
|
||||
# Page 2 therefore terminates normally: without the guard the walk completes and certifies a
|
||||
# zero count (exemption GRANTED), with it the page is refused (exemption withheld). Only
|
||||
# then does the assertion discriminate.
|
||||
if page > 1:
|
||||
print(os.environ.get("STUB_TIMELINE_TERMINATOR", "null"))
|
||||
else:
|
||||
print(json.dumps([{"id": 1}, {"id": 2, "type": 7}, {"id": 3, "type": "comment"}]))
|
||||
sys.exit(0)
|
||||
if mode == "transport-error":
|
||||
sys.exit(22)
|
||||
# Page 2+ terminates the walk. THE DEFAULT IS `null`, NOT `[]`, because that is what this
|
||||
# endpoint really returns past the end — measured at Gitea 1.27.1 (ersatztv#751). This stub
|
||||
# printed `[]` for two rounds of #706 work while the comment above claimed it mirrored measured
|
||||
# reality, so every fence test was green against a shape the server never produces, and the
|
||||
# fence's `array`-only type gate — which reads `null` as unreadable — was never exercised. On the
|
||||
# real instance that made `rt_ok` false for EVERY pr, so the fence withheld every exemption.
|
||||
# Parameterised rather than simply corrected: `/issues/{n}/comments` really does return `[]` when
|
||||
# empty, so both shapes are live on this server and the job must accept either.
|
||||
if page > 1:
|
||||
# MULTI-PAGE TIMELINES (ersatztv#803 review). Until this existed the double always terminated
|
||||
# after page 1 and put every event on it, so nothing in the suite exercised the walk ACCUMULATING
|
||||
# across pages — a walk that read page 1 and stopped passed every fence test. `STUB_TIMELINE_PAGES`
|
||||
# says how many REAL pages there are; page P+1 is the terminator. Events go on the LAST real page,
|
||||
# which is where the server would put them: timeline rows are ordered ASCENDING, so the newest
|
||||
# events — the ones a fence is looking for — are the furthest from page 1. Earlier pages carry
|
||||
# filler `comment` rows so they are full-length and cannot be mistaken for the end.
|
||||
#
|
||||
# PAST THE LAST REAL PAGE THE DEFAULT IS `null`, NOT `[]`, because that is what this endpoint
|
||||
# really returns past the end — measured at Gitea 1.27.1 (ersatztv#751). This stub printed `[]`
|
||||
# for two rounds of #706 work while its comment claimed it mirrored measured reality, so every
|
||||
# fence test was green against a shape the server never produces, and the fence's `array`-only
|
||||
# type gate — which reads `null` as unreadable — was never exercised. On the real instance that
|
||||
# made `rt_ok` false for EVERY pr, so the fence withheld every exemption. Parameterised rather
|
||||
# than simply corrected: `/issues/{n}/comments` really does return `[]` when empty, so both
|
||||
# shapes are live on this server and the job must accept either.
|
||||
pages = int(os.environ.get("STUB_TIMELINE_PAGES", "1"))
|
||||
if page > pages:
|
||||
print(os.environ.get("STUB_TIMELINE_TERMINATOR", "null"))
|
||||
sys.exit(0)
|
||||
if page < pages:
|
||||
print(json.dumps([{"id": 100 + i, "type": "comment"} for i in range(50)]))
|
||||
sys.exit(0)
|
||||
|
||||
n_before, n_after = 0, 0
|
||||
if mode.startswith("stable:"):
|
||||
n_before = n_after = int(mode.split(":", 1)[1])
|
||||
@@ -995,12 +1041,39 @@ if "/timeline" in url:
|
||||
# before the POST. This is the race-1 window: the PR was retargeted while the job classified.
|
||||
a, b = mode.split(":", 1)[1].split(",")
|
||||
n_before, n_after = int(a), int(b)
|
||||
# THE PUSH AXIS IS INDEPENDENT OF THE RETARGET AXIS (ersatztv#803/#664), and it has to be, or the
|
||||
# head-fence tests could not distinguish which fence fired. Both counts come off the SAME page —
|
||||
# the job makes one walk and tallies two `.type` values — so the stub serves them from one
|
||||
# response, but the two `moves:`/`stable:` knobs are separate.
|
||||
pmode = os.environ.get("STUB_PUSH_MODE", "none")
|
||||
p_before, p_after = 0, 0
|
||||
if pmode.startswith("stable:"):
|
||||
p_before = p_after = int(pmode.split(":", 1)[1])
|
||||
elif pmode.startswith("moves:"):
|
||||
a, b = pmode.split(":", 1)[1].split(",")
|
||||
p_before, p_after = int(a), int(b)
|
||||
ctr = out / "timeline_reads.txt"
|
||||
seen = int(ctr.read_text()) if ctr.exists() else 0
|
||||
ctr.write_text(str(seen + 1))
|
||||
n = n_before if seen == 0 else n_after
|
||||
np = p_before if seen == 0 else p_after
|
||||
# `is_force_push` is emitted because the real endpoint emits it (measured on PR #761), NOT
|
||||
# because the job reads it — the fence counts rows by `.type` and never parses the body. A stub
|
||||
# that omitted it would leave a reader thinking the field is unused by contract rather than by
|
||||
# choice; one that made the count DEPEND on it would test a job we did not write.
|
||||
#
|
||||
# IT ALTERNATES, STARTING FALSE. Every row carried `true` until 2026-08-28, which made the
|
||||
# documented invariant untestable: narrowing the tally to
|
||||
# `select(.type == "pull_push" and (.body | fromjson | .is_force_push))` passed the ENTIRE fence
|
||||
# suite. That narrowing is wrong precisely where it matters — an ordinary push also invalidates a
|
||||
# mid-flight enumeration, and an ABA's restoring push can be non-forced when H1 is an ancestor —
|
||||
# so the double has to contain at least one row the narrowed predicate would drop.
|
||||
print(json.dumps([{"id": 1000 + i, "type": "change_target_branch",
|
||||
"old_ref": "main", "new_ref": "scratch"} for i in range(n)]
|
||||
+ [{"id": 1500 + i, "type": "pull_push",
|
||||
"body": json.dumps({"is_force_push": bool(i % 2),
|
||||
"commit_ids": ["a" * 40, "b" * 40]})}
|
||||
for i in range(np)]
|
||||
+ [{"id": 900, "type": "comment"}]))
|
||||
sys.exit(0)
|
||||
|
||||
@@ -1490,6 +1563,8 @@ def _run_classify(
|
||||
status_creator: str | None = "timothy",
|
||||
status_desc: str = "Review-verdict: MERGEABLE @ a9e3e23 (base: main)",
|
||||
timeline_mode: str = "none",
|
||||
push_mode: str = "none",
|
||||
timeline_pages: int = 1,
|
||||
history_mode: str = "none",
|
||||
history_creator: str = "timothy",
|
||||
midrun_creator: str = "timothy",
|
||||
@@ -1530,6 +1605,8 @@ def _run_classify(
|
||||
env["STUB_STATUS_CREATOR"] = status_creator or ""
|
||||
env["STUB_STATUS_DESC"] = status_desc
|
||||
env["STUB_TIMELINE_MODE"] = timeline_mode
|
||||
env["STUB_PUSH_MODE"] = push_mode
|
||||
env["STUB_TIMELINE_PAGES"] = str(timeline_pages)
|
||||
env["STUB_TIMELINE_TERMINATOR"] = timeline_terminator
|
||||
env["STUB_STATUS_EMPTY_SHAPE"] = status_empty_shape
|
||||
env["STUB_HISTORY_MODE"] = history_mode
|
||||
@@ -2751,6 +2828,472 @@ def test_positive_control_a_QUIET_run_still_posts_its_exemption(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def _fold_continuations(lines):
|
||||
r"""Join backslash-continued shell lines the way bash does: delete the backslash AND the newline,
|
||||
joining with NOTHING.
|
||||
|
||||
The exit-status detector is per-line, so a `jq \` whose flag sits on the next line would slip
|
||||
past it. Folding first closes that — but only if the fold matches the shell, and the separator is
|
||||
where it goes wrong. An earlier version joined with a SPACE, which is not cosmetic: it turns
|
||||
`jq -\` + `e '.'` into `jq - e '.'` (two tokens, no flag) where bash produces `jq -e '.'`.
|
||||
|
||||
WHICH SPLITS ARE ACTUALLY REACHABLE, measured rather than assumed, because the obvious
|
||||
construction is not one. Bash does NOT strip the continuation line's leading whitespace, so
|
||||
`echo -\` followed by an INDENTED `e X` prints `- e X` — three tokens, no flag re-formed, and
|
||||
`jq -\` + indented `e` exits 3 rather than acting as `-e`. The reachable case is a continuation
|
||||
whose next line begins at COLUMN 0, and in this file that is not exotic: YAML strips the `run:`
|
||||
block's common indentation (10 spaces here), so any line written at the block's base indent runs
|
||||
at column 0. Verified end to end: a mutant of that exact shape parses as YAML, passes `bash -n`,
|
||||
forms a live `jq -e` — and reddens the guard under this fold while passing under the space-joining
|
||||
one.
|
||||
|
||||
NO `rstrip()`, for the same reason. A backslash followed by trailing whitespace is not a
|
||||
continuation to bash — the backslash escapes the SPACE — and tolerating it was the one route by
|
||||
which this fold could DESTROY a `jq` token rather than fabricate one: `ok=y\` plus invisible
|
||||
trailing spaces, then a dedented `jq -e ...`, folds to `okyjq -e`, and `\bjq\b` finds no word
|
||||
boundary after the `y`. Every other divergence here over-joins, which can only ever cost a false
|
||||
positive. Matching the shell exactly is both simpler and the only direction that cannot lose a
|
||||
`jq`.
|
||||
"""
|
||||
joined, buf = [], ""
|
||||
for ln in lines:
|
||||
if ln.endswith("\\"):
|
||||
buf += ln[:-1]
|
||||
else:
|
||||
joined.append(buf + ln)
|
||||
buf = ""
|
||||
if buf:
|
||||
joined.append(buf)
|
||||
return joined
|
||||
|
||||
|
||||
def _uses_jq_exit_status(line: str) -> bool:
|
||||
"""True if `line` invokes jq with the exit-status flag, in any spelling of the FLAG.
|
||||
|
||||
Scope, stated because the obvious reading is wider than the truth: this is per-line and knows
|
||||
nothing about shell continuations. `jq \\` on one line and `-e` on the next is a real evasion,
|
||||
and it is closed by the CALLER, which folds continuations before scanning — not here.
|
||||
|
||||
THIS IS THE THIRD VERSION AND IT IS DELIBERATELY THE DUMBEST. The first was
|
||||
`"jq -e" in line`, which missed `jq -re`, `jq -e` and `jq --exit-status` (it caught `jq -er`
|
||||
only because `jq -e` is a substring of it). The second parsed
|
||||
the LEADING option tokens and stopped at the first non-option, on the reasoning that everything
|
||||
after the jq program is source — and that reasoning bought two more false negatives:
|
||||
`jq --argjson e 1 -e '.'` (the walk stops at the bare `e` argument) and `jq '.a' -e` (jq accepts
|
||||
options after the filter). Three defects in one string-matching predicate is this repo's
|
||||
documented signal to stop adding cases and remove the cleverness instead.
|
||||
|
||||
So: scan EVERY whitespace token after each `jq`, with no attempt to find where the program
|
||||
begins. That over-approximates — a jq program containing a token that looks like a short flag
|
||||
with an `e` in it would trip this — and the over-approximation is the SAFE direction. It guards
|
||||
one short function we own: a false positive costs a rewrite, a false negative restores the
|
||||
jq-1.6 exit-status divergence inside the code that writes a required status.
|
||||
|
||||
BE EXACT ABOUT WHY THERE IS NO FALSE POSITIVE TODAY, because the loose version of that sentence
|
||||
is false. The guarded function DOES contain `-`-prefixed tokens carrying an `e`: `-eq`, `-ne`
|
||||
and `-le`, the shell test operators. They are invisible to this only because none of them shares
|
||||
a LINE with a `jq` invocation, and the scan starts at `jq`. Measured: of its five jq-bearing
|
||||
lines, none carries a `-`-prefixed token after `jq` other than `-r`. A future
|
||||
`if [ "$(... | jq -r .)" -eq 0 ]` would trip this guard for no real reason — and the fix then is
|
||||
to split the line, not to make the detector clever again.
|
||||
"""
|
||||
for m in re.finditer(r"\bjq\b", line):
|
||||
for tok in line[m.end() :].split():
|
||||
if tok == "--exit-status":
|
||||
return True
|
||||
if tok.startswith("-") and not tok.startswith("--") and "e" in tok[1:]:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw,folded",
|
||||
[
|
||||
# The reachable shape: the continuation's next line is at column 0, which is what a line
|
||||
# written at the `run:` block's base indent becomes once YAML strips it. Bash re-forms the
|
||||
# token; so must the fold, or the detector sees `jq - e` and reports nothing.
|
||||
([" x=$(... | jq -\\", "e 'length')"], [" x=$(... | jq -e 'length')"]),
|
||||
# An INDENTED continuation does NOT re-form the token — bash keeps the leading whitespace —
|
||||
# so the fold must not invent one either. Measured: `echo -\` + indented `e X` prints `- e X`.
|
||||
([" x=$(... | jq -\\", " e 'length')"], [" x=$(... | jq - e 'length')"]),
|
||||
(["a\\", "b\\", "c"], ["abc"]), # two consecutive continuations
|
||||
(["plain", "lines"], ["plain", "lines"]), # nothing to fold
|
||||
(["trailing\\"], ["trailing"]), # continuation with nothing after it
|
||||
# A backslash followed by whitespace is NOT a continuation — bash escapes the space.
|
||||
# Nothing bound this before, so dropping the shell-faithfulness survived every other
|
||||
# case while opening the one route by which the fold can HIDE a `jq` token instead of
|
||||
# inventing one: `ok=y\` + trailing spaces then a dedented `jq -e` folds to `okyjq -e`,
|
||||
# and `\\bjq\\b` finds no boundary after the `y`.
|
||||
(["a\\ ", "b"], ["a\\ ", "b"]),
|
||||
],
|
||||
)
|
||||
def test_the_continuation_fold_matches_the_SHELL(raw, folded):
|
||||
r"""It joins with NOTHING, because that is what `\<newline>` removal does.
|
||||
|
||||
Joining with a space is the intuitive choice and it silently defeats the guard downstream: it
|
||||
turns `jq -\` + `e` into `jq - e`, two tokens carrying no flag, where bash produces `jq -e`.
|
||||
"""
|
||||
assert _fold_continuations(raw) == folded
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"line,expected",
|
||||
[
|
||||
(""" if ! printf '%s' "$raw" | jq -e 'all(.[]; .a)' ; then""", True),
|
||||
(""" x=$(jq --exit-status '.a' <<< "$raw")""", True),
|
||||
(""" x=$(jq -re '.a')""", True),
|
||||
(""" x=$(jq -er '.a')""", True),
|
||||
(""" x=$(jq -e '.a')""", True),
|
||||
# The two the leading-token parser missed, named by cold review of round 4.
|
||||
(""" x=$(jq --argjson e 1 -e '.')""", True),
|
||||
(""" x=$(jq '.a' -e)""", True),
|
||||
(""" n=$(printf '%s' "$raw" | jq -r 'length')""", False),
|
||||
(''' kind=$(printf '%s' "$raw" | jq -r 'type' 2>/dev/null) || kind=""''', False),
|
||||
# The jq PROGRAM may legitimately contain an `e`, or a `-e` inside a string. These pass
|
||||
# because neither carries a `-`-prefixed token at all — NOT because the scan stops at the
|
||||
# program. It does not: that was the v2 reasoning this file withdrew, and restating it here
|
||||
# would invite someone to "restore" the leading-token walk and its two false negatives.
|
||||
(""" bad=$(jq -r '[.[] | select(.type != "e")] | length')""", False),
|
||||
(""" m=$(jq -r --arg e x '[.[] | select(.type == $e)] | length')""", False),
|
||||
],
|
||||
)
|
||||
def test_the_jq_exit_status_detector_reads_FLAGS_not_a_substring(line, expected):
|
||||
"""The detector is itself a string-matching predicate, so it gets its own cases.
|
||||
|
||||
`"jq -e" in line` was the first version. It misses `jq -re`, `jq -er`, `jq -e` and
|
||||
`jq --exit-status` — three spellings of the same request (it catches `jq -er`, since `jq -e`
|
||||
is a substring of it) — and a guard a rename walks straight
|
||||
through is not a guard. The false-positive rows matter as much: an `e` inside the jq PROGRAM is
|
||||
not a flag, and a detector that reddens on one would make the rule unusable and get waived.
|
||||
"""
|
||||
assert _uses_jq_exit_status(line) is expected
|
||||
|
||||
|
||||
def test_count_pr_mutations_uses_NO_jq_e(tmp_path):
|
||||
"""The timeline walk reads jq output as VALUES; `jq -e`'s exit status is banned inside it.
|
||||
|
||||
The function's own comment states the rule and the reason: `jq -e` reports the truthiness of its
|
||||
LAST OUTPUT, and over empty input jq 1.6 exits 0 where >= 1.7 exits 4 — the divergence that
|
||||
already took this workflow's enforced gate down once (ersatztv#647), on a runner that still ships
|
||||
1.6. Every tally here is therefore read with `jq -r` and range-checked in shell.
|
||||
|
||||
This exists because the rule was BROKEN one commit after it was quoted (ersatztv#803 round 2 added
|
||||
a row-validation guard using `jq -e`, three lines below the comment forbidding it) and nothing
|
||||
caught it — it was found by hand while re-reading the diff. A convention stated only in prose is
|
||||
one refactor from being false, and this one is function-scoped: `jq -e` is legitimate elsewhere in
|
||||
this same workflow and in the hook, so a file-wide grep would be wrong.
|
||||
|
||||
Comments are stripped, so the paragraphs explaining the rule do not redden it.
|
||||
"""
|
||||
body = _classify_step()["run"]
|
||||
lines = [ln for ln in body.splitlines() if not ln.lstrip().startswith("#")]
|
||||
fn, depth, inside = [], 0, False
|
||||
for ln in lines:
|
||||
if "count_pr_mutations() {" in ln:
|
||||
inside = True
|
||||
if inside:
|
||||
fn.append(ln)
|
||||
depth += ln.count("{") - ln.count("}")
|
||||
if depth == 0 and len(fn) > 1:
|
||||
break
|
||||
assert inside and depth == 0, (
|
||||
"could not locate the `count_pr_mutations` body in the classify step — if it was renamed, "
|
||||
"rename it here too rather than deleting this guard"
|
||||
)
|
||||
# A BALANCED PREFIX IS NOT THE WHOLE FUNCTION. `depth == 0` is reached by the real closing brace
|
||||
# today, but it would also be reached early by any line with a net-negative brace count, and the
|
||||
# assertion above cannot tell the two apart — so a `jq -e` past that point would be invisible
|
||||
# while the guard reported success.
|
||||
#
|
||||
# The check is STRUCTURAL, not a pinned statement. An earlier version asserted that the body
|
||||
# contained `page=$(( page + 1 ))`, which is a real line near the end and would have worked —
|
||||
# and would also have reddened on any refactor of the increment, for no reason connected to
|
||||
# this guard. A guard that cries wolf gets waived, which is how the repo already has to
|
||||
# document one CI job as "do nothing". Requiring the capture to END on the closing brace says
|
||||
# the same thing about extent while surviving every edit to the body.
|
||||
assert fn[-1].strip() == "}", (
|
||||
"the extracted body does not end on `count_pr_mutations`'s closing brace, so it is a PREFIX "
|
||||
f"of the function rather than the whole of it — this guard would be scanning only part of "
|
||||
f"what it claims to cover. Last captured line: {fn[-1]!r}"
|
||||
)
|
||||
joined = _fold_continuations(fn)
|
||||
offenders = [ln.strip() for ln in joined if _uses_jq_exit_status(ln)]
|
||||
assert not offenders, (
|
||||
"`jq -e` appeared inside `count_pr_mutations`, whose own comment bans it because the runner "
|
||||
"ships jq 1.6 and `-e`'s exit status over empty input diverges there (ersatztv#647/#803). "
|
||||
"Read the value with `jq -r` and range-check it in shell instead:\n " + "\n ".join(offenders)
|
||||
)
|
||||
|
||||
|
||||
def test_a_HEAD_ABA_DURING_the_run_posts_NOTHING(tmp_path):
|
||||
"""THE ersatztv#803/#664 test: `H1 -> H2 -> H1` across the enumeration.
|
||||
|
||||
This is the case no sha comparison can see, and the reason the fence keys on a COUNT. The head
|
||||
is force-pushed away and back while the job classifies, so `$SHA` still equals `.head.sha` at
|
||||
both ends — `pr-changed-files.sh` exits 0, having observed no movement — while the
|
||||
middle pages were served from `H2`. A mixed file list can then produce a docs-only exemption
|
||||
that no single head ever justified.
|
||||
|
||||
TWO push events, not one, because that is what the ABA costs: away, and back. The retarget axis
|
||||
is held at `none` deliberately, so a pass here cannot be the BASE fence firing.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode="none", push_mode="moves:0,2")
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert posted is None, (
|
||||
"the job posted an exemption for a head that was force-pushed away and back underneath it "
|
||||
f"— the head-mutation fence did not fire. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
# The DISCRIMINATOR, and specifically the head one: the retarget arm also ends in "posted
|
||||
# nothing", so without this the test would pass against a job whose base fence fired for the
|
||||
# wrong reason.
|
||||
assert "head branch was pushed while this job was classifying" in r.stdout, (
|
||||
f"nothing was posted, but NOT via the head fence. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
assert "retargeted while this job was classifying" not in r.stdout, (
|
||||
"the BASE fence fired on a run whose base never moved, so this test is not measuring the "
|
||||
f"head axis. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminator", ["null", "[]"])
|
||||
def test_the_head_fence_holds_under_EITHER_terminator_shape(tmp_path, terminator):
|
||||
"""The `[]` and `null` walk-exits are separate arms, and the head axis must publish from both.
|
||||
|
||||
Deleting `hp_count=$ptotal` from the empty-ARRAY arm alone left every fence test green, because
|
||||
every one of them terminated on the default `null`. The head fence would then be silently dead
|
||||
for any timeline ending in `[]` — a shape this code explicitly supports and this server really
|
||||
produces on a sibling endpoint.
|
||||
"""
|
||||
posted, r = _run_classify(
|
||||
tmp_path,
|
||||
_emitting("docs/a.md"),
|
||||
timeline_mode="none",
|
||||
push_mode="moves:0,2",
|
||||
timeline_terminator=terminator,
|
||||
)
|
||||
assert posted is None, (
|
||||
f"an exemption was granted over an ABA on a timeline terminating with `{terminator}` — the "
|
||||
f"head count is not published from that arm. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
assert "head branch was pushed while this job was classifying" in r.stdout, (
|
||||
f"nothing was posted, but NOT via the head fence. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_the_head_arm_DEFERS_to_the_trust_guard_when_the_second_count_fails(tmp_path):
|
||||
"""An untrusted re-count is "cannot tell", never "the head moved".
|
||||
|
||||
Both outcomes post nothing, so only the DIAGNOSTIC separates them — and the difference is not
|
||||
cosmetic: the untrusted branch is an `::error::` saying an exemption cannot be shown to have been
|
||||
computed at a single head and that a later run only helps if the cause was transient, while the
|
||||
head arm is a `::notice::` promising a successor run that the `synchronize` event has queued.
|
||||
Reporting a push that was never observed would send a reader looking for a force-push that did
|
||||
not happen.
|
||||
|
||||
Dropping the `rt_ok` conditions from the head arm leaves the rest of the suite green, because
|
||||
every other test has both counts trusted (guard is a no-op) or both untrusted (`pushes_before`
|
||||
is 0, so the arm cannot fire). Only a trusted-then-untrusted pair separates them.
|
||||
"""
|
||||
posted, r = _run_classify(
|
||||
tmp_path,
|
||||
_emitting("docs/a.md"),
|
||||
timeline_mode="trusted-then-unreadable",
|
||||
push_mode="stable:3",
|
||||
)
|
||||
assert posted is None, f"an exemption was granted on an untrusted count. Log:\n{r.stdout[-900:]}"
|
||||
assert "Could not establish a trusted retarget/push count" in r.stdout, (
|
||||
f"the untrusted re-count was not reported as such. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
assert "head branch was pushed while this job was classifying" not in r.stdout, (
|
||||
"an untrusted re-count was reported as observed head movement — the head arm is firing "
|
||||
f"without its trust guard. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_SINGLE_head_push_during_the_run_also_posts_NOTHING(tmp_path):
|
||||
"""One push is the ordinary one-way move, and the fence covers it too.
|
||||
|
||||
`pr-changed-files.sh` already fails closed on this via its own sha comparison, so the exemption
|
||||
was withheld before #803 — but through a DIFFERENT mechanism, one that reports an enumeration
|
||||
error rather than a handoff. Asserting the fence arm here pins that the head axis is not
|
||||
narrowed to "two or more pushes" by some future edit reasoning that one-way is already covered.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode="none", push_mode="moves:0,1")
|
||||
assert r.returncode == 0, f"the job died rather than abstaining cleanly: {r.stderr[-600:]}"
|
||||
assert posted is None, f"an exemption was posted for a PR pushed mid-classification. Log:\n{r.stdout[-900:]}"
|
||||
assert "head branch was pushed while this job was classifying" in r.stdout, (
|
||||
f"nothing was posted, but NOT via the head fence. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_PR_PUSHED_BEFORE_the_run_but_QUIET_during_it_is_STILL_exempt(tmp_path):
|
||||
"""The head fence keys on MOTION during this run, never on "has ever been pushed".
|
||||
|
||||
This is the test that would go red on the most plausible wrong implementation. EVERY pull
|
||||
request has a non-zero `pull_push` count — it is created by a push, and PR #802 carries
|
||||
eighteen — so a fence keying on the count being non-zero, rather than on it CHANGING, would
|
||||
withhold the exemption from every PR that has ever existed. That is not a subtle regression: it
|
||||
is the #751 shape, where a fence shipped and silently refused every exemption on the instance.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode="none", push_mode="stable:18")
|
||||
assert posted is not None and posted["state"] == "success", (
|
||||
"a PR with a settled, non-zero push history was refused its exemption — the head fence is "
|
||||
f"testing the count's VALUE instead of its MOVEMENT. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
# Each row: (timeline_mode, push_mode, arm expected to fire, arm that must stay silent).
|
||||
# BOTH DIRECTIONS ARE POSED, because they fail to different mutations and only one of them is
|
||||
# reachable at all. The arms are evaluated base-first, so a tally that folds PUSHES into the retarget
|
||||
# total is caught only by the push-moves row (the base arm fires and pre-empts the head message);
|
||||
# folding retargets into the push total is NOT observable from here for the same ordering reason,
|
||||
# and is deliberately not claimed to be. Stating that is the point — an earlier version of this test
|
||||
# asserted the base-moves row alone while its docstring claimed it caught the folding mutation, and
|
||||
# it stayed GREEN under exactly that mutation.
|
||||
_AXIS_ROWS = [
|
||||
(
|
||||
"moves:0,1",
|
||||
"stable:18",
|
||||
"retargeted while this job was classifying",
|
||||
"head branch was pushed while this job was classifying",
|
||||
),
|
||||
(
|
||||
"stable:2",
|
||||
"moves:0,2",
|
||||
"head branch was pushed while this job was classifying",
|
||||
"retargeted while this job was classifying",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tl_mode,push_mode,expected,silent", _AXIS_ROWS)
|
||||
def test_the_head_and_base_axes_are_counted_SEPARATELY(tmp_path, tl_mode, push_mode, expected, silent):
|
||||
"""One walk, two tallies, and neither may be read for the other.
|
||||
|
||||
The cheapest wrong implementation reuses one tally for both axes; it passes every single-axis
|
||||
test above, because with only one axis in motion a shared counter still moves. What distinguishes
|
||||
it is holding one axis STABLE AND NON-ZERO while the other moves, then demanding that the arm
|
||||
which reports is the one that actually moved.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode=tl_mode, push_mode=push_mode)
|
||||
assert posted is None, f"neither fence fired. Log:\n{r.stdout[-900:]}"
|
||||
assert expected in r.stdout, f"the moving axis was not the one reported. Log:\n{r.stdout[-900:]}"
|
||||
assert silent not in r.stdout, (
|
||||
f"a STABLE axis was reported as having moved — the two counts are sharing a tally. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_push_landing_BEYOND_page_1_is_still_counted(tmp_path):
|
||||
"""The walk must ACCUMULATE across pages, not answer from the first one.
|
||||
|
||||
Timeline rows are ordered ASCENDING, so the newest events — exactly the ones a fence looks for —
|
||||
are furthest from page 1. A walk that read page 1 and stopped would see a stable zero on both
|
||||
counts and let the ABA through, while passing every other fence test in this file: until the
|
||||
double grew `timeline_pages`, every event it served was on page 1.
|
||||
"""
|
||||
posted, r = _run_classify(
|
||||
tmp_path,
|
||||
_emitting("docs/a.md"),
|
||||
timeline_mode="none",
|
||||
push_mode="moves:0,2",
|
||||
timeline_pages=3,
|
||||
)
|
||||
assert posted is None, (
|
||||
"an exemption was granted over an ABA whose push events lived past page 1 — the walk is "
|
||||
f"answering from the first page. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
assert "head branch was pushed while this job was classifying" in r.stdout, (
|
||||
f"nothing was posted, but NOT via the head fence. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_positive_control_a_MULTI_PAGE_quiet_timeline_still_exempts(tmp_path):
|
||||
"""Without this, the test above passes against a walk that refuses every multi-page timeline."""
|
||||
posted, r = _run_classify(
|
||||
tmp_path,
|
||||
_emitting("docs/a.md"),
|
||||
timeline_mode="none",
|
||||
push_mode="stable:2",
|
||||
timeline_pages=3,
|
||||
)
|
||||
assert posted is not None and posted["state"] == "success", (
|
||||
f"a quiet PR with a multi-page timeline lost its exemption. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminator", ["null", "[]"])
|
||||
def test_an_EMPTY_FIRST_page_is_untrusted_WHICHEVER_empty_shape_it_is(tmp_path, terminator):
|
||||
"""Both empty shapes must fall through to `rt_ok=no`, and only one of them did.
|
||||
|
||||
The `null` arm required `page > 1`; the empty-ARRAY arm trusted any page, so a `[]` first page
|
||||
certified "nothing was retargeted and nothing was pushed" over a response the walk could not
|
||||
explain, and a docs-only PR was exempted on it. The comment three lines above already claimed the
|
||||
safe behaviour, so the code contradicted its own stated rule for one of the two shapes — and this
|
||||
server produces both, on different endpoints. Parameterised rather than corrected in place,
|
||||
because the point is that the two shapes now take the SAME rule.
|
||||
"""
|
||||
posted, r = _run_classify(
|
||||
tmp_path,
|
||||
_emitting("docs/a.md"),
|
||||
timeline_mode="empty-first-page",
|
||||
timeline_terminator=terminator,
|
||||
)
|
||||
assert posted is None, (
|
||||
f"an exemption was granted from an empty FIRST page ({terminator}) — a zero count was "
|
||||
f"trusted from a response the walk cannot explain. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_timeline_row_with_NO_READABLE_TYPE_is_not_counted_as_nothing(tmp_path):
|
||||
"""A shape we cannot read is not evidence that nothing happened.
|
||||
|
||||
Both tallies select on `.type`. A row lacking one, or carrying a non-string one, matches neither
|
||||
and was silently treated as some other event — so a page of unclassifiable rows certified a zero
|
||||
count. This is the same validate-what-you-consume rule `pr-changed-files.sh` applies to every row
|
||||
IT extracts, which the walk gating the write did not have.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode="untyped-rows")
|
||||
assert posted is None, (
|
||||
"an exemption was granted over a timeline page whose rows carry no readable `.type` — the "
|
||||
f"count was trusted from rows the walk cannot classify. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_the_head_fence_reports_the_OBSERVED_counts_in_its_notice(tmp_path):
|
||||
"""The notice must name the numbers it fenced on.
|
||||
|
||||
A fence whose diagnostic says only "something moved" cannot be triaged from a run log, and this
|
||||
workflow's history is full of runs that posted nothing for reasons nobody could reconstruct
|
||||
afterwards (#751 went unnoticed for exactly that reason). Pin the before/after pair.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode="none", push_mode="moves:3,5")
|
||||
assert posted is None, f"the head fence did not fire. Log:\n{r.stdout[-900:]}"
|
||||
assert "(3 -> 5 push events)" in r.stdout, (
|
||||
f"the head fence notice does not report the counts it fenced on. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_PROTECTED_pr_pushed_mid_run_ALSO_posts_nothing(tmp_path):
|
||||
"""The fence covers `pending` as well as the exemption `success`.
|
||||
|
||||
Same rule as the base axis, and the same reason it is one rule rather than a
|
||||
reason-about-it-per-state condition: the successor run is guaranteed either way, so there is
|
||||
nothing to buy by writing a value this run already knows was computed across two heads.
|
||||
"""
|
||||
posted, r = _run_classify(tmp_path, _emitting("ErsatzTV/Program.cs"), timeline_mode="none", push_mode="moves:0,2")
|
||||
assert r.returncode == 0, f"the job died rather than abstaining cleanly: {r.stderr[-600:]}"
|
||||
assert posted is None, (
|
||||
"a run that saw its head move still wrote a status for a non-exempt PR — the fence is "
|
||||
f"scoped to `success` only. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
# Assert the DISCRIMINATOR. "Posted nothing" is also produced by a crash, an unreadable timeline
|
||||
# and several unrelated abstentions, so without this the test proves only that something went
|
||||
# wrong somewhere.
|
||||
assert "head branch was pushed while this job was classifying" in r.stdout, (
|
||||
f"nothing was posted, but NOT via the head fence. Log:\n{r.stdout[-900:]}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_PR_retargeted_BEFORE_the_run_but_QUIET_during_it_is_STILL_exempt(tmp_path):
|
||||
"""The fence keys on MOTION during this run, never on "has ever been retargeted".
|
||||
|
||||
@@ -2977,7 +3520,9 @@ def test_an_UNTRUSTED_count_withholds_the_exemption_BY_THAT_BRANCH(tmp_path):
|
||||
posted, r = _run_classify(tmp_path, _emitting("docs/a.md"), timeline_mode="unreadable")
|
||||
assert posted is None
|
||||
assert r.returncode == 0, f"the job died rather than declining cleanly: {r.stderr[-800:]}"
|
||||
assert "Could not establish a trusted retarget count" in r.stdout, (
|
||||
# The wording covers BOTH axes since ersatztv#803 — one walk certifies one trust flag, so an
|
||||
# unreadable page abandons the push count and the retarget count together.
|
||||
assert "Could not establish a trusted retarget/push count" in r.stdout, (
|
||||
f"nothing posted, but not via the untrusted-count branch. Log:\n{r.stdout[-800:]}"
|
||||
)
|
||||
|
||||
@@ -3453,7 +3998,8 @@ def test_the_fence_TRUSTS_the_count_and_POSTS_when_the_timeline_terminates(tmp_p
|
||||
from posting anything.
|
||||
|
||||
A page past the end of `/issues/{n}/timeline` is the JSON value `null` on this instance, not `[]`.
|
||||
`count_retargets` gated on `type == "array"` and so treated the real terminator as unreadable: the
|
||||
`count_pr_mutations` (named `count_retargets` then) gated on `type == "array"` and so treated
|
||||
the real terminator as unreadable: the
|
||||
walk never reached a validated empty page, `rt_ok` was never `yes` for ANY pull request, and the
|
||||
fence therefore withheld every exemption `success`. Renovate and docs-only PRs got NO status —
|
||||
the same user-visible outcome as #751, by an unrelated route.
|
||||
@@ -3475,7 +4021,7 @@ def test_the_fence_TRUSTS_the_count_and_POSTS_when_the_timeline_terminates(tmp_p
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert posted is not None, (
|
||||
f"a docs-only PR whose timeline terminates with `{terminator}` got NO status at all. The "
|
||||
"fence could not establish a trusted retarget count, so it withheld the exemption — which "
|
||||
"fence could not establish a trusted retarget/push count, so it withheld the exemption — which "
|
||||
"leaves the required review-verdict/h10 absent and the PR unmergeable with no bypass "
|
||||
f"(ersatztv#751).\n{r.stdout[-1200:]}"
|
||||
)
|
||||
@@ -3728,7 +4274,7 @@ def test_an_UNREADABLE_page_2_refuses_to_conclude_that_no_verdict_exists(tmp_pat
|
||||
"""The two refuse branches of the completeness probe, which cold review found untested.
|
||||
|
||||
Worth a test rather than trusting the shape: this file's history is two consecutive guards that
|
||||
were UNREACHABLE — the `count_retargets` type gate that never saw a real terminator, and a
|
||||
were UNREACHABLE — the timeline walk's type gate that never saw a real terminator, and a
|
||||
full-page check written against a limit of 100 on a server that caps at 50. An unexercised branch
|
||||
here has a track record.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user