Skip to content

Do not let test processes inherit the CI runner's output pipe - #113039

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stateless-job-silence-inherited-pipe
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stateless-job-silence-inherited-pipe

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108689

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 (amd_asan_ubsan, distributed plan, parallel) on
this report
lost its server around test 4291/12235, then produced no output for 1 h 55 m until the 9000 s
watchdog killed it. No test failed and no server log was uploaded.

Root cause: clickhouse-test spawned each test with start_new_session=True and no
stdout/stderr, so the bash -c "<test> > out 2> err" wrapper inherited its own fd1/fd2
(the redirect binds only the command it execs). Under CI those are the write end of
clickhouse-test | ts | tee, so a test escaping into its own session kept ts from seeing EOF:
tee never exited, proc.wait() never returned, and the job was SIGKILLed before
CHECK_ERRORS and COLLECT_LOGS. That is also why the shape carries no crash trace or
sanitizer report: those were never produced, so their absence says nothing about the server
(1 report link, versus 5 for the sibling job).

The spawn now passes explicit sinks: 12.03 s -> 0.03 s, with no timeout configured. Both
descriptors matter, since Shell.run joins both reader threads. Nothing is lost: the test's own
output already went to the per-test .stdout/.stderr files, and the wrapper writes nothing to
fd 1. Its fd 2 carries job status (a killed test, a bad redirect target, a syntax error) and
gets a .stderr-wrapper file of its own, reported after the retry check rather than sharing the
test's 2> target, which the test truncates and which is read back as the verdict. The job also
runs clickhouse-test --cleanup in a finally.

This does not fix #108689 and makes no claim about OOM; it makes the class attributable by
letting log collection and the dmesg OOM check run. A wedged but alive server is out of scope.
A local batch of 220 stateless tests gives identical statuses and reasons.


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

Stateless jobs intermittently finished with a job-level ERROR after producing
no output at all for almost two hours, until the 9000s job watchdog killed
them. No test failed and no server log was ever uploaded, which is what made
this class unattributable: the job was SIGKILLed before CHECK_ERRORS and
COLLECT_LOGS, so the crash trace, the sanitizer report and the dmesg OOM check
were never produced. Their absence said nothing about the server.

ci/jobs/functional_tests.py runs the suite as a shell pipeline,
`clickhouse-test ... | ts | tee -a`, and run_single_test spawned each test with
start_new_session=True and no stdout/stderr arguments. The spawned
`bash -c "<test> > out 2> err"` wrapper therefore inherited the write end of
that pipe, since the redirect binds only the command the wrapper execs. A test
that escaped into its own session outlived the worker, so `ts` never saw EOF,
`tee` never exited, the top-level bash never exited, and Shell.run blocked in
proc.wait() plus both reader joins until the watchdog fired.

Pass explicit sinks at the spawn site. The test's own output is already
redirected to the per-test .stdout/.stderr files and read back from them by
process_result_impl, so nothing is lost. The wrapping shell's stderr is
appended to the .stderr artifact rather than discarded, so shell level errors
that happen before the redirect takes effect (a bad redirect target, a syntax
error) stay visible. Detaching only stdout is not sufficient: Shell.run joins
the stderr reader too, so an orphan holding fd2 alone still blocks for its
whole lifetime.

Also run `clickhouse-test --cleanup` in run_tests' finally, so a test that
escaped stops consuming the machine and querying the server during teardown.
The finally placement covers every invocation, which matters because bugfix
validation calls run_tests once per build type.

Measured on the failing shape, with no timeout or watchdog configured:
12.03s -> 0.03s. A local batch of 211 stateless tests gives byte-identical
statuses and failure reasons with and without the change.

This does not fix the underlying runner-wide failures tracked in ClickHouse#108689 and
makes no claim about OOM. It makes that class attributable by letting the
diagnostic stages run. The claim covers the observed connection-refused shape,
where the server had already terminated; a wedged, alive-but-unresponsive
server is out of scope.

Related: ClickHouse#108689
The previous commit sent it to the test's `2>` target. That file is the wrong
destination for two measured reasons.

It is truncated by the test's own redirect, which opens it after the sink is
already open, so a message the shell emits before that point is written and then
destroyed. Measured with `LC_ALL` set to a bogus locale: the shell warns and the
file ends at 0 bytes.

And it is read back as `stderr`, where it decides the verdict. Non-empty `stderr`
is itself a FAIL, `<Fatal>` and `Connection refused` force `SERVER_DIED`, and the
string reaches the retry matcher. A job-status line quotes the whole command, and
`MESSAGES_TO_RETRY` holds substrings as generic as `No such file or directory`, so
a shell reporting an unopenable redirect target could retry a deterministic
failure up to `MAX_RETRIES` and report it as flaky.

Only the shell's own messages move; the two emitted after the fork with the
redirect already installed (`Permission denied` and `No such file or directory`
from a failed exec) are the test's stderr and are unaffected. The relocated text
is appended by `process_result`, which runs after the retry check, so it stays
visible in the job log without entering the verdict path. `hide_db_name` scrubbing
covers the new file, since those lines quote `--database=`.

An empty one is removed right after `proc.wait()`: `Popen` creates it whether or
not the shell writes, and the existing cleanup only runs for a passing test, so
without this a 220-test batch left 13283 empty files in the suite's tmp dir.

The tests now pin the spawn's argument VALUES rather than the presence of the
keyword names, which a mutation to `stdout=sys.stdout` satisfied while restoring
the wedge, and resolve the sink through the local assignment so a decoy `open` of
the same path cannot stand in for it.

The path is derived in both entry points, next to `fatal_sanitizer_prefix` and for
the same reason: `test_expect_debuglog_separation.py` drives them on namespace
stubs that carry only the artifact paths.
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open blockers)

I put this change through two rounds of independent review before opening it. Round 1 bounced it
with two majors; both are closed, and round 2 found nothing further. Recording the substantive
ones, since the second is the kind of defect that normally ships silently.

Round 1

⚠️ The wrapper's stderr shared the test's 2> target, which opened a retry channel. bash
emits two message classes from that wrapper and the first version treated them as one. Measured
with distinct sink and target paths:

class example where it goes
child-side (after the fork, redirect installed) Permission denied, exec No such file or directory the test's 2> target, unchanged by this PR
parent-side (the wrapper's own fd 2) Killed, Segmentation fault, syntax error, bad redirect target the runner pipe before, the new artifact now

Relocating a parent-side line into .stderr matters because that file feeds five decision
branches: non-empty stderr is itself a STDERR failure, <Fatal> and Connection refused each
force SERVER_DIED, and the text reaches MESSAGES_TO_RETRY twice. A job-status line quotes the
whole command, and that list holds substrings as generic as No such file or directory, so a
deterministic failure could have retried to MAX_RETRIES and been reported as flaky. Fixed by
giving the wrapper a separate .stderr-wrapper artifact, which also removes a truncation: with a
shared path, anything the shell emits before the test's redirect opens is destroyed (verified with
a pre-redirect setlocale warning: 73 bytes preserved with the separate sink, 0 bytes with the
shared one).

⚠️ The tests did not pin the production spawn. The timing arms drive an emulation of
run_single_test, because driving the real one needs a running server, and the only pin on the
real call site asserted keyword NAMES. So stdout=sys.stdout restored the original wedge with the
whole suite still green. Fixed by resolving argument VALUES through the AST, including the sink's
local assignment so a decoy open elsewhere cannot satisfy it.

💡 Two nits I disagreed with, on evidence: a request to duplicate the reap proof (already covered
end-to-end by ci/tests/test_cleanup_test_groups.py, which SIGKILLs a real worker and asserts the
group is gone), and a black reformat (only ruff is registered in the Style check, and it is at
merge-base parity).

Round 2

I re-derived the mechanism independently rather than re-reading the round-1 account: a live
/proc probe confirms the wrapper keeps fd1 = fd2 = pipe:[...] while its redirect binds only
the command it execs, which is why detaching one descriptor is insufficient.

Both fixes were then checked by mutation against the real file, each arm run, tree restored after
each: stdout=sys.stdout, stderr=DEVNULL, folding the report into the pre-retry description,
"ab" to "wb", deleting the empty-file guard, and pointing the wrapper path back at
stderr_file. All six redden, each on the intended test.

I also stressed the timing threshold, since a 3 s bound on a ~0.02 s operation is the sort of
thing that turns into a flaky test: 370 repetitions across idle, half-load, full 384-core load,
and 16-way concurrency. Worst observed 0.72 s, so the margin is over 4x at the worst and ~100x
typically; the full suite passed 12/12 consecutively, and separately 50/50.

Two properties worth naming because they were easy to get wrong. The empty-file removal cannot
discard a real message: when the wrapper itself is the kill victim it never writes (0 bytes at
proc.wait(), still 0 after killpg), and when only the test dies the wrapper does write
(105 bytes) and the getsize == 0 guard leaves it. And nothing downstream consumes the new
artifact: prepare_logs attaches only declared logs plus run_r* dirs, and the results parser
reads stdout lines, so the report-after-retry ordering holds at the call site and not just in the
AST pin.

@groeneai

groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The runner's pipeline shape (cmd | ts | tee) with an escaped test wrapper holding the inherited pipe: proc.wait() blocks for the orphan's full lifetime, 100% of runs, with no timeout or watchdog configured.
b Root cause explained? Yes. clickhouse-test spawned tests with no stdout/stderr, so the bash -c "<test> > out 2> err" wrapper inherited fd1/fd2 (the redirect binds only the command it execs). Under CI those are the write end of clickhouse-test | ts | tee, so an escapee keeps ts from seeing EOF, tee never exits, proc.wait() never returns, and the 9000 s watchdog SIGKILLs the job before CHECK_ERRORS/COLLECT_LOGS. Verified at fd level via /proc/<pid>/fd: the wrapper holds the pipe while the test and its children hold the redirect files.
c Fix matches root cause? Yes. It removes the inheritance at the single spawn site that creates it, rather than adding a timeout, watchdog or reaper to survive the wedge. Nothing under ci/praktika/ is touched.
d Test intent preserved / new tests added? Yes. No existing test weakened: where this change first broke test_expect_debuglog_separation.py, the code was changed to fit that file's contracts, not the reverse. 13 new tests across two files, including a documented negative arm that passes even unpatched, so a future author cannot silently disarm the fixture. Update 2026-09-27: master removed ci/tests and the CI Tests job that ran it, so the master merge drops both files; their 13 checks now run as a throwaway script, all passing on df5f3eb894204, and 8 of them fail against master's runner.
e Both directions demonstrated? Yes. Inherit 12.03 s vs detach 0.03 s. Separately, the retry channel is proven both ways on the real process_result_impl path: with the fix the wrapper text yields no MESSAGES_TO_RETRY match, with the old shared sink it matches No such file or directory. Nine mutation arms were each run and each reddens exactly one test.
f Fix is general across code paths? Yes. The change is inside clickhouse-test, so all three callers benefit (stateless via Shell.run, fast test via ClickHouseProc.run_test, quick functional tests). Swept every Popen in the file: the other two are short-lived diff/sed helpers that already pass sinks.
g Fix generalizes across inputs? Exercised .sh and .sql tests, --trace on and off, --memory-limit set and unset (the preexec_fn path), and tests that pass, fail on diff, fail on stderr, or fail at the wrapper level before any redirect takes effect. Both bash message classes were measured separately: child-side (Permission denied, No such file or directory from a failed exec) keep reaching the test's own stderr unchanged, parent-side job status goes to the new file.
h Backward compatible? Yes. CI harness only: no setting, no serialization format, no SettingsChangesHistory.cpp entry. The per-test .stderr artifact is byte-identical to before, so every consumer that reads it back keeps its current behavior.
i Invariants and contracts preserved? The invariant is that a test subprocess must not hold descriptors belonging to the CI runner's output pipeline; it now holds at the sole carrier. Preserved: the > {stdout} 2> {stderr} redirect, start_new_session=True (per-test killpg and the --memory-limit cgroup depend on it), proc.pid == PGID, the content of stderr (which drives the STDERR and SERVER_DIED verdicts and the retry matcher), and hide_db_name scrubbing, applied to the new file too since job-status lines quote --database=. The per-test artifact set still leaves nothing behind: an empty wrapper file is removed at proc.wait(), a non-empty one on the OK path. The sink fd is closed in a finally immediately after the spawn, so none leaks into the worker even if Popen raises, while the child keeps its own dup.

Validation detail: a real local batch of 220 stateless tests (.sh and .sql, 12 jobs,
--trace, one shared server, both arms in one run) gives identical statuses and failure reasons
with and without the change, and leaves zero stray artifacts either way. The new tests pass 50
consecutive runs (50/50). The full ci/tests/ suite goes from 6 failures on the merge-base to 4
with this change applied, a strict subset; all of them need a live server this environment does
not provide.

One deliberate behavioral change: with --memory-limit, a cgroup setup failure from
preexec_fn used to go to the job log and now lands in the test's .stderr artifact. The
verdict is unchanged; the message travels with the test result instead.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv @azat, could you review this? clickhouse-test spawned each test with start_new_session=True and no stdout/stderr, so the bash -c "<test> > out 2> err" wrapper inherited the write end of the job pipeline (the redirect binds only the command it execs), and a test escaping into its own session kept ts from seeing EOF, so the job produced no output until the 9000 s watchdog killed it before log collection ran.

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

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [df5f3eb]

Summary: ✅


AI Review

Summary

This PR fixes the stateless-job hang by detaching the per-test wrapper shell from the runner pipeline, routing the wrapper shell's stderr into its own reported artifact, and running clickhouse-test --cleanup after each run_tests invocation. I did not find a correctness or CI-behavior regression in the current diff: child-side stderr still drives verdicts and retries, the wrapper-only stream no longer pollutes the retry matcher, and the added stateless-job cleanup matches the existing orphan-reaping pattern already used by the other clickhouse-test entrypoints.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit df5f3eb.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
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: +183 lines in 51 files (-130 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 2, 2026
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 50efca4

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

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, sequential) / 04650_replace_cancellation oracle defect: one match, long instruction list: no timeout. The case reports the un-numbered channel, so the assertion falls back to bounding the client's wall clock, which a run whose in-function checkpoint never participated also satisfies #113034 (ours, open)
Build (arm_release) / Post Hooks telemetry hook: LogCluster query failed with code 500 on the build_time_trace INSERT (build_profile_hook.py); the build itself succeeded (check_status = success), so it does not gate this PR a fix task is moved to pending (investigating at full effort — fixing-PR link to follow on this PR)
CH Inc sync — CH Inc sync (private, not actionable)

All 175 check-runs are complete: 80 success, 94 skipped, 1 failure. Config Workflow,
Finish Workflow and Style check pass.

Neither row is caused by this diff. The 04650 row is the same signature #113034 was opened to
fix: that PR rewrites this exact oracle so a folded case must report the numbered channel instead
of falling back to wall clock, and its own description records this shape on arm_binary, sequential. The lane's own diagnosis on this run agrees the outcome is not reproducible (2 reruns
with the identical randomized settings, 0 failed). Breadth for this test on this check over 30 days
is 8 rows across 8 distinct pull requests plus 1 on master, so it predates this head. This PR
changes how the wrapping shell's stderr is routed, not the test's own stdout, which is what the
.reference diff is taken from — the failing line is a stdout line, and the recorded failure
carries no wrapper-stderr block.

The Post Hooks row is the build-profile telemetry upload path; breadth over 7 days is 1405 rows
across 201 distinct pull requests and 587 distinct commits.

Session id: cron:our-pr-ci-monitor:20260803-033000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 4, 2026
groeneai and others added 3 commits September 27, 2026 12:19
Master removed the `ci/tests` suite and the `CI Tests` job that ran it
(`5b3d66b1a66`, `8ff3720644b`), then removed a file a branch cut before that
had re-created (`5e8bf203b14`). `.claude/CLAUDE.md` now asks for a throwaway
check of a CI-script change rather than a committed test. This branch was cut
before the removal, so the two files it adds there are dropped: nothing would
run them, and keeping them would re-open that decision.

The one conflict is in `run_tests` in `ci/jobs/functional_tests.py`: master
changed how `outer_timeout` is derived, and this branch wraps the `Shell.run`
call below it in a `try`/`finally`. Kept master's derivation and the `finally`.

The fix itself is unaffected; what is lost is its CI-side unit coverage, which
has no runner upstream any more.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A non-passing test whose wrapping shell wrote a job-status line (for example a
test killed by a signal) keeps its `.stderr-wrapper` file next to its `.stdout`
and `.stderr`, like those two. When `clickhouse-test` runs from the repository,
that directory is `tests/queries/0_stateless`, where `.stdout` and `.stderr`
are ignored but the new file showed up as untracked. Add it next to
`*.stderr-fatal*`, the pattern the sanitizer report files got for the same
reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
It names the function, not a call, which `.claude/CLAUDE.md` asks to write
as `f`.

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

Copy link
Copy Markdown
Collaborator Author

Superseded by #112265 (merged 2026-09-27), which gives the per-test wrapper its own stdout and stderr, and #113393 (merged 2026-10-01), which reaps the groups the abort path orphans. Re-measured on current master's runner: with clickhouse-test SIGKILLed mid-test, its | cat pipeline sees EOF 0.01 s later; with the runner from before #112265, the orphaned wrapper holds it open for 38.7 s, until its test ends.

What is left here (a separate .stderr-wrapper file and a clickhouse-test --cleanup after the run in functional_tests.py) fixes no failure I can show on master, so I am not resolving the conflict. Can this PR be closed as superseded?

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

Labels

can be tested Allows running workflows for external contributors comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Runner-wide OOM (OOM in dmesg / Server died) on Stateless test runners, especially arm_asan_ubsan, azure

2 participants