Skip to content

Auto-retry infra failures on fork PRs - #113564

Merged
alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-retry-infra-failures-fork-gate
Sep 22, 2026
Merged

alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-retry-infra-failures-fork-gate

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113052

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

The fork-approval gate consumes run_attempt 1, concluding action_required with zero jobs, so a
fork PR's first attempt that runs anything is attempt 2. retry_infra_failures.yml assumed attempt 1
is the real run, leaving infra-killed fork runs invisible to the hourly auto-retry. I hit this via
the slowdown #113052 fixed, which killed Config Workflow on ~65 PRs.

Attempt and window. The filter widens to .attempt <= 2, accepting attempt 2 only if attempt 1
concluded action_required, so a real retry stays excluded. The cutoff compared createdAt, which
GitHub pins to the gated attempt, while startedAt advances to the attempt that ran; that skew
reaches p99 45.1h over 8946 runs.

Scan depth. The listing is createdAt-ordered, so a gated run sits deeper than its window
implies and no row cap exhausts it. The scan walks createdAt in 24 hour timestamp partitions over
31 days, bounding the 30 day approval expiry (observed max 26.6 days). A partition at the API's
1000 row ceiling fails the step instead of dropping rows.

Order. The walk feeds more candidates than MAX_RERUNS, so their order decides who is reached.
sort -u also sorted by the leading databaseId, oldest-created first, only a 0.90 pairwise proxy
for startedAt order. Entries now lead with startedAt so the same dedup orders by deadline: the
candidate nearest the 6 hour edge is retried on this tick or never, while a fresher one is still
admitted by later ticks. Over 312 hourly clocks every clock exceeded MAX_RERUNS, and of the
candidates on their final tick this loses 35%, against 56% and 100% for ascending and descending id.

Attempt 3 stays excluded and the infra heuristic is unchanged, so this restores visibility rather
than reruns.


Workflow [PR]
Sync PR [sync-upstream/pr/113564]

Version info

  • Merged into: 26.10.1.463-master (included in 26.10 and later)

groeneai and others added 15 commits August 4, 2026 21:11
retry_infra_failures.yml selects candidate runs with `.attempt == 1`, which
encodes "attempt 1 is the first real run". That holds for a same-repo PR but not
for a fork PR: GitHub's fork-approval gate consumes attempt 1, which concludes
`action_required` and executes zero jobs, so the first attempt that actually runs
anything is attempt 2. An infra-killed fork run is therefore structurally
invisible to the hourly auto-retry and never gets rerun.

Measured on 211 approval-gated runs: attempt-1 conclusion `action_required` and
attempt-1 job count 0 in 100% of them.

Replace the proxy with the property it stands for, "exactly one attempt has
executed": widen the listing filter to `.attempt <= 2`, then for a candidate at
attempt 2 accept only if attempt 1 concluded `action_required`. A run that
genuinely had a retry already (attempt 1 ran and failed) stays excluded, and
same-repo runs are unaffected.

Keying on `head_repository.fork` instead was rejected: a fork run is not always
gated (26 of 57 sampled fork failure runs had attempt 1 conclude `failure`), so
`fork` over-selects while `action_required` is the exact gate signature.

Live cross-check against the cron's own listing: the current selector sees 11 of
the last 50 failed PR runs, the fixed one sees 15, and all 4 newly visible runs
are approval-gated with 174 jobs executed. No run is lost. Reruns stay bounded:
a rerun of a gated run produces attempt 3, which the `<= 2` filter excludes, and
MAX_RERUNS is unchanged.

This prevents recurrence. It does not unstick runs already older than the
6 hour cutoff.
Follow-up edits to the same change, from review round 1.

The ci/tests/ guard for this selector could never have executed on a
workflow-only change: CI Tests is digest-cached and its include_paths did
not cover .github/, so a PR reverting the selector would have left the
digest unchanged, the job served from cache, and the regression shipped
green. Measured: traverse_paths over the old list yields 606 files and
zero under .github, and appending a byte to the workflow left the digest
at 82bd0cc90266. Naming the one file (not ./.github, which would pull in
about 32 generated workflows) moves the digest from e0fe663d344c to
38c449e98407 on a mutation and back on restore.

jq is absent from the CI Tests image, so the behavioural matrix skips
there and only the static asserts run. Those asserts pinned the selector's
TEXT but not its SEMANTICS: three string-preserving mutants were measured
to pass, the worst of which makes the reject branch inert so the retry
starts re-running already-retried runs. Three asserts close that, and all
ten workflow mutants are now caught with jq absent.

The stub answered every jobs query with an empty list, so gh run rerun was
never reached and the oracle stopped at "considered". It now records its
argv, and two rows assert that a gated fork run is actually rerun while an
already-retried one is not, each with its own mutant.

The rerun log line hard-coded attempts/2, which was correct while only
attempt 1 was admitted but points an operator at the failed attempt now
that attempt 2 is a candidate. It derives the attempt instead.

Full ci/tests/ failure set is byte-identical to the 27 pre-existing;
610 to 619 passed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…uard

The guard for the auto-retry's fork gate has two halves: static substring
assertions that always run, and a behavioural matrix gated on jq, which is
absent from the CI Tests image. Only the static half executes in CI, and it did
not cover three lines the fix introduces:

  - the listing projection "\(.databaseId):\(.attempt)",
  - run_id="${run_entry%%:*}",
  - run_attempt="${run_entry##*:}".

Transposing the projection or either split exchanges run_id and run_attempt, so
the probe requests actions/runs/<attempt>/attempts/1, the 2>/dev/null || echo ""
fallback yields an empty conclusion, and every attempt-2 candidate is rejected.
The gate goes inert while all six existing static assertions still pass.
Measured: mutants that swap the projection, swap both splits, or swap either
split individually were all green with jq absent, and red only in the jq-gated
rows.

Three substring assertions close that. Each fires its own message: swapping the
projection reports "projection must emit id:attempt", swapping the run_id split
reports "run id must come from the head field", swapping the run_attempt split
reports "attempt must come from the tail field". The two splits need separate
mutants because assert short-circuits, so a mutant that breaks both proves only
the first assertion load-bearing.

The rerun-URL suffix, changed from a hard-coded attempts/2 to
attempts/$((run_attempt + 1)), was likewise asserted by nothing in either half;
shifting it to + 2 was green everywhere. The rerun test now checks the printed
suffix, and no-oping gh run rerun still reddens that row on the rerun-log
assertion, so the row keeps asserting the rerun happened.

Net: 13 of 15 mutants are caught with jq absent, covering every mutant of the
workflow itself. The remaining two mutate a log line and the test's own stub.
No production file changes: the workflow and ci/defs/job_configs.py are
byte-identical to the previous commit.
The attempt-1 probe added by this PR reads `.conclusion` and falls back to an
empty value on an API error. Neither line had an assertion in either arm of the
guard, so both could be mutated with CI green:

- Reading `.status` instead of `.conclusion` returns `completed` for a real
  gated attempt 1 (measured on runs 30947170951, 30945977252, 30948038715 and
  30939874921: `status=completed` / `conclusion=action_required`, 4 of 4). The
  comparison against `action_required` then fails for every fork candidate and
  the fix goes inert, which is the exact failure mode the previous round's
  asserts existed to prevent.
- Deleting `2>/dev/null || echo ""` makes a failing command substitution abort
  the step under `set -euo pipefail` (`x=$(false)` exits 1, whereas
  `x=$(false 2>/dev/null || echo "")` exits 0 with an empty value), so one
  transient API error takes down the whole hourly retry rather than skipping a
  single run.

Both mutants were measured green in both arms against the previous commit.

Two static asserts close them in CI, where `jq` is unavailable. The stub was
also structurally unable to see them: it echoed a fixed string on the
`attempts/1` path whatever field the caller's `--jq` requested, and could never
exit non-zero. It now evaluates the caller's own `--jq` against a full
`{status, conclusion, run_attempt}` payload and honours an `ATTEMPT1_FAIL`
switch, so requesting the wrong field is observable and the fallback is
reachable. One row asserts the step survives an attempt-1 API error, rejects
the run, and reports the fallback's own empty value.

Both halves are needed: before the stub change the wrong-field mutant did not
redden the behavioural row either.

The remaining 16 mutants redden the identical set of arms as before, and the
new row is controlled in both directions by mutating the stub switch itself.
The CI-runnable half of the fork-gate guard pinned its targets by substring, so a
mutation that ADDED a line or a conjunct, rather than editing an asserted substring,
left every assertion true while the fix went inert.

jq is absent from clickhouse/integration-tests-runner, so in CI only
test_selector_admits_gated_fork_runs executes (1 passed, 9 skipped) and its assertions
were all substring presence or exact-old-spelling absence. Three additive mutations were
green in that arm before this change and are red after it: adding a redundant
.attempt == 1 beside the correct bound, dropping the cutoff conjunct, and appending a
second run_id assignment that takes the attempt field. The first is the original defect
reinstated with the guard green - over a two-row fixture the mutant jq expression emits
only 43:1 where the shipped one emits 42:2 and 43:1, so every fork run is dropped again.

The listing-filter assertion now compares the select() body's conjunct SET against the
expected pair instead of matching a substring. Selection was measured over three
predicates against eight arms (shipped, five mutants, two semantically identical
refactors): the substring form kills 2 of 5 mutants and falsely refuses a reordering;
byte-exact equality of the clause kills 5 of 5 but falsely refuses both refactors; the
conjunct set kills 5 of 5 with no false refusal. So this is also a de-brittling - the
reorder control was red before and is green now.

The helper is anchored to the gh run list invocation rather than taking the step's first
select(, of which there are nine. On the current file both forms select the listing filter,
since it is the first occurrence, so the anchor is future-proofing rather than a fix:
measured over six arms, the anchored and unanchored forms return the same verdict in six of
six. If the listing select() is moved or removed, the anchored form fails on its own assert
at the extraction site, while an unanchored first match would slide silently to the verdicts
expression at .conclusion == "failure" and compare the wrong clause.

The three field-order assertions are kept and joined by a multiplicity check, since
presence alone cannot see a later assignment that overwrites the correct value.

The full matrix is 21 mutants plus one control, each run with and without jq: 19 of the
21 are caught in the jq-absent arm, up from 16 of 18, and the two that are not mutate a
log line and the test's own stub. No pre-existing mutant changed its failing set. The
ci/tests suite is green in both arms.

The workflow and ci/defs/job_configs.py are unchanged by this commit.
`jq` is absent from the `clickhouse/integration-tests-runner` image, so of this
module's ten arms only `test_selector_admits_gated_fork_runs` executes in CI
(`1 passed, 9 skipped`); the other nine are `skipif`-gated. Every assertion in
that arm was a text predicate over the probe's own lines, and none of them said
anything about whether those lines are reached. Wrapping the whole
`if [ "$run_attempt" != "1" ]` block one level deeper inside `if false; then`
leaves the block's text untouched, so all of them still passed.

What such a mutation breaks is this change's own stated contract -- retry only a
run that has never been retried. Measured eligibility under the wrap: an
attempt-2 run whose attempt 1 concluded `action_required` stays eligible (the
listing widening itself is unaffected), but an attempt-2 run whose attempt 1
concluded `failure` becomes eligible too, i.e. a run that has genuinely been
retried once is retried again. The `.attempt <= 2` bound still excludes attempt
3 and higher, so the blast radius is one extra rerun per run.

So assert that the guard IS the condition gating the probe: it sits at
loop-body indent with no enclosing conditional left open between the loop
header and it. Hoist the guard literal into a local so this assertion and the
pre-existing text assertion cannot drift apart; the assertion message is
unchanged.

Verified on the real workflow before prescribing: between the loop header and
the guard the body holds exactly one balanced `if`/`fi` (the `MAX_RERUNS`
break), the two split assignments and three comment lines, so the shipped file
scores depth 0 and body indent equal to guard indent.

Three new mutants, each red in both arms on the new assertion's own message and
green against the previously committed test: the block wrapped in
`if false; then`, in `if [ 1 = 0 ]; then`, and in `if true; then`. The third
matters because it is semantics-preserving, which is what shows the assertion
pins nesting rather than the wrapper's truthiness. Two semantics-preserving
controls stay green in both arms: reordering the two split assignments, and
adding a comment line before the guard. Over the full carried 23-mutant set no
recorded failing set changes.
The reachability assertion added in the previous round scans only the lines
between the loop head and the guard, so it sees a conditional wrapped around
the guard from outside but not one opened inside it. Inserting
`if false; then` immediately after the guard line, wrapping the probe and its
reject branch, leaves every existing assertion true: the guard literal, the
`/attempts/1` read, the `.conclusion` projection, the scoped `continue`, the
depth scan and the indent check all still hold, because none of them looks at
what the guard's body actually begins with.

Under that shape the never-retried invariant this test exists to pin stops
holding for one case: an attempt-2 candidate whose attempt 1 concluded
`failure` is a genuine retry and must be skipped, but with the probe
unreachable it becomes eligible. A gated fork run stays eligible either way,
so the fork fix itself keeps working; what is lost is the promise that a run
which has already been retried is left alone, costing one extra rerun per run.
`MAX_RERUNS` still bounds the tick.

So assert the guard's matched body directly: extract the lines after the guard
up to the first line at or above its indent, and require that its first
significant line is the probe assignment and that no conditional is still open
where the reject branch begins. Keying on the first significant line is
construct-agnostic, which also covers `case`/`while`/`&&` wrappers that a
keyword-counting scan alone would miss.

Four new matrix arms cover the inside-nesting shapes and one control covers a
comment added inside the body. The `if true; then` arm is the load-bearing
one: it preserves semantics, so it demonstrates the assertion pins nesting
rather than truthiness. Against the previous round's committed test all four
are green in the CI arm, which is what makes this a real gap rather than a
restatement of the outside-nesting one.

The module docstring said the behavioural test covers the listing filter
through real `jq` without noting that `jq` is absent from the CI Tests image,
so nine of the ten arms skip there and the static assertions are the whole of
the CI coverage. The `skipif` reason already said so; the docstring now does
too.

Co-Authored-By: Claude Fable 5 <[email protected]>
The static half of the fork-gate guard is what runs in CI: jq is absent from the
clickhouse/integration-tests-runner image, so nine of the ten arms skip there and the
substring assertions carry the contract alone. Two of the sixteen semantic lines the
workflow diff adds were consumed by no CI-executable assertion.

The probe URL was covered only by the bare substring "/attempts/1", which pins the
attempt but not the run: replacing $run_id with $run_attempt, or with the literal 1,
keeps that substring present while the probe reads a run that does not exist. The API
returns 404, the fail-closed fallback yields the empty string, and the empty string is
not "action_required", so every gated fork candidate is skipped and the fix declines to
a silent no-op. The reject condition was covered only by its own substring, so an added
always-true disjunct kept the text intact while making the branch unconditional, skipping
every attempt-2 candidate the same way. Neither is visible to the behavioural arms: the
stub matches the glob *attempts/1*, which any run identifier satisfies.

Assert the probe command as a whole against a normalized form of the step, with line
continuations joined and runs of whitespace collapsed, so that re-wrapping the command
is not a false refusal while any change to the run identifier, the attempt, the field or
the fallback is caught. Assert the set of "if" lines testing $attempt1_conclusion equals
exactly the one shipped condition, so an added disjunct is a different string and cannot
pass. Both are static, so both execute in CI. The existing part-wise assertions stay for
their targeted failure messages.

Eight mutants covering the run identifier, the attempt, the field, the fallback and three
shapes of weakened condition are all caught in the jq-absent arm; three of them
(identifier to $run_attempt, identifier to 1, prepended disjunct) pass against the
previous revision of this file, which is what shows the gap was real. Five
semantics-preserving controls stay green, and the harness asserts every row genuinely
alters the extracted step before scoring it, so a no-op cannot pass for a verdict. No
pytest arm is added and no workflow line changes: ci/tests/ collects 678 tests in both
arms, and the target file is 10 passed with jq, 1 passed and 9 skipped without.
Three of the fork-gate guard's assertions read raw substrings of a command
that spans line continuations, so they refuse a harmless re-wrap of the
workflow with a message that misdescribes the defect. Moving the fallback
onto its own continuation line fails "the probe must fail closed on an API
error" while the fallback is present and correct; breaking the line between
--jq and '.conclusion' fails "the probe must read the conclusion field"
while the probe reads exactly that field. A maintainer reformatting the step
is sent hunting for something that is not missing. Measured over a table of
semantics-preserving reformats, three of eleven were refused this way.

Point those three at the normalized form the whole-command assertion already
builds, hoisted to the top of the test. The targeted messages are the reason
to keep all three rather than collapse them into the whole-command check.

Two assertions were also satisfiable while the guard was inert. The
whole-command check is a substring test, so appending a second
attempt1_conclusion= assignment after the correct command leaves it intact
while the reject branch reads the overwritten value and skips every gated
fork run. Assert instead that the assignment is the SOLE one, which is
already precedented in this file for run_id and run_attempt. And the reject
branch's skip was matched by \s*continue\b, which also accepts
continue=false: a variable assignment, not the builtin, so the branch logs
and falls through to the rerun logic. Require continue as the command word,
rejecting the assignment while still accepting continue 1 and a trailing
no-op, both of which skip identically.

The three shapes are caught by no other arm in the CI configuration, where
jq is absent from the runner image and nine of the ten arms skip. With them
the guard catches 21 of 21 mutants and stays green on all 11
semantics-preserving reformats, against 18 and 8 before.
The guard's assertions covered the attempt-1 probe thoroughly and the listing
that feeds it barely at all, so six mutations of the listing left all twenty
shipped assertions green while making the whole fix inert. The listing sits
upstream of the probe, so an escape there means the loop body never runs: with
a second filtering stage appended to the same --jq expression the fork run is
gone before the loop, and the step prints "No recent failed runs found."

The conjunct set pins what is inside select() and nothing outside it, so
appending "| select(.attempt == 1)" keeps that set identical while filtering
every fork run back out. Pin the expression's top-level shape too. Requesting
attempt in --json is likewise load-bearing: without it jq yields null, null <=
2 still admits the row, and run_attempt becomes the string "null", which skips
a same-repo attempt-1 run and aborts the step at $((run_attempt + 1)).

The two remaining escapes were shapes the old spellings structurally could not
see. A count anchored on the expected expansion cannot see run_attempt=1
appended afterwards, and a ^-anchored one cannot see a semicolon-separated
overwrite on the same line, so count assignments of any form, once per
variable that carries a candidate to the rerun decision. And a
\n\s*continue search matches a continue nested in "if false; then ... fi",
which never executes, so the already-retried run falls through and is rerun:
depth-track the reject branch instead, keeping the (?!=) lookahead that
rejects continue=false.

Fifteen mutants covering these shapes all redden, each on the assertion
written for it and with jq absent, which is the CI Tests image's state.
Sixteen semantics-preserving reformats were run alongside them, since a false
refusal sends a maintainer hunting for something that is not missing: fourteen
stay green, and the two that are refused are refused identically by the
previous revision of this file, so neither refusal is introduced here.
Three checks in the guard were enumerations, and each kept leaking one shape
further out. All three escapes below were green on the complete 20-assertion
set, so a change of kind rather than three more instance patches:

- The multiplicity check whitelisted four named variables and omitted
  run_entry, the loop variable this change introduces and the source of both
  splits. Forging it rewrites both at once, upstream of both, so run_attempt
  becomes 1, the attempt-1 probe never runs, and an already-retried run is
  rerun anyway. Replaced with a census of every assignment between the loop
  header and the reject condition, which no unlisted name can escape;
  run_entries keeps an explicit bound because it is assigned before the loop.

- The listing filter was pinned by shape (three stages, stage 2 starting with
  select), leaving the projection free. A filter nested inside it keeps the
  stage count, the stage-1 prefix and the projection substring intact while jq
  emits nothing, so the listing yields no candidates and the fix is inert.
  Replaced with exact equality on all three stages, which subsumes the
  select-conjunct set and the projection literal; both are removed, and the
  four mutations they caught were confirmed still caught.

- The reject branch's `continue` was found by tracking nesting depth, which has
  to enumerate every construct that can nest one. Nine of ten spellings were
  already refused; `{ if false; then` on the brace's own line with `fi; }`
  joined escaped, because the brace opens no tracked depth while `fi; }` closes
  one. Replaced with a whitelist of the branch body: log lines, then a
  `continue` as the last command.

Also pin the ci_tests digest entry for the workflow. It is what makes this
guard run at all on a workflow-only change, and nothing asserted it, so
deleting it left the repository green while restoring the cache-skip blind spot
the guard exists to close. Membership only, so a later entry cannot be
false-refused.

Verified over 18 mutants and 19 semantics-preserving controls with the shipped
workflow asserted green first: 18 redden, 19 stay green. Re-run against the
previous test file, eight of the 18 were green there and are now caught while
ten were already caught and still are, so no coverage is traded away. The
digest test's negative control was measured: with the entry removed it fails
and is_affected_by returns false, and job_configs.py was restored byte-identical.
The guard's oracle for the candidate's data path censused ASSIGNMENTS with a
regex anchored on a leading-separator enumeration, `(?:^|;|\bthen\b|\bdo\b)`.
That enumeration cannot see an assignment introduced after any separator it
does not list, and the two neighbouring bounds had the same defect from the
same cause: the `run_entries` bound was `(?:^|;)`-anchored and the
`attempt1_conclusion` sole-assignment check `^`-anchored.

Thirteen edits to the workflow therefore passed the whole static test. Six are
worth naming because they split across two different failure modes. Forging
`run_attempt` to 1 -- `&& run_attempt=1` on the split's own line, or a
plausible-looking `[ -n "$run_attempt" ] || run_attempt=1` defensive default --
makes every attempt-2 candidate eligible, so the "exactly one attempt executed"
contract this change adds stops being pinned at all. Forging `run_id` or
`attempt1_conclusion`, or emptying `run_entries` after the empty-listing block,
leaves the gate inert instead. Neither mode is visible in CI: `jq` is absent
from the CI Tests image, so the static assertions are the only half that runs.

Adding the missing separators would be another instance patch. A regex cannot
see an assignment form it does not enumerate -- a refined one still admitted
`read -r run_attempt <<< "1"` and `printf -v run_attempt %s 1` -- so pin the
region's 15 commands as a closed whitelist instead, in the shape the reject
branch already uses. It also refuses `{ run_attempt=1; }`, `declare` via an
indirect name, and the `&`/`||` separators. The region starts at the
`run_entries` assignment rather than the loop header, so the listing and the
empty-listing guard are inside it. Continuations are joined and whitespace
collapsed first, so a re-wrap or a reindent is not a false refusal.

The `run_entries` bound is deleted as subsumed: the whitelist refuses a second
assignment to it, which that bound did not.

Measured with `jq` hidden, which is CI's state: 13 harmful edits red, each by
the whitelist alone; 4 benign edits green (probe collapsed to one line,
re-wrapped elsewhere, a comment added inside the region, a line reindented).
Deleting the new assertion turns the first carrier green again. The workflow and
`ci/defs/job_configs.py` are unchanged.
…h whitelist

The whitelist that pins the candidate's data path compared all 15 of the
region's commands by exact list equality, including the whole `gh run list`
invocation and the two `echo` log lines. That closed every assignment form a
separator-enumerating census cannot name, and it also refused seven ordinary
maintenance edits: raising `--limit`, reordering or extending the `--json`
field list, reordering the `gh` flags, and adding a log line in the region.
None of those touches the invariant.

The listing command is now matched as a pattern and a single simple `echo` is
dropped before comparing. Both loosenings are redundant with assertions that
already sit upstream rather than being new latitude. The listing's semantics
are pinned by the exact three-stage equality on its `--jq` expression and by
the assert that `--json` requests `attempt`; an `echo` with no separator,
grouping or substitution is one simple command and cannot bind a variable, so
dropping it admits a log line without admitting an assignment.

Text appended after the listing line falls into one of two cases and both are
still refused: text ending in `")` is swallowed into the greedily captured jq
expression, so stage equality fails, and text not ending in `")` fails that
capture's own assert. Measured with jq hidden, which is CI's state: all 13
harmful forms the whitelist was written for stay red, as do six further
adversarial arms and ten attacks aimed at the two loosenings themselves, each
attributed to the assertion that fires. Of the nineteen semantics-preserving
controls, reds drop from seven to one. That one, the two run-entry splits
reordered, stays refused deliberately: the comparison is ordered, and the
ordering is what pins that run_id is assigned before the probe reads it.
Deleting the whitelist assertion turns the first carrier green again, so it is
the assertion doing the work.

Also drop `_listing_select_conjuncts`, which has had no call site since the
conjunct-set assert was replaced by three-stage equality, and correct the
module docstring: the listing filter's coverage is static, and the jq-gated
rows cover eligibility and rerun.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The guard test's data-path whitelist matches the `gh run list` invocation as a
pattern, so flag spelling, flag order and `--limit` stay free. That also left the
three flags that carry the listing's semantics unpinned: swapping `--status
failure` for `--status success`, naming another workflow, or naming another
repository each leaves the whole static test green while the hourly job retries
the wrong runs. Assert those three individually, against the normalized
invocation so a re-wrap or a reorder is still not a refusal. `--limit` stays
unpinned deliberately: it is a tuning knob and the 6 hour cutoff bounds the
window independently.

Separately, the assertions pin the gate and everything up to the reject
condition, but not the region from the gate's own `fi` to `gh run rerun`.
Re-emitting the guard condition there with a bare `continue`, or forcing
`should_rerun=false` for an attempt-2 candidate just before the rerun call,
restores the pre-fix behaviour of skipping every gated fork run with all
eighteen assertions passing; re-assigning `run_attempt=1` past the whitelisted
region does the same. Pin that exactly one line branches on `run_attempt`, the
gate, and that `run_attempt` is assigned once. Reads that do not branch, such as
the rerun log line, stay free, which is why this is a branch-shape test rather
than a closed list of the lines that mention the variable.

Both are measured load-bearing: deleting the flag loop turns each of the three
flag mutations green again, and deleting either new assert turns its own mutants
green again while the fixed workflow stays green. Across all twenty-eight
mutant and control arms the verdict changes exactly six times, every one from
green to red, so no benign edit becomes a refusal. The two previously measured
control sets are unmoved at one of nineteen and four of sixteen red. No
workflow, CI-config or behavioural change: `jq` is absent from the CI Tests
image, so the static assertions are the whole signal there.
Two of the fork-gate guard's assertions accepted a mutation that repoints the
real query or neutralizes the gate.

The three semantic listing flags were matched by substring membership, which any
extension of a value satisfies: --workflow pull_request.yml.bak, --status
failurefoo and --repo "$GH_REPO"x each read the wrong workflow, status or
repository while the whole static test stayed green. The invocation is already
whitespace-normalized, so a token-bounded match is exact and still admits a
re-wrap or a flag reorder.

The post-gate scan for lines branching on run_attempt anchored its keyword
alternation at line start, so a branch introduced after a command separator was
invisible: `echo x; if [ "$run_attempt" = "2" ]; then should_rerun=false; fi`,
the same inside a brace group or a subshell, and `: ; case "$run_attempt" in`
each skipped every gated fork run with the file green. The keywords now fire at
any command position, and `[` is included because a test invocation reading
run_attempt is a branch in every practical form. An exact-list whitelist of the
run_attempt lines was measured instead and rejected: it catches the same
mutations but falsely refuses harmless edits such as re-texting the rerun log
line to mention the attempt.

Seven new mutants redden and every one is caught with jq absent, which is the CI
Tests image's state and therefore the only arm that runs there. Reverting either
assertion alone turns exactly its own mutants green again and leaves the other's
red. No previously caught mutant is lost and no control changes verdict.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Six review rounds, two independent reviewers per round (a cold code review plus a separate
second-model gate), all findings adjudicated against measurement.

❌ Blockers (fixed before this PR was opened)

  • The selector's CI-runnable guard could not see a string-preserving mutation: three
    semantics-destroying edits kept every asserted substring, so the fix could go inert with CI
    green. Closed with three static assertions, one per site.
  • Nor an additive mutation: adding a redundant .attempt == 1 conjunct beside the correct
    bound, dropping the cutoff conjunct, or appending a second run_id assignment that reads the
    wrong field. All three were green before; the listing-filter assertion now compares the
    select() body's conjunct set, and the field-order asserts are joined by a multiplicity
    check.
  • Nor a structural re-nesting mutation: wrapping the whole attempt-1 probe in an
    always-false conditional left every text assertion true while the "retry only a run that has
    never been retried" invariant stopped holding. Closed with an assertion that the guard is the
    sole condition gating the probe.
  • Two of the probe's own lines, the --jq '.conclusion' payload and the
    2>/dev/null || echo "" fallback, had no assertion in either arm. Reading .status instead
    would reject every fork candidate; dropping the fallback would let one transient API error
    abort the whole hourly tick under set -euo pipefail.
  • CI Tests did not list this workflow in its cache digest, so the guard would have been
    served from cache on a change to the very file it reads.

⚠️ Majors

  • A commit message claimed a measured effect that was not real (that an unanchored helper
    would match the wrong select() on the current file; it matches the right one). Corrected:
    the anchor is future-proofing plus a fail-loud extraction assert, and the anchored and
    unanchored forms were measured to agree on six of six arms.
  • One reviewer prescription was itself vacuous: a regex not bounded by the branch's own fi,
    which matched a continue ninety lines away and so passed on the mutant it existed to catch.
    Replaced with a form that slices the reject branch first.
  • A reviewer prescription was found infeasible on inspection and withdrawn rather than
    worked around.

💡 Noted, not changed

  • jq is not installed in the CI Tests image, so nine of the ten test arms skip there and CI
    relies on the static assertions. Providing jq would mean changing an image shared by four
    jobs, and the step under test invokes jq at twenty sites so a jq-free harness cannot run
    it at all. skipif-on-missing-binary is the existing convention in this directory. The
    static half is therefore where the coverage has to live, and every mutation of the workflow
    itself is caught there.
  • The hourly cron is only observable after merge. The selector change was validated read-only
    against live data instead; absolute run counts are not quoted because the query is a rolling
    window.
  • #113368 also appends an entry to the same include_paths list. Additive entries to a
    shared list, so a textual conflict if both land, with no behavioural interaction either way.

Verification. Twenty-one mutants plus one semantics-preserving control, each run in two
arms: with jq, where the behavioural rows execute, and without it, which is the CI image's
real state. Nineteen of the twenty-one are caught with jq absent, i.e. every mutation of the
workflow itself. The remaining two mutate a log line and the test's own stub. The control must
stay green, which is what shows the assertions are a tightening rather than an over-fit to one
spelling.

Session id: cron:clickhouse-review-slot-11:20260805-050114

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. python3 -m pytest ci/tests/test_new_tests_check.py ci/tests/test_retry_infra_failures_fork_gate.py -q fails on the pristine workflow and passes on the fixed one, deterministically. Live, on the same 50-run listing the workflow itself reads: the fixed selector picks a strict superset of the old one, so no run is lost, and every newly visible run was individually confirmed approval-gated with its jobs executed on attempt 2.
b Root cause explained? Yes. The fork-approval gate consumes run_attempt 1 as a zero-job action_required placeholder, so the selector's attempt == 1 proxy for "first real run" is false for every fork PR. Verified on run 30707054164: attempts/1 conclusion action_required, the run itself run_attempt: 2.
c Fix matches root cause? Yes. It replaces the proxy with the property it stands for (exactly one attempt executed) at the site where the wrong assumption lived. MAX_RERUNS untouched, no downstream heuristic changed.
d Test intent preserved / new tests added? Yes. No existing test weakened. ci/tests/test_retry_infra_failures_fork_gate.py pins both directions; its static half runs unconditionally, so the fork-blindness stays guarded in CI where jq is unavailable, and two rows assert the gated run actually reaches gh run rerun while an already-retried one does not. A further row asserts the probe fails closed when the attempt-1 API call itself errors. CI Tests now lists this workflow in its digest, so the guard is not served from cache on a change to it.
e Both directions demonstrated? Yes, twice. Offline: this change's own 11 arms pass on the fix (10 in the new file plus the digest arm in test_bugfix_validation_not_cached.py); the command in row a collects 29, because it also runs the 19 pre-existing test_new_tests_check.py arms. On the pristine workflow 4 fail (test_selector_admits_gated_fork_runs, test_eligibility[2-action_required-1-True], test_gated_fork_run_is_actually_rerun[action_required-True], test_attempt1_probe_fails_closed_on_api_error), and 1 of those 4 fails with jq absent, which is CI's state. Live: the fixed selector is a strict superset, no run is lost, and each newly visible run was individually confirmed approval-gated with its jobs executed on attempt 2.
f Fix is general across code paths? Yes. revert_broken_prs.yml and cherry_pick.yml do not filter on run_attempt; fix-stuck-auto-merge in the same file reads mergeStateStatus; the downstream job-level and S3 heuristics are attempt-agnostic and were simply never reached. Same-repo runs still match via attempt == 1, pinned by a test case.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the input space here, the attempt-1 conclusion: parametrized over action_required (accept) and failure (reject), attempts 1/2/3, and inside/outside the 6 hour window. A failing attempt-1 API call falls to the reject branch rather than aborting the step, asserted by its own row driven by a stub that exits non-zero.
h Backward compatible? (maintainer-approved exception only) Yes. No settings, serialization or SettingsChangesHistory.cpp. Same-repo behaviour is unchanged; the only change is that previously invisible gated fork runs become eligible.
i Invariants and contracts preserved? Yes. "Retry only a run that has never been retried" now holds in both directions. set -euo pipefail is respected: the new gh api is || echo ""-guarded so a transient API error cannot abort the job. MAX_RERUNS still caps a tick and the <= 2 bound caps per-run reruns at 1 (a rerun of a gated run becomes attempt 3, which the filter excludes).

Every guard site has its own dedicated mutant, each run in two arms: with jq, where the
behavioural rows execute, and without it, which is the state of the CI Tests image. The probe
half was covered first, by 35 mutants against 11 semantics-preserving controls; the listing half
was then covered by a second matrix of 15 against 16, and a third of 18 against 19 closed three
further oracle escapes. A fourth then closed six more: three that leave the gate's own text
intact but neutralize it downstream (re-emitting the guard condition after the gate's fi with a
bare continue, forcing should_rerun=false for an attempt-2 candidate just before the rerun
call, and re-assigning run_attempt=1 past the whitelisted region), and the three listing-flag
mutations named below. The first three are pinned by requiring that exactly one line branches on
run_attempt (the gate) and that run_attempt is assigned exactly once; reads that do not
branch, such as the rerun log line, stay free. Its nine controls hold, the one exception being a
comment appended to the guard line, which the data-path whitelist already refused before this
matrix existed. Counts are given per matrix rather than
summed, because a few shapes appear in both and "distinct" would rest on a judgement about which
of those are the same mutation.
The probe half:
Reverting the widening, dropping the upper bound, deleting the attempt-1 probe, making the probe
accept any conclusion, inverting the probe's comparison, reading .status instead of
.conclusion, deleting the error fallback, the pristine upstream file, making the reject branch
inert, inverting the outer guard, pointing the probe at the wrong attempt, transposing the
listing projection, transposing the run-id split, transposing the run-attempt split, transposing
both splits together, shifting the rerun-URL attempt, sabotaging the step extractor, no-oping
gh run rerun, adding a redundant .attempt == 1 conjunct beside the correct bound, dropping
the cutoff conjunct, appending a second run_id assignment that overwrites the correct value
from the wrong field, re-nesting the whole attempt-1 probe block one level deeper from OUTSIDE
the guard inside if false; then, inside if [ 1 = 0 ]; then, and inside if true; then, and
nesting it from INSIDE the guard inside if false; then at the shipped indent, the same
re-indented, inside if true; then re-indented, and inside case x in x) ... ;; esac. Four
more target the probe command and its reject condition as wholes rather than as substrings:
pointing the probe's run identifier at $run_attempt and at the literal 1, appending a
tautological disjunct to the reject condition, and prepending an always-true disjunct on another
variable. Three more target a correct construct followed by an overwrite, which a substring
assertion cannot see: appending attempt1_conclusion="failure" and appending
attempt1_conclusion="" after the intact probe command, and replacing the reject branch's
continue with continue=false, a variable assignment that does not skip the iteration.
Each reddens a different case on its own assertion, and 33 of those 35 are caught with
jq absent
(every mutant of the workflow itself); the remaining two mutate a log line and the
test's own stub, so they are behavioural by construction. Its eleven controls are semantically
identical to the shipped file: reordering the two listing conjuncts, reordering the two run-entry
splits, adding a comment line before the guard, adding one inside the guard's body, adding a log
line before the skip message, collapsing the probe onto one line, re-wrapping it at a different
continuation point, moving its || echo "" onto a line of its own, breaking the line between
--jq and '.conclusion', and writing the reject branch's skip as continue 1 and as
continue ; :. Nine stay green. The two refused are refused deliberately, by later
assertions than the ones this control set was written against: the reordered listing conjuncts by
the exact three-stage equality on the --jq expression, and the reordered splits by the ordered
data-path whitelist, which is what pins run_id being assigned before the probe reads it.

The listing half sits upstream of the probe, so an escape there means the loop body never runs at
all. Its 15 mutants: appending a second select(.attempt == 1) stage to the same --jq
expression, expressing that filter as a parenthesised if .attempt == 1 then . else empty end
stage and as a bare one, dropping attempt from --json, blanking run_entries after the
listing and overwriting it before the loop, appending run_attempt=1 and run_id=99 after the
splits and a semicolon-separated run_attempt=1 on the split's own line, an
attempt1_conclusion="failure" overwrite on the probe's own line and on the next, and wrapping
the reject branch's continue in a one-line and a multi-line if false; then ... fi, in
while false; do ... done, and two levels deep. All 15 redden, each on the assertion written
for it and with jq absent
, and none is a silent no-op: the harness asserts every row
genuinely alters the extracted step, and refuses an ambiguous anchor rather than guessing (the
step has three continue lines, and only the reject branch's is the target). Its 16 controls
are semantically identical to the shipped file: re-wrapping the listing --jq value onto its own
continuation line and across three, reordering and extending the --json field list, raising
--limit, reordering the gh flags, swapping the two select conjuncts, re-indenting --repo,
collapsing the inner whitespace of the select, dropping the quotes on the run_id split,
moving the probe's fallback onto its own line, and writing the reject branch's skip as
continue 1, as continue ; :, and with a comment, a log line or a complete one-line inner if
above it. Twelve stay green. The four that are refused -- the whitespace-collapsed select,
the unquoted run_id split, the swapped select conjuncts and the one-line inner if above the
continue -- are refused by assertions that predate this matrix and pin those spellings
deliberately; all four were re-run against the earlier test file and refused there identically,
so none of the four refusals is introduced here. Controls are what show the assertions are
tightenings rather than over-fits to one spelling or one layout, and the if true; then mutants
are the load-bearing pair: they preserve semantics, so they demonstrate the reachability
assertions pin nesting rather than truthiness. Over the four server-dependent modules excluded
(their whole-suite failure set is not reproducible run to run), the ci/tests/ suite is green in
both arms and gains exactly eleven passing arms with jq and two without, which is the eleven
this change adds and the nine of them that need jq.

A third matrix then replaced three enumerated checks with closed predicates, because each
enumeration kept leaking one shape further out: the listing filter's three jq stages are now
pinned by exact equality, the reject branch's body is a whitelist of log lines followed by a
continue, and the candidate's whole data path -- from the run_entries assignment to the reject
condition -- is a closed whitelist of the 13 commands in it that can bind a variable. A census of
the ASSIGNMENTS in that region had to enumerate the separators one can follow, and that
enumeration leaked: 13 edits passed it, among them &&/||/& separators, a { ... } group,
read -r, printf -v and an indirect declare. Each forges run_attempt -- making every
attempt-2 candidate eligible, so the never-retried contract this change adds goes unpinned -- or
forges run_id/attempt1_conclusion/run_entries, leaving the gate inert. All 13 redden with
jq absent, each by the new whitelist alone
, while 12 of 12 benign edits stay green (the
probe collapsed onto one line and re-wrapped at a different continuation, a comment added in the
region, a line reindented, three added echo lines -- one whose string contains = -- and the
--json list reordered and extended, --limit raised, the gh flags reordered and --repo
reindented). Two of the whitelist's entries are deliberately not verbatim: the gh run list
listing is matched as a pattern, so its flag spelling, flag order and --limit stay free, while
--repo "$GH_REPO", --workflow pull_request.yml and --status failure are each asserted
individually and the jq expression and the --json field set are pinned by the stage-equality
and --json ... attempt asserts above; and a single simple echo -- one with no separator,
grouping or substitution, so it cannot bind a variable -- is dropped before comparing. The ten
attacks on those two loosenings (&&/||/; re-assignment appended to the listing line,
${run_attempt:=1} inside an echo, an echo then a newline assignment, a backtick assignment
and a redirect followed by one, and swapping --status failure for --status success,
--workflow pull_request.yml for another workflow and --repo for another repository) all stay
red, as do three harder listing appends whose own text ends in "), caught upstream by the
stage-equality assert. Deleting the whitelist assertion turns the first carrier green again;
deleting the three-flag loop turns each of those three flag mutations green again.

Two of those predicates were then measured to be satisfiable by a narrower mutation than the one
each was written for, and both are tightened in the shipping revision. The three listing flags
were matched by substring membership, which any extension of a value satisfies:
--workflow pull_request.yml.bak, --status failurefoo and --repo "$GH_REPO"x each repoint the
real query while the whole static test stays green. They are now matched token-bounded, which is
exact because the invocation is already whitespace-normalized, so a re-wrap or a flag reorder is
still not a refusal. Separately, the post-gate scan for lines branching on run_attempt anchored
its keyword alternation at line start, so a branch introduced after a command separator was
invisible: echo x; if [ "$run_attempt" = "2" ]; then should_rerun=false; fi, the same inside a
{ ... } group or a ( ... ) subshell, and : ; case "$run_attempt" in each skip every gated
fork run with the file green. The keywords now fire at any command position, and [ is included
because a test reading run_attempt is a branch in every practical form. Seven new mutants
redden, every one with jq absent
, and reverting either tightening alone turns exactly its own
mutants green again while the other's stay red. Ten semantics-preserving controls stay green,
including a flag reorder, a raised --limit, the --json list reordered and extended, the whole
listing collapsed onto one line, and the rerun log line re-texted to mention run_attempt.

One limit is worth stating plainly rather than hardening further. The static assertions are keyed
on run_attempt, so they cannot see a neutralization that never names it: branching on
run_entry instead, case "$run_entry" in *:2) continue ;; esac, a bare continue, or a copy
into another variable that is then tested. All four are caught by the behavioural rows, which are
skipped here because jq is absent from the CI Tests image. The class has no closed static form --
the three spellings that do not mention run_attempt are invisible to any predicate keyed on it,
and the region legitimately contains should_rerun assignments and continue statements, so a
whitelist over it would refuse ordinary maintenance (five of this workflow's last fourteen upstream
commits changed the should_rerun count, each new infra heuristic adding one) while still
admitting a run_id=0 clobber that neither names run_attempt nor assigns should_rerun.

The matrix
that preceded
it had 18 mutants: forging the loop variable
run_entry at four different placements, nesting select(false), select(.attempt == 1) and
empty inside the projection, adding an attempt == 1 conjunct inside the select, rewriting
.[] as map(.)[], appending a second top-level select stage, five spellings of a defeated
reject branch, run_attempt=1 after the split, dropping attempt from --json, and reverting
the <= 2 bound to == 1. All 18 redden with jq absent, each attributed to the assertion
written for it by source line. Its 19 controls -- a comment above the guard, an echo above the
splits, the splits reordered, the probe collapsed to one line and re-indented, a blank line in
the body, the fallback on its own line, a comment whose text contains run_attempt=1, an echo
whose string contains =, an extra echo and a comment inside the reject branch, continue 1,
continue ; :, the --jq value re-wrapped, the --json list reordered and extended, a raised
--limit, reordered gh flags and a re-indented --repo -- 18 stay green. The one
exception is the reordered splits, refused deliberately: the data-path whitelist compares in
order, and that ordered compare is what pins run_id being assigned before the probe reads it
(reordering is harmless only because both splits read run_entry, whereas an order-insensitive
compare would admit a genuine use-before-assign, which aborts the step under set -u).

Every one of those 18 was also run against the PREVIOUS round's test file, which is what
separates a real escape from an assertion rewritten for its own sake: eight were green there
and are now caught
(the four run_entry placements, the three projection wraps, and one brace
spelling), and ten were already caught and still are, so the closed predicates lose no
coverage the enumerated ones had. The brace case is narrower than it first appears and is stated
precisely rather than generally: of ten nesting spellings measured, nine were already refused,
and only { if ...; then on the brace's own line with fi; } joined escaped, because the brace
opens no tracked depth while fi; } closes one. The two assertions the stage-equality check
replaces were confirmed subsumed by re-running the four mutations they used to catch -- a dropped
cutoff conjunct, a widened bound, a transposed projection and a projection missing attempt --
all four still red. The digest entry that makes this guard run at all on a workflow-only change
is now pinned too, with the negative control measured: remove it and the new assertion fails and
is_affected_by returns false, while an unrelated workflow returns false either way.

Session id: cron:clickhouse-review-slot-8:20260805-193900

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @Felixoid, could you review this? The hourly auto-retry selects candidate runs with .attempt == 1 as a proxy for "first real run", which is false for a fork PR: the approval gate consumes attempt 1 as a zero-job action_required placeholder, so an infra-killed fork run is never retried. This keys on the property instead, exactly one attempt executed, by widening the filter to .attempt <= 2 and accepting an attempt-2 candidate only when attempt 1 concluded action_required.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4b5a837]

Summary: ✅


AI Review

Summary

This PR rewrites the retry_infra_failures.yml candidate selector so approval-gated fork runs are found by walking createdAt partitions and then filtering on the actual startedAt. The overall direction looks right, but the current head still has one silent false-negative path in the new attempt-1 probe and no in-tree regression coverage for the selector invariants that earlier review rounds depended on.

Findings

⚠️ Majors

  • [.github/workflows/retry_infra_failures.yml:44-96] The new 31-day partition walk now carries the whole correctness contract of the PR, but the current diff no longer ships the focused regression coverage discussed earlier. With only Build profile diff running on this head, a later edit can silently regress the stale-createdAt/fresh-startedAt admission, cross-partition dedup, or oldest-startedAt ordering under MAX_RERUNS.
    Suggested fix: keep a small in-tree workflow test for those boundary cases, or point this workflow at the replacement harness that covers it now.
  • [.github/workflows/retry_infra_failures.yml:115-123] Attempt-2 fork eligibility still depends on a single unreadable-prone gh api call. If /attempts/1 flakes on a candidate's last eligible tick, the code logs a warning and skips the run; by the next hourly tick the same run can already be outside the 6-hour startedAt window, so an actually eligible fork run is lost permanently.
    Suggested fix: retry the attempt-1 probe the same way the partition listing is retried, or fail the tick closed when the probe stays unreadable.
Tests
  • ⚠️ The current head has no automated proof for the exact invariants this PR changes. The smallest useful coverage would admit a gate-delayed fork run with stale createdAt but fresh startedAt, prove adjacent createdAt partitions do not double-spend MAX_RERUNS, and prove candidate order stays oldest startedAt first after dedup.
Final Verdict

⚠️ Needs changes before merge. The selector rewrite is close, but the current head still has a silent false-negative path on the new attempt-1 probe and no committed regression coverage for the boundary conditions it relies on.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 5, 2026
The 6 hour window selected on `createdAt`, which GitHub pins to the
approval-gated attempt 1 while `startedAt` advances to the attempt that
actually executed jobs. A fork PR held in the gate longer than the window
was therefore invisible to the retry, which is the class this workflow
exists to cover.

Measured over 400 failed `pull_request.yml` runs: 87 (22%) are gate-skewed
by more than a minute, p50 1.23h, p90 6.94h, max 22.98h, and 13 exceed the
6 hour cutoff outright. Run 31020274752 is one carrier: `createdAt`
15:26:09Z, `startedAt` 18:56:33Z, attempt 1 concluded `action_required`
with zero jobs on a fork head.

Switching the field alone is not sufficient. `gh run list` orders by
`createdAt` descending, so a gate-delayed run's page position is set by its
old `createdAt` and it sits below a 50-row page: at `--limit 50` the field
swap rescues no additional gated run (5 genuine fork-gate candidates either
way), while at `--limit 200` it rescues one that the shipped predicate
misses, and loses none. At roughly 13 failures per hour, covering a 6 hour
`startedAt` window needs well over 6 hours of `createdAt` lookback; the
deepest index observed to matter was 106. `updatedAt` was rejected as the
field because it also advances on post-completion edits, requiring a deeper
page for no additional candidate.

The rescue is admission-only: 31020274752 is then correctly declined by the
job-level heuristic, since its failures are a real integration test and a
stress test. This restores visibility, not reruns.

The static assertions gain the `startedAt` field requirement and a lower
bound on `--limit`, which the previous comment wrongly described as a mere
tuning knob bounded independently by the cutoff. A new behavioural test
covers the stale-`createdAt`/fresh-`startedAt` case with the inverse skew
and both-inside/both-outside controls, so the window cannot be satisfied by
a predicate that admits everything or merely ORs the two fields.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Related finding on this same step, from triaging a codeload.github.com 429 wave today. I am not pushing it here: half of it needs a policy decision that is yours, not mine.

What happens. When codeload throttles the actions/checkout tarball, jobs die inside GitHub's own Set up job step with ##[error]Failed to download archive ... after 3 attempts. The retry cron classifies them as infra correctly, then declines the run anyway, because the gate requires every failed job to be infra (retry_infra_failures.yml:86) and these runs also carry 1-2 genuine failures. From the cron's own log (run 32047726914):

Checking run https://github.com/ClickHouse/ClickHouse/actions/runs/32033887100 ...
  Not an infrastructure failure, skipping.

That run had 7 such jobs. Four heads in one window lost 7-12 jobs each (runs 32032664263, 32041698289, 32033887100, 32027696933). Over 24h: 8 runs affected, 82 job-minutes of coverage abandoned. Recovery needs a push, since gh run rerun requires admin.

Two separable pieces.

  1. Mechanical. gh run rerun re-runs the whole matrix. Measured on run 32046560241: 177 of 177 jobs re-executed, 0 carried over. --failed would re-run only the failed set and its dependents. On the existing all-infra path that is a strict saving of 174-176 job re-executions per rerun, with no policy change. Happy to send this alone.

  2. Policy, and this is the part I am asking about. Rescuing a mixed run means re-running jobs classified as genuine, because --failed cannot target a subset. Two consequences I could measure:

    • It can launder a flake. On run 32027696933 exactly one attempt-1 failure was actually re-executed, and it flipped red to green. (I had initially recorded that as 9 failures reproducing; that was wrong. The other nine were carried-over records, never re-run.)
    • Cost is real: for those 8 runs, 82 rescued job-minutes against 1231 collateral job-minutes in the failed set alone, before dependents. Worst single job 127 min.

    So it trades coverage recovery against flake risk, and the all-failures-infra invariant looks deliberate: it has been explicit since c4986368 and 17556ef6 only changed classification, never the gate.

If you want the mixed-run rescue, two mechanisms work. Keying it on steps == ["Set up job"] is not sufficient on its own: checkout, setup-python, upload-artifact and download-artifact all resolve in that step, so a genuinely broken action reference produces the same shape. Fail-closed options are (a) match the Failed to download archive line from the job-log API, which is readable and gave exactly 1 hit on each of the 8 casualties, or (b) gh run rerun --job per confirmed job, which isolates properly but costs N calls and N serialized attempts.

My recommendation: take (1) now, and (2) only via mechanism (a) if you consider the flake-laundering risk acceptable. Full measurements available if useful.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
…infra-failures-fork-gate

The only conflict was ci_tests's include_paths list in ci/defs/job_configs.py:
master added ./tests/config/install.sh and ./tests/integration/helpers/cluster.py
for the CFI build-classification guards, this branch adds
./.github/workflows/retry_infra_failures.yml for the fork-gate guard. All three
entries are independent, so both sides are kept. Verified the resolved file
equals origin/master's byte for byte plus this branch's three lines.
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d6f9e6e23 with master 7a32e0fb6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d3d7dc9bb; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.16 MiB 702.14 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 8 s compile time in total, 7 of them have a recent master baseline.

Job report

The scan reads a fixed page of the failure listing, but the listing is ordered by
createdAt while the retry window keys on startedAt. An approval-gated run's page
position is therefore set by a createdAt arbitrarily older than the window it
belongs to, so a row cap cannot bound the scan: how deep the oldest in-window
candidate sits is a function of failure volume, not of the selector.

Replaying 900 failed pull_request.yml runs at 46 hourly clocks, reconstructing
what each clock could see from updatedAt, the deepest in-window candidate was p50
row 116, p90 row 384, max row 430. Ten of the 46 clocks had at least one
in-window candidate below --limit 200, 15 missed candidates in total, four of
them genuine gated fork carriers.

A larger constant does not fix this, and neither does a fixed createdAt bound.
Measured on 8946 unique failed runs sampled by createdAt windows across 30 days
(a single deep page is censored to its own span and so cannot show a longer
skew), startedAt - createdAt is p95 6.4h, p99 45.1h, p99.9 285.8h, max 637.9h
(26.6 days); 77 runs exceed 54h and 34 of those are genuine gated carriers, that
is attempt 1 concluding action_required with zero jobs. Witness 30996214795:
createdAt 2026-08-05T10:08:35Z, startedAt 2026-08-20T12:26:49Z, on a fork head.

The quantity being bounded is an approval wait, whose only structural bound is
the 30 day expiry of a run awaiting approval, which the observed 26.6 day maximum
sits just under. So walk createdAt in 24 hour partitions across 31 days: each
partition is independently bounded, making the candidate set exhaustive rather
than resting on an estimated delay.

Partition edges are timestamps, not bare dates. Both endpoints of a bare-date
range are inclusive whole days, so a bare-date "$from..$to" ignores the partition
width entirely: 2026-08-18..2026-08-19 returns 927 rows against 480 and 447 for
the days individually, which can saturate the per-query ceiling with no width
left to reduce. With timestamps the partitions sum exactly (480 + 447 = 927) and
the walk costs half as many API calls.

A partition that saturates the API's 1000-result ceiling would be truncated
silently, reopening the same blind spot, so the step fails with an annotation;
the busiest single day observed holds ~480 failed runs. The listing is retried
three times per partition because ~140 sequential calls make a transient 502
likely, and one would otherwise abort the tick and skip every later partition; a
partition that never answers fails the step rather than being skipped. Both range
endpoints are inclusive, so boundary runs are deduplicated to stop one run
consuming two of MAX_RERUNS.

Verified against live data at one pinned cutoff, so the arms share a window: the
row cap admits 197 candidates and a 54h fixed bound 336, neither containing
30996214795; the walk admits 346, gaining 149 runs and, compared by run id,
losing none. The saturation guard fires at 1000 rows and not at 999; a transient
listing failure is survived and a persistent one exits non-zero.

The guard test pins the walk rather than a page depth, including the constants
and the timestamp granularity, since a flag-shaped assertion passes while
--limit 1, PAGE_LIMIT=2000, a missing databaseId field or bare-date edges each
leave the fix inert. Nine mutations redden it.
groeneai and others added 2 commits August 21, 2026 23:50
MAX_RERUNS bites the candidate list, so its order decides which candidates are
reached at all. Deduplicating with `sort -u` on an entry led by databaseId also
sorted by it, which is ascending, i.e. effectively oldest-created first. That is
only a 0.90 pairwise proxy for the startedAt order the 6 hour admission window
actually uses (measured over 4711 failed runs), and it is the wrong quantity to
rank by: a candidate is admitted by startedAt, so the one closest to leaving the
window must be reached first, because this tick is its last chance while a fresher
one is still admitted by later ticks.

Leading each entry with startedAt makes the existing dedup sort order by that
deadline instead, then awk drops the key. Replayed over 312 hourly clocks of the
last 13 days, every clock had more candidates than the cap (p50 80, max 160), and
of the candidates on their final tick the orderings lose: 35% keyed on startedAt,
56% on ascending id (the previous behaviour), 100% on descending id.

The attempt-1 probe's skip message is now an annotation, and no longer reports an
unreadable conclusion as an observed retry: a token or endpoint fault that skips
every fork candidate was otherwise invisible on a run reporting success.

The guard test pinned `sort -u` as a literal command shape, which is what let the
ordering defect through, so it now asserts the observed processing order over a
fixture whose startedAt order disagrees with its id order in both directions.
Master removed the `ci/tests` suite and the `CI Tests` job that ran it in
`5b3d66b1a66` ("Remove ci/tests (attempt 2)"), on the grounds that the suite pins
CI-script internals rather than observable behaviour. This branch only extended
that job's digest include paths and added a guard under `ci/tests`, so both sides
of the conflict are obsolete: the `ci_tests` job config is dropped with master and
the branch's `ci/tests` file goes with it.

The fork-gate fix itself (`.github/workflows/retry_infra_failures.yml`) is
unaffected; what is lost is its CI-side unit coverage, which has no runner
upstream any more.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

# The listing is ordered by createdAt, so a gated run sits arbitrarily deeper in it
# than its startedAt window implies: no row cap and no fixed bound exhausts it.
run_entries=""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This 31-day partition walk is now the whole correctness contract of the PR: stale-createdAt/fresh-startedAt admission, cross-partition dedup, and oldest-startedAt ordering under MAX_RERUNS all live here. The current head no longer carries the focused regression test coverage mentioned in the discussion, and the only CI signal on this PR is Build profile diff, so a future edit can collapse back to a fixed-depth createdAt page or change the dedup/order semantics without any automated failure. Please keep a small in-tree workflow test for those boundary cases, or point this workflow at the replacement harness that covers it now.

# concludes attempt 1 as "action_required" with zero jobs, so attempt 2 is
# still its first real run; any other attempt-1 conclusion means a retry.
if [ "$run_attempt" != "1" ]; then
attempt1_conclusion=$(gh api \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Eligible fork runs still hinge on a single gh api .../attempts/1 read here. If that probe 502s on a candidate's last eligible tick, attempt1_conclusion becomes empty, we warn, continue, and on the next hourly run the same workflow can already be outside the 6-hour startedAt window. That reintroduces a silent false negative for exactly the approval-gated runs this PR is trying to rescue. Please retry this probe (or fail the tick closed if it stays unreadable) instead of treating an unreadable answer as "not the approval gate".

@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
Merged via the queue into ClickHouse:master with commit a5b077e Sep 22, 2026
174 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Correcting a measurement I posted on this thread on 2026-08-17, and closing out the mixed-run rerun question I raised in it.

The --failed change I offered there rested on a wrong measurement, and the error was mine. I claimed a whole-run rerun re-executes all 177 jobs. I had compared each job's started_at against the attempt's run_started_at, which marks every job record in an attempt as re-executed even when the job only skipped. Re-measured with conclusion != "skipped", on the same run I cited and on the three reruns this workflow triggered in the last 8 hours:

run jobs in attempt actually executed skipped
32046560241 attempt 2 (the run I cited) 177 3 174
35925067114 attempt 2 173 4 169
35946333277 attempt 2 173 4 169
35934295535 attempt 3 173 4 169

The cache_success_base64 term in each generated job's if: already skips every job that succeeded on an earlier attempt, so a whole-run rerun costs 3 to 4 job executions, not 177. gh run rerun --failed would therefore save close to nothing, and it would additionally have to keep needs.config_workflow.outputs.data populated for the re-run jobs, which I have not verified. So I am not proposing it.

The all-failures-infra gate is not costing coverage at the current failure mix. In the 8 hours to 2026-09-24 04:54Z this workflow logged 93 run checks and skipped 88 as not-infra. Across the 29 distinct runs it skipped, the gate discarded 7 infra-classified jobs: 5 Finish Workflow and 2 Style check. All 53 failed jobs in that window ran the full Set up job | Checkout code | Prepare env script | Run | Post Checkout code | Complete job sequence, so none of them died before checkout and no test coverage was lost. A per-job rerun would have rescued nothing here. The same structural predicate applied to the four heads I measured on 2026-08-17 finds 34 of 43 failed jobs dying before checkout, so the predicate does detect the class when it is present. On that evidence the codeload throttling has abated and I am not pursuing the per-job rerun further.

One thing worth knowing while you are in this file: Style check fails the "Run step under 120 s means infrastructure" test. Its Run step takes 73 to 97 s, so a genuine style violation is classified as an infrastructure failure. That is why 3 of the 5 reruns triggered in that window were runs whose only failure was a real one, and all 3 re-failed on the retry.

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

Labels

can be tested Allows running workflows for external contributors comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding manual approve Manual approve required to run CI pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants