Skip to content

Reap the test process groups the abort path orphans - #113393

Merged
alexey-milovidov merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/reap-orphaned-test-groups-on-abort
Oct 1, 2026
Merged

alexey-milovidov merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/reap-orphaned-test-groups-on-abort

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112911

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

When a stateless run aborts, the report can come back empty: files: [], no server log, no
fatal.log, no test rows. This
Stateless tests (amd_debug, parallel) run
aborted at test 7326/12303 and emitted nothing until the 9000 s job timeout.

Root cause: the parent force-kills its workers on the abort path. A worker killed there sits
inside kill_process_group's own sleep, and SIGKILL runs no finally, so the test process
group survives, holding the inherited stdout, and clickhouse-test | ts | tee never sees EOF.
Nothing can reap it either: run_single_test unlinks its PGID record in the finally around
proc.wait, before process_result_impl reaches kill_process_group. #112265 has since
stopped it from wedging the pipeline; it still outlives the run.

The change keeps the record until the group is gone, checked with killpg(pgid, 0) rather
than inferred from the leader's exit status, and names it <run token>.<worker>.<pgid>, so a
kept record survives that worker's next test and a reap is scoped to one invocation: the
records are repo-wide and a live parent must not signal another invocation's tests. The token
is seeded through a new _CLICKHOUSE_TEST_RUN_TOKEN variable, because a spawn worker
(selected for aarch checks) re-executes the runner and would otherwise mint its own. Reaping
runs in the parent, the only process guaranteed alive there, in a finally around each runner,
so a signal to the parent and a normal finish are covered too. It passes diagnostics=False to
skip what is otherwise paid per group, serially: a 60 s sanitizer wait, a 10 s stacktrace wait,
an unbounded ps.

Verified by killing the server mid-test on a local Debug build: five processes of the group
survive on master, none with this change, exit code unchanged. The original ci/tests guards
went with that suite (#115650); the abort-path contracts (token and worker scoping, spawn
propagation, signal masking, quiesce before the reap) are now pinned by the cluster-less
integration test tests/integration/test_clickhouse_test_abort_reap. This does not explain the server death.


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

Version info

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

A stateless run that aborts can report nothing at all: `files: []`, no server log, no
fatal.log, no test rows. The Stateless tests (amd_debug, parallel) run on
c41e24c aborted at test 7326/12303 and then emitted
nothing for 2 h 17 min until it was killed at the 9000 s ceiling, so the evidence for
the server death was destroyed by the abort that was supposed to report it.

The parent force-kills its workers on the abort path. A worker killed there is inside
kill_process_group's own sleep - the parent's join timeout and that sleep are both 10 s,
so this is structural rather than a rare race - and SIGKILL runs no Python finally, so
the test process group it was killing survives. Nothing can reap it afterwards, because
run_single_test unlinked its PGID record in the finally around proc.wait, which runs
before process_result_impl reaches kill_process_group. cleanup_test_groups locates groups
only through those records, so both it and `clickhouse-test --cleanup` find nothing.
Measured on a local repro: `Process group ... should be killed` is printed 0 times, and
the record is removed 26 s before the abort even begins.

The orphan keeps the stdout it inherited, which in CI is the write end of
`clickhouse-test | ts | tee`, so ts and tee never see EOF and Shell.run's reader threads
never join. The plain stateless path passes no timeout, so the wait runs to the job
ceiling and the SIGKILL lands inside Shell.run, before the log-collection step.

Keep the PGID record until the group is known to be dead, and reap the recorded groups
from the parent - the one process still guaranteed alive there, since it masks SIGTERM -
before every StopTesting on that path, so the graceful global-time-limit and
--max-failures stops are covered too.

The reap passes diagnostics=False, which skips both evidence-gathering delays. They are
independent and behind different flags: 60 s when SANITIZED (true for every sanitizer
job) and 10 s for the client stacktrace. cleanup_test_groups walks records serially, so
skipping only one would add a minute per group on exactly the jobs where this failure is
most frequent, inside the window the job is being timed against. The default stays True,
so the sanitizer report window and the stacktrace dump are preserved everywhere else and
no other caller changes behaviour.

Verified end to end by killing the server mid-test on a local Debug build: five processes
of the test's group survive the runner before this change and none do after, with the
runner's exit code unchanged, so the synthetic "Server died" leaf the job side builds is
unaffected. The new ci/tests guards fail without the change and pass with it.

This fixes no hang and does not explain the server death itself, which is not
attributable from a job whose artifacts were never collected. It makes the next
occurrence arrive with them attached.
Review round 1 on the previous commit. Six gaps, all in tests/clickhouse-test
plus its guard:

1. process_result_impl reached forget_test_process_group only if os.getpgid and
   kill_process_group both returned. Either raises into TestCase.run's generic
   handler, which returns UNKNOWN without setting stop_testing, so the worker
   continues and its next test overwrites the same record path. That leaves a
   live group with nothing pointing at it, which is the defect this change
   exists to remove. The kill is now wrapped: the failure is reported, one last
   SIGKILL is attempted, and the record is dropped in a finally.

   The per-test alarm path needs no reaper of its own: timeout_handler calls
   stop_tests, whose cleanup_child_processes already kills the group. That is
   now stated at the helper rather than left to be re-derived.

2. cleanup_test_groups globbed the repo-wide ci/tmp with no run identity. Safe
   while its only callers were --cleanup at job teardown; called from a live
   parent it could SIGKILL a concurrent invocation's in-flight tests, and
   concurrent invocations over one tree are already a known condition here.
   It takes an optional worker_pids filter, and do_run_tests records its own
   worker pids in a set that is never pruned (unlike processes, which is pruned
   as workers exit, so a worker that died before the abort would be skipped and
   its orphan missed).

3. The reap sat inside the parallel branch, so no abort out of the sequential
   runner reached it. Both call sites now go through one bounded, non-raising
   helper. The sequential runner is the parent, so it passes its own pid too.

4. No test drove do_run_tests, so deleting the reap call left the suite green.
   The new guard runs the real do_run_tests against a worker stub that records
   a real group through the real helpers and then has to be SIGKILLed.

5. diagnostics=False documented itself as skipping the evidence gathering but
   the per-group process listing sat between the two guards, so it still paid
   an unbounded full ps per record - relocated by this change from a worker the
   parent can kill into the parent itself, on the one path with no outer
   timeout. Now gated with the rest.

6. Test hygiene: the shared-directory assumption in the record cleanup is
   stated, and the killpg swap uses monkeypatch like the rest of the file.

Both directions, re-run for this round: all 7 tests fail on the base commit and
pass with the change. Four mutation arms, each removing one behaviour from the
fixed source, each reddening only the test that owns it.

The mutation arm for diagnostics=False was vacuous at first and the probe had
to be sharpened: the runner sets SANITIZED and CAPTURE_CLIENT_STACKTRACE False
at import, so in the default shape neither arm pays a delay and the flag gates
nothing. The guard now sets the sanitizer shape for the run, which is what
makes the flag observable.

The poll loops no longer call the /proc-wide walk once per iteration, only for
verdicts. Note that walking the leader's children file instead is not a valid
substitute: when the leader dies first its children are reparented out of that
tree, so the walk reports an empty group while live members still hold the
inherited fd, which is exactly the state these tests exist to catch.
The previous round removed the PGID record on two paths that do not establish
what the record's own contract requires.

The first is `proc.returncode is not None`. With `start_new_session=True` the
leader's pid is the pgid, and its members can outlive it: `Popen("sleep 30 &
exit 0", ...)` leaves `returncode=0` while `killpg(pgid, 0)` still succeeds and
/proc lists a live member in that group. So any .sh test that backgrounds
something and returns dropped the only pointer to a live group.

The second is a `BaseException` unwinding through the `finally`. The runner's
own `Terminated` is a `KeyboardInterrupt`, so it is not an `Exception` and is
not caught, but the `finally` still runs. The parent's `terminate()` on the
abort path delivers exactly that SIGTERM, and it can land inside
`kill_process_group`'s SIGTSTP wait.

Both leave a group that holds the runner's inherited stdout, which is the wedge
this change exists to prevent, and nothing else recovers them:
`cleanup_child_processes` signals the pgid of each direct child, so a group
whose leader has exited is invisible to it, and the `--cleanup` post-hook is
registered on Fast test only.

Removal is now gated on one `killpg(pgid, 0)`. It is pessimistic on EPERM and
on an unreaped zombie, which is the safe direction: a record that survives one
extra test is consumed by the abort-path reap or by `--cleanup`, whereas a
dropped record is unrecoverable. The leader is reaped with a bounded wait first,
because `proc.wait(args.timeout)` timed out without reaping it and a zombie
satisfies `killpg` indefinitely, which would otherwise leak a record on every
timed-out test.

Two oracles cover the gap that let this through: the stub returned
`returncode=None` unconditionally, so the branch was exercised in neither
direction and a mutation deleting its removal would have reddened nothing.
A record that process_result_impl correctly keeps for a live group was not
durable. test_process_group_record() was named for the WORKER, one path for
every test that worker runs, and write_text_atomic ends in os.replace, so the
retention lasted only until the worker's next run_single_test: the pgid was
gone from disk within seconds and the group was unreachable again while still
holding the runner's inherited stdout. Measured on the previous head: after a
second launch the only record on disk names the second group while the first
is still alive.

The record is now keyed on the pgid as well as the worker pid. The worker pid
stays in the name because it is what scopes a reap to one invocation's own
records, so cleanup_test_groups' parse had to stop reading the LAST dot field,
which is now the pgid; with the old parse the scoping rejects every record and
four of the guards redden.

The reap itself ran only inside the stop_testing branch, and the parallel block
had no enclosing try. signal_handler raises Terminated from wherever the parent
happens to be, so a signal anywhere else in that loop unwound past every reap
site to the top-level handler, leaving the group alive with the job's stdout. A
worker that simply finishes while holding a retained record had no reap site on
its path either. Wrapping the block in try/finally makes the reap unconditional
rather than one branch's responsibility. The in-branch call is kept: it must run
before the StopTesting raise, while the parent is masked against SIGTERM, and a
second pass is a no-op because each record is unlinked in its own finally.

Two guards cover this: one drives the real run_single_test and
process_result_impl over a leaderless group and then a real second launch, and
asserts the first group is alive, its record is on disk, and cleanup_test_groups
still kills it; the other signals the parent instead of setting stop_testing and
asserts the group is dead. Each reddens only under the mutation that deletes its
own behaviour. A legacy two-field record written by an older runner still parses
and is still reaped, and --cleanup with no arguments is unchanged.

Also fixes two defects in the test helper it extends: the queue it uses leaked a
feeder thread, so a later fork warned about deadlocks, and in the signalling
shape nothing reaped the workers, which hung the file for an hour.
The reap this PR added to process_result_impl's finally is not
observation-only. Popen.wait's _wait calls _handle_exitstatus, which
assigns self.returncode, and the same proc object is re-read about 140
lines below to choose the failure reason. So every timed-out test was
reported as EXIT_CODE instead of TIMEOUT, and whenever the stderr the
classifier reads carried a " <Fatal> " line - ordinary on a sanitizer
build, where the client's fatal log is appended to that same file - the
reason escalated to SERVER_DIED, which calls stop_tests and raises
StopTesting. One timed-out test could therefore abort a whole 12000-test
run, which is the damage class this change exists to prevent. Timeout and
return code are also distinct buckets in TEST_FAILURE_PATTERNS, so every
future timeout would have been mis-triaged in the CI database.

Snapshot the decision once, next to the existing pgid local, and classify
from the snapshot. Measured on the real function with a real Popen, no
wait stub: before, EXIT_CODE with returncode -15, and SERVER_DIED on the
fatal arm; after, TIMEOUT on both arms, matching the merge-base, with the
group still fully dead. The wait itself is kept: removal is gated on
killpg(pgid, 0), an unreaped zombie leader still answers that probe, and
without the reap two existing tests fail because the record outlives the
group on the normal timeout path.

Add the oracles that pin the reason. The one existing arm that asserted
TIMEOUT drove a SimpleNamespace whose wait was a plain attribute, which
cannot mutate returncode, so it was blind to this by construction. The
new tests hand a real Popen straight to process_result_impl and assert
the precondition that the leader is still unreaped.

Scope the reap to the invocation rather than to a pid. worker_pids holds
bare numbers and is deliberately never pruned, the records live in the
repo-wide ci/tmp that concurrent invocations over one tree share, and
pid_max is finite, so a retired worker's pid recycled into a concurrent
run's worker would have put that run's live tests in this run's sweep.
Records now carry a token minted once per invocation; workers are forked,
so they inherit it (measured). The --cleanup path keeps matching every
record shape, including ones written before this change, because it is an
orphan sweep that runs when nothing else is live.

Mask SIGTERM across the two new outer reaps, as the abort block above
already does. The reap catches Exception, and the runner's own Terminated
is a KeyboardInterrupt, so a signal landing in the finally would have
replaced an in-flight StopTesting and the job side would have read 143
instead of the exit code it parses. Widening the catch to BaseException
was rejected: it would swallow a genuine Terminated.

Also fix the two documentation snippets, which called both helpers with
no pgid and would have raised TypeError if copied.
The sentence added for the --cleanup shape-agnostic note used an em-dash,
which is not allowed in ClickHouse contributions.
The token that scopes the abort-path reap to one invocation was minted in the
module body, which makes it invocation-wide only under fork. __main__ selects
the spawn start method whenever CHECK_NAME contains aarch, and a spawned worker
re-executes the runner as __mp_main__ and minted its own token. Every record it
wrote therefore failed cleanup_test_groups' token comparison, and the
parent-side reap walked past all of them: an orphaned test group survived the
abort and kept holding the job's stdout, which is the wedge this whole change
exists to close. Measured on a real spawned worker before the fix, the group
survived the reap (alive=[3652939, 3652940, 3652941]) while the fork arm was
reaped correctly, and the sequential shape, whose record the parent writes
itself, was also correct - so the defect was specific to a worker-written
record under spawn. Live carrier: Bugfix validation (functional tests,
aarch64), which runs clickhouse-test --jobs <nproc> down the parallel path.

Seed the token through the environment instead, which both start methods
propagate. A nested invocation must not adopt an outer run's token, or its
sweep would match the outer run's in-flight records, so a top-level invocation
re-mints. The guard keys on __name__ rather than on the pid prefix alone: a
spawned worker also sees a foreign prefix, because the token it inherited was
minted by its parent, and it must keep what it inherited. Only __main__
distinguishes the two, since a spawn child re-executes the module as
__mp_main__.

cleanup_test_groups' matching rule is unchanged. The defect was the token's
lifetime, not the comparison, and loosening the comparison to a pid-only match
would reintroduce the recycled-pid hazard that
test_a_recycled_worker_pid_does_not_widen_the_reap forbids. The --cleanup
orphan sweep stays shape-agnostic and still consumes a foreign-token record.

Two arms cover this. The existing scoping arms build their foreign record from a
hand-written string, which pins the matching rule while never asserting that a
real worker's record can satisfy it, which is why 17 of 17 passed against a
contract that was void on aarch. The new spawn arm has a real spawn child write
the record through the real helpers, obtaining its token the way a worker does
rather than being handed it, and judges group liveness. The nested arm drives a
real subprocess with the variable pre-set. Verified by mutation: reverting the
token to a per-process mint reddens the spawn arm, dropping the re-mint reddens
the nested arm, and loosening the comparison reddens the recycled-pid arm.
Running the new arm under fork, or handing the token to the child, leaves it
green on unfixed code, which is what makes the chosen shape load-bearing.
The reap catches `except Exception`, and the runner's own `Terminated` is a
`KeyboardInterrupt`, so a signal arriving inside it is not caught: raised from a
`finally` it replaces the exception unwinding through it, and the job side then
reads 128+signal / "terminated unexpectedly" instead of the exit code it parses.

`__main__` routes SIGTERM, SIGINT and SIGHUP to that handler, but the reap was
guarded against SIGTERM alone - the two masks added with the new call sites
mirrored the pre-existing abort-block one, which is itself SIGTERM-only. So the
"reap on every exit" invariant held for one of the three signals. praktika only
ever sends SIGTERM then SIGKILL, and the runner has no controlling terminal
(`start_new_session=True`), so CI is not affected today; a developer pressing
Ctrl+C during the reap is, and loses the test group holding their terminal.

Mask inside `reap_recorded_test_groups` instead of at the call sites, so a site
added later cannot miss the guard, and drop the two masks this branch added.
The pre-existing mask at the abort block stays: it spans the whole terminate /
join / kill sequence, not just the reap, because a worker's `stop_tests()`
broadcasts SIGTERM to the group and would otherwise reach the parent mid-join.
Nesting is harmless - the function restores whatever disposition it found.

The existing arm asserting a real signal delivered from inside the reap gains a
second parametrisation axis over the three signals. Removing any one of them
from the mask reddens exactly that signal's two arms.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (7 rounds, final round clean)

Before opening this, the change went through an internal review pipeline: an
independent reviewer reads the resulting code cold, a second model re-reviews the
full scope, and every finding is adjudicated against recorded evidence. Seven
rounds; the last one found nothing in the code. The ledger below keeps the whole
history, because what the earlier rounds caught is the useful part.

Round 7 (final) - clean

The second-model pass returned no findings. My own cold pass found no blocker
and no major either. Two things I checked and recorded rather than changed:

  • No anti-drift oracle on the handled-signal set. The reap masks
    SIGTERM, SIGINT, SIGHUP, which is exactly the set __main__ routes to
    signal_handler (verified by parsing the file, not by reading it). The test
    repeats those three as a literal, so a fourth signal registered later would
    silently un-cover the reap with all 23 arms still green. That is the same drift
    class round 6 caught, so it is worth a follow-up arm; it is not a defect today.
  • Comment budget. 41 added comment lines against 99 added code lines,
    measured whitespace-insensitively so the block that merely moved into a try
    does not inflate the count. Within budget, nothing trimmed.

Round 6 - the reap was guarded against SIGTERM only, but the runner handles three signals

AGREE, on a corrected premise.

reap_recorded_test_groups catches Exception, and the runner's own Terminated
is a KeyboardInterrupt (Terminated.__mro__ is
['Terminated', 'KeyboardInterrupt', 'BaseException'],
issubclass(Terminated, Exception) is False), so a signal landing inside the
reap unwinds past it and the top level exits 128 + signal with the test group
still alive. That is why the reap sites are wrapped in a SIG_IGN mask at all.
signal_handler is installed for SIGTERM, SIGINT and SIGHUP, but all three
masks covered SIGTERM alone: the two this change added were written to mirror
the pre-existing abort-block mask, which is itself SIGTERM-only.

The premise correction: the finding as first written implies CI can still wedge
this way, and I measured that it cannot. The signal census over ci/praktika/
and ci/jobs/ is SIGKILL 8, SIGTERM 7, SIGTRAP 1 and zero SIGINT or
SIGHUP sends; the timeout net is SIGTERM then SIGKILL; and the runner is
started with start_new_session=True, so it has no controlling terminal and can
receive neither a terminal SIGINT nor a hangup. What is genuinely wrong is
narrower: the change states "reap on every exit" and guarded one of the three
signals it handles, and a developer pressing Ctrl+C during the reap does leak the
group. Recorded that way rather than as a flat agreement, because conceding a CI
hole I had measured not to exist would have been wrong.

Fixed by moving the mask into reap_recorded_test_groups itself, covering all
three signals and restoring each, and dropping the two call-site masks this change
had added. The pre-existing abort-block mask stays: it also covers the worker
terminate/join/kill sequence, which a worker's own SIGTERM broadcast would
otherwise interrupt. The signal-inside-the-reap test is now parametrised over reap
site and signal, giving six arms, and each signal has its own mutation cell:
dropping one from the mask reddens exactly that signal's two arms.

Round 5 - the reap was a no-op on every aarch check

The token that scopes a reap to one invocation was minted in the module body.
That is invocation-wide under fork only, and __main__ selects spawn whenever
CHECK_NAME contains aarch. A spawned worker re-executes the runner as
__mp_main__ and minted its own token, so every record it wrote failed the token
comparison and the reap did nothing on that whole configuration, with
Bugfix validation (functional tests, aarch64) as a live carrier.

Closed by seeding the token through the environment, which both start methods
propagate. Confirmed from CPython source rather than by re-running a probe:
multiprocessing/util.py passes no env to fork_exec, so a spawn child
inherits the environment, and multiprocessing/spawn.py re-executes the module as
__mp_main__, where os.environ.setdefault returns the inherited value. The
__main__ guard is the right discriminator and is not replaceable by a
pid-prefix test alone: a spawned child also sees a foreign prefix, because its
parent minted the token, and must keep what it inherited.

Worth noting why sixteen earlier arms all passed against a contract that was void
on aarch: both scoping arms built their foreign record from a hand-written
string, which pins the matching rule while never asserting that a real worker's
record can satisfy it. The two arms added here have a real spawned child write the
record through the real helpers and obtain its token the way a worker does.

Nits, adjudicated and either fixed or recorded

  • A test docstring said the nested-invocation subprocess "exits early for want of
    a server". True in the CI Tests job, where the binary is on PATH; anywhere
    else the exit is earlier, inside find_binary via argparse's type=, before
    main. Corrected. The assertion was unaffected, but the wording would send the
    next debugger hunting a connection failure that never happens.
  • The PR body did not mention the new _CLICKHOUSE_TEST_RUN_TOKEN variable,
    which reaches every .sh test through the inherited environment. Fixed at
    body-freeze.
  • The process-management doc rendered the token but was not greppable for the
    variable name. Fixed.
  • Five countable claims in the pre-PR validation gate comment were stale against
    the final tree (an arm count that predated round 6, and four smaller
    enumerations). Re-derived each from the source and corrected them, and dropped
    one clause that claimed an arm which does not exist: the malformed-record-name
    branch is handled by except ValueError: continue but no test constructs such a
    name, so it rests on inspection rather than on an oracle. Saying so is more
    useful than implying coverage that is not there.

Verified, no finding

  • write_text_atomic's temp sibling is name + ".tmp", not Path.with_suffix.
    With the four-field record name the latter would have produced
    ...<worker>.tmp and the .tmp skip would have stopped catching partial
    writes.
  • The test_-prefixed module-level helpers in tests/clickhouse-test cannot be
    collected by pytest: the runner is outside the collected tree, has no .py
    extension, and is loaded via runpy into a local dict.
  • --cleanup stays shape-agnostic, so a legacy-shape or foreign-token orphan is
    still swept. Both out-of-tree callers (fast_test's finally and its
    post-hook) pass no worker scope, so neither is affected by the record rename.
  • The timeout classification cannot be perturbed by the reap: the decision is
    snapshotted before the group is touched, and the bounded wait that sets
    returncode sits inside the timeout branch, so the exit-code branch can never
    see it.
  • No threads anywhere in the runner, so masking signals from the reap is
    main-thread-only by construction rather than by assumption.

One earlier acceptance criterion (delete proc.wait(1)) was withdrawn by the
reviewer who wrote it and stays withdrawn: an unreaped zombie leader still answers
killpg(pgid, 0), so removing the reap would make a killed group read as alive
and redden two oracles this change itself adds.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, not a rate. clickhouse-test --queries ci/tests --hung-check --capture-client-stacktrace --stress-tests --jobs 1 <long-lived fixture> against a local Debug server, SIGKILLing the server while the test is in flight. Reproduced the job's own signature verbatim (Hung check failed -> Unable to locate any ClickHouse server process -> Force killing process Process-3). Twenty-three unit oracles in ci/tests/ reproduce it with no server at all. The spawn half is deterministic rather than a rate: a probe driving the real reap over a record written by a real spawned worker leaves the group alive every run (ORPHAN_SURVIVED=True alive=[3652939, 3652940, 3652941]) while the fork arm is reaped, because the token mismatch is structural.
b Root cause explained? Yes. The parent force-kills its workers on the abort path; a worker killed there is inside kill_process_group's own sleep and SIGKILL runs no finally, so the group it was killing survives. Nothing can reap it, because run_single_test unlinks its PGID record in the finally around proc.wait, which runs before process_result_impl reaches kill_process_group. The survivor holds the inherited stdout, so clickhouse-test | ts | tee never sees EOF and the job is killed at its ceiling before log collection. Each step measured, not inferred: Process group ... should be killed printed 0 times, and the 0.5 s sampler shows the record removed 26 s before the abort began. A second, independent reason the reap could find nothing: the token that scopes it to one invocation was minted in the module body, which is invocation-wide only under fork, and __main__ selects spawn whenever CHECK_NAME contains aarch. A spawned worker re-executes the runner as __mp_main__ and minted its own token, so every record it wrote failed the token comparison and the reap was a no-op on that whole configuration (live carrier: Bugfix validation (functional tests, aarch64), which runs --jobs <nproc>).
c Fix matches root cause? Yes. It keeps the record for as long as the group may still be live, dropping it only once one killpg(pgid, 0) shows the group is gone rather than inferring that from the leader's exit status, and gives the abort path a reaper that survives the workers. No widened bound, no no-random-* tag, no reduced dataset, no silenced check: the hung check here is a true positive (the server really was gone) and is untouched, as is the test that was merely in flight when it fired. The spawn half likewise corrects the token's LIFETIME, seeding it through the environment because both start methods propagate that, rather than loosening the comparison that reads it. Loosening it to a pid-only match would reintroduce the recycled-pid hazard, and a mutation arm forbids exactly that.
d Test intent preserved / new tests added? Yes. No existing test weakened; one was strengthened (its spy now performs the real kill, with a new precondition pinning that the group is empty, instead of relaxing its assertion to fit the new contract). One new file, eighteen test functions collecting twenty-three arms (one function is parametrised over reap site x signal). Two of those functions close a blind spot the other sixteen shared, since both pre-existing scoping oracles build their foreign record from a hand-written string, which pins the matching RULE while never asserting that a real worker's record can satisfy it, which is why all sixteen passed against a contract that was void on aarch. The new pair has a real spawned child write the record through the real helpers and obtain its token the way a worker does, never by being handed it. The diagnostics default stays True, so the sanitizer report window, the client-stacktrace dump and the per-group process listing are preserved everywhere except the abort-path reap, and one oracle asserts BOTH directions of that so the change cannot silently delete the evidence path the delays exist for.
e Both directions demonstrated? Yes, and re-measured for every review round. End to end: five processes of the test's group survive the runner on master, none with the fix, exit code 2 in both arms. Unit: every oracle passes with the fix and fails without it, on behaviour rather than on a missing API. The classification is measured on the real function with a real Popen and no wait stub: EXIT_CODE with returncode -15, and SERVER_DIED when the stderr carries a fatal line, before; TIMEOUT on both arms after, identical to the merge-base, with the group still fully dead. Plus one mutation arm per shipped decision, each deleting exactly one of them and reddening only the oracle that owns it, including a separate arm per reap site since one arm can only pin one finally, and one arm per signal the runner handles: dropping SIGTERM, SIGINT or SIGHUP from the mask reddens exactly that signal's two arms and nothing else, and reverting the mask entirely reddens all six; every restore verified byte-identical by md5sum. The scope key has its own three mutants: reverting the token to a per-process mint reddens the spawn oracle, dropping the top-level re-mint reddens the nested-invocation oracle, and dropping the token comparison reddens the recycled-pid one. Two further mutants test those ORACLES rather than the code, because a mutant that only ever reddens shows an oracle fires, not that its power comes from the property it names: running the new oracle under fork instead of spawn, and handing the token to the child, each leave it green on unfixed source.
f Fix is general across code paths? Yes. The reap is a finally around the parallel runner and a finally around the sequential one, so it covers every exit of either: the hung-check path that produced this report, the graceful global-time-limit stop, the --max-failures stop, a signal delivered to the parent, and a normal finish. Both go through one helper so they cannot drift. Every caller of the two renamed record helpers was updated by enumeration, including cleanup_test_groups, the sole reader of the record name. There are three kill_process_group call sites in all; the two this change does not touch (cleanup_child_processes and the timeout kill in process_result_impl) keep the default diagnostics=True, verified by enumeration, so neither changes behaviour. The timeout decision is read exactly once and every later use goes through that snapshot: grep -n "proc\.returncode" tests/clickhouse-test gives three sites, the one that snapshots the timeout and two on the already-exited path, so no sibling read is left able to see a value the reap changed. The mask is inside reap_recorded_test_groups rather than at the call sites, so all three reap sites, and any added later, are covered by construction; it spans all three signals __main__ routes to signal_handler, enumerated by grep rather than mirrored from the pre-existing mask. The token is read at exactly two sites, test_process_group_record and cleanup_test_groups, and both now see the invocation-wide value; reap_recorded_test_groups is the only other caller and delegates. --cleanup's shape-agnostic path is untouched and re-measured to still consume a foreign-token record.
g Fix generalizes across inputs (params/datatypes/wrappers)? The inputs here are process states, not value types. Covered: group alive vs already exited (the existing ESRCH/EPERM handling is untouched), zero records vs many (a missing record is a no-op), a foreign record naming a pid this run never started, a kill that raises, a T-state member (measured: SIGKILL does kill it), a leader that exited while a member lives, and a zombie-only group (measured: a zombie satisfies killpg(pgid, 0) indefinitely, so the leader is reaped first with a bounded wait before the group is judged). The settings matrix is SANITIZED x CAPTURE_CLIENT_STACKTRACE x diagnostics; the asan/msan/tsan corner (both flags true) is pinned in both diagnostics directions. The record NAME is also an input now that it carries three fields, and the parse is exercised by an arm over each shape it can meet in practice: this run's own, both historical shapes written by an older runner, and a foreign token whose worker pid collides with one of ours. It matches only the first and skips the rest rather than raising. The malformed shapes a ValueError would catch (a non-integer worker field, a truncated name) are handled by the same except ValueError: continue, but no arm constructs one, so that branch rests on inspection rather than on an oracle. The reason classification is covered for a plain stderr and for one carrying a fatal line, the arm that decides whether the whole run is torn down. The start method is an input too, and the matrix is method x nesting: fork top level, spawn top level, a nested invocation under either (which must re-mint, or its sweep would match the outer run's live records), and a worker under either (which must NOT re-mint but keep what it inherited). That last cell is why the guard keys on __main__ rather than on the pid prefix alone: a spawned worker also sees a foreign prefix, because the token it inherited was minted by its parent, so a prefix-only test would have made every worker re-mint and left the defect in place.
h Backward compatible? Yes. CI-only, no user-visible behaviour, no setting default and no serialization format, so no SettingsChangesHistory.cpp entry and no versioning. All three new parameters are keyword-with-default, so every existing caller is unchanged, and the --cleanup CLI contract is byte-identical: it passes no worker_pids, so it stays the repo-wide orphan sweep it was. kill_process_group's default-path output is unchanged, which is what the stress-job parser reads. The one compatibility surface is the record file name, now <token>.<worker>.<pgid>: the glob is unchanged and both readers were verified against it, and --cleanup deliberately matches every shape, including both names an older runner could have written, so a mixed-version ci/tmp is safe and no pre-existing orphan is stranded. An oracle asserts that explicitly rather than leaving it to inspection. The token is now also passed to workers through an environment variable; it is namespaced with a leading underscore, collides with nothing else in tests/ or ci/, and os.environ.setdefault on a variable is the established idiom in this file (six existing uses). It reaches .sh tests because tests_env is an unfiltered copy, harmlessly: no stateless test inspects the whole environment.
i Invariants and contracts preserved? Yes. The record's invariant is one-directional: kept whenever the group MAY be live, removed only when it provably is not, so the failure mode is a harmless extra record rather than an orphan nothing can find. That holds on every path out of process_result_impl, including a BaseException such as the runner's own Terminated, which is a KeyboardInterrupt and so is not caught by except Exception while still running the finally; it still propagates, so the worker's except KeyboardInterrupt contract is intact. A double unlink is harmless. A record is named for the group as well as the worker, so one that is kept because the group may still be live is no longer overwritten by that worker's next test; a residual leak is one small file per surviving group and --cleanup clears it. The reap cannot kill a group still in use: it is scoped by a token that identifies the invocation, not by a pid the OS may recycle into a concurrent run's worker, so it cannot reach another invocation's live tests even when the pids collide; and by the time either finally runs this run's own workers are joined or dead. That token is genuinely invocation-wide under both start methods because it is seeded through the environment, and the one invariant this adds, that only a top-level invocation may re-mint it, is pinned by an oracle and by a mutation arm: without it a nested run would inherit the outer token and sweep the outer run's in-flight records, which is the signal-a-stranger hazard the scoping exists to prevent. It is idempotent, so the in-branch call plus the finally is a no-op second pass. It cannot replace the StopTesting either: it swallows Exception, and every signal the runner handles (SIGTERM, SIGINT, SIGHUP) is ignored for the duration of the reap inside the function itself, each previous disposition restored in a finally, because the runner's own Terminated is a KeyboardInterrupt and would otherwise be raised inside that block and replace the exception the job side keys on. Restoring what was found, rather than a default, is what makes nesting inside the pre-existing abort-block mask harmless. The catch was deliberately not widened to BaseException, which would swallow a genuine Terminated. Reporting is invariant too: the failure reason is decided from a state snapshotted before the group is touched, so reaping the leader can no longer turn a timeout into an exit code or, on a sanitizer build whose fatal log lands in the same stderr, into a SERVER_DIED that aborts the entire run.

Session id: cron:clickhouse-impl-slot-6:20260804-185300

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @leshikus @maxknv, could you review this? On the abort path the parent force-kills a worker that is inside kill_process_group, so SIGKILL runs no finally and the test process group survives holding the inherited stdout, which keeps clickhouse-test | ts | tee from ever seeing EOF; and nothing could reap it, because run_single_test unlinked the PGID record in the finally around proc.wait, before process_result_impl reaches the kill. This keeps the record until one killpg(pgid, 0) shows the group is gone, scopes a reap to one invocation, and reaps from the parent on every exit of both runners.

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

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c4eea1c]

Summary: ✅


AI Review

Summary

This PR hardens tests/clickhouse-test process-group cleanup by retaining per-group records until the group is actually gone, scoping live-run reaps by run token and worker pid, and restoring executable coverage for the load-bearing abort-path contracts in a cluster-less integration module. After checking the current code and reconciling it against the prior discussion, I did not find a remaining correctness or coverage gap that warrants a new review comment.

Final Verdict

✅ No new blockers or major issues found in the current revision.

LLVM Coverage Report

Measured on commit c4eea1c.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Uncovered code analysis did not run: No coverable C/C++ source files changed (contrib/ is excluded from coverage).

Newly covered: +158 lines in 47 files (-124 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 5, 2026
Comment thread tests/clickhouse-test Resolved
The reap walks the record directory once, so it is only complete when no
worker can still add a record. The `finally` added for the abort path ran
that walk while every worker was still live, so a sibling could write its
next `<token>.<worker>.<pgid>` after the walk had passed the directory.
Nothing walks again, so that group survived holding the runner's stdout,
which is the failure this whole path exists to prevent.

Measured on the unfixed runner, instrumenting the worker's write and the
parent's glob separately: the walk saw one record while two worker pids
were in scope, and the second group was still alive afterwards with its
record still on disk. It is the record's absence at walk time, not the
scope, that leaks the group.

The `stop_testing` branch already had the right sequence and documented
the reason ("Safe only here: every worker is joined, and the parent is
the last process still alive"). That sequence is now a helper used by
both sites, so the precondition holds wherever the reap runs. The scope
stays `worker_pids` - this does not widen the sweep.

`processes` is bound before the `try`, because an exception between the
`try` and the worker loop (`multiprocessing.Value`, `Manager`, or a
signal) otherwise made the teardown raise `UnboundLocalError` and replace
the real cause.

Reported by the AI reviewer on the PR, which named the mechanism and the
reproduction. Its trigger (a signal to the parent alone) is developer
local rather than a CI shape: praktika signals the whole process group
(`os.killpg`, ci/praktika/utils.py:291 and :309) and the one
pid-targeted helper has no callers. The same `finally` is reachable in
CI with no signal at all, through an exception out of the poll loop's
liveness, memory or lldb helpers.

The new guard asserts the liveness invariant rather than a surviving
group, so it is deterministic in both directions; whether a given
interleaving actually loses a record is a race. Mutation-checked: the
outer quiesce, the reap itself and the `processes` hoist each redden a
distinct arm and nothing else.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in e27f594.

I reproduced your case 3/3 with the fixture unchanged, then instrumented the worker's
write_text_atomic and the parent's record walk separately to establish the ordering,
because whether the record was missing at walk time or merely out of scope decides whether
this is a runner defect or a fixture race. It is the former:

WROTE_END   worker 3254256
WROTE_BEGIN worker 3254265
GLOB_SAW    n=1  scope=[3254256, 3254265]   <-- the walk ran inside the second write
WROTE_END   worker 3254265
leftover: ...3254265.3254274   alive: [3254274, 3254285, 3254286]

The second worker's pid was in scope, so the sweep was scoped correctly; the record simply
did not exist yet, and nothing walks again. Two of four runs interleaved that way.

The stop_testing branch already had the right sequence and stated the reason ("Safe only
here: every worker is joined, and the parent is the last process still alive"). The outer
finally satisfied neither clause, so that sequence is now a helper used by both sites.
Scope stays worker_pids, so this is not a widened sweep. I also had to bind processes
before the try: an exception between the try and the worker loop otherwise made the
teardown raise UnboundLocalError and replace the real cause.

One correction to the framing, since it affects how the risk reads. A signal reaching the
parent alone is a developer-local shape rather than a CI one: praktika's timeout net is
os.killpg on the whole group (ci/praktika/utils.py:291 and :309), send_signal
prefers killpg (:1166), and terminate_process, the one pid-targeted helper (:531),
has no callers under ci/. The defect is real without that trigger, which is why it is
worth fixing: the try opens before the pool is built, so its finally also runs while
while processes: is still iterating, reachable through an exception out of the poll loop's
own liveness, memory or lldb helpers, including on the hung-check path this PR came from.

On the new coverage: I did not add your jobs=2 group-survival assertion, because on my
runs it passes on the unfixed runner about half the time. It asserts the liveness invariant
instead, which is deterministic in both directions and is the same precondition the branch
already documented: RED on 733c56d (alive per walk: [[171017, 171016]], two live workers)
and GREEN with the fix, 3/3 each, and RED in the whole-file run with the other 24 passing. A
second arm pins the processes binding. Mutation-checked one per site: dropping the stop
reddens only the liveness arm, dropping the reap reddens the three reap arms, un-hoisting
processes reddens only the pre-pool arm.

I also disagree with one point I want to record rather than leave implicit, since a later
round may raise it: the reap's SIG_IGN window is not something to replay or re-raise
signals out of. Terminated is a KeyboardInterrupt, so replaying it there replaces the
StopTesting the job-side parser keys on, which is a defect this PR closed earlier. That
window is unchanged by this commit anyway, measured over 200 iterations of the
normal-completion shape: median 8.5 us before and after, with a shorter tail.

ci/tests/test_cleanup_test_groups.py::test_cleanup_kills_orphaned_test_process and the
three ruff findings in tests/clickhouse-test are pre-existing: they fail identically with
pristine origin/master:tests/clickhouse-test swapped in, and this PR does not touch either.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Updated pre-PR validation gate for e27f594. The arm counts in rows (a) and (d) changed with the two new oracles (twenty functions collecting twenty-five arms, re-derived from the AST and confirmed by collection); rows (e), (f) and (i) record the new mutants and the single-pass-walk invariant.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, not a rate. clickhouse-test --queries ci/tests --hung-check --capture-client-stacktrace --stress-tests --jobs 1 <long-lived fixture> against a local Debug server, SIGKILLing the server while the test is in flight. Reproduced the job's own signature verbatim (Hung check failed -> Unable to locate any ClickHouse server process -> Force killing process Process-3). Twenty-five unit oracles in ci/tests/ reproduce it with no server at all. The spawn half is deterministic rather than a rate: a probe driving the real reap over a record written by a real spawned worker leaves the group alive every run (ORPHAN_SURVIVED=True alive=[3652939, 3652940, 3652941]) while the fork arm is reaped, because the token mismatch is structural.
b Root cause explained? Yes. The parent force-kills its workers on the abort path; a worker killed there is inside kill_process_group's own sleep and SIGKILL runs no finally, so the group it was killing survives. Nothing can reap it, because run_single_test unlinks its PGID record in the finally around proc.wait, which runs before process_result_impl reaches kill_process_group. The survivor holds the inherited stdout, so clickhouse-test | ts | tee never sees EOF and the job is killed at its ceiling before log collection. Each step measured, not inferred: Process group ... should be killed printed 0 times, and the 0.5 s sampler shows the record removed 26 s before the abort began. A second, independent reason the reap could find nothing: the token that scopes it to one invocation was minted in the module body, which is invocation-wide only under fork, and __main__ selects spawn whenever CHECK_NAME contains aarch. A spawned worker re-executes the runner as __mp_main__ and minted its own token, so every record it wrote failed the token comparison and the reap was a no-op on that whole configuration (live carrier: Bugfix validation (functional tests, aarch64), which runs --jobs <nproc>).
c Fix matches root cause? Yes. It keeps the record for as long as the group may still be live, dropping it only once one killpg(pgid, 0) shows the group is gone rather than inferring that from the leader's exit status, and gives the abort path a reaper that survives the workers. No widened bound, no no-random-* tag, no reduced dataset, no silenced check: the hung check here is a true positive (the server really was gone) and is untouched, as is the test that was merely in flight when it fired. The spawn half likewise corrects the token's LIFETIME, seeding it through the environment because both start methods propagate that, rather than loosening the comparison that reads it. Loosening it to a pid-only match would reintroduce the recycled-pid hazard, and a mutation arm forbids exactly that.
d Test intent preserved / new tests added? Yes. No existing test weakened; one was strengthened (its spy now performs the real kill, with a new precondition pinning that the group is empty, instead of relaxing its assertion to fit the new contract). One new file, twenty test functions collecting twenty-five arms (one function is parametrised over reap site x signal). Two of those functions close a blind spot the other sixteen shared, since both pre-existing scoping oracles build their foreign record from a hand-written string, which pins the matching RULE while never asserting that a real worker's record can satisfy it, which is why all sixteen passed against a contract that was void on aarch. The new pair has a real spawned child write the record through the real helpers and obtain its token the way a worker does, never by being handed it. The diagnostics default stays True, so the sanitizer report window, the client-stacktrace dump and the per-group process listing are preserved everywhere except the abort-path reap, and one oracle asserts BOTH directions of that so the change cannot silently delete the evidence path the delays exist for.
e Both directions demonstrated? Yes, and re-measured for every review round. End to end: five processes of the test's group survive the runner on master, none with the fix, exit code 2 in both arms. Unit: every oracle passes with the fix and fails without it, on behaviour rather than on a missing API. The classification is measured on the real function with a real Popen and no wait stub: EXIT_CODE with returncode -15, and SERVER_DIED when the stderr carries a fatal line, before; TIMEOUT on both arms after, identical to the merge-base, with the group still fully dead. Plus one mutation arm per shipped decision, each deleting exactly one of them and reddening only the oracle that owns it, including a separate arm per reap site since one arm can only pin one finally, and one arm per signal the runner handles: dropping SIGTERM, SIGINT or SIGHUP from the mask reddens exactly that signal's two arms and nothing else, and reverting the mask entirely reddens all six; every restore verified byte-identical by md5sum. The scope key has its own three mutants: reverting the token to a per-process mint reddens the spawn oracle, dropping the top-level re-mint reddens the nested-invocation oracle, and dropping the token comparison reddens the recycled-pid one. Three later mutants cover the quiesce: dropping the worker stop before the outer reap reddens only the liveness oracle, dropping the reap while keeping the stop reddens the three reap oracles, and un-hoisting processes reddens only the pre-pool oracle. Two further mutants test those ORACLES rather than the code, because a mutant that only ever reddens shows an oracle fires, not that its power comes from the property it names: running the new oracle under fork instead of spawn, and handing the token to the child, each leave it green on unfixed source.
f Fix is general across code paths? Yes. The reap is a finally around the parallel runner and a finally around the sequential one, so it covers every exit of either: the hung-check path that produced this report, the graceful global-time-limit stop, the --max-failures stop, a signal delivered to the parent, and a normal finish. Both go through one helper so they cannot drift, and that helper stops the workers before it walks the records, so the precondition the in-branch reap always documented (every worker joined, the parent the last process alive) now holds wherever the reap runs rather than only on the branch that happened to join first. Every caller of the two renamed record helpers was updated by enumeration, including cleanup_test_groups, the sole reader of the record name. There are three kill_process_group call sites in all; the two this change does not touch (cleanup_child_processes and the timeout kill in process_result_impl) keep the default diagnostics=True, verified by enumeration, so neither changes behaviour. The timeout decision is read exactly once and every later use goes through that snapshot: grep -n "proc\.returncode" tests/clickhouse-test gives three sites, the one that snapshots the timeout and two on the already-exited path, so no sibling read is left able to see a value the reap changed. The mask is inside reap_recorded_test_groups rather than at the call sites, so all three reap sites, and any added later, are covered by construction; it spans all three signals __main__ routes to signal_handler, enumerated by grep rather than mirrored from the pre-existing mask. The token is read at exactly two sites, test_process_group_record and cleanup_test_groups, and both now see the invocation-wide value; reap_recorded_test_groups is the only other caller and delegates. --cleanup's shape-agnostic path is untouched and re-measured to still consume a foreign-token record.
g Fix generalizes across inputs (params/datatypes/wrappers)? The inputs here are process states, not value types. Covered: group alive vs already exited (the existing ESRCH/EPERM handling is untouched), zero records vs many (a missing record is a no-op), a foreign record naming a pid this run never started, a kill that raises, a T-state member (measured: SIGKILL does kill it), a leader that exited while a member lives, and a zombie-only group (measured: a zombie satisfies killpg(pgid, 0) indefinitely, so the leader is reaped first with a bounded wait before the group is judged). The settings matrix is SANITIZED x CAPTURE_CLIENT_STACKTRACE x diagnostics; the asan/msan/tsan corner (both flags true) is pinned in both diagnostics directions. The record NAME is also an input now that it carries three fields, and the parse is exercised by an arm over each shape it can meet in practice: this run's own, both historical shapes written by an older runner, and a foreign token whose worker pid collides with one of ours. It matches only the first and skips the rest rather than raising. The malformed shapes a ValueError would catch (a non-integer worker field, a truncated name) are handled by the same except ValueError: continue, but no arm constructs one, so that branch rests on inspection rather than on an oracle. The reason classification is covered for a plain stderr and for one carrying a fatal line, the arm that decides whether the whole run is torn down. The start method is an input too, and the matrix is method x nesting: fork top level, spawn top level, a nested invocation under either (which must re-mint, or its sweep would match the outer run's live records), and a worker under either (which must NOT re-mint but keep what it inherited). That last cell is why the guard keys on __main__ rather than on the pid prefix alone: a spawned worker also sees a foreign prefix, because the token it inherited was minted by its parent, so a prefix-only test would have made every worker re-mint and left the defect in place.
h Backward compatible? Yes. CI-only, no user-visible behaviour, no setting default and no serialization format, so no SettingsChangesHistory.cpp entry and no versioning. All three new parameters are keyword-with-default, so every existing caller is unchanged, and the --cleanup CLI contract is byte-identical: it passes no worker_pids, so it stays the repo-wide orphan sweep it was. kill_process_group's default-path output is unchanged, which is what the stress-job parser reads. The one compatibility surface is the record file name, now <token>.<worker>.<pgid>: the glob is unchanged and both readers were verified against it, and --cleanup deliberately matches every shape, including both names an older runner could have written, so a mixed-version ci/tmp is safe and no pre-existing orphan is stranded. An oracle asserts that explicitly rather than leaving it to inspection. The token is now also passed to workers through an environment variable; it is namespaced with a leading underscore, collides with nothing else in tests/ or ci/, and os.environ.setdefault on a variable is the established idiom in this file (six existing uses). It reaches .sh tests because tests_env is an unfiltered copy, harmlessly: no stateless test inspects the whole environment.
i Invariants and contracts preserved? Yes. The record's invariant is one-directional: kept whenever the group MAY be live, removed only when it provably is not, so the failure mode is a harmless extra record rather than an orphan nothing can find. That holds on every path out of process_result_impl, including a BaseException such as the runner's own Terminated, which is a KeyboardInterrupt and so is not caught by except Exception while still running the finally; it still propagates, so the worker's except KeyboardInterrupt contract is intact. A double unlink is harmless. A record is named for the group as well as the worker, so one that is kept because the group may still be live is no longer overwritten by that worker's next test; a residual leak is one small file per surviving group and --cleanup clears it. The reap cannot kill a group still in use: it is scoped by a token that identifies the invocation, not by a pid the OS may recycle into a concurrent run's worker, so it cannot reach another invocation's live tests even when the pids collide; and by the time either finally runs this run's own workers are joined or dead. That token is genuinely invocation-wide under both start methods because it is seeded through the environment, and the one invariant this adds, that only a top-level invocation may re-mint it, is pinned by an oracle and by a mutation arm: without it a nested run would inherit the outer token and sweep the outer run's in-flight records, which is the signal-a-stranger hazard the scoping exists to prevent. The walk is single-pass, so its completeness rests on no worker being able to add a record while it runs: measured on the unfixed shape, the walk saw one record while two worker pids were in scope and the unseen group survived, so the workers are stopped first and an oracle asserts that liveness directly rather than asserting a surviving group, whose loss on any given interleaving is a race. It is idempotent, so the in-branch call plus the finally is a no-op second pass. It cannot replace the StopTesting either: it swallows Exception, and every signal the runner handles (SIGTERM, SIGINT, SIGHUP) is ignored for the duration of the reap inside the function itself, each previous disposition restored in a finally, because the runner's own Terminated is a KeyboardInterrupt and would otherwise be raised inside that block and replace the exception the job side keys on. Restoring what was found, rather than a default, is what makes nesting inside the pre-existing abort-block mask harmless. The catch was deliberately not widened to BaseException, which would swallow a genuine Terminated. Reporting is invariant too: the failure reason is decided from a state snapshotted before the group is touched, so reaping the leader can no longer turn a timeout into an exit code or, on a sanitizer build whose fatal log lands in the same stderr, into a SERVER_DIED that aborts the entire run.

Session id: cron:clickhouse-impl-slot-6:20260804-185300

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Master landed the stop-cause carrier (try_claim_stop_cause /
raise_stop_from_carrier) across the same lines this branch re-indented when it
wrapped the worker pool in a try/finally. One conflicted file, three hunks, all
in do_run_tests, and no competing fix: the carrier decides which exit code the
run reports, the reap decides which process groups are killed first.

Resolution takes master's text at this branch's indentation, and drops this
branch's local global_time_limit_reached flag plus its stop_exit_code.value
ladder. Both were a single-process re-implementation of "remember why the run
stopped"; the carrier does it across processes, which the local flag could not,
since a worker's StopTesting never reaches the parent. GLOBAL_TIME_LIMIT and
MAX_FAILURES still surface, now through the worker-side claims and
raise_stop_from_carrier. Master's claim-based guard also replaces the racy
`not stop_testing.is_set()` pre-check that the local flag needed.

The merged abort sequence was verified rather than assumed: claim, collect
stacktraces, stop the workers and reap their recorded groups, then classify. The
reap cannot remove a process the trace collection needs, because
print_c_stacktraces resolves server pids via get_all_server_pids, which is
deliberately not pgid-scoped, while the reap only kills pgids read from
clickhouse_test_group_pid records, that is test groups.

Master also deleted ci/tests/test_cleanup_test_groups.py, untouched by this
branch; the deletion is accepted as master's.

Both test files still fail when they should: 25/25 and 14/14 green on the merged
tree, and one mutant per guard site reddens a distinct arm (dropping the outer
reap fails 2, restoring the unconditional record drop fails 1, binding
`processes` late fails 1). The three ruff findings on tests/clickhouse-test are
present identically on pristine master.
Three comments still described the pre-token record format: that a worker's next
test overwrites the same record path because it is named for the worker's pid,
and that records carry no run identity. Records are named
clickhouse_test_group_pid.<token>.<worker>.<pgid>, so each group has its own
record and the token IS the run identity the scoping test asserts.

Comments and one assertion message only.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to clear the conflict (c10622ab5, appended, nothing force-pushed).

Master had landed the stop-cause carrier (try_claim_stop_cause / raise_stop_from_carrier)
across the same lines this branch re-indented when it wrapped the worker pool in a
try/finally. One conflicted file, three hunks, all in do_run_tests. I took master's text
at this branch's indentation and deleted this branch's own global_time_limit_reached flag
plus its stop_exit_code.value ladder: both were a single-process re-implementation of
"remember why the run stopped", and the carrier does it across processes, which the local
flag could not, since a worker's StopTesting never reaches the parent. Master's atomic
claim also replaces the racy not stop_testing.is_set() pre-check the flag needed.

Ordering, since reaping and stacktrace collection now meet on the same path: verified as
claim, collect stacktraces, stop the workers and reap their groups, then classify. The reap
cannot take a process the trace collection needs, because print_c_stacktraces resolves
server pids through get_all_server_pids, which is deliberately not pgid-scoped, while the
reap only kills pgids read from clickhouse_test_group_pid records, that is test groups.

Master also deleted ci/tests/test_cleanup_test_groups.py, which this branch never touched;
the deletion is accepted as master's.

Both test files still fail when they should, which is the part a rebase can silently break:
39 of 39 pass on the merged tree, and one mutant per guard site reddens a distinct arm
(dropping the outer reap fails 2, restoring the unconditional record drop fails 1, binding
processes late fails 1). The three ruff findings on tests/clickhouse-test are present
identically on pristine master.

One follow-up in the same push: three test comments still described the pre-token record
format, saying a worker's next test overwrites the same record and that records carry no run
identity. Records are clickhouse_test_group_pid.<token>.<worker>.<pgid>, so each group has
its own record and the token is the run identity the scoping test asserts. Comments only.

The branch now carries 11 commits, so it wants a squash before the next review pass. I left
it unsquashed here because that would turn an append into a force push over a branch with a
live review comment, for no reviewer benefit in a rebase-only round.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 697880944 with master 400ba9d99 (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 704.52 MiB 701.50 MiB -3.02 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

…uite

Two independent failures of this PR's own `CI Tests` job, both in test fixtures.

`process_result_impl` now reads the pgid on every arm, not only on the timeout
one: the record cleanup added here drops a record once the group is gone, which
is a decision the normal-exit path has to make too. `_FailedProc` stands in for
the declared `Optional[Popen]` and carried only a `returncode`, so four
pre-existing classification tests raised AttributeError. Completing the stub
keeps the runner's contract as it is; narrowing the read back was measured not
to help, because those four take the normal-exit branch that needs the pgid.
Its pid is our own, so the group is alive and the cleanup is a no-op there.

The nested-invocation arm drove `clickhouse-test` with a bare argv on the
assumption that it exits early for want of a binary or a server. This job
supplies both, so it started a whole test run instead and was killed at the
subprocess timeout. `--help` returns from `parse_args`, which is still after the
module body that mints the run token, so the arm asserts what it asserted
before: with the re-mint guard disabled it fails either way, with or without a
binary on PATH.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI Tests failed on c10622ab5 for two independent reasons, both in test fixtures rather
than in the runner. Fixed in 697880944.

Four pre-existing arms in ci/tests/test_hung_check_exit_code.py. This PR reads the
pgid on every arm of process_result_impl, not only on the timeout one, because the record
cleanup it adds has to make a decision on the normal-exit path too. _FailedProc stands in
for the declared Optional[Popen] but carried only a returncode, so those four raised
AttributeError. Completing the stub leaves the runner's contract as it is; I measured the
alternative of narrowing the read back and it does not help, because all four take the
normal-exit branch that needs the pgid. The stub's pid is the test process, so the group is
alive and the cleanup neither writes nor drops a record. Same shape as the stubs already in
test_expect_debuglog_separation.py.

One arm of mine hitting its subprocess timeout. test_a_nested_invocation_... drove
clickhouse-test with a bare argv, assuming it exits early for want of a binary or a
server. This job supplies both, so it started a whole run and was killed at 180 s. --help
returns from parse_args, still after the module body that mints the run token, so the arm
asserts what it asserted before.

Verification, on this worktree with only tests/clickhouse-test swapped between the two
arms: test_hung_check_exit_code.py goes 14 failures to 10, and 10 is exactly what pristine
master scores here, with the ours-only set now empty. The remaining 10 all need a real
binary on PATH and fail identically on master. The nested arm passes in 0.5 s both with and
without a binary on PATH, and still fails in both conditions when the re-mint guard is
disabled, so --help did not make it vacuous. Full suites: 25/25 abort-path (run with a
binary on PATH, i.e. this job's condition) and 14/14 debuglog. ruff check clean.

One residual I am not fixing here, disclosed rather than left to be found: a record retained
because a background member outlived its leader is validated by run token and worker pid,
not by the current owner of the numeric pgid, so a pgid recycled inside one run would be
signalled. Reaching it needs pid allocation to wrap pid_max, which is 4194304 here against
a bounded retention window, and master signals every recorded pgid with no token check at
all, so this PR narrows that exposure rather than widening it.

Comment thread tests/clickhouse-test Resolved
…e sweep

The conflict offered master's copy of the parent monitor loop against this
branch's post-loop comment, but the merge had already placed this branch's
restructured loop above it - wrapped in `try`/`finally` and reaping through
`quiesce_workers_and_reap` instead of the inline terminate/join/kill. Dropped
that duplicate body and kept this branch's structure.

The one master-side change inside the region is the SQL stacktrace sweep added to
the hung-check path in ClickHouse#113059, which this branch predates; re-applied it before
`print_c_stacktraces`.

Verified by running `ci/tests/test_abort_path_reaps_test_groups.py` and
`ci/tests/test_hung_check_exit_code.py` before and after the merge: no test fails
after it that did not already fail on this branch's head, and
`test_new_reason_is_matched_by_a_failure_pattern` now passes. The rest are this
environment's Python 3.14 `multiprocessing` forkserver failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread tests/clickhouse-test Resolved
Master removed the whole `ci/tests` directory in `5b3d66b1a66` ("Remove ci/tests
(attempt 2)", 51 files, no replacement location), so this branch's edits under
`ci/tests` arrive as modify/delete conflicts. Accepted the removal, and dropped
the files this branch adds there as well - keeping them would re-create a
directory master deliberately deleted.

The product change this pull request is about is unaffected; what is lost is its
CI-side unit coverage, which has nowhere to live upstream any more.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 4, 2026
Comment thread tests/clickhouse-test Resolved
…ned-test-groups-on-abort

Resolve the conflict in `tests/clickhouse-test`: master extracted the worker
stop into `terminate_workers`, which `quiesce_workers_and_reap` now calls
instead of its inline copy of the old flat-10s version.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts.

groeneai and others added 3 commits September 27, 2026 22:37
…ned-test-groups-on-abort

Resolve the conflict with ClickHouse#119793 in `do_run_tests`: keep its worker pool
(`live_workers`, `start_worker`, `reap_finished_workers`, the recovery
threshold) inside the `try` whose `finally` reaps, and register each pid in
`worker_pids` inside `start_worker`, so a worker started again after a shed
is covered by the abort-path reap like the initial ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ned-test-groups-on-abort

Keep ClickHouse#112265's new stdio invariant section in the process management
document ahead of the renamed PGID-tracking section; the rest merged
cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#112265 the per-test wrapper gets its own stdout and stderr, so a
group that outlives the run no longer holds the pipeline the runner heads.
Two comments still gave that as the reason the group must be reaped; say
only that it stays live, which is still true.

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

Copy link
Copy Markdown
Collaborator Author

Merged master in 988105f and c6ee85e; the conflicts were with #119793 and #112265. start_worker now also registers each pid for the reap, so a worker that #119793 starts in place of a shed one is covered too. Since #112265 already keeps an orphaned group off the pipeline, 22db0ce drops that claim from two comments and the description.

alexey-milovidov and others added 3 commits September 28, 2026 10:35
… test

The `ci/tests` guards for the abort-path reap went away with that suite
(ClickHouse#115650), leaving no automated coverage. `tests/integration` is the remaining
collected pytest root, so the essential oracles move to a cluster-less module
there, `test_clickhouse_test_abort_reap`, which loads `tests/clickhouse-test` as
a module and drives real process groups:

- `reap_recorded_test_groups` reaps only records of this run's
  `_CLICKHOUSE_TEST_RUN_TOKEN` and of the named workers;
- a `spawn` worker inherits the token, so its records are in the reap scope;
- SIGTERM/SIGINT/SIGHUP during `reap_recorded_test_groups` and during the
  worker stop in `quiesce_workers_and_reap` do not raise `Terminated`;
- `quiesce_workers_and_reap` stops a worker that keeps recording groups before
  the single walk, so no record or group survives.

Each test was checked to fail against a runner with its contract broken
(token check dropped, token not seeded through the environment, signals not
masked, reap before terminate).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ned-test-groups-on-abort

Conflict with ClickHouse#122522 in `process_result_impl`: master passes `proc.pid` to
`kill_process_group` instead of `os.getpgid(proc.pid)`, which fails with ESRCH
on macOS for an exited, unreaped leader. Kept this branch's timeout path and
record bookkeeping, calling `kill_process_group(pgid, ...)` with the
`pgid = proc.pid` it already binds; same in the process management notes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`clickhouse-test --cleanup` calls `cleanup_test_groups` without
`worker_pids`, so it must not parse record names: on a reused runner
`ci/tmp` can hold a record of a killed invocation (another token) and one
an older runner wrote as `clickhouse_test_group_pid.<worker>`. Nothing
covered this after `ci/tests` was removed.

The new arm writes both, calls `cleanup_test_groups` and checks that both
groups are killed and both records removed. It fails if the sweep starts
parsing names (the legacy record is skipped) or filtering on the token (the
killed invocation's record is skipped), while the other tests of the module
stay green in both cases.

Also drop the module docstring's claim that a regression here brings back
the hung `clickhouse-test | ts | tee` pipeline: since ClickHouse#112265 a test group
no longer holds the runner's stdout or stderr.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit a435c5d Oct 1, 2026
149 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 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-testing Test content only (no production code). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants