Skip to content

Do not let an orphaned test process wedge the functional-test pipeline - #112265

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-clickhouse-test-wrapper-stdio-wedge
Sep 27, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-clickhouse-test-wrapper-stdio-wedge

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 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

Stateless tests jobs fail with a job-level error after burning the full wall-clock budget, and upload
no per-test results (results: []), invisible to any test-name query: 16 times in 30 days across
14 unrelated pull requests, 0 on master:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111693&sha=005d71edc8389539f2661acd34f2bd165de3b108&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29

ci/jobs/functional_tests.py heads the pipeline clickhouse-test ... | ts | tee -a <file>, and
TestCase.run_single_test spawned each test with no stdout/stderr, so the per-test wrapper shell
inherited the write end of that pipe. The wrapper has its own session and StopTesting never reaps it, so
on an abort the orphan keeps the pipe open, ts/tee never see EOF, and praktika's watchdog kills the job
before FTResultsProcessor.run runs.

The wrapper now gets its own sink: DEVNULL for stdout, and for stderr the per-test file the harness
already collects, in append mode so bash's job-control diagnostic lands after the test's own output
instead of overwriting a <Fatal> line that process_result_impl promotes to SERVER_DIED. 227
instrumented spawns carried zero bytes on either inherited stream.

pipeline outcome abort to pipeline exit
before never finishes (5/5) 71.8 - 142.4 min in CI
after finishes, runner's exit status survives (5/5) 0.60 - 0.65 s

Scoped to per-test wrappers and their descendants; workers and multiprocessing.Manager processes keep
the runner's stdout deliberately. It does not reap orphans or fix the hung-check false positives.

Covered by 05218_clickhouse_test_wrapper_stdio_contract.sh: a stateless test that loads
clickhouse-test as a module and drives run_single_test with the Popen seam replaced, with no
server and no timing threshold. Each of the five elements has a mutation arm reddening only its own
reference lines, and against master's own tests/clickhouse-test the runner reports [ FAIL ]. It
replaces the ci/tests suite dropped in 0a04b3fc when 8ff3720644b2 removed the CI Tests job.


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

Version info

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (10 rounds, 46 findings adjudicated) - click to expand

Before opening this pull request I ran it through an independent cold review plus a separate
reviewing model, for ten rounds. The reviewing model raised 23 findings (2, 2, 3, 2, 5, 1, 1, 2, 4
and 1 per round) and my own cold review raised 26; three of those were reached independently by
both, so 46 distinct findings were adjudicated. One was a blocker, 20 major and 25 nits. I agreed
with 39, disagreed with three (with evidence) and dropped four as non-findings. The final round
found one cosmetic issue and nothing else.

Round 10 (final)

# Finding Verdict
💡 A comment in test_fatal_cgroup_failure_is_reported_as_the_test_result still says "see the privilege table above", but the previous round replaced that table with prose AGREE, noted rather than fixed. The information is intact and immediately above the reference (unprivileged: makedirs under cgroupfs fails with Permission denied and is retried; as root, which is how CI runs, the memory.max write fails with Invalid argument and is not), so only the noun is stale. It changes no code, no assertion and no test behaviour, and I did not think one stale word justified an eleventh round.

I also raised, and then withdrew, a concern that the test teardown's os.killpg has no equivalent
of Popen.send_signal's pid-recycling guard: the window is microseconds, pid_max is 4194304 on
the runner, and two of the other tests have used that same primitive since the suite was written.

Round 9

# Finding Verdict
⚠️ The implementation was buried under narrative: 29 comment lines around five statements at the spawn site, including an 18-line uninterrupted block guarding a single statement, which was the longest such block in a 6945-line file whose previous maximum was 11, with the same rationale restated in 47- and 40-line test docstrings and again in the process-management document AGREE, trimmed. The spawn comment now keeps only the invariant and the two non-obvious open reasons; the mechanism lives in tests/clickhouse-test-process-management.md, which the comment links and which already carried eleven of the twelve rationales. The longest comment run no longer exceeds the file's own pre-existing maximum, and the two docstrings are back inside the range of the rest of ci/tests/ (median 2 lines across its 172 function docstrings in 48 modules; the longest anywhere else is 14).
⚠️ Two of the five tests killed only the top-level runner on timeout, leaving its forked worker and manager processes alive in a shared CI job, and one of them ran the subprocess outside its try, so a timeout skipped artifact cleanup entirely AGREE, both now spawn with Popen inside the try and reap the runner's whole process group through the same helper the other tests already used. subprocess.run's timeout path signals a single pid, not the group, and even with one selected test the runner still forks a worker, which is precisely the process that owns the per-test wrapper. No assertion, expected value, flag or timeout value changed.
💡 The source comment still said a wrapper must not inherit "our stdio", although fd 0 stays inherited by design AGREE, it names stdout and stderr, matching the document and the test module.
💡 No commit message carried the CI report URL for the run this addresses AGREE, added, with the report link and a Related: link to the pull request whose run exhibited the failure.

Earlier rounds (all agreed and fixed unless noted)

  • The comment and the document claimed the wrapper's stderr file also collects "anything bash writes
    before the redirect takes effect". It does not: the wrapper's file and the command's 2> {stderr}
    are the same path, so bash truncates it at exec. The accurate producer set is the job-control
    messages bash emits after the redirect is installed, plus anything it writes when the redirect
    itself fails, in which case the file is never truncated. Measured in both directions: an
    apparent survivor turned out to be the inner shell re-emitting its own startup warning after the
    redirect, which a /bin/sh test does not produce at all.
  • The scope paragraph justified excluding the multiprocessing.Manager on the grounds that it
    prints test results. It does not: only the parallel workers run run_tests_array. The workers'
    rationale stands; the two manager processes (the shared test queue and the restarted-tests list)
    are simply not per-test wrappers.
  • The prose did not distinguish which process's death routes a diagnostic where. The job-control
    message reaches the wrapper's stream only when the wrapper's own child dies from a signal; when a
    background job the test script started is signalled, it goes to the test's own stderr file
    exactly as before. That is why no passing test gains a new stderr writer, which matters because
    any non-empty collected stderr is a failure reason even at exit code 0.
  • The benign "cgroups are not available" notice was being erased by the new redirect, so it moved to
    a parent-side report. Its documented frequency was then wrong twice, "once per process" and then
    "once per worker, up to --jobs", before landing on "once per test-executing process, up to
    --jobs + 1": the cache lives in a per-function closure, and run_single_test is reached both
    from the forked parallel workers and directly from the parent for a suite's sequential tests.
  • The output-preservation test asserted on the wrong file, and was re-pointed at the runner-managed
    per-test stdout file.
  • A fatal preexec_fn failure was reported as UNKNOWN / FileNotFoundError instead of as the
    test's own failure, because that path never runs the command's own > {stdout} while the post-run
    normalization opens that file unconditionally. It is now created before spawning.
  • The wrapper's diagnostics could overwrite the test's own stderr, including a <Fatal> line
    that gets promoted to "server died". The parent-side descriptor is now opened O_APPEND, pinned
    by a fixture that writes stderr and then dies from a signal.
  • A retried attempt inherited earlier attempts' diagnostics, so the file is truncated up front, and
    the oracle for that was vacuous in the privileged CI arm, where the cgroup errno is not retryable.
    The test now forces three attempts with --test-runs and asserts the attempt count before the
    per-attempt count.
  • The exit-code assertion pinned only the reason prefix, so deleting the code that appends the
    wrapper's numeric status left every assertion passing. It now pins the value, built from the enum
    rather than from a literal.
  • The cgroup cleanup added for an earlier finding failed open; it now returns what it could not
    remove, and the test asserts on it.
  • The lldb runtime note framed a 600 s timeout as this test's own headroom; it is the budget for the
    whole ci/tests/ suite, so the note now carries the measured margin.
  • Documentation: the empty-result causality was mis-attributed to a lost exit code. The real cause
    is that the results processor never runs.
  • Three findings I disagreed with, with evidence. The signal fixture's kill -SEGV $$ was
    flagged as possibly dropping a core file: cosmetic and self-cleaning, since the job runs
    git clean -ffd before every run and has no core-collection hook, and SEGV is the crash-like
    shape the test documents. Two of my own late findings about the wording of the producer set were
    withdrawn after re-reading the shipped text: the signal-shape caveat is already stated in the very
    next sentence, and the failed-redirect clause is true in both of its arms.

Session id: cron:clickhouse-review-slot-8:20260728-101100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. python3 .scratch/probe/measure_wedge.py drives the real clickhouse-test inside the real CI pipeline shape (set -o pipefail; <runner> | cat), waits for a live per-test wrapper via the PGID file the runner writes right after Popen, then kills the runner tree while leaving the wrapper alive. On master the pipeline never finishes: WEDGED 5/5 (hit every cap given, 60 s). Not a "~1%" reproduction.
b Root cause explained? Yes. ci/jobs/functional_tests.py runs the runner as the head of clickhouse-test | ts | tee. run_single_test spawned each test with start_new_session=True and no stdout/stderr, so the wrapper inherited the runner's stdout (the pipe write end) while being out of reach of the runner's process-group signals. On abort (except StopTesting: sys.exit(...); __main__ has no finally) the wrapper group is never reaped, so ts/tee never see EOF and the pipeline never finishes. global_time_limit = 0 on the regular path makes outer_timeout None, so only praktika's watchdog ends the job - and praktika then tears the job down: it signals the process group it created (TeePopen.send_signal → os.killpg, ci/praktika/utils.py:1124, :1162-1170) and runs docker rm -f on the job's container. These jobs run in a container (ci/defs/job_configs.py:102 run_in_docker=clickhouse/stateless-test+…; ci/praktika/runner.py:440 builds docker run … {job.command}), so that host process group holds the docker run client, which forwards the signal inward - the job script is not a member of it. ci/jobs/functional_tests.py therefore dies inside Shell.run before reaching FTResultsProcessor.run(runner_exit_code=...) (:967), so the per-test results are never processed at all: praktika marks the incomplete result ERROR and fills info from its rolling log buffer (ci/praktika/runner.py:490-509), giving results: []. The exit status is not the cause - importing the real module shows ABORTED_RUN_EXIT_CODES == frozenset({-15, -9, 2, 137, 143}), so -15 is already accepted (its own comment says the set covers job-level timeouts); the processor simply never runs. Confirmed by this PR's own artifacts: result_pr.json's node is status=ERROR / results=[] with the StopTesting traceback as info (not a Server died leaf), and the 34 job.log lines after the abort contain zero Server died / All tests have finished / exited with code lines. Measured across all 14 runs of this signature: deciding to stop takes 0.2–7.7 min; abort → kill is 71.8–142.4 min.
c Fix matches root cause? Yes. The inherited descriptor is the mechanism, so it is removed at the spawn site: the wrapper gets its own sink (stderr appended to the per-test stderr file the harness already collects - the file is truncated once up front and then opened in append mode; stdout to DEVNULL). No timeout tightening, no no-random-* tag, no data reduction, no downstream guard. The alternatives (finite outer_timeout, a post-hook, dropping start_new_session=True, or a ~70-line teardown/reaping redesign) were each rejected with a stated reason - notably, the A/B below shows the pipeline exits cleanly with the orphan still alive, so reaping is not what fixes this.
d Test intent preserved / new tests added? Yes. No existing test was weakened or retagged. New ci/tests/test_test_process_does_not_hold_runner_stdio.py (5 tests) + fixture ci/tests/0_stateless/02_wrapper_stdio_wedge.sh: (1) no process in the test's process group holds the runner's stdio; (2) an orphaned wrapper does not wedge the pipeline and the runner's own exit status survives; (3) the test's output is still collected into the runner-managed per-test stdout file (no-regression guard; the file is located by globbing suite_tmp_path, since its basename carries the worker's pid); (4) a preexec_fn that dies before exec (the fatal cgroup branch) still has its diagnostic reported as the test's own failure rather than as an internal error - asserting the runner's exit status (1), the [ FAIL ] marker, the exit-code reason, and that the diagnostic appears exactly once per reported attempt, across three attempts forced with --test-runs 3 --long-test-runs-ratio 1.0 --dont_retry_failures (a run relying instead on the retry path would report a single attempt on the privileged CI arm, where the errno is the non-retryable Invalid argument, and the per-attempt count would then hold whether or not the file was truncated). (5) a test that writes to its own stderr and then dies from a signal keeps both records: the collected per-test stderr file carries the test's own line and the wrapper shell's bash job-control diagnostic, in that order, and the reported failure carries the test's line and the <Fatal>-driven server died reason - which is what pins the append-mode open (fixture ci/tests/0_stateless/03_wrapper_stderr_signal.sh). Tests 1 and 4 are gated on their real platform requirements (/proc for the descriptor comparison; cgroup v2 for the negative-limit trigger, since on v1 -1 means unlimited and the fatal branch is never taken); test 5 needs neither, so it carries no gate. Test 4 also removes the root-level cgroup its own run creates (rmdir of the after - before set only), because the runner's v2 cleanup_cgroup computes a different path from /proc/self/cgroup and cannot remove it - a pre-existing runner defect, deliberately out of scope here. The committed suite has a single .sh fixture - I verified the same descriptor property for a .sql test with a scratch probe while developing the fix, which is not part of the PR. ci/tests/ is a real merge gate (ci/jobs/ci_tests_job.py runs pytest ci/tests/, digest include_paths=["./ci"]).
e Both directions demonstrated? Yes, on the same deterministic repro. Pipeline: master WEDGED 5/5 vs fixed FINISHED 5/5 in 0.60–0.65 s, with the orphan alive in both arms. Descriptors: master has 1 holder (the wrapper, fd1 and fd2 = the runner's pipe); fixed has 0 - measured for a .sh and, via a scratch probe, for a .sql test. Tests 1+2 FAIL on master and PASS with the fix; and they FAIL again with the same assertions on a mutant where only the stdout=/stderr= arguments are reverted, so they discriminate this change specifically. Test 3 is a no-regression guard rather than a discriminator, and it is non-vacuous: deleting the > {stdout} half of the harness's own redirect makes it FAIL (expected exactly one runner-managed per-test stdout file ..., found []). Test 4 discriminates the stdout-file pre-creation: with it the run reports [ FAIL ] Reason: return code: 1 carrying the cgroup message; deleting only that line makes the test FAIL with found 'Test internal error', so the failure was reported as an unrelated internal error (the run degrades to UNKNOWN / FileNotFoundError, exactly as origin/master does - so this half is an improvement on master, not a restoration). Its vacuity guard reads the per-test stderr file, which carries the diagnostic in both arms, so it cannot mask the reporting assertion. Test 5 discriminates the append mode: on a mutant that opens the wrapper's stderr with a single non-append "wb" it FAILS with the test's own stderr was overwritten by the wrapper's diagnostic - the parent-side descriptor on this file is not in append mode (observed file = the bash diagnostic only), while tests 1-4 still pass; and a mutant that drops the up-front truncation instead leaves test 5 passing and makes test 4 fail on its count assertion (observed {1, 2, 3} == {1} over the three forced attempts), so each half of the pair is independently pinned. That mutant was also run in the privileged single-attempt shape (no --test-runs, retries off) to show the counterfactual: there the observed counts is [1], i.e. a retry-dependent version of this assertion would have passed with the truncation deleted - which is why the attempt count is now forced by flags and asserted (len(counts) == 3) rather than left to the errno. Its own vacuity guard requires the bash diagnostic to be present, so a run whose child was not signalled cannot pass by default.
f Fix is general across code paths? Yes. The sole orphan-producing spawn is fixed at source (grep -n "start_new_session=True" → one real call site; the other hits are comments). Every other Popen/subprocess.run/subprocess.call/getstatusoutput/os.system in the runner was enumerated and classified: all are synchronous and captured (shell_get_output, the lldb installer, the two grep probes, the diff/sed pair in process_result_impl, extract_key, replace_in_file_re), so none can outlive the runner - and none was blanket-redirected. Sequential and --no-self-parallel runs use the same run_single_test, so they are covered with no per-path work. Because the fix is in the shared runner, all functional-test variants with the same | ts | tee shape benefit (the same job-level error signature appears on 40+ others, likewise 0 on master).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, for this component's actual input space (test kind and abort path - there is no SQL/type surface here). Both .sh and .sql verified at descriptor level. Wrapper-stream content was measured, not assumed, before choosing the sink: instrumenting the spawn to hand every wrapper a private file per stream and running the 227-test stateless sweep (31 .sh + 195 .sql + 1 .sql.j2, including the one failing test) put 0 bytes on either stream in 227/227 spawns; and across 8 abnormal cases the only content is bash job-control diagnostics naming the killing signal (Killed/Segmentation fault 157 B, Terminated 11 B, unwritable-redirect 64 B) - which is why stderr is preserved into the file the harness reports rather than discarded. Descendants covered transitively and verified (0 holders).
h Backward compatible? Yes - nothing to be compatible with. No settings (so no SettingsChangesHistory.cpp), no serialization format, no protocol, no on-disk layout, no exit-code semantics. Test-harness only. The stderr_file truncate/delete lifecycle is unchanged, verified with a pre-seeded stale file: on the normal path the resulting stderr file is byte-identical (md5 accaa20edf637d47) across truncate-then-append, single-wb, seeded and clean arms, because the command's own 2> truncates it.
i Invariants and contracts preserved? Yes. run_single_test's contract is unchanged: it still returns (proc, total_time) and still writes the PGID file immediately after Popen. The with open(...) block closes only the parent's copy of the descriptor, after Popen has duplicated it into the child, so the child keeps its stderr for its whole lifetime - verified on the running child (its fd2 points at the stderr file) and on the timeout/kill path (the one timing-out test in the sweep produces an identical Reason: Timeout! Killing process group description and process-group listing). The invariant added is deliberately scoped: per-test wrappers and their descendants only - the parallel workers and the Manager inherit the runner's stdout by design (run_tests_array reports results via sys.stdout.write), so top-level-runner-SIGKILL coverage is explicitly not claimed, in the code comment, the doc, and the PR body. No locks, no shared mutable state, no durability surface touched. One consequence of installing these streams was traced and handled: preexec_fn (setup_cgroup_with_memory_limit_cb, --memory-limit only) also writes to fd 2, in the child, after Popen has installed them. Its fatal Failed to configure cgroup ... report is written on the one path where bash never execs (os._exit(1)), so the command's own 2> {stderr} never truncates the file - and an append-mode open made every attempt sharing that file report all the earlier attempts' diagnostics (measured per-attempt copies [1, 2, 3] over three forced attempts) and could carry a stale <Fatal> line, which process_result_impl promotes to SERVER_DIED. The stderr file is therefore truncated once up front (like the neighbouring fatal_sanitizer_prefix files) and then opened in append mode, and both halves are load-bearing for opposite reasons. Truncating alone is not enough: the test command's own 2> {stderr} opens the same path through an independent descriptor with its own offset, so a non-append parent descriptor starts at 0 and overwrites whatever the test already wrote to its stderr - measured on the real spawn shape, a wrapper whose child writes a <Fatal> line and then dies from SIGSEGV yields 212 B with both records under append mode but 129 B carrying only the bash diagnostic under a bare "wb", with " <Fatal> " in stderr flipping True -> False and thereby silently disarming that same SERVER_DIED promotion (strictly worse than master, which keeps the test's stderr). With the pair, measured per-attempt copies are [1, 1, 1] (vs [1, 2, 3] for append-without-truncate), the test's own stderr survives ahead of the wrapper's diagnostic, and a normally-executing test's report is byte-identical with deliberately seeded stale content (bash's own 2> truncates; stderr md5 accaa20edf637d47 in all four arms). That same path also means > {stdout} never created the stdout file, and run_single_test's post-run replace_in_file(self.stdout_file, ...) opens it unconditionally - so a FileNotFoundError there would be reported by run's generic handler as UNKNOWN / "Test internal error" without ever reading the stderr file, discarding the diagnostic. The stdout file is therefore pre-created before spawning; measured, the run then reports [ FAIL ] Reason: return code: 1 with the cgroup message in the description - the message is attached to the test instead of buried in the job log, i.e. better than master (which reports UNKNOWN / FileNotFoundError here too). On the normal path the pre-creation is a proven no-op: with deliberately seeded stale content the resulting stdout file is byte-identical (md5 9dd27fbb1ce702ed51895f0e1e8f88e8) across pre-created-stale, pre-created-empty and not-pre-created arms, because bash's > truncates. The benign "cgroups are not available" notice would have been truncated, so it is now emitted once per process from the parent (report_cgroups_unavailable, @cache_ignore_args) - measured 1 occurrence for a 3-test run with --memory-limit, 0 without it, against 3 (once per spawn) on master.

Session id: cron:clickhouse-impl-slot-45:20260727-235100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @maxknv @leshikus - could you review this? It stops a per-test wrapper process that outlives clickhouse-test from holding the runner's stdout, which is the write end of the | ts | tee pipeline the functional-test job heads: the pipeline then never sees EOF, the job runs to praktika's wall-clock ceiling, and the results processor never runs, so the check uploads results: []. The wrapper now gets its own sink instead (stdout to DEVNULL, stderr appended to the per-test stderr file the harness already collects).

@leshikus, flagging one interaction with your stacktrace work in the same file: one of the new tests drives SERVER_DIED, so it reaches print_c_stacktraces and pays the on-demand lldb install. Its docstring documents that as expected slowness rather than a hang.

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

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ba6cfb]

Summary: ✅


AI Review

Summary

This PR fixes the functional-test runner so per-test wrapper shells no longer inherit the runner's own stdout/stderr, pre-creates the per-test output files for the fatal preexec_fn path, and adds a stateless regression test that exercises the current hand-off contract in CI. I reviewed the current diff and prior discussion, and I do not see any remaining correctness, safety, or coverage issue that warrants an inline comment. The previously reported missing executed coverage is resolved by 05218_clickhouse_test_wrapper_stdio_contract.sh, and that test passes locally with output matching its reference exactly.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 5ba6cfb.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.60% 79.60% +0.00%

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

Newly covered: +225 lines in 65 files (-63 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 28, 2026
…line

`Stateless tests` jobs have been failing with a job-level `error` that burns the
full wall-clock budget and reports no per-test results at all: `check_status`
is `error` and `results` is empty, so the failure is invisible to every
test-name-based query. Over the last 30 days this happened 16 times across 14
unrelated pull requests and 0 times on master.

In CI the runner heads a shell pipeline,
`clickhouse-test | ts | tee -a <file>` (`ci/jobs/functional_tests.py`). A
per-test wrapper is spawned with `start_new_session=True` and inherited stdio,
so it holds the pipeline's write end and lives in its own session. When the
runner aborts and exits, a wrapper that outlives it keeps that descriptor open,
`ts` and `tee` never see EOF, and the pipeline never finishes. The job-level
wall-clock timeout then replaces the runner's real exit status, which is why
the underlying `Server died` report is never produced and no per-test rows are
written.

The wrapper does not need the runner's streams: the command already redirects
the test's own output to the per-test `{stdout}`/`{stderr}` files that
`process_result_impl` reads back, so the inherited descriptors carried nothing.
Its stdout is now `DEVNULL` and its stderr is appended to the per-test stderr
file, which removes the coupling without reaping anything. The parallel workers
and the bookkeeping manager keep the runner's stdout by design, since they
report results through it; fd 0 is likewise still inherited.

Also fixed here, found while validating the above:

- The per-test stderr file is truncated before each attempt, so a retried
  attempt no longer inherits the previous one's diagnostics, and the wrapper
  appends rather than overwrites, since the command's own `2> {stderr}` holds a
  second descriptor on that path with its own offset.
- A `preexec_fn` that dies before `exec` is now reported as the test's failure
  with its numeric exit status, instead of being lost.

Documented in `tests/clickhouse-test-process-management.md`.

Verified in the job's own image with a live server: the pipeline finishes with
the runner's status while the orphan is deliberately left running, and
reverting the redirect reproduces the wedge.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111693&sha=005d71edc8389539f2661acd34f2bd165de3b108&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112265&sha=afd4ae8bc5b3cbfa78cad8f1bf5e0a5a66c33b54&name_0=PR&name_1=CI%20Tests
Related: ClickHouse#111693
Related: ClickHouse#112265

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai
groeneai force-pushed the fix-clickhouse-test-wrapper-stdio-wedge branch from afd4ae8 to 897bb1d Compare July 28, 2026 20:40
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI Tests failure on afd4ae8 was mine, fixed in 897bb1d

test_orphaned_test_process_does_not_wedge_the_ci_pipeline failed with
could not locate the clickhouse-test runner process while passing everywhere else.

Root cause is in the test's own process discovery, not in the change under test. The test
located the runner by matching the absolute path of tests/clickhouse-test against the command
column of a local ps -eo pid,ppid,pgid,args helper. Without -ww, ps cuts that column to the
terminal width, so a path longer than the remaining columns can never match.

Measured inside the job's own image (clickhouse/integration-tests-runner, procps-ng 3.3.17):
the COMMAND column starts at 24, leaving 56 characters, and under pytest COLUMNS=80 is
exported to children, so the args column is cut at 56. The CI checkout puts the runner at
/home/ubuntu/actions-runner/_work/ClickHouse/ClickHouse/tests/clickhouse-test, which ends at
character 90 of the command line. Instrumenting the failing loop confirmed the runner was found
as a direct child of the pipeline shell on every iteration, with its command reported as
len=56 and truncated mid-path. On a shallower checkout the whole path fits, which is why it
passed locally rather than being a race.

pgrep in tests/clickhouse-test already passes -ww for exactly this reason, and its
ppid/command filters are the same ones the loop applied by hand, so the local helper is
removed and both call sites use the imported one. The module already imports it and states that
helpers come from the runner so changes there propagate. No assertion, expected value, timeout or
fixture changed.

Verification in the job's image with a live server: 5 passed, and the failing test drops from a
90s deadline to 0.27s. Removing -ww from pgrep reproduces the original failure with the same
assertion, so the behaviour is pinned in both directions.

Also squashed the branch to a single commit, since it had grown to 13. The tree hash is
unchanged (75469b7792a5), so the squash preserved the content exactly.

The re-run of this PR's workflow (attempt 2 of run 30397395779, created
2026-07-28) checks out refs/pull/112265/merge as it stood then, so the tested
tree was this head merged with master at 71ec9af (2026-07-28 19:52 UTC). That
tree predates c5b976c (PR ClickHouse#112385, merged 2026-07-29 14:35 UTC), which pins
--enable_parallel_replicas 0 in 01666_merge_tree_max_query_limit.sh. Without
that pin the holder query becomes several reads of the same table on the same
server and is rejected by its own max_concurrent_queries = 1 slot, so the last
throttle assertion sees no holder. Merging master brings the pin onto the
branch, so the outcome no longer depends on which merge base CI picks.

Pinned master: 6764095
Cut the added comment block above report_cgroups_unavailable from seven lines to
two and folded the four blocks around the spawn into two. What is gone is
motivation and history rather than any invariant: that a per-function
cache_ignore_args closure makes the report per process and a suite with both
parallel workers and sequential tests therefore emits it up to --jobs + 1 times;
that the workers and the bookkeeping manager keep the runner's stdout by design;
that open(path, "wb") truncates, which the mode already says.

Also restored the pre-existing comment above pattern. It describes a 2>> that
fe90c97 had already replaced with 2>, so it was stale before this branch and
correcting it is not this change's business. The property the append-mode open
depends on is stated where that open is.

Comments added by this change to tests/clickhouse-test: 20 -> 10, against 10
added code lines, with no block longer than three lines.
The teardown removed every clickhouse-test-* directory that appeared at the
cgroup root during the run. Appearing after the snapshot does not establish
ownership: the CI Tests job runs --cgroupns=host, so a co-scheduled runner's
directory is visible, and it is removable while still empty in the window
between its os.makedirs and its memory.max write. This teardown could therefore
delete it and make that runner's preexec_fn fail. On the machine this was
developed on, /sys/fs/cgroup held 220 such directories from other processes.

run_single_test names the cgroup clickhouse-test-{os.getpid()}, and
TestCase.__init__ builds the per-test file names in that same process, so
<test>.<pid>.stdout carries exactly the owning worker's pid. A path is now
removed only if it is both new and attributed that way, so a recycled pid from an
earlier run is not adopted, and an unattributed new path is left alone rather
than reported, which keeps a foreign directory from turning into a false failure.
The PGID files are not usable: run_single_test unlinks each one when its test
finishes, so none survives a teardown that runs after the runner has exited. That
leaves the attribution able to come up empty, so the test asserts it did not - in
the body, not in the finally, where it would mask a real failure. Nothing is
added to that set unconditionally, the runner's own pid included, because that
would make the assertion unfalsifiable; this fixture carries no sequential tag,
so its spawns happen in workers.

Checked against a fake cgroup root, since makedirs under cgroupfs fails as a
non-root user and the shipped test creates no directory there at all: ours empty
is removed, ours non-empty survives and is reported leaked, a foreign directory
survives and is never reported, one named after a pid present before the run
survives, and the pid really does come from the artifact name. The same state run
through the previous loop deletes the foreign directory. Breaking only the
artifact match, with every call site left as it ships, fails this test and no
other.

A pid still identifies the owner only within this container, which does not share
the host's pid namespace, so a directory another container created inside the
snapshot window under a colliding pid would match. That is narrower than what it
replaces, and closing it needs a host-unique token in the name, which is the
runner's to choose; noted where the filter is.

Also deleted the comment above `pattern`. It describes a `2>>` redirect that
fe90c97 had already replaced with `2>`, and the properties that matter here
- that the test's own redirect truncates and holds a second descriptor with its
own offset - are stated where the append-mode open is. And dropped the runner
class from one skip reason: the job moved to RunnerLabels.ARM_SMALL, and the
Linux-only point the reason makes does not depend on which one it is.

Correction to 897bb1d's message, which said the bookkeeping manager
reports test results through the runner's stdout: only the workers run
run_tests_array and print assembled results. The manager processes host the
shared queue and the restarted-tests list. Both do hold the runner's stdout, and
both are deliberately out of the invariant's scope, which is what that paragraph
was about.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 897bb1d

Check / test Reason Owner
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit the tested tree predates that test's own parallel-replicas fix #112385 (ours, merged 2026-07-29) - merged master @ 6764095e to pick it up
CH Inc sync pending CH Inc sync (private, not actionable)

That run is attempt 2 of a workflow created 2026-07-28, so it checked out refs/pull/112265/merge as it stood then: this head merged with master at 71ec9afe (2026-07-28 19:52 UTC). #112385 pinned --enable_parallel_replicas 0 in 01666_merge_tree_max_query_limit.sh at 2026-07-29 14:35 UTC, so that tree does not carry it. Without the pin the holder query becomes several reads of the same table on the same server and is rejected by its own max_concurrent_queries = 1 slot, after which the last throttle assertion sees no holder. The run's server log has the holder failing with Code: 202 ... Received from 127.0.0.2:9000 220 ms after it started. On master that test has 22 to 52 OK rows a day on that exact lane and no failure in 21 days. Merging master puts the pin on the branch, so the outcome no longer depends on which merge base CI picks.

Two other changes in this push, unrelated to that red:

  • The comments earlier rounds added to tests/clickhouse-test are trimmed to the local invariants: 20 added comment lines down to 10, against 10 added code lines.
  • The cgroup teardown in the new test now removes only directories named after this invocation's own worker pids, rather than every clickhouse-test-* that appeared during the run. The job runs --cgroupns=host, so the previous form could remove a co-scheduled runner's directory while it was still empty.

One thing worth flagging: ci/tests/0_stateless/ is empty on master since 3a69545d, and the two fixtures here re-create it. ci/tests/test_check_style_server_data_manipulation.py builds its fixture under tmp_path instead, which would avoid committing them; I can switch to that if you prefer it.

Session id: cron:clickhouse-maint-slot-12:20260828-012700

@groeneai

Copy link
Copy Markdown
Collaborator Author

Ledger discharge - 0342f70

The ledger on the previous head owned the 01666_merge_tree_max_query_limit red with #112385 plus "merged master @ 6764095e to pick it up". That is now confirmed on the merged head: Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), the check the failure was in, ran and passed here, so the red is gone rather than merely unreported.

CI is finished at this commit with zero failures (praktika PR = OK, Finish Workflow green, no dropped jobs, and zero FAIL/ERROR rows in the CI database), so no owner column is owed this time. The 110 skipped entries are cache-reused amd build jobs; every suite that depends on them ran, including all ten Stress test flavours.

Session id: cron:our-pr-ci-monitor:20260828-070000

pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Aug 29, 2026
On an ASan build, a stateless run that aborts on the hung check records no
stack of the hung server anywhere:

    Hung check failed: server is not responding
    Cannot collect C stacktraces under ASan: debugger attach is disabled.

Two things combine to produce that. print_c_stacktraces declines to attach
lldb on ASan builds, because a ptrace attach disables LeakSanitizer for the
rest of the process; that refusal is correct and stays. And
print_sql_stacktraces, the collector that needs no debugger at all, was
unreachable in this state: its availability pre-check went through
check_server_liveness, which probes HTTP on http_port (default 8123), while
the collector itself shells out to args.client on the native TCP port
(default 9000). Those are different listeners on different ports served by
different code paths, so a server whose HTTP endpoint is wedged or whose
handler pool is exhausted while TCP still answers queries failed the gate and
was never asked. That is precisely the reported signature: the process alive,
not responding. The hung-check abort site did not call the SQL collector in
the first place, and neither did the FailureReason.SERVER_DIED site.

Drop the pre-check and let the bounded TCP query be its own liveness test.
The reason the pre-check existed was to keep "Code: 210 Connection refused"
tracebacks out of every failed run, and that concern is now covered where it
belongs: get_stacktraces_from_clickhouse runs under shell_get_output with
timeout=30, which caps a dead or wedged socket at 30 seconds and reduces a
failure to a single trim_for_log-bounded stderr line with no traceback. The
existing "if bt:" guard still means nothing is written and nothing is claimed
when nothing was collected; an else branch now records that the attempt was
made, so "tried and got nothing" is distinguishable from "never tried".

Then add the SQL dump to the two abort sites that had only the C path. It
goes before the C dump for the reason the per-test timeout handler documents:
dump while the client connections are still up, because once they drop the
server cancels the wedged queries and their threads disappear.

A server-side alternative was considered and rejected. Sending SIGTSTP so the
server logs its own stacks would work mechanically, but onFault emits its
report at LOG_FATAL, check_fatal_messages_in_logs greps for any <Fatal> line
and appends a result carrying Result.Label.BLOCKER, and FuzzerLogParser
classifies "Received signal" as a signal failure. The diagnostic would have
manufactured a merge-blocking failure out of itself, which is worse than the
present silence. Teaching those scanners a benign exception was rejected too:
six independent consumers key on those strings, so it would weaken real-crash
detection in six places for a diagnostic gain. Nothing in this change writes
to the server log.

This does not fix any hang, and it does not restore C++ stacks on ASan
builds. What it changes is that a server alive but not answering HTTP now
yields the full system.stack_trace view with per-thread thread_name and
query_id, which identifies the query that wedged the server.

Measured on a live server, with HTTP dead and TCP live: master skips and
writes nothing, this change writes a 357 KB sql_stacktraces.log carrying
thread_name and query_id. An abort with HTTP wedged rather than closed gets
9.7 seconds faster, because the pre-check itself blocked for 10 seconds and
then collected nothing; the worst case is 20 seconds slower when both
transports are wedged, bounded by timeout=30. Green runs are unaffected,
since no caller runs on a passing test.

Regression coverage goes in the existing ci/tests/test_print_stacktraces.py.
The oracles key on the sql_stacktraces.log artifact and its columns, or on
per-site call order, never on stdout: the unfixed code, the rejected
call-site-only variant, and print_c_stacktraces all print lines, so a test
asserting that some output appeared would pass in every case and measure
nothing. The two abort sites are asserted independently, because the per-test
timeout handler and the end-of-run hung-query check already called both
collectors and would otherwise mask a revert of either new site.

Related: ClickHouse#42701
Related: ClickHouse#112265
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 4, 2026
…-wrapper-stdio-wedge

One conflict, in tests/clickhouse-test. 182a59e ("Remove the old-analyzer
test mode") deleted cache_ignore_args together with its only user,
is_old_analyzer_used; this branch had added a second user of that decorator,
report_cgroups_unavailable.

Resolved by taking the deletion and decorating report_cgroups_unavailable with
functools.cache instead: it takes no arguments, so the "ignore args" helper that
existed for non-hashable ones has nothing left to do here, and functools.cache
keeps the same per-process, once-per-notice behaviour the notice relies on.
Keeping the helper alive for this one caller would have restored code master
deliberately removed. tests/clickhouse-test-process-management.md described the
old decorator by name, so it is updated to match.

Everything else merged cleanly: master's 662 added lines in tests/clickhouse-test
since 6764095 do not touch the spawn path, and the five files this branch owns
are unchanged by it.
The `CI Tests` job that ran `pytest ci/tests/` was removed in 8ff3720
("Remove the `CI Tests` job along with `ci/tests`", 2026-08-22), together with
`ci/jobs/ci_tests_job.py`, `JobConfigs.ci_tests` and the `ci_tests` lane in
`.github/workflows/pull_request.yml`. No current job executes `ci/tests`:
`ci/defs/defs.py` and `ci/defs/job_configs.py` register none, and the stateless
job selects from `tests/queries`, so these files and their digest inputs are
never reached. `.claude/CLAUDE.md` states the position directly: a throwaway test
for a CI-script change does not need to be committed, because there are no
automated CI tests.

So the three files this branch added under `ci/tests` could not fail, could not
report, and re-created a directory the repository had deleted. They are removed
here rather than left as 740 unreachable lines in front of a reviewer. The
change under test is unaffected: the invariant, its two producers and the reason
each half of the `open` pair is load-bearing stay documented in
tests/clickhouse-test-process-management.md, whose now-dangling pointer to the
deleted module is dropped with them.

The suite was run one last time against this merge before deletion: all five
pass on this tree, and the same five against master's own tests/clickhouse-test
fail four (the fifth is the no-regression guard on output collection, which
master passes by construction), so the fix is still load-bearing after master's
662 added lines in that file.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master; the ci/tests suite is dropped

Head 0a04b3fc merges master (d1ba1699) into the branch, so this is mergeable again. One conflict:
182a59e5d ("Remove the old-analyzer test mode") deleted cache_ignore_args together with its only
caller, and this branch had added a second caller, report_cgroups_unavailable. Resolved by taking the
deletion and decorating with functools.cache (that function takes no arguments, so the ignore-args
helper had nothing left to do here) rather than keeping alive code master removed. Master's 662 added
lines in tests/clickhouse-test since the previous base do not touch the spawn path.

The three files under ci/tests are dropped in 0a04b3fc: 8ff3720644b2 removed the CI Tests job
together with ci/tests, so nothing runs pytest ci/tests/ any more, and .claude/CLAUDE.md states that
a throwaway test for a CI-script change does not need committing. They stay reachable in this branch's
history: git show dea0186793e7:ci/tests/test_test_process_does_not_hold_runner_stdio.py, plus the two
fixtures under ci/tests/0_stateless/.

Verification on the merged tree, at the same tests/clickhouse-test content that is pushed:

  • the suite is 5/5 green;
  • with master's own tests/clickhouse-test in place, same tree and same server, 4 of the 5 turn red (the
    fifth is the no-regression guard on output collection, which master passes by construction);
  • the notice moved to the parent prints 1 line for 3 calls, and 3 lines with the decorator removed.

If executed coverage in-tree is preferable, I can port it to a stateless test shaped like
05099_clickhouse_test_keeper_retry_matching.sh, which loads the runner as a module.

Session id: cron:clickhouse-maint-slot-12:20260916-121300

Comment thread tests/clickhouse-test Resolved
@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Sep 16, 2026
The `ci/tests` suite that covered this change was dropped in 0a04b3f, because
8ff3720 removed the `CI Tests` job together with the directory, so nothing
ran it. That left the load-bearing pieces of the spawn without any check that
runs in CI: they could be reverted and every job would still be green.

This ports the coverage to the stateless suite, following
05099_clickhouse_test_keeper_retry_matching.sh: load `clickhouse-test` as a
module and drive `run_single_test` with the `Popen` seam replaced by a stand-in
that records how the streams were handed over and then replays what the real
wrapper does to the per-test files, including the fatal `preexec_fn` path that
exits before bash execs. No server, no sockets and no wall-clock threshold, so
it is not a new flake source under the sanitizer jobs; it runs in 0.7 s.

Every element has a mutation arm that reddens only the reference lines it owns,
measured against the runner in this branch:

  stdout=subprocess.DEVNULL       "wrapper stdout is not the runner's own", for
    dropped, and for stdout=1 or subprocess.STDOUT: the oracle resolves the
    handed descriptor against the runner's own stdout, so neither a plain fd nor
    another negative sentinel passes in its place
  stderr=wrapper_stderr           "wrapper diagnostic reaches the collected
    stderr", plus the append line below
  the "ab" mode                   "wrapper stderr lands after the test's own",
    which collects `Terminated\nites this to its own stderr\n` under "wb" - the
    clobbering of a ` <Fatal> ` line that append prevents
  open(stdout_file, "wb")         the two lines for a wrapper that dies before
    exec, where the post-wait normalization raises FileNotFoundError; and, for
    "ab" in place of "wb", "earlier attempt's stdout is cleared"
  open(stderr_file, "wb")         "earlier attempt's stderr is cleared", which
    needs the truncation rather than the file, since the append open that
    follows creates it anyway

Against master's runner verbatim the whole reference differs and
`clickhouse-test` reports [ FAIL ].
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 27, 2026
groeneai and others added 2 commits September 27, 2026 01:58
ClickHouse#121387 made `run_single_test` call `get_timeout`, which reads `flaky_check`
and `no_self_parallel` from the test case arguments and `is_concurrent` from
the test case. The stand-in built by `make_case` had none of them, so
`run_single_test` raised `AttributeError` before it reached the replaced
`Popen`, and the test failed in the merge queue with a `TypeError` on `seen`.

With the attributes set to their defaults the test passes against the merged
runner again, and against master's runner (without the spawn change) all seven
reference lines still differ.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=gh-readonly-queue/master/pr-112265-00721e1919652f65821d92356b3d8eea5848f8d2&sha=3b6d2a99a5abb1aa1963c91a8df6d403053f2eeb&name_0=MergeQueueCI&name_1=Fast%20test

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

Copy link
Copy Markdown
Collaborator Author

The merge queue run failed on 05218_clickhouse_test_wrapper_stdio_contract (report): #121387 made run_single_test call get_timeout, and the stand-in test case arguments the test builds had no flaky_check. Merged master and fixed it in 5ba6cfb. The test passes against the merged runner again, and still fails against master's runner without this change.

@clickhouse-gh clickhouse-gh Bot added comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). and removed comp-testing Test content only (no production code). labels Sep 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 27, 2026
Merged via the queue into ClickHouse:master with commit 4f64700 Sep 27, 2026
172 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 27, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
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 added a commit to groeneai/ClickHouse that referenced this pull request Sep 28, 2026
`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]>
@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Nov 22, 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-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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