Skip to content

Bound each docker image build and retry transient mirror and registry failures - #118217

Closed
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:bound-praktika-docker-image-builds
Closed

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:bound-praktika-docker-image-builds

Conversation

@groeneai

@groeneai groeneai commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117996

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

On 2026-09-04 both Dockers Build legs of #117996 failed in the same apt layer of
ci/docker/fuzzer/Dockerfile while us-east-1.ec2*.ubuntu.com was degraded, dropping
20 downstream nodes.
Report.

Docker.build ran docker buildx build unbounded, with
Error response from daemon: manifest unknown as its whole retry surface. The amd leg sat silent
for 5 h 28 m until the 19800 s job timeout killed it (a bare Timeout); the arm leg's
E: Failed to fetch ... 503 matched nothing. _build_dockers fail-fasts, so one stalled image
costs the whole leg.

Each invocation now gets two bounds from one absolute deadline; Docker.build owns the ladder:

  • a 2700 s output-silence bound detects a wedge (worst healthy silence measured: 314 s);
  • a total bound equal to the remaining budget, recomputed per attempt, so the ladder always
    ends inside the job timeout; a total expiry is terminal.

The classifier fails closed: both apt classes are read from the step the build stopped on, its
fenced E: error plus, for a partial index, that step's own Some index files failed to download,
so a fetch failure an earlier step recovered from cannot make a permanent failure retryable. The
buildx helpers were moved out of ci/jobs/docker_server.py, not copied, so the two jobs cannot
drift.

Also fixed during review: the docker manifest inspect existence probe is bounded; and this path
now retries the partial-index class too, as the release-image path already did: 2 of 98
Dockers Build (*) failures over 90 d, both arm64 images left with an incomplete index, neither
retried.

No image digest changes, so this PR's own legs do not exercise it; validation was local, both
directions, mutant per assertion.

Not fixed here: --error-on=any under ci/docker/ would have prevented neither leg; a mirror
fallback cannot reach ci/docker/fuzzer (no apt_archive ARG); Docker.merge_manifest stays
unbounded (9 s peak).

Measurements
Dockers Build (amd) Dockers Build (arm)
duration 19801.4 s (job timeout 19800 s) 483.8 s
verdict ERROR, errors: [{message: Timeout}] FAIL, empty info
what happened apt-get update produced no output for 5 h 28 m 42 s, then the runner SIGTERMed. Node labels: under-utilized RAM and CPU apt-get install drew 503 on pool files after apt's own retries, exit code: 100

Max output silence, over every leg log I could still fetch:

leg max output silence
worst healthy of 4 legs (SBOM generation, binary-builder) 314 s
integration/runner built locally, apt phase, degraded mirror 61.6 s
the silent 400 MB spark curl -fsSL in integration/runner 54 s
#117996 amd, the pathology 19722 s

A fixed small total bound cannot do this job. The slowest healthy single image needs 6646 s, so one
retry of it already overruns a 19800 s leg:

SELECT test_name, test_status, round(test_duration_ms/1000) AS s FROM default.checks
WHERE check_name IN ('Dockers Build (amd)','Dockers Build (arm)') AND test_name LIKE 'build:%'
  AND check_start_time > now() - INTERVAL 60 DAY
ORDER BY test_duration_ms DESC LIMIT 4
build: clickhouse/integration-tests-runner:b7484ad5f893cebd6c4b_amd   OK   6646
build: clickhouse/binary-builder:8d5d8c3b98ed66660e01_amd             OK   4638
build: clickhouse/integration-tests-runner:1ceaaaf7366e674e8dff_arm   OK   4459
build: clickhouse/integration-tests-runner:1ceaaaf7366e674e8dff_amd   OK   3880

Honest limit: the two shapes above are recovered. A mirror that talks slowly for longer than the
leg's whole remaining budget is only diagnosed, not recovered, and the matrix is still dropped.
Nothing can recover inside 5.5 h from a mirror that is unusable for 5.5 h, and widening the job
timeout would only make the failure slower.


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

groeneai and others added 9 commits September 4, 2026 15:59
… failures

`Docker.build` ran one `docker buildx build` per image with no time bound of any
kind: `Result.from_commands_run` never passed `timeout=` down, so `Shell.run`'s
watchdog was never started. Its whole retry surface was the single string
`Error response from daemon: manifest unknown`. A broken apt mirror produces
neither of those, in either of its two shapes, so a wedged build was bounded only
by the 19800 s job timeout and `_build_dockers` then fail-fast dropped every
remaining image and every downstream job.

On 2026-09-04 that cost 20 downstream nodes on one pull request while
`us-east-1.ec2*.ubuntu.com` was degraded. One leg produced no output for 5 h
28 m 42 s and reported a bare `Timeout` with the mirror error nowhere in the
verdict; the other drew `503` on pool files, reported
`E: Unable to fetch some archives`, and was not retried. The leg log records both
halves: `Retry 1/2: command failed` followed by
`No retryable errors found, stopping retries`.

Each invocation now carries two bounds derived from one absolute deadline, and
`Docker.build` owns the only retry ladder.

The output-silence bound is what detects a wedge, and it is sized at 2700 s: 8.6x
the longest silence a healthy leg produced in 60 days (314 s, generating the SBOM
attestation on `binary-builder`) and 7.3x below the 19722 s of silence that
consumed the leg above. Sizing a total bound to tell those two apart is not
possible, because the slowest healthy single image needs 6646 s, so one retry of
it already overruns the leg. Silence does not scale with how long a healthy build
takes; the locally measured extremes agree, at 61.6 s for the longest image's apt
phase against a degraded mirror and 54 s for its silent 400 MB `curl -fsSL`.

The total bound is always the leg's remaining budget, recomputed from the clock
before every attempt, so no attempt can outlive the runner's own kill and the
ladder always ends inside the job timeout. When what is left cannot fit an
attempt, a shaped result naming the exhausted budget is returned rather than a
doomed attempt. A total expiry is terminal by construction and never reaches the
classifier: since the bound equals the remaining budget, its expiry means the
budget is gone.

The classifier fails closed and reads the untruncated attempt log rather than
`Result.info`, whose truncation window can centre on an early compiler warning
and discard the terminal error entirely. The apt class is matched only inside the
terminal failing step's fenced block and only at `E:` severity, so a
`W: Failed to fetch` that an earlier successful step recovered from cannot make a
later permanent failure look retryable. Registry and push errors are anchored on
the terminal buildx error instead, because they happen while resolving base and
SBOM-scanner images or while uploading layers, outside every Dockerfile step, so
requiring a fence would make that class unretryable.

`Shell.run` grows one unified watchdog evaluating both deadlines rather than one
thread per bound. Two threads cannot be made safe: `_terminate` spends up to
100 s between SIGTERM and SIGKILL, and a second watchdog firing inside that
window overwrites the cause of a kill that already happened, turning a retryable
idle expiry into a terminal budget failure. Both bounds are anchored on the
process rather than on the watchdog thread, so an equal pair resolves by rule
instead of by scheduling latency. The cause is recorded before termination
begins, and the watchdog is joined before the cause is read.

The buildx failure classifier and its two string lists are moved out of
`ci/jobs/docker_server.py` into praktika rather than copied, so the two docker
build jobs cannot drift; that code was hardened twice in two weeks. The shared
retry strings become an immutable tuple, so the in-place `+=` that used to extend
them now rebinds a local list instead of mutating an object the other job reads.
`docker_server.py` keeps its own separately-sized bound, its mirror-fallback
policy and every call site unchanged.

Two remedies were considered and declined because measurement says neither would
have prevented either leg. Adding `--error-on=any` to the 41 `apt-get update`
sites under `ci/docker/` only changes the exit status of an update that
completed, and one of the two failures never completed one while the other failed
during `apt-get install`; it is also blocked by an `ubuntu:20.04` image whose apt
predates the option, by a deliberate insecure-repository fallback the flag would
defeat, and by six third-party repositories added at build time. Giving this job
the release images' mirror fallback cannot reach the image that actually failed,
which declares no `apt_archive` build argument and inherits an in-region mirror
baked into its cached parent, and build arguments are not part of the image
digest, so such a rebuild would push the same tags.

This changes no image digest, so it triggers no image rebuild, which also means
this job's own legs are cache hits and do not exercise the new code. Validation
was local and in both directions, with a mutation arm for every assertion.
…horitative

Eight review findings on the previous commit, none of them a redesign.

`Docker.build` stamps the ladder's absolute deadline before the
`docker manifest inspect` metadata probe instead of after it, so the probe is
charged against the leg's budget like every other step, and `_build_with_retries`
takes that deadline rather than `job_timeout`/`elapsed` so there is one source of
truth for the bound.

The docker build job dumps the shaped result BEFORE `_clean_buildx_volumes`, and
bounds each of the three cleanup commands at 120 s. Cleanup runs inside the 600 s
reserve the ladder holds back for recording a result, and the likeliest reason for
it to hang is the wedged buildkit this change exists to handle. Unbounded and
running first, it could still leave the leg reporting a bare `Timeout` with the
shaped result computed and then lost.

`Shell.run` treats a bound that fired as authoritative: a command that traps
SIGTERM and exits 0 has not finished, whatever it reported, so the normalised
status is returned everywhere the tail previously read `proc.returncode`. Blast
radius, enumerated with an AST walk rather than by inspection: 13 call sites pass
`timeout=` or `idle_timeout=` into `Shell.run`, `Shell.check` or
`Result.from_commands_run`, and 9 of those are pre-existing, in
`changelog_nightly.py`, `fast_test.py` twice, `functional_tests.py`,
`revert_ci_regressions.py`, `result.py` twice and `utils.py` twice, the last three
being internal forwarding rather than independent callers. None of their commands
installs a SIGTERM trap, and the representative shapes (pipeline, plain, nested
bash, xargs) already return non-zero once a bound fires, so nothing in tree
changes today and the only available direction of change is from a false success
to a correct failure.

`Shell._terminate`'s grace waits on the process GROUP instead of on the leader. A
descendant that survives SIGTERM keeps the inherited pipes open, and that is what
blocks the caller's reader threads, so escalating on the leader's liveness meant
the new bound did not bound: a call whose 45 s descendant ignored SIGTERM returned
only when that descendant exited, and now returns after the grace plus one poll
interval with the descendant reaped. That `os.killpg(pgid, 0)` succeeds for a
group whose leader has been reaped but which still has members was asserted before
this was written, with the whole-group-dead case as the negative control. The
escalation window is still 100 s at 5 s intervals and the printed lines are
unchanged, but the sequence is no longer byte-identical to the pre-move original,
which the previous commit's notes had claimed.

The registry class no longer carries the three apt signatures. It is read from
buildx's terminal error, which embeds the failing `RUN` recipe verbatim, so a
recipe naming a mirror error would match on its own text; the apt class already
avoids this by matching only inside the failing step's fenced block at `E:`
severity. `BUILDX_TRANSIENT_ERRORS` keeps its content and order, because
`docker_server.py` consumes it as the first 15 entries of its own list. In-tree
reachability is nil today: all 61 `Dockerfile` and docker shell files were
scanned, and the only hits are `500 Internal Server Error` and
`503 Service Unavailable` inside a comment in seven files under `docker/`, none of
which is an image path, so this ships as hardening and not as a live bug fix.

The budget-exhausted `Result` carries the last attempt's log file and its own
timing. `from_commands_run` attaches a log exactly when it had to truncate `info`,
which is when `info` is least trustworthy, and the exhausted path was shipping
that same `info` as its only evidence, so the path meant to replace a bare
`Timeout` carried strictly less diagnostic material than an ordinary failure of
the same build. A successful attempt still attaches nothing, so a passing leg
uploads no extra logs.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit's message and the `_IMAGE_BUILD_IDLE_CAP_S` comment both said
2700 s is "8.6x the longest silence a healthy leg produced in 60 days". That
overstates the evidence, so both are corrected here.

No 60-day silence census exists, and none could be built from CIDB, which records
per-test durations but has no per-step output-silence column. The real basis is the
maximum gap between consecutive timestamped `job.log` lines across the four healthy
leg logs still retrievable from S3, and 314 s is the worst of those four. Over the
same 60 days the two docker build checks ran 585 legs between them, so the retired
phrasing generalised a four-leg measurement to 585.

The 60-day window belongs to the build-DURATION query, which is a different
measurement and remains correct: it is what shows the slowest healthy single image
needs 6646 s, and therefore that no fixed total bound can separate a wedge from a
slow healthy build. The multipliers are unchanged: 2700 s is still 8.6x 314 s, and
still 7.3x below the 19722 s of silence that consumed the amd leg on 2026-09-04.

Co-Authored-By: Claude Opus 5 <[email protected]>
The corrected comment came out at five lines, one over the four this file's review
budget allows for a single block. Same content, same figures, four lines.

Co-Authored-By: Claude Opus 5 <[email protected]>
…hole

Three changes that compose. Each on its own is small; the second is what makes the
third necessary.

An expired deadline is no longer committed once the caller is done with the process.
The watchdog computed which bound had passed before it consulted `finished`, so a
command that completed microseconds past its deadline was reported as a failure with a
kill sentinel appended to its log. In the image-build ladder that surfaced as a shaped
budget-exhausted result for an image that had in fact been built and pushed. The
ordering that produced it is: the wait returns at the deadline, the command completes
and `Shell.run` sets `finished`, the loop re-checks and finds the deadline passed.

`Shell.run` now joins the watchdog for `SHELL_TERMINATE_MAX_S` rather than 30s. The
grace `_terminate` grants waits on the process group, so it can legitimately occupy the
full 100s; a descendant that survives SIGTERM without holding the inherited pipes lets
the readers unblock at the leader's exit, and the call then returned at ~30s with the
group still alive. The next attempt started 15s later alongside a straggler from the
previous one, and an interpreter exit before the daemon watchdog's SIGKILL leaked the
descendant. The old comment justified the 30s bound with the pre-group-wait poll loop,
which is exactly the case the group wait exists to handle.

A bounded call's worst case is therefore its own bound plus `SHELL_TERMINATE_MAX_S`,
and the cleanup budget is re-derived from that. Three serial commands at 120s each
would cost 3 x (120 + 120) = 720s against a 600s reserve, so per-command bounds cannot
bound the phase at all. Cleanup is now one 240s budget sliced across the three
commands from a live stopwatch, which charges each earlier command's timeout and its
termination; a command with nothing left prints a skip line instead of taking a fresh
bound. Worst case is 240s plus one grace, 360s, which leaves the reserve enough for the
ladder's own last kill and the result upload, so the reserve itself is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
The ladder is capped at six attempts and printed "retrying in 15s" after any transient
failure whose deadlines were still open, including the sixth. Exhausting the backstop
therefore always logged a retry that never happened and slept 15s before returning. The
returned result is still the last attempt's own, so the tail that names the last
transient signature is unchanged.

Also moves the two lines about the retry class being a tuple onto the object they
describe. A rename left them above `_BUILDX_REGISTRY_TRANSIENT_ERRORS`, which is
praktika-private, while the shared object is `BUILDX_TRANSIENT_ERRORS`.

Co-Authored-By: Claude Opus 5 <[email protected]>
… kill

Two independent ways the watchdog could still get its own contract wrong.

First, `_check_timeout` consulted `finished` before committing an expiry, but
the consult and the commit were not atomic, and `Shell.run` converts any
recorded expiry into a non-zero return even when the child exited 0. A command
that completed between the sample and the commit was therefore reported as a
timeout. Only the total bound can reach the window, because arriving output
keeps pushing the idle deadline out while the readers drain, and it is
microseconds wide. Both sides now take one lock around the decision: the
watchdog holds it from the `finished` sample through the assignment, and the
caller sets `finished` under it, so whichever gets there first decides and the
loser changes nothing. A committed expiry keeps its old meaning: the bound
stays authoritative and a later exit 0 is still a failure. `_terminate` is
deliberately called after the lock is released, since it sleeps out the grace
and holding the lock across it would stall the caller for that whole window.

Second, `_terminate` guarded only `ProcessLookupError` around its three
`os.killpg` calls. `killpg` also raises `PermissionError` when permission is
denied for every member of the group, which is reachable once the leader is
gone and a foreign-uid member remains, i.e. exactly the shape the group
liveness probe exists to detect. That probe is new here, and the loop it
replaced tested `process.poll()`, which cannot raise EPERM, so this change
increased the reachability of an unguarded exception on the path its own
contract depends on: the exception left the daemon watchdog thread, the SIGKILL
escalation never ran, and the reader threads stayed blocked for the
descendant's natural lifetime. All three calls now treat EPERM as "the group is
alive", which is the fail-safe answer, because a signal the kernel rejects
costs nothing while calling a live group dead stops enforcing the bound.

Not reachable from `docker buildx build`, whose buildkit is the docker daemon's
child rather than ours, so both ship as hardening. The EPERM half is worth its
round for a second reason: PR ClickHouse#112972 rewrites this same function with the same
fail-safe and a written rationale, so whichever of the two lands second has to
resolve here, and a version without the guard would silently drop it.

Measured both directions in `r3_arms.py`, with the previous head's module
loaded from git as the mutant rather than an imitation of it. Arbitration: a
caller that completes while the watchdog is at its decision records no expiry
and kills nothing in 20 of 20 runs, where the pre-fix module commits `total`
and kills in 20 of 20; in the symmetric case the caller cannot interleave with
the commit in 5 of 5, where the pre-fix module lets it complete between the
sample and the commit and commits an expiry anyway in 5 of 5. EPERM: injected
at each of the three calls, the fixed code still reaches SIGKILL and its thread
returns normally, while the pre-fix code lets `PermissionError` escape the
thread; the `ProcessLookupError` paths and the 20-poll grace are unchanged in
both.
The backstop break sat after the two tests that govern a next attempt, so a
sixth transient failure with 599s of budget left returned "Out of job budget
after 6 attempt(s): 599s left, an attempt needs 600s", and an expired retry
deadline was announced the same way. Both are true statements about a next
attempt the cap had already ruled out, so they name a cause that was never
operative. Moving the break ahead of those two tests reports the cap instead,
and the break path already prefixes the last attempt's own log with "Failed
after N attempts, last transient signature [...]".

Diagnosability only: both shapes are a shaped FAIL carrying the same log. It is
worth the two-line move because diagnosability is this change's whole thesis,
and a reader who is told the budget ran out will go looking for a budget that
did not.

Measured in `r3_arms.py` group `item3`, with the previous head's `docker.py`
loaded from git as the mutant. Tuned from the constants so a constant change
cannot silently un-tune the arm: six 10s attempts leave exactly one second less
than an attempt needs, and the fixed ladder returns the cap result with no
budget claim while the mutant returns "599s left". With the retry deadline first
reached only at the last attempt, the fixed ladder prints no deadline line and
the mutant does. Unchanged and re-measured in both: first-attempt success, a
permanent failure stopping on attempt 1, mid-ladder budget exhaustion three
attempts in, and the retry deadline still cutting the loop before the cap when
it genuinely fires mid-ladder.
Both budget sites in `native_jobs.py` derived their spent term from
`Utils.Stopwatch`, which is `datetime.now().timestamp()`, while every bound that
enforces those budgets is monotonic: `Docker.build` stamps
`time.monotonic() + max(0, job_timeout - elapsed - _IMAGE_BUILD_JOB_RESERVE_S)`
and reads it back as `job_deadline - time.monotonic()`, and the cleanup bound is
handed to `Shell.check`, which anchors on `state["started"] = time.monotonic()`.
So a wall-clock step of D seconds taken while the docker phase runs moved the
subtracted term without moving the enforcing clock: backward by D granted the
remaining images and the cleanup phase D extra seconds, forward by D rejected
viable attempts D seconds early.

The clock this budget exists to stay inside is monotonic on both ends, so a
wall-clock term in the middle has nothing to cancel it: the outer job timeout is
enforced by `TeePopen._check_timeout`, which is
`self.finished.wait(self.timeout)`
on a `threading.Event`, monotonic under CPython. `_IMAGE_BUILD_JOB_RESERVE_S`
bounds the damage but does not make the derivation correct.

Enforcement now reads `time.monotonic()` at both sites. `Utils.Stopwatch` stays
for reporting, including `Docker.build`'s own stopwatch, which feeds
`Result.start_time` and `Result.duration`: CIDB stores those as epoch
timestamps, so making that one monotonic would corrupt every reported start
time. The two `sw` locals are removed rather than left unread, which `F841`
would otherwise flag.

Measured in `r4_arms.py`, with the previous head's `native_jobs.py` loaded from
git as the mutant, under two injections per site so neither arm can pass
vacuously. Stepping the wall clock back 1200s: the fixed cleanup hands out
bounds of 239s while the mutant hands out 1440s against a 240s budget, and the
fixed `elapsed` stays at 0.002s per image while the mutant passes -1200.0s.
Leaving the wall clock alone and jumping the monotonic clock instead: the fixed
cleanup bounds one command and skips two, where the mutant bounds all three, and
the fixed `elapsed` tracks the jump at 500/1000/1500s where the mutant reports
zero. A fix that read a constant would pass the first injection and fail the
second. Over-application guarded on both `Docker.build` return paths, whose
`start_time` stays epoch-scale at 1.79e9 rather than this host's 3.15e6 of
uptime, and by asserting `elapsed` is a delta and not an uptime. The 66-value
`elapsed` property arm, the cleanup skip path, and the round 1 to 3 arms are
unchanged: 179 arms across nine harnesses.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

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

An independent-model gate (engine: codex) plus my own cold review, per round, on the exact tree.

round head findings AGREE (fixed) DISAGREE (terminal)
1 07d7f68 17 9 major, 5 nit 3 nit
2 992748e 7 3 major, 3 nit 1 major
3 43571ae 6 3 major, 3 nit 0
4 43b8147 3 1 major, 1 nit 0
5 dcd7cd8 3 0 0

Round 4's major: the spent-budget term was read from a wall clock (datetime.now) while every bound
that enforces it, including the outer job timeout, is monotonic - so a clock correction mid-job could
move the budget without moving the deadline. Now measured with time.monotonic(); Utils.Stopwatch
stays for reporting, where Result.start_time must remain an epoch timestamp.

At round 5 the gate returned zero findings; the three listed below are my own, all nits, none
blocking. Its diffstat and delta-diffstat both matched the intended change set, so the re-review was
not run off a wrong base.

Declined with evidence, or noted and not changed:

Sev Finding Why
⚠️ "Both shapes recovered" needs real-buildx proof that a killed solve is not reused It exists, locally: against a slow-loris server, attempt 1 is killed by the idle bound and attempt 2 is a fresh solve whose own output proves the RUN re-executed, with a mutant where the loris stays slow and attempt 2 is killed too
💡 ci/jobs/docker_server.py derives its own per-invocation bound from Utils.Stopwatch as well The same clock-domain mismatch, but outside this PR's contract, absent from its changed lines, and clamped at the site to [BUILDX_TIMEOUT_FLOOR, BUILDX_TIMEOUT], so it carries none of the unclamped exposure that made the round-4 finding a major. Noted, not raised
💡 The ladder's closing line can quote a transient signature from an earlier attempt It says "last transient signature", which is what it prints, and the terminal attempt's own output follows it in info
💡 Attempts for one image share a log path, so only the final attempt's log is attached Each attempt is classified from its own untruncated log while that log is current, and earlier attempts in this ladder are transient by construction
💡 The sentinel-skip branch in _terminal_error_tail looks unreachable It defends that function's own contract, since the kill sentinels also start with ERROR:
💡 Refusing an attempt with under 600 s left is a new failure mode The worst legitimate leg total is 16083 s against 19800 s; the alternative is an attempt the runner kills mid-way
💡 A bare-string retry_errors would iterate characters Real but unreachable: all six call sites pass a list or an empty string, and this diff does not touch them

One gate finding was true about behaviour but pre-existing in code, so the claim was corrected rather
than the code: ci/jobs/docker_server.py retries the server image on an apt signature found anywhere
in stderr. That list is element-wise and order-identical to master's, and the two decisions there are
deliberately different - the unrestricted list governs the cheap retry against the same mirror, the
fenced E:-severity classifier governs the expensive switch to the next one. The description is
scoped to the new ladder instead.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, both shapes, on demand. Trickle: a child that writes nothing runs unbounded today and is killed at the idle bound after the change. Refuse: a real docker buildx build whose apt pool files are answered 503 by a local server while indexes stay valid, so apt-get install fails fetching a .deb exactly as on 2026-09-04. Neither is probabilistic.
b Root cause explained? Docker.build ran one docker buildx build per image with no time bound (from_commands_run never passed timeout= to Shell.run, so its watchdog never started) and with Error response from daemon: manifest unknown as its whole retry surface. A trickling mirror emits no message and a refusing one emits E: Failed to fetch ... 503, so neither is retried, and _build_dockers fail-fasts. The failing leg's own log says so: Retry 1/2: command failed then No retryable errors found, stopping retries.
c Fix matches root cause? The defect is an unbounded invocation plus a one-string retry surface, and the change adds the two bounds and the ladder at exactly that layer. No Dockerfile is touched, no bound is loosened, no assertion is widened. The two Dockerfile-level remedies the task proposed are declined with measurements: neither would have prevented either leg.
d Test intent preserved / new tests added? No test is weakened. No test file is added, and the reason is measured: ci/tests/ was a ~60-module suite including test_docker_buildx_timeout.py, deleted in #115650, with a later re-added file deleted again. Validation is local and in both directions.
e Both directions demonstrated? Yes, and every assertion has a mutant that reddens it: two watchdog threads (near-equal pair reports total 20/20 instead of idle), flat-substring classifier (both stale-signature negatives flip to transient), clamp computed once at entry (worst case 23215 s > 19800 s), inner retry_errors restored (2 buildx invocations per attempt, not 1), set_timing dropped (duration collapses to 0.00 s), idle_timeout=None (the silent child runs to completion), spent budget read on the wall clock (a 1200 s backward step inflates the cleanup bounds to 1440 s against a 240 s budget, and makes a monotonic jump invisible).
f Fix is general across code paths? One code path serves both legs (amd/arm differ only in runs_on; arch is chosen at runtime) and all 36 images, including the alpine/apk and centos/yum ones no Dockerfile-level fix reaches uniformly. The manifest-merge job calls Docker.merge_manifest, not Docker.build, and is seconds long, so it is out of scope by construction (CIDB 60 d, test_name LIKE 'merge:%': 6677 rows, p50 0.73 s, p99 2.81 s, max 9.00 s). The sibling docker/ job keeps its own bound and ladder, byte-identical: 50 observables compared against the pre-move module loaded from git, in both import orders, with a one-character sensitivity control. Docker.pull_image already had both and is unchanged.
g Fix generalizes across inputs? Bounds: elapsed over 66 values in range(0, 19800, 300) with the invariant that no computed bound ever exceeds the remaining budget; the four cause-matrix pairs including idle == total; timeout only, idle_timeout only, both, neither, and job_timeout=0. Degenerate ends (budget <= 0, budget < 600) start no child and return a shaped result. Classifier: 8 crafted shapes, 7 real captured logs, 2 real builds.
h Backward compatible? No user-visible behaviour, no setting, no serialization, so no SettingsChangesHistory.cpp entry applies. Every new parameter defaults to None/0, meaning unbounded, so a caller that passes no bound is untouched. Three measured deltas, all confined to a call whose bound has already fired: (1) it returns up to one _terminate poll interval later, because the watchdog is joined before its cause is read; (2) a command that traps SIGTERM and exits 0 is now reported as the failure it is instead of a success; (3) the grace waits on the process group and the caller now waits for that grace, so a call whose descendant outlives SIGTERM returns after the 100 s escalation with the group gone, rather than either blocking until that descendant exits or returning while it is still running. That holds whether or not the descendant is holding the inherited pipes; both shapes are measured. Enumerated structurally: 11 call sites pass a bound at this head and 8 already did before this PR (the new three are the ladder, the cleanup loop, and from_commands_run's forwarding call); none of their commands installs a SIGTERM trap, since every trap in ci/ is an ERR trap, so (2) changes nothing in tree today and can only turn a false success into a correct failure.
i Invariants and contracts preserved? (1) No docker buildx build may outlive the leg's remaining budget: every bound derives from one absolute monotonic deadline, and the spent-budget term subtracted from it is read on that same clock, so a wall-clock step cannot move one without the other; property-checked over 66 values of elapsed. (2) One Result per one buildx invocation (retries=1), counted by the child itself. (3) Result.name stays build: <image>:<tag>, because it is the CIDB row key. (4) A command is finished or timed out, never both: the caller's completion and the watchdog's expiry are committed under one lock, so the first of the two decides and the loser changes nothing; the commit still precedes termination, which is what makes the cause readable. (5) log_fp has a single writer when the sentinel is appended, because the reader threads have joined. (6) Every return path carries ladder timing, including the SKIPPED "image exists" branch, which never enters the loop.

Session id: cron:clickhouse-impl-slot-7:20260904-130900

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [05bac4f]

Summary: ✅


AI Review

Summary

This PR moves the buildx failure classifier into ci/praktika/docker.py, adds total and idle watchdogs to Shell.run, and uses them to keep Docker.build retries inside the docker-leg budget instead of letting a wedged build consume the whole 19800 s job timeout. The new Docker.build path looks substantially better, but one retry-classification gap still remains in the sibling server/keeper image path, so the change is not ready to merge yet.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118217#discussion_r3939932062] [ci/jobs/docker_server.py:474] build_and_push_image still decides should_try_next_mirror from build_result.info instead of the attached full log. Result.from_commands_run keeps only a 300-line tail once a shell log is long, but terminal_build_failure needs the opening ------ fence from the terminal step. On the current helpers, a synthetic buildx log with a 350-line terminal step reproduces the false negative directly: is_apt_mirror_failure(full) == True, while the exact 300-line tail that Result.from_commands_run would keep evaluates as is_apt_mirror_failure(tail) == False. That means the retryable apt-mirror failure is still treated as permanent as soon as the final fenced step is longer than the info window.
    Suggested fix: when build_result.files is present, reopen build_result.files[0] and pass that untruncated text to should_try_next_mirror and terminal_build_failure, exactly as Docker.build now does.
Final Verdict

Needs changes: the new bounded retry ladder in Docker.build is a real improvement, but the server/keeper image path can still drop the next-mirror fallback on long terminal logs because it classifies from truncated info.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? Docker.build ran docker buildx build with no time bound and Error response from daemon: manifest unknown as its only retry signature, so on 2026-09-04 an apt-mirror stall silently consumed a whole Dockers Build (amd) leg and dropped 20 downstream jobs. This gives each invocation an output-silence bound plus a total bound derived from the leg's remaining budget, and a retry ladder whose classifier fails closed by reading only the terminal failing step at E: severity.

Comment thread ci/praktika/docker.py Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 5, 2026
`Docker.build` stamps its per-image deadline before the metadata probe, so the
probe was charged against the leg's budget but never bounded by it:
`Shell.get_res_stdout_stderr` passes no `timeout` to `subprocess.run`, and the
docker CLI bounds only part of the request on its own.

Measured on docker 29.5.1 against a registry that answers `/v2/` and then never
answers the manifest fetch: the CLI is still blocked after 120s, and it does not
take SIGTERM while blocked on that read, so the guard has to escalate to SIGKILL
(the run exits 137). The connect and TLS-handshake stalls, by contrast, the CLI
does bound itself, at 30s and 20s. A registry that is reachable but degraded is
therefore an unbounded wait in the one code path whose purpose is that no wait
is unbounded, and it ends in the 19800s runner timeout that drops the whole
downstream matrix.

The probe is otherwise fast, so the cap can be generous: over 60 days of
`Dockers Build (*)`, the 18802 `SKIPPED` "image exists" results answered in
0.60s at p50 and 0.98s at p99, and never took longer than 7.70s. The 120s cap is
15.6x that worst case, and is clamped to whatever is left of the budget so the
probe cannot outlive the ladder it precedes. The worst case is the cap plus the
10s kill grace, which `_IMAGE_BUILD_JOB_RESERVE_S` is already documented to
cover. The bound is floored at 1 because `timeout 0` runs unbounded.

A timed-out probe exits non-zero, which is the existing "build the image"
branch, so the failure direction is a rebuild and never a wrongly skipped build.

Raised in review on this PR. Both directions are covered in
`r5_inspect_arms.py` with the published head's `docker.py` loaded from git as
the mutant: against the stalling registry the bounded probe returns after 34s
(24s bound plus the kill grace) while the mutant never returns inside a 60s
window, and both legs assert they actually reached the manifest fetch, because
an untrusted certificate makes the CLI fail in 0.1s and would let the arm pass
without ever exercising the stall.
Comment thread ci/jobs/docker_server.py
from ci.praktika.docker import (
BUILDX_TRANSIENT_ERRORS,
is_apt_mirror_failure,
terminal_build_failure,

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.

Docker.build now works around Result.from_commands_run truncating info by reopening result.files[0] before it calls terminal_build_failure / is_apt_mirror_failure, but this sibling path still feeds both helpers from build_result.info only.

That means the next-mirror fallback can still disappear on long server-image logs: Result.from_commands_run pivots info to a window around the first : warning: / : error: and moves the full log to build_result.files. With that shape, both helpers return false on build_result.info even though the attached log still contains the final fenced apt mirror failure, so should_try_next_mirror stops retrying a transient mirror error. Please classify from build_result.files[0] when it is present, the same way Docker.build now does.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Checked at the live head: docker_server.py:469 does classify from build_result.info. I am not making the change, because the pivot never fires on that path and the remedy would not have changed a single real outcome there.

cidb.py:297 stores test_context_raw = result.info, so CIDB holds the exact string that call site reads. 90 days of per-image FAIL/ERROR rows for Docker server image and Docker keeper image, n=206:

  • rows containing : warning: or : error:, which is what moves the window: 0. These images assemble prebuilt .deb/.tgz, so no file:line:col: diagnostic is emitted in them.
  • pivoted 0, tail dropped 0, truncated at all 2. Both truncated rows are real 503 stalls with ~18k lines dropped, and both took the last-300-lines branch, so the fenced terminal step survived (1824 and 1995 chars). info is the log's tail, so the last solve error and the two fence lines before it are the same in the attached file: re-opening files[0] returns the identical block and the identical verdict.

The pivot is real where Docker.build guards it. Same window and query for Dockers Build (*): 64 failing rows, 14 pivoted, 8 with the tail dropped, all toolchain images such as clickhouse/cctools. The precondition is a property of what the image builds, not of the call site.

The fallback does still go blind there, for a different reason. On master today, afb5ae2d / clickhouse-server:head-distroless-arm64 at 04:21:01Z: the mirror returned 503 for all three InRelease files, apt logged every fetch failure at W: severity, and the only E: line was E: Unable to correct problems, you have held broken packages. is_apt_mirror_failure reads its signatures at E: severity only, so the verdict was False with 1824 chars of fence in hand. That shape is 86 of the 206 rows, and #118023 fixes it at the root with apt-get update --error-on=any.

Comment thread ci/praktika/docker.py Resolved
`Docker.build`'s classifier only asked `is_apt_mirror_failure`, which decides at
`E:` severity inside the failing step's fence. A mirror that withholds an index
never gets that far: apt reports every failed `InRelease` fetch at `W:`, warns
`Some index files failed to download`, carries on with the suites it did get and
then fails resolving packages against the partial index. `is_apt_index_failure`
was written for exactly that shape and `should_try_next_mirror` already asks it
on the release-image path, but the praktika classifier this PR added did not, so
the shape stayed permanent and the build failed on its first attempt.

Measured over 90 d of `Dockers Build (*)` FAIL/ERROR rows (n=98): two rows carry
the shape, both arm64 image builds on 2026-07-15 whose `E: Unable to locate
package` lists were `python3-lxml`, `rustc`, `jq` and friends after
`ports.ubuntu.com` came back unreachable for all four `InRelease` files. Both
were retryable and neither was retried. No other row in the corpus changes
verdict, because the predicate still needs an `E:` resolution error inside the
terminal fence plus the index warning carrying that same step's `#N ` prefix: a
misspelled package name against a healthy mirror, a warning from an earlier step
that recovered, and a log truncated before the terminal error all stay permanent.
@maxknv
maxknv marked this pull request as draft September 10, 2026 08:16
@maxknv

maxknv commented Sep 10, 2026

Copy link
Copy Markdown
Member

ai slope

@maxknv maxknv closed this Sep 10, 2026
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-own-pr PR origin: CI on a groeneai PR exposed a separate defect manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants