Skip to content

Bound the integration-test job's post-run archiving so it cannot starve the result upload - #112972

Open
groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:ci-bound-integration-test-archiving
Open

groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:ci-bound-integration-test-archiving

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

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

Related: #112175

An integration-test shard can publish a job-level ERROR with results: [] even though every
test produced a result.

What breaks. On 6cdf4dfaea6e071cddeea4daeb74ea26e0d96e19,
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) reported ERROR with no
children and is absent from the CI database, while its five siblings uploaded 600-1300 test
rows each. Its job log holds 502 per-test outcome lines: the results existed and were
discarded. Correcting the report: the harness survived both timeouts, then hung ~80 min in
archiving.

Root cause. main collects every result but dumps it only after unbounded
post-processing. Utils.compress_files_gz sits in between with no timeout, archiving whole
tests/integration/<suite> trees, so an archive that never returns costs a report already in
memory. Runner._get_result_object runs the on_error_hook the same way, even earlier
(comment: # Add hook timeout once it's needed).

The change. Both paths are bounded at 30 minutes and fail non-fatally, so an overrun
costs the tarball, not the report. compress_files_gz returns failure instead of raising,
publishes by rename from a per-writer temporary, uses a direct tar -czf instead of
tar -cf - | gzip, and judges the archive by reading it back, not by tar's exit code; all
four load-bearing, see below. Bounding needs a working watchdog, so Shell._check_timeout
waits on an event set when the attempt's child is reaped, not sleeping the timeout out.
main also checkpoints the results first.

Scope limits. The checkpoint does not recover the job above, where the runner died, nor
an externally cancelled job. 30 minutes comes from healthy shards' 4491-5747s of 18000s.

Validation. 41 tests, each shown to fail against a mutation of what it pins: a matrix
reddening exactly its predicted arms, plus a probe for the four it did not reach. Empty
failure-set diff over ci/tests/, as host user and as root.

Why each detail of the change matters

Four measured properties beyond the bound.

  • Must not raise. Shell.check(..., strict=True, timeout=N) raises RuntimeError, so
    merely adding timeout= turns the hang into an exception that still skips the dump. Nor an
    absent declared input (Result.from_pytest_run registers its log and report before
    running pytest) or a failed publish.
  • Must not publish a partial archive. A timed-out tar leaves a large truncated archive
    and the upload only checks the file exists. The temporary is per writer: both target one
    ci/tmp/logs.tar.gz, so sharing it lets the loser write into the published file.
  • Must not reject a usable archive over tar's exit code. Two reachable cases exit
    non-zero with a complete, listable archive: 1 for a member appended to while read, which
    every archive here holds, and 2 for an unstattable input, which the hook hits whenever its
    _instances* glob is unexpanded. Rejecting on the code discards both, timeout unfired. So
    only 0 is accepted outright and every other code is settled by tar -tzf: 0 on those,
    non-zero on every truncated archive (~1.6s for 367MB). 1 is read back rather than trusted,
    since Shell.run reports an internal failure of its own as 1 too.
  • Must see tar's status at all. Shell.run uses bash without pipefail, so the old
    tar -cf - | gzip > out reported only gzip's status: a tar failing part-way exited 0.

The watchdog event is per attempt (a shared one is already set when attempt 2 starts waiting),
and all three of its liveness tests ask about the process GROUP. A descendant holding the
inherited pipes keeps the readers blocked, so the event is unset while the leader is already
reaped, and a leader-only poll() signals nothing or skips the SIGKILL. The exception path
kills the group for the same reason, since it cancels the watchdog on the way out.


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

groeneai and others added 8 commits August 1, 2026 13:23
An integration-test shard can publish a job-level ERROR with results: []
even though every test produced a result. On
6cdf4df, Integration tests
(amd_asan_ubsan, db disk, old analyzer, 5/6) reported ERROR with no
children and is absent from the CI database, while its five sibling
shards uploaded 600-1300 test rows each. Its job log holds 502 per-test
outcome lines, so the results existed and were discarded. The harness
survived both the graceful xdist timeout and the hard subprocess
backstop, then hung in archiving for ~80 minutes until the runner was
cancelled.

integration_test_job.main collects every result, runs unbounded
post-processing, and dumps the results only at the end.
Utils.compress_files_gz sits in between and had no timeout, archiving
whole tests/integration/<suite> trees, so an archive that never returns
costs a report already held in memory. Runner._get_result_object has the
same shape for the on_error_hook, whose comment already asked for a
timeout, and that hook archives the same directories even earlier
relative to the upload.

Both paths are now bounded at 30 minutes and fail non-fatally, so an
overrun costs the tarball rather than the report. Three further
properties are required, each measured:

- compress_files_gz reports failure by return value instead of raising.
  Shell.check(..., strict=True, timeout=N) raises RuntimeError, so
  merely adding a timeout would turn the hang into an exception that
  still skips the result dump.
- The archive is built under a temporary name and renamed in on success
  only. A tar killed by the timeout leaves a large truncated archive
  (41418752 bytes for a 1s bound over a 400-file tree) and the upload
  path only checks that the file exists, so it would be published as the
  logs. Both writers target the same ci/tmp/logs.tar.gz, so the rename
  also stops a failing second writer destroying the first one's complete
  archive. No pre-removal is added, which would do exactly that.
- tar -cf - | gzip becomes a direct tar -czf. Shell.run uses bash
  without pipefail, so the pipe reports only gzip's status and a tar
  that fails part-way exits 0 (measured, with a 293-byte archive). The
  previous strict=True therefore never caught a tar failure at all, so
  master can already attach a silently incomplete archive.

Bounding needs a working watchdog, so Shell._check_timeout no longer
sleeps its timeout out unconditionally before signalling the process
group: a command that finished early left a live watchdog that would
later signal a reaped, possibly PID-recycled group (measured, two live
threads in one probe process). It now waits on an event set when that
attempt's child is reaped, with a poll() backstop. The event is created
inside the retry loop, because one shared event would already be set
when the second attempt's watchdog began waiting, leaving every retry
after the first with no enforcement. This is the twin of
TeePopen._check_timeout, fixed in cfb2ac8.

main additionally checkpoints the collected results into the existing
RUNNING result before post-processing, which recovers the cases where
the job script dies but the runner survives. It updates that result
rather than building a new one, since Result.create_from takes no ext
and would drop the on_error_hook that Runner._get_result_object gates
the hook on, and it assigns no status so every status decision further
down main still decides the final verdict. It does not recover the job
above, where the runner process itself died, and external cancellation
of the runner cannot be handled from inside the job.

The 30 minute bound is derived from the healthy shards, which ran
4491-5747s against an 18000s job budget.

Reported by alexey-milovidov on ClickHouse#112175.
…dants

Review of the previous commit found that the switch from tar -cf - | gzip to
a rename-gated direct tar -czf made the archiving strictly worse in the
common case. GNU tar exits 1 for "some files differ", which includes a file
appended to while being read, and the archive is complete. Every archive
these paths build contains such files: ci/tmp/job.log, which the praktika
entrypoint keeps open line-buffered for the whole job, the dockerd debug
log, ci/tmp/host_metrics.jsonl, and live test instance directories. Treating
1 as failure therefore discarded a complete archive on essentially every
failing shard, without the timeout ever firing, so the change regressed the
artifact it exists to preserve. Measured rc 1 with a fully listable archive
in 10 of 10 runs at each of 1, 2, 4, 8 and 20 MB. The status classes are
separable, so 1 is now accepted while 2 and a signal death are not, in both
the helper and the hook. --warning=no-file-changed only silences the
message; it leaves the code at 1. --ignore-failed-read is not used, since it
turns a missing input into 0.

The watchdog's poll() backstop was a regression of its own. Shell.run joins
the output reader threads before signalling that the attempt is over, so a
background descendant that inherited those pipes keeps the readers blocked
while the shell leader is already reaped: the event stays unset, the
leader-only test sees the reaped leader, and nothing is enforced. Measured
against a master-equivalent watchdog, sleep 60 & with a 3s bound ran the
full 60s where master stopped it in 3s. The backstop now tests the process
group. A setsid --fork descendant remains unbounded, as it is on master,
because it leaves the group killpg can reach.

compress_files_gz no longer raises at all, as its own docstring promised.
Result.from_pytest_run registers the pytest log and report files before
running pytest, and a conftest import error leaves both uncreated, so a
declared path that never existed is a real input; it is now dropped with a
warning, and a failed publish returns None like any other failure. The
temporary archive name is unique per writer, because both writers target one
ci/tmp/logs.tar.gz and sharing one temporary lets the loser keep writing
into the archive the winner published, which grew a published archive to
81990028 bytes and left tar -tzf rejecting it.

The structural tests permitted the wiring to become a no-op: timeout=None
kept the keyword while disabling the bound, and set_results([]) with a
status satisfied every checkpoint assertion while writing the empty report
the checkpoint exists to prevent. They now assert the resolved timeout
value, the checkpoint's argument, and the absence of any status assignment
at the call site. The retry test's ceiling could not discriminate a 64s
mutation from a 6s baseline; it is tightened, and its comment now says what
actually catches the mutation, which is that an unenforced second attempt
succeeds and returns 0.
The previous commit accepted tar's exit 1 ("some files differ") because every
archive built here contains files the job is still writing. The same reasoning
applies to exit 2, which it still rejected: tar returns 2 for an input it cannot
stat while archiving every input that it could and finishing the stream. Both
archiving paths reach that routinely - the on_error_hook's
./tests/integration/test_*/_instances*/ glob is unexpanded whenever the job
errored before a cluster started, and bash has no nullglob, so the literal
pattern reaches tar.

Measured with the two hook literals run verbatim, ci/tmp/{job.log,
host_metrics.jsonl} present and no _instances directory: master publishes a
207-byte logs.tar.gz listing all three members, the previous commit publishes
nothing. So it discarded the artifact it exists to preserve, on the hard-timeout
path, without the timeout ever firing - the mirror image of the exit-1 defect.

The exit code cannot separate that archive from a truncated one, so it no longer
decides alone: 0 and 1 are accepted as before, and any other positive code is
settled by reading the archive back with tar -tzf, which walks the member stream
and so rejects a write cut short mid-member. A negative code is the watchdog's
SIGTERM and needs no probe, since it interrupted the write by construction; a
timeout kill surfaces through Shell.run as -15, never as 2. The probe costs
about 1.6s for a 367MB archive against the 1800s bound. Verified at three kill
points that a truncated tar still publishes nothing and leaves a previously
published archive byte-identical. The glob was deliberately kept: it is what
makes the input set correct across suites.

Also extracts the interim checkpoint into checkpoint_collected_results, so the
tests drive the code main runs rather than re-implementing its setter sequence.
Two runtime no-op mutations that keep the call site intact - inverting the guard,
and disabling the body - previously left the suite green; a third, a guard
wrapped around the call site, was found while testing the fix. All three now
redden. The precedent is is_empty_best_effort_skip in the same file, extracted
for the same reason.

The suite grows to 31 tests, each checked in both directions: reverting the gate
to the exit code alone reddens exactly the new complete-archive arm, while
accepting every positive code blindly reddens the truncation arms, so the gate is
pinned from both sides. Full ci/tests/ has an empty fix-only failure set.

Test docstrings lose the incident history - shard statistics, byte counts and
"measured N/N" - and keep the local invariant and the oracle.
`Shell._check_timeout` tested the process group before sending SIGTERM but
still asked `process.poll()` in the graceful-termination loop and at the
SIGKILL gate, so the function tested the group in one place and the leader in
two.

A descendant that ignores SIGTERM while holding the inherited output pipes
survives the signal, and both leader-only tests see the already-reaped shell
leader: the loop ends on its first iteration and the SIGKILL never runs, so
`Shell.run` stays blocked in its reader joins for the descendant's whole
natural lifetime. Measured through the real `Shell.run`:
`trap '' TERM; sleep 200 &` with `timeout=1` returned after 200.0s, and after
this change after 101.0s, which is the grace loop's own 100s budget plus one
interval. That case is unbounded on master too, so this part is a hardening
rather than a regression fix; the pre-signal test fixed earlier was the
regression.

The three tests now go through one `group_alive()` helper. `PermissionError`
counts as alive because that is the fail-safe direction: signalling a group
`killpg` will reject costs nothing, while calling it dead silently stops
enforcing the bound.

Two arms cover the two sites, because they carry different properties and
one duration assertion cannot separate them. Reverting the grace loop alone
makes the call FASTER (1.0s, escalating straight to SIGKILL), so that site is
pinned by whether a SIGTERM handler completes, while the SIGKILL gate is
pinned by the duration plus the escalation's own log line.

Also documents that `ARCHIVE_TIMEOUT_SEC` bounds the `tar` write and again
the `tar -tzf` read-back, so one call's worst case is twice the constant.
Comment only; the measured read-back cost is ~1.6s for a 367MB archive.

Co-Authored-By: Claude Fable 5 <[email protected]>
test_fuzzer and test_stress in ci/tests/test_e2e.py rename ci/tmp to
ci/tmp_result in a finally block and never remove it, so running the
suite leaves an untracked directory behind. It holds a core dump and a
generated AES key, and one member, cores/core.test.zst.enc, is
classified as text by git because its OpenSSL "Salted__" header looks
textual, so tooling that diffs untracked files inlines raw encrypted
bytes.

ci/tmp is already ignored here and in the root .gitignore; its two
siblings are the same kind of build output and were simply missed.
ci/tmp_backup is added alongside because the same two tests create it
on the path where the rename back does not run.

Co-Authored-By: Claude Fable 5 <[email protected]>
This reverts commit c017e6f.

Ignoring ci/tmp_result and ci/tmp_backup does not only silence git
status, it takes both directories out of git clean -ffd's reach, which
is what removes them today. The clean has no -x, so it cannot touch an
ignored path, and Runner._pre_run only runs it when git status --short
is non-empty, so ignoring the paths stops the cleanup from being
triggered at all. On a runner whose checkout persists between jobs that
leaves a core dump and a generated AES key accumulating.

ci/tmp is safe to ignore because Runner.__init__ recreates it on every
job. ci/tmp_result exists only as leftover state, so ignoring it is
pure accumulation.
compress_files_gz documents that nothing in it raises, because an
exception would skip the caller's result upload, which is the outcome
the bound exists to prevent. Both failure branches removed the
temporary archive with unlink(missing_ok=True), which suppresses only
FileNotFoundError, so the cleanup could still throw out of the
function:

  - a temporary path that already exists as a directory makes tar exit
    2, and the unlink that follows raises IsADirectoryError;
  - a destination directory the job cannot write makes os.replace raise
    PermissionError, and the unlink inside that handler raises
    PermissionError again.

The second is reachable on a runner where the from-root chown of
ci/tmp in Runner._run failed with its return value discarded, leaving
entries root-owned while the job script runs as the host user.

Route both through a helper that reports the failure and continues. The
new test arm uses the directory trigger rather than a permission one
because the CI Tests job runs as root, where a mode-based arm would
pass without exercising anything.
The added tests carried far longer docstrings than the suite they join:
45 percent were over six lines against 2 percent in the rest of
ci/tests, the longest 15 lines. Cap every test docstring at six lines
across both files, keeping only what a reader cannot re-derive, that is
what the arm pins and why the obvious cheaper assertion does not work.
Measured timings, source-line citations and mechanism walk-throughs go
to the pull request description instead.

No assertion, assertion message or in-body comment is touched. The
watchdog file's share of this trim rides in the preceding commit
because the same file also gains the new cleanup arm there.
@groeneai

groeneai commented Aug 2, 2026

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

Five rounds of independent review before this PR opened: 6 approach-review rounds, then 5
code-review rounds by a reviewer that does not write the code, each followed by a second-model
cold re-review. 24 findings were AGREEd and fixed, 3 refuted with evidence. The final round
found 0 blockers and 0 majors. Recorded here because two of the refusals are the kind a
reviewer should have to justify in public.

❌ Blockers/majors fixed during review (24; the ones that changed the design)

  • Bounding alone was not enough: Shell.check(..., strict=True, timeout=N) raises, which still
    skips the result dump. The helper now returns None instead of raising, on every path
    including a missing input and a failed publish.
  • Two successive versions gated on tar's exit code and each discarded a complete archive
    with the timeout never firing
    - first at rc 1 (a member appended to while read, which every
    archive here contains), then at rc 2 (an unexpanded _instances* glob, i.e. every job that
    errored before a cluster started). The gate is now the archive's own readability.
  • tar -cf - | gzip reported only gzip's status without pipefail, so a tar failing part-way
    exited 0. Replaced with a direct tar -czf.
  • Both archiving paths write the same ci/tmp/logs.tar.gz, so a shared temporary name let a
    losing writer write into the file the winner had already published. Made unique per writer.
  • The watchdog's timeout Event was shared across retry attempts, so with retries > 1 every
    attempt after the first ran unbounded. Made per attempt.
  • Eight test arms were added because a mutation reddened nothing or an arm proved vacuous -
    including one that passed on the very mutation it targeted (a create_from rewrite removes
    the set_results call that arm iterated over) and one where a guard around the call site
    would stop the checkpoint from ever running while every other arm still passed.
  • The archive cleanup could itself raise (unlink(missing_ok=True) suppresses only
    FileNotFoundError), costing the caller the upload the bound exists to protect.

⚠️ Refuted, with evidence (3)

  • "A timed-out error hook leaves a large truncated staging archive permanently in ci/tmp,
    surviving on reused workers because ci/tmp is ignored and cleanup uses git clean -ffd."

    The survival step is false. Every praktika job's generated Prepare env script step starts
    with rm -rf ./ci/tmp && mkdir -p ./ci/tmp, emitted unconditionally by the generator
    (ci/praktika/yaml_generator.py:175). Mapping every wipe to its enclosing job block:
    pull_request.yml 174 jobs / 174 wipes, master.yml 159/159, backport_branches.yml 38/38,
    merge_queue.yml 8/8, none missing. The staged name is also absent from set_files and
    matched by no artifact glob. On this same path master writes the truncated archive directly
    to the published path
    , so the change strictly improves the outcome.
  • "The watchdog can outlive Shell.run, leaving a timed-out descendant running and enabling a
    late signal to a recycled process group."
    The mechanism reproduces, and the A/B says the
    post-return watchdog is what prevents the leak: same command
    (( trap '' TERM; echo hello; sleep 6; exec >/dev/null 2>&1; sleep N ) &, timeout=2), on
    master the watchdog exits without escalating and the descendant is still alive at t+115s; with
    this change it is SIGKILLed and gone. The recycling half is unreachable - a process group
    persists while any member lives, so the pgid cannot be re-issued as a new PID in the window
    where the watchdog signals (verified: killpg(pgid, 0) still succeeds after the leader is
    reaped; 0 collisions over 400 PID allocations, pid_max 4194304). This case was unbounded on
    master too, which the PR body states.
  • "The checkpoint adds a way for the job script to die on an absent or corrupt result file."
    main already opens with an unguarded Result.from_fs(...) 584 lines earlier, which I
    measured raising on both of those inputs, so the script dies there identically before and
    after and never reaches the checkpoint. Adding a guard would be a defensive change for an
    unreproducible mechanism.

💡 Noted, not blocking

  • Added source comments slightly outnumber added code (113 vs 103 lines, six blocks over 3
    lines). Every block states a local invariant and each factual claim in them was reproduced
    independently; the same files' existing convention is 32 of 151 blocks over 3 lines. Module
    and per-test docstrings were already trimmed twice on review (46->33, 32->27, then every
    per-test docstring capped at 6 lines).

Session id: cron:clickhouse-review-slot-49:20260802-012400

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, six on-demand ones, all re-measured for this change: Shell.check("sleep 20", timeout=3, strict=True) raises RuntimeError in 3.0s; Shell.run("echo fast", timeout=25) returns in 0.00s and leaves a live _check_timeout thread (two after two calls); a -T list naming a missing path exits 0 through the pipe and 2 with tar -czf; a timeout-killed tar leaves a 42205184-byte truncated archive and returns -15 through Shell.run, never 2; a member appended to while being read makes tar -czf exit 1 with a complete, fully listable archive; and an unmatched shell glob makes it exit 2 with a complete archive of every input that did exist (tar -tzf accepts it, 209 bytes / 3 members).
b Root cause explained? Yes. integration_test_job.main collects every result, then runs unbounded post-processing, and dumps the results only at the end, so an archive that never returns discards a report already in memory. Utils.compress_files_gz had no timeout; Runner._get_result_object runs the on_error_hook (another archive of the same directories) unbounded and even earlier relative to the upload.
c Fix matches root cause? Yes. The bound is placed on the two archiving paths that sit ahead of the upload. Raising the job timeout or shrinking what is archived was rejected as mitigation: the archive stays unbounded and the report is still lost whenever archiving outlives the budget. Reclassifying the empty result was rejected too; is_empty_best_effort_skip deliberately keeps a non-timeout empty result as ERROR and is untouched. Two earlier versions of this change gated on tar's exit code and each discarded a COMPLETE archive without the timeout ever firing: first at rc 1 (a member appended to while read - essentially every failing shard), then at rc 2 (an unmatched _instances* glob - every job that errored before a cluster started). The gate is now the archive's own usability: 0 and 1 are accepted outright, a negative rc is the watchdog's SIGTERM and always truncated, and any other code is settled by tar -tzf. Measured separable: tar -tzf returns 0 on the complete rc=2 archive and 2 on every SIGTERM-truncated one (5/5 kill points, 12-82 MB), at ~1.6s for 367 MB against an 1800s bound. gzip -t was rejected as the oracle - it accepted a truncated archive at one of those kill points where tar -tzf rejected it.
d Test intent preserved / new tests added? Yes. No existing test was weakened, removed or rescoped; 34 were added. test_timeout_terminates_a_long_running_command is carried as an explicit must-not-regress for the enforcement direction, so the watchdog change cannot be satisfied by never firing. Two arms that would have skipped or passed trivially as root were rebuilt around privilege-independent triggers, a ulimit write limit and a directory occupying the staged path, so the suite runs 34/34 with 0 skips as root, which is who the CI Tests job runs as, and each of those two was confirmed to redden as root without the fix.
e Both directions demonstrated? Yes, by a 28-case mutation matrix run one mutation at a time from a pristine copy, with an md5sum-verified restore between them and the failing set predicted before each run. Every case reddened exactly its predicted arms and nothing else, with one recorded prediction miss whose mechanism was traced: reverting the watchdog's PRE-signal group test gates all downstream enforcement, so no SIGTERM is ever sent and it reddens the two later group arms as well; the mutations targeting those later sites each redden exactly one arm, which is what proves they are disjoint. Two mutations are predicted to redden NOTHING and do: the usability gate subsumes both rc-code special cases, so reverting either leaves the behaviour correct. Eight arms were ADDED across the four rounds because a mutation reddened nothing or an arm proved vacuous: an unbounded call site is invisible to behavioural tests; the shared-destination invariant was unpinned; a unique temporary name is unobservable with a single writer; the failed-publish path had no arm; a create_from rewrite removes the set_results call the from_fs arm iterated over, so that arm passed on the very mutation it targeted; and a guard wrapped around the CALL SITE stops the checkpoint from ever running in CI while every other arm still passes. The last round added two: the watchdog's grace loop and its SIGKILL gate are separate sites carrying different properties, and reverting the grace loop alone makes the call FASTER (1.0s against the fixed 101.0s) because it escalates straight to SIGKILL, so a duration ceiling passes and only the SIGTERM handler's own completion marker catches it.
f Fix is general across code paths? Yes. compress_files_gz has exactly two call sites repo-wide, both bounded (the configs.tar.gz one is easy to forget, so a test fails if any call site lacks a bound). The third path, the on_error_hook, is bounded and given the same publish-by-rename, the same usability gate and the same per-writer temporary name, so the Python helper and the shell hook agree on all four properties. The watchdog's group-liveness backstop fixes every Shell.run caller, not just archiving. TeePopen._check_timeout was the already-fixed twin and is not re-touched; Shell._check_timeout was the remaining one. Deliberately out of scope and stated in the body: the dmesg and iptables calls in the same job, and the archiving in the functional-test job, which are separate failure classes.
g Fix generalizes across inputs? Yes for the dimensions this code has (no type wrappers here). Every tar exit class is covered in both directions: 0, benign 1, positive-with-usable-archive, positive-with-unusable-archive, and signal death. All four combinations of timeout present/absent by success/failure are covered, including absent+success, which is what keeps every other caller unaffected. The retry dimension is covered at retries=2 explicitly, and the destination dimension both empty and already holding a valid archive.
h Backward compatible? Yes. timeout is a new keyword defaulting to None, so unbounded behaviour is preserved for any caller that does not opt in, pinned by a test. The return type gains None on failure and both call sites were updated; there are no others. TAR_OK_RETURN_CODES was renamed to TAR_UNCONDITIONALLY_OK_RETURN_CODES because its meaning narrowed; it was introduced by this same change and has no other reader. No setting, format or protocol, so no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? Yes: no post-collection step may starve the runner of the time it needs to upload the collected results, and no archive may be published unless it is complete and readable. The first of those makes "nothing in compress_files_gz raises" a contract, not a comment, so the cleanup on both failure branches goes through a helper that reports and continues: unlink(missing_ok=True) suppresses only FileNotFoundError, and a temporary path occupied by a directory, or a destination the job cannot write, otherwise threw out of the function and cost the caller the very upload the bound protects. Both writers share ci/tmp/logs.tar.gz, so publish-by-rename with no pre-removal is what keeps a failing second writer from destroying the first one's complete archive. The checkpoint assigns no status, so every later status decision still decides the verdict, and it preserves ext so the error hook still runs; it lives in a module-level helper that the tests invoke directly, because structural assertions cannot tell a checkpoint that runs from one that never does. The watchdog event is created per attempt and set in that attempt's own finally, so it fires on the success, failure and exception paths, and all three of its liveness tests - before the SIGTERM, inside the graceful-termination loop, and at the SIGKILL gate - ask about the process GROUP rather than the leader: when the shell exits while a background descendant holds the inherited output pipes, the reader threads stay blocked so the event is unset while the leader is already reaped, and a leader-only poll() then either returns without signalling at all, or ends the grace period on its first iteration and skips the SIGKILL, leaving the call blocked in its reader joins for the descendant's whole natural lifetime. Only the pre-signal case is a regression introduced here; a descendant that IGNORES SIGTERM is unbounded on master too (measured), so that part is a hardening and the PR body says so. The PermissionError-means-alive direction is the fail-safe choice but is not pinned by a test, since a not-ours process group is not reproducible in the test environment. One pre-existing defect is fixed as a side effect: the previous strict=True could never catch a tar failure, so master can already attach a silently incomplete archive.

Session id: cron:clickhouse-impl-slot-44:20260802-004300

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? An integration-test shard can report a job-level ERROR with zero test results even though every test produced one: main collects the results but dumps them only after unbounded post-run archiving, so an archive that never returns discards a report already in memory. This bounds both archiving paths ahead of the upload non-fatally, and fixes three pre-existing defects in compress_files_gz that could publish a truncated archive or discard a complete one without any timeout firing.

@maxknv maxknv self-assigned this Aug 17, 2026
@maxknv
maxknv self-requested a review August 17, 2026 12:47
@maxknv maxknv added the can be tested Allows running workflows for external contributors label Aug 17, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ec4dcae]

Summary: ❌

job_name test_name status info comment
CI Tests FAIL
ci/tests/test_settings_history_source_gate.py::test_renaming_a_record_in_place_is_allowed FAIL cidb

AI Review

Summary

This PR bounds post-run archiving in the integration-test harness, hardens Shell.run, and adds a checkpoint that persists collected test results before the archive step. The timeout and archive-handling changes look directionally sound, but the checkpoint still violates its own durability contract by rewriting the live result JSON in place, so the PR should not merge with that part enabled.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Bound the integration-test job's post-run archiving so it cannot starve the result upload #112972#discussion_r3796559150] [ci/jobs/integration_test_job.py:859], [ci/praktika/utils.py:83], [ci/praktika/runner.py:1155] The new checkpoint_collected_results path still persists through Result.dump(), which truncates the live JSON file in place. If the job is terminated during that write, the existing RUNNING result becomes unreadable, and Runner.run still performs an unguarded Result.from_fs(job.name) before the later guarded recovery path. That means the runner can still die before it uploads the already-collected children, turning the checkpoint into a new corruption window rather than the durable recovery point promised in the PR description. Suggested fix: make persisted Result.dump() writes atomic, or drop the checkpoint from this PR until the atomic-write change lands.
Final Verdict

Needs changes before merge: the checkpoint should be atomic or omitted.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 17, 2026
"""
if is_local_run:
return
Result.from_fs(job_name).set_results(test_results)

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.

checkpoint_collected_results only helps if this write leaves a parseable result file, but Result.dump() still rewrites the live JSON in place with open(..., "w"). If the job is terminated while this checkpoint is being dumped, the existing RUNNING stub is truncated, and the runner's next Result.from_fs(job.name) read fails before it can recover the collected children. That turns the new checkpoint into a new corruption window instead of a durable recovery point.

Please make the checkpoint write atomic (for example by staging the updated result to a temporary file and os.replace-ing it, or by teaching Result.dump() to do atomic writes) before relying on it for recovery.

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.

Confirmed, and the exposure is worse than described. All three links check out at d70428f1:

  • Result inherits MetaClasses.Serializable.dump (ci/praktika/utils.py:82-85), which is open(path, "w"): truncate in place, no staging, no fsync. set_results reaches it through _dump_if_persisted.
  • Serializable.from_file (utils.py:61-72) re-raises JSONDecodeError. A 403,262-byte checkpoint truncated to 0/1/50/99 percent fails to parse in 4 of 4 cases.
  • The read that hits it first is unguarded. An AST census of every Result.from_fs in runner.py gives no handler at :502, :845, :868, :1115, and a handler only at :564, :803, :893. run()'s try spans 1093-1108 and ends before :1115, and the frame above it (__main__.py:382-417) has zero handlers. So the process dies at :1115, before _get_result_object (:1125) and _post_run (:1152) upload anything.

A/B with the child SIGKILLed mid dump, 6 trials each: this head leaves an unreadable file 6/6, and with an atomic dump() grafted in, 6/6 stay readable as the pre-checkpoint stub.

I was wrong to reason that this is never worse than today. That assumed the guarded fallback at :564, but :1115 runs first.

On scale: the mechanism is not new, since the base already dumps in place at :643 and :652, but this PR widens the window from 206 bytes and 0.36 ms to 415 KB and 18 ms at 1300 children.

I am not fixing it in this PR. Result.dump() is the right place and I have that open already: #112252 stages a sibling temp, fsyncs and os.replaces, and routes the unguarded reads through a helper that degrades to RUNNING instead of raising. It is approved and covers all six Serializable subclasses. Open-coding atomicity at this one call site would duplicate the to_dict serialization and still leave the other readers exposed. #112252 needs a rebase first: it forked before HostMetricsCollector landed, so it conflicts with master in _run, independent of this PR.

If you would rather not widen the window while #112252 is unmerged, I can drop the checkpoint from this PR instead. It does not recover the job this PR is about, where the runner itself died and nothing local was left to upload, and the bounds work without it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d70428f

CI is fully finished on this commit with no failures: 180 check-runs, 0 incomplete, 13 success,
166 skipped, 0 failure. CIDB reports 0 FAIL/ERROR test rows at this head (partitioned to the newest
run, which started 2026-08-17 15:26:18).

Nothing is owed, so there is no failure table.

Two rows that look like reds but are not:

  • request-reviews-fork is cancelled (12:48:19Z). It is the fork review-request helper, not a test
    job, and it carries no test rows.
  • The two Integration tests (amd_asan_ubsan, targeted) rows are skipped with their own context
    reading "No failed tests found from previous runs" - the targeted job legitimately no-ops when there
    is no prior failure to re-run, and its Post Hooks row is OK.

Session id: cron:our-pr-ci-monitor:20260817-160000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Only ci/praktika/runner.py conflicted, at the module-constant block just below
the imports: master added the image-pull retry constants there and this branch
added ON_ERROR_HOOK_TIMEOUT_SEC. Both are kept; the resolution introduces no
line that is not already in one of the two parents.

The image-pull retry passes no timeout= to Shell.run and bounds itself with an
external 'timeout --verbose 300', so it never arms this branch's watchdog and
the two bounds cannot be confused for one another.
…ook by running it

Four defects a second-model re-review raised on the merged tree, each reproduced
before being fixed.

The staging name was derived from the pid, but the two writers of the job's
logs.tar.gz are the job script inside Docker and the on_error_hook on the host,
which share the worktree across a pid namespace boundary and can both be pid 1.
Both writers now take a name that is unique per invocation.

Writing the tar manifest was outside the function's exception handling, so a full
or read-only temporary filesystem raised through a docstring that promises nothing
here raises. Injecting ENOSPC reproduced it; it now returns None like every other
archiving failure.

The hook's own test asserted only that tokens were present in the shell literal, so
an 'exit 0' after the rc branch left every assertion satisfied while the hook could
no longer publish or clean up. It is now executed, on the unexpanded-glob path it
exists to serve and on a rejected truncated archive, with privileges stubbed on PATH
rather than edited out of the body under test.

The checkpoint call-site oracle flattened the arguments into an unordered set, so
swapping two of them handed the results list to the truthy local-run guard and
turned the checkpoint into a no-op with the suite still green. It now binds each
argument to the parameter the helper reads it as.

The cleanup arm reached its failure by pre-seeding the pid-derived staging path, so
a per-invocation name would have left it passing over a run that never reached the
cleanup. It now occupies the name the call itself chooses.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (the branch had drifted 11544 commits behind) and fixed four defects a re-review found on the merged tree. Only ci/praktika/runner.py conflicted, at the module-constant block below the imports: master added the image-pull retry constants there, this branch added ON_ERROR_HOOK_TIMEOUT_SEC. Both kept, and the resolution introduces no line that is not already in one of the two parents.

Master's image-pull retry passes no timeout= to Shell.run and bounds itself with an external timeout --verbose 300, so it never arms this branch's watchdog. The two bounds cannot be confused for one another.

The four fixes, each reproduced first:

  • The staging name came from the pid, but the two writers of the job's logs.tar.gz are the job script inside Docker and the on_error_hook on the host. They share the worktree across a pid namespace boundary and can both be pid 1, so both writers now take a per-invocation name.
  • Writing the tar manifest sat outside the function's exception handling, so a full temporary filesystem raised through a docstring promising nothing there raises. Injecting ENOSPC reproduced it; it now returns None like every other archiving failure.
  • The hook's test asserted only that tokens appeared in the shell literal. An exit 0 after the rc branch kept every assertion satisfied while the hook could no longer publish or clean up. The hook is now executed, on the unexpanded-glob path it exists to serve and on a rejected truncated archive, with privileges stubbed on PATH rather than edited out of the body under test.
  • The checkpoint call-site oracle flattened its arguments into an unordered set, so swapping two of them handed the results list to the truthy local-run guard and made the checkpoint a no-op with the suite green. Each argument is now bound to the parameter the helper reads it as.

Repairing the first fix also made an existing cleanup arm vacuous: it reached its failure by pre-seeding the pid-derived staging path, which a per-invocation name never chooses. It now occupies the name the call itself picks.

Verification on the merged tree: 37 tests pass as host user and as root with no skips, and every arm was shown to fail against a mutation of what it pins, prediction recorded before each run. The two mutations that previously reddened nothing now redden exactly the new arms. Full ci/tests/ against a pristine master snapshot: 23 failed / 980 passed on master, 23 failed / 1017 passed here, so the fix-only and base-only failure sets are both empty and the 37 additions are exactly the delta. The 23 are pre-existing and need a live server. ruff clean.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ec4dcaeca with master 95607bfa9 (stripped binary size, per-symbol sizes and ThinLTO time; 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 709.21 MiB 706.16 MiB -3.04 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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 62c3d74

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) / test_server_overload::test_overload flaky, host-load dependent (3 rows / 3 unrelated PRs / 0 master in 90d, first 2026-06-18) a fix task is created (investigating at full effort, fixing-PR link to follow here)

Not caused by this PR: the diff is ci/praktika plus the integration test job wrapper, and the
failure is the test's own assertion Expected to get the server overloaded error at least once.

Note on why an existing merged fix is not linked here: #113529 ("Make test_server_overload
deterministic instead of probabilistic") is merged and is already an ancestor of this head, and the
assertion still fired, so that fix does not resolve this case. It saturates the throw probability at
1, which removes the Bernoulli draw, but the test still depends on the runner actually reaching a CPU
wait ratio above the threshold. On an under-loaded runner the ramp never triggers and the loop
exhausts its 60 attempts. That residual is what the new fix task owns.

Session id: cron:our-pr-ci-monitor:20260821-203000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for test_server_overload::test_overload (the ledger line above): #115905.

Root cause is not an under-loaded runner. checkCPUOverload reads getCPUOverload with reset=false (ProfileEvents.cpp:1972) and gets 0 at :2039 while the busy time accrued since the last reset is below os_cpu_busy_time_threshold, so the ratio and the probability ramp are never evaluated. The only resetting caller is AsynchronousMetrics.cpp:2734, so every window opens blind for its first threshold / busy_rate (~0.43 s on this runner), and the probe loop samples that grid at ~0.99 s with ~9 ms of drift per iteration - a run that starts inside the blind window stays there. #113529 removed the Bernoulli lottery; this was the sampling one.

Master relocated the docker image-pull policy constants
(`_IMAGE_PULL_RETRY_ERRORS`, `_IMAGE_PULL_TIMEOUT_S`, `_IMAGE_PULL_RETRIES`)
out of `ci/praktika/runner.py` into `ci/praktika/docker.py`, which re-exports
them, and deleted the module-level block this branch had appended
`ON_ERROR_HOOK_TIMEOUT_SEC` to. Took master's relocation and kept the new
constant, so the block now holds only the on_error_hook bound and the pull
policy is read from `docker.py`.
`Shell.run` reports an internal failure of its own as 1, the same value `tar`
uses for "some files differ", and on that path it kills only the shell leader,
so `tar` can still be writing the staging archive when the 1 arrives. Accepting
1 unconditionally therefore renamed a truncated archive into place, and the
upload only checks that the file exists. Only a clean exit now skips the
read-back; 1 is settled by `tar -tzf` like any other non-zero code. A file
appended to while being read still publishes, since such an archive reads back.

Two wiring oracles could not see their own regression. The checkpoint call-site
test bound `job_name` but asserted only the other two arguments, so a call
writing another result file stayed green; it now asserts all three. The two
bound-wiring tests accepted any positive timeout while the behavioural arms use
their own short values, so cutting either promised 30-minute bound to a second
stayed green as well; both now pin the contracted value.

Every direction verified: each of the three reproduces on the merged tree
before the change and reddens after it.
The call-site oracle reduced each argument to its trailing attribute, so
`info.job_name`, `args.job_name` and `undefined.job_name` were the same string
to it: a receiver that raises before anything is checkpointed stayed green. It
now compares the unparsed expression, which reddens on all three.

The hook's rc branch publishes on `tar` exit 1 as well as on a readback, but
both runtime arms reached it via the unexpanded `_instances*` glob, which exits
2, so the exit-1 half was never executed and a discard inserted for it alone
kept them green. A third arm populates that glob and grows a log while tar reads
it, which is what makes tar report 1 and is the rc every job producing live logs
actually hits. It asserts the reported rc, so it cannot pass without reaching
the path.
Making the watchdog wait on an event set when the attempt ends introduced one
exit that no longer enforces the bound. The exception handler killed only the
shell leader, and the `finally` then set the event, so a background descendant
that survived the leader was never signalled by anyone: it outlived the attempt
and kept writing. Under the previous blind sleep the watchdog still killpg'd
unconditionally, so this path only opened up with the event.

Now the handler signals the group and reaps the leader, falling back to the
leader alone when the group is gone or not ours. A marker-driven arm covers it:
the descendant writes the marker only if it survived, and a control confirms the
same fragment does outlive an ordinary call, so a missing marker is the kill
rather than a fragment that never ran.
Signalling the group rather than the leader made a stale handle dangerous. The
handle is assigned outside the retry loop, so an attempt that raises before its
own Popen - a failed log-file open - still saw the previous, already-reaped
attempt and SIGKILLed that pid as a process group. A recycled pid there is
unrelated work. It is cleared per attempt now, so such an attempt signals
nothing; a probe of that exact shape recorded the stray killpg before the change
and records none after it.

The rc-1 comments said tar could still be writing, which the group cleanup in
the preceding commit no longer allows. The read-back is still required, because
an internal failure can leave the write cut short, so both now say that instead.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto master (the branch was conflicting) and fixed four things the merge surfaced.

The conflict was one block in ci/praktika/runner.py: master moved the docker image-pull
policy constants into ci/praktika/docker.py, which re-exports them, and deleted the block
this branch had appended ON_ERROR_HOOK_TIMEOUT_SEC to. Kept master's relocation and the
new constant. ci/tests/test_job_image_pull_retry.py imports those three names from
runner, so the re-export has to stay.

Four fixes on top, each measured in both directions:

  • A tar exit of 1 is no longer accepted without reading the archive back. Shell.run
    reports an internal failure of its own as 1 as well, and it killed only the shell leader,
    so tar could still be writing the staging archive that 1 published.
  • Shell.run now kills the process group when it raises. The watchdog is cancelled on the
    way out, so a leader-only kill left a background descendant that nothing would ever
    signal. Under the previous blind sleep the watchdog still killed the group, so this path
    only opened up with the event.
  • The child handle is cleared per attempt. It was assigned outside the retry loop, so an
    attempt that raised before its own Popen sent that group kill to the previous,
    already-reaped attempt's pid.
  • Two wiring tests could not fail: the checkpoint call site was checked by trailing
    attribute name only, and the timeout assertions accepted any positive value while the
    behavioural arms use their own. Both now pin what they claim.

41 tests, and the hook's exit-1 path now runs for real rather than only being read: the
other two runtime arms both reached the rc branch through the unexpanded _instances*
glob, which exits 2.

I did not squash. The branch is over ten commits, but two review threads are anchored to
the current head and a squash would drop nine master commits from the ancestry, so it would
need a force-push where an append works. Happy to squash before merge if you prefer.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ec4dcae

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CI Tests / ci/tests/test_settings_history_source_gate.py::test_renaming_a_record_in_place_is_allowed trunk CI-infra regression, not PR-caused: the gate self-test pins version 26.8 and the 26.9 version bump broke it on every PR #116107 (ours, open)

Session id: cron:our-pr-ci-monitor:20260824-180000

@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Dear @maxknv, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch has not been deployed

No deployments
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-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants