Skip to content

Report why the stress script failed, not just its exit code - #114029

Open
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:stress-script-failure-reason
Open

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:stress-script-failure-reason

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113857

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

Stress test (*) and Upgrade check (*) wrap the stress script like this:

... && echo -e "Test script exit code$OK" \
    || echo -e "Test script failed$FAIL script exit code: $?"

The script's output is never redirected, so it reaches only the job console; the only thing
stress_job.py::read_test_results gets from test_results.tsv is the exit status. In the 30 days to
2026-08-09, all 152 Test script failed rows (133 pull requests, 6 on master, 11 flavours) had a
byte-identical info cell of script exit code: 1, and three of those job logs gave two unrelated
causes, so the family cannot be triaged from the CI database.

This captures the output and puts its tail into the info cell of the row the wrapper already emits,
outside /test_output (uploaded wholesale) so a passing run gains no artifact. The script is
redirected there and mirrored to the console with tail --pid, not piped: prepare_for_hung_check
drops databases with a fire-and-forget Popen(..., shell=True) inheriting the wrapper's stdout, so a
pipe reader waits for those clients long after the script exits.

Those clients can also append after the script exits, so the wrapper waits for the capture to stop
growing, then prints the bytes the mirror missed. The wait is a bounded size poll, never a wait on the
descriptor, which is what deadlocked the pipe form. An EXIT trap looks once more at job end, and
the advancing offset keeps anything from printing twice. A failing
run keeps the capture as stress_script.log.

escaped_tail encodes at one level for the Escaped rule, bounded so a wedged encoder costs the
cell rather than the row; escaped is untouched. The reader decodes \t, \r and \n only, so an
escape it does not decode keeps a visible backslash, and #113857 makes the codec reversible. This
fixes visibility, not the trigger: verify with length(test_context_raw) > 20, not by the rows
disappearing.

Validation (click to expand)

Every arm extracted the real wrapper block from each runner by content anchor and drove it with a
stub, asserting through the real read_test_results. None of it is in the tree: ci/tests/ has no
runner on master since #115650 removed it with the CI Tests job, so the 40 arms below are evidence
for this description rather than coverage this branch ships.

Row content: master gave a 20-byte info, this gives 517 bytes with the exception line, one parsed
row either way, and the same for a tab, CR, NUL, quote, backslash, embedded \n, a cut mid-UTF-8,
708 KB / 40001 lines, an empty capture and three replayed job logs.

Late writers, with a console pipe that ends with the container and survivors killed, as the job log
behaves: the piped form times out with an empty test_results.tsv; a child printing 2 s or later
lost the line from row and console before the drain and keeps it after; at 20 s and 30 s the console
and the artifact keep it where the previous head lost both, on both runners and when the epilogue
aborts early, matching master's console at every delay. A descriptor never closed bounds the wait at
16 s instead of hanging. Each line appears once, exit codes 0/1/42/143 are unchanged with an empty
capture, a non-empty capture and an unwritable artifact directory, where preservation warns, and a
passing run adds about 6 s and no artifact.

Mutations each reddened the relevant arm: inverting the exit-code comparison, deleting set +e or
the restoring set -e, capturing to /dev/null, echo -e for printf, the counted offset for the
file size (console 20/20 to 0/20 at a 1.0 s child), and removing the trap.

A passing run leaves the /test_output file set unchanged, and the shellcheck -x finding set
matches master on all three files.

@groeneai

groeneai commented Aug 9, 2026

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

An independent model reviewed the diff cold each round; a reviewer separate from the author
adjudicated. Final round returned 0 findings.

❌ The wrapper test proved the row but not the shell contract (raised 3 rounds, fixed)
The test sourced the real wrapper block and captured stdout/returncode, then asserted on
neither. Two mutations stayed green with a correct row: deleting the restoring set -e, which
leaves errexit off for ~60 further lines of stress_runner.sh and ~450 of upgrade_runner.sh;
and sending tee to /dev/null, which loses the console copy - today the only place the reason
appears. Both are now asserted from the run ($- for errexit, the stub's own output for the
console) and both mutations flip.

❌ The escaping caveat named the wrong class (fixed in the description)
The description claimed a literal backslash was the only display artefact. The Escaped rule also
escapes ', backspace and form feed, none of which the reader decodes. Measured against three real
Test script failed job logs: each has 2-3 escaped single quotes in its last 30 lines and none has
a backslash. The row is still one physical line with the exception legible; #113857 makes the codec
reversible.

⚠️ The byte cap truncates without a marker - not changed. FAILURE_TAIL_MAX_BYTES cuts from the
left, so the exception line, being last, always survives; the three real payloads are 1488-1706
bytes against a 3000-byte cap. A cut landing mid-UTF-8 was checked and does not corrupt the row.

⚠️ set +e is justified by more than a hypothetical pipefail - not changed. Without it, a
failing tee aborts the script under plain set -e and no row is written at all (reproduced).

⚠️ Encoder failure degrades silently - disagreed, with evidence. The degraded row is master's
row plus a (last N of M lines) marker, so it carries more than today. Propagating the failure
would abort before appending the only row that attributes the job failure, which is the
Unknown job error mode read_test_results exists to prevent.

💡 Three hunks reformat neighbouring test functions (black 26.5.1; the base file is not
black-clean). Left as is - black is not run in CI, and re-touching those lines adds conflict
surface with #113857.

Session id: cron:clickhouse-review-slot-11:20260809-101900

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The real wrapper block is extracted from the shipped runner and driven by a stub that prints a traceback and exits 1; the emitted test_results.tsv is asserted through the real read_test_results. No CI run needed, no randomness.
b Root cause explained? Yes. The stress script's stdout and stderr are never redirected, so they reach only the job console; the wrapper's `
c Fix matches root cause? Yes. The reason is written into the info cell of the row the wrapper already emits, at the one place the failure is already detected. No new gate, no new row name, no parser or consumer change, no change to any passing path.
d Test intent preserved / new tests added? Yes. 5 new test functions in ci/tests/test_stress_job.py, 17 collected cases before and 31 after; the 17 pre-existing cases are untouched. 14 distinct mutations of the change each redden, so the cases are not vacuous. Four make the feature actively wrong rather than merely absent: repointing the tee target, deleting the capture pipeline, and inverting the exit-code comparison in either runner. The last is what the row's polarity depends on, so it is driven end to end: the committed block is sourced against a stub for both outcomes and the row is read back through the real parser. Four more cover the block's shell contract rather than its row: deleting the post-pipeline set -e in either runner, and silencing tee's console half in either runner. All four wrote a correct row and were green until this round, so the row alone was not a sufficient oracle.
e Both directions demonstrated? Yes. Same repro: on master the row's info is 20 bytes with none of the stub's output; with the change it is 517 bytes containing the exception line. Measured on both stress_runner.sh and upgrade_runner.sh.
f Fix is general across code paths? Yes. Both wrapper carriers are fixed, and every acceptance arm runs against both. The other test_results.tsv producers already write a descriptive info. escaped()'s 9 pre-existing echo -e callers fragment multi-line rows by the same mechanism, which is a pre-existing defect owned by #113857 and deliberately untouched here.
g Fix generalizes across inputs? Yes. Payload matrix: python traceback, tab, CR, NUL, literal backslash, an embedded \n sequence, a double quote, 708 KB / 40001 lines, and an empty capture. Each yields exactly one physical line and one parsed row with no malformed rows; truncation is marked in the row; an empty capture degrades to exactly today's content. The truncation boundary is covered in both terminations, since a capture whose last line lacks a newline must be counted in the same unit tail -n drops or a truncated tail is presented as the complete output.
h Backward compatible? Yes. No settings, no serialization, no SettingsChangesHistory entry. The passing path, the /test_output file set and the console output are unchanged; the failure row only gains content in a cell that was previously empty. The console claim is asserted from the run, not just stated: the test requires the wrapped script's own output in the block's stdout, and appending >/dev/null to tee reddens it while leaving the row correct.
i Invariants and contracts preserved? Yes, and two the fix plan had not stated were found and guarded. First, with pipefail in effect set -e aborts at the capture pipeline, i.e. on the very failure this branch reports, before PIPESTATUS can be read; pipefail is not enabled in these scripts today, so it is latent, and it is guarded with the file's own set +e / set -e idiom and covered end to end in both directions: deleting the opening set +e writes no row at all, and deleting the closing set -e is caught by observing $- after the block, which is what proves errexit is actually restored for the ~60 further lines of stress_runner.sh and ~450 of upgrade_runner.sh rather than merely re-enabled in the text. Relatedly $? after the pipeline is tee's status, so the exit code comes from ${PIPESTATUS[0]}. Second, the count that decides the truncation marker must be the same unit tail -n drops; wc -l counts newline bytes instead, so an unterminated capture, which is what a killed script leaves behind, was counted one short.

Session id: cron:clickhouse-impl-slot-40:20260809-092900

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @maxknv, could you review this? The stress and upgrade wrappers only wrote $? into test_results.tsv, so all 152 Test script failed rows in the last 30 days carry a byte-identical 20-byte info cell and the reason lives only in the job console; this captures the output with tee and puts its tail into the same row, taking the exit code from ${PIPESTATUS[0]}.

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

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [27c390e]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

The PR moves the stress/upgrade script-output capture into shared helpers, mirrors the captured output back to the console without reintroducing the inherited-stdout hang, and appends the failure reason into the parsed Test script failed row instead of reporting only $?. I did not find any new correctness or reliability issues in the current diff, and the last prior clickhouse-gh finding about the unbounded escaped_tail path is fixed in the current code.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 9, 2026
Comment thread tests/docker_scripts/stress_tests.lib Resolved
@PedroTadim PedroTadim self-assigned this Aug 9, 2026
Comment thread ci/tests/test_stress_job.py Outdated

import os
import re
import shutil

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai remove this test file

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in c609339. ci/tests/test_stress_job.py is byte-identical to master again, so this PR is
three shell files.

One consequence worth stating: those arms were the only thing pinning the wrapper contract. With them
gone, inverting the exit-code comparison or sending tee to /dev/null leaves the suite green - I
checked both as mutants rather than assuming it. The measurements themselves are unaffected and stay
in the PR description, now marked as evidence from 1323f8d rather than as coverage this branch
ships.

If you would rather keep the contract pinned in a different shape, say where and I will add it.
Otherwise it stays out.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would leave ci/tests/test_stress_job.py out. The diff is back to shell-only, and the remaining concern is in the wrapper's parent-bound capture rather than in read_test_results, so reviving that removed Python harness would not close it.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai resolve the merge conflicts

@groeneai

Copy link
Copy Markdown
Collaborator Author

Resolved in 25177bb by merging master. The single conflict was in tests/docker_scripts/stress_runner.sh: master added --test-cmd carrying the storage-backend flags, and this branch had replaced the same invocation with a tee/PIPESTATUS capture. Both are kept, so the captured call now passes --test-cmd="/usr/bin/clickhouse-test${test_cmd_opts}".

Verified by running the resolved block with a stub stress.py: the stub receives --test-cmd with --s3-storage/--azure-blob-storage per the policy variables, and the failure row still carries the encoded output tail. Net diff against master is unchanged at 3 files, +77/-6.

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing da3a17e04 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, 3542 s compile time in total, 416 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 25177bb

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

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) job timeout at 10800s: the capture wrapper piped the script into tee, and prepare_for_hung_check leaves clients holding its stdout, so the pipeline never ended and no result row was written PR-caused -> fixed in this PR @ f083090
Stress test (amd_asan_ubsan) / Sanitizer (STID: 1367-26c6) LeakSanitizer, 0 direct leaks, allocation rooted at QueryTreeBuilder::buildExpression -> ConstantNode -> IDataType::createColumnConst; all four durability gates OK a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found wedged in TableFunctionMerge::executeImpl -> StorageMerge -> OptimizedRegularExpression under QueryAnalyzer::resolveTableFunction, i.e. plan-time work that does not observe cancellation #113140 (external, open)

Notes on the two non-mine rows, so the attribution is checkable:

The amd_tsan row is worth one extra line because it was mine and it was new: stress.py logged
Stress test finished, then the job printed nothing for 2h09m and was killed by the wrapper timeout,
producing zero result rows. Reproduced locally by running the real wrapper block from each runner
against a stub whose descendant keeps stdout: the piped form times out with an empty
test_results.tsv, the redirect form now shipped exits with the script's own status and writes the
row with its captured tail.

Session id: cron:clickhouse-maint-slot-19:20260810-161502

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_asan_ubsan) / Sanitizer (STID: 1367-26c6) row above: #113397
(external, open). That row's owner upgrades from a fix task to this link.

I had left it as a fix task because the STID did not match the one #113397 was attached to. It is the
same defect. Splitting the artifact into individual leak blocks and counting frames per block:

artifact blocks direct resolveMaterializingCTEs / DelayedMaterializingCTEsStep MaterializedCTE
1367-26c6 (master b2111a71) 1083 0 16 67
2064-22d0 (master ddf3e53e) 788 0 16 60
2868-2d0a (master c8fd3653) 936 0 16 60
2064-2dbf (control) 46 0 0 0
3671-3a9b (control) 2 2 0 0

The three buckets carry the same cycle; the controls carry none of it, so the frame test
discriminates rather than matching every report on this lane. MaterializingCTEStep.h at both
failing master shas is byte-identical to master and still has the strong member, so #113397 is
absent from those builds and none of these rows is evidence against it.

This branch changes three shell files under tests/docker_scripts/ and nothing else, so it cannot
leak analyzer memory.

Comment thread tests/docker_scripts/stress_runner.sh Resolved
`Stress test (*)` and `Upgrade check (*)` never redirected the stress script's
output, so it reached only the job console and `test_results.tsv` recorded the
exit status alone. In the 30 days to 2026-08-09 all 152 `Test script failed` rows
carried a byte-identical ` script exit code: 1`, so the family could not be
triaged from the CI database; reading three of those job logs gave two unrelated
causes.

The script is now redirected to a capture outside `/test_output`, which is
uploaded wholesale, and mirrored to the console with `tail --pid`. It is not
piped: `prepare_for_hung_check` drops databases with a fire-and-forget
`Popen(..., shell=True)` that inherits the wrapper's stdout, and a pipe reader
waits for those clients long after the script exits, which timed the job out at
10800 s. The exit code is `$?` after `wait`, and the tail of the capture goes
into the `info` cell of the row the wrapper already emitted.

Those clients can also append after the script exits while the mirror ends with
it, so the wrapper waits for the capture to stop growing and then prints the
bytes the mirror missed. The wait is a bounded size poll rather than a wait on
the descriptor, since that is what deadlocked the pipe form, and the flush offset
is the mirror's own byte count because the file size afterwards can already
include unmirrored bytes.

`escaped()` pre-compensates its row terminator for `echo -e`, which collapses one
escape level, so a `printf '%s'` caller would get a backslash before every
decoded newline. `escaped_tail()` is its single-level sibling and `escaped()` is
untouched. The reader decodes `\t`, `\r` and `\n` only, so a byte the `Escaped`
rule encodes but it does not keeps a visible backslash; ClickHouse#113857 makes the codec
reversible. This fixes visibility, not the trigger.

Related: ClickHouse#113857

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai
groeneai force-pushed the stress-script-failure-reason branch from f083090 to ac22635 Compare August 10, 2026 21:20
The wrapped script leaves clients holding its stdout, so the capture keeps growing
after the script exits. The settle wait bounds how long the result row waits for
that, which is deliberate: waiting on the descriptor is what timed the job out at
10800 s before the wrapper stopped using a pipe. But once the wait gave up, the
remaining bytes were only in /tmp/stress_script.log, which is outside /test_output
and is not collected, so they reached neither the console nor the artifacts. Master
piped the script straight to the job log and therefore printed that output at any
delay, so this was a regression against it rather than a pre-existing gap.

The wrapper now looks at the capture once more when the job ends, from an EXIT trap
so that an epilogue command failing under errexit, the post-stress start_server
failure and the upgrade allow-list exit are all covered. Whatever arrived since the
row was composed goes to the console, and a failing run keeps the capture next to
the other artifacts. flush_capture reports where it stopped and finalize_capture
advances that offset, so no byte is printed twice. Nothing in the trap may fail: a
failure inside a trap body under errexit would replace the status the job reports,
which is why a failed preservation warns instead of returning non-zero.

Measured on both runners with a parent exiting 1 after spawning a child that prints
later. Console and artifact keep a 20 s and a 30 s line where the previous head lost
both, including on an epilogue that aborts before its last line, and master's console
keeps it at every delay. An immortal descriptor holder still finishes in seconds
rather than hanging, a passing run gains no artifact, no line is printed twice, and
exit codes 0/1/42/143 are unchanged with an empty capture, a non-empty capture and an
unwritable artifact directory.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a00d437

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
Stress test (arm_tsan) / Hung check failed, possible deadlock found trunk bug, not PR-caused — a cancelled DROP TABLE prometheus (is_cancelled: 1, elapsed 968 s) never returns from DatabaseCatalog::waitTableFinallyDropped, reached via StorageTimeSeries::dropInnerTableIfAny; the whole test-database teardown then convoys behind the DDL guard. This job's Test script exit code node is OK, so the shell changes in this PR are not implicated #113397 (external, open)

Build (arm_release) / Post Hooks is fleet-wide bookkeeping noise on a check that concluded
success, so it is not an owned failure.

Session id: cron:our-pr-ci-monitor:20260812-113000

@PedroTadim

Copy link
Copy Markdown
Member

cc @maxknv and @leshikus this PR is worth to merge to improve the CI report, but a more careful review is needed first

andremm pushed a commit to andremm/ClickHouse that referenced this pull request Aug 12, 2026
…on one client timeout

The stress harness died before any stress testing started: in
`install_thread_pool_fault_injection`, the verify query
`SELECT value FROM system.server_settings WHERE name = 'cannot_allocate_thread_fault_injection_probability'`
hit the client's 15 s `receive_timeout` right after `SYSTEM RELOAD CONFIG`
and the single `check_output` call took the whole job down with
"Test script failed, script exit code: 1". The reload itself already goes
through `call_with_retry`, but the verification did not. Seen on unrelated
PRs ClickHouse#110970 and ClickHouse#114029 on 2026-08-09 (`Stress test (arm_debug)`): a debug
server under ThreadFuzzer can be slow enough right after a config reload.

Give the verify query the same retry treatment (5 attempts, backoff), and
keep the fail-close behavior if it persistently fails or the setting is
inactive.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110970&sha=2ece842784cf0369655d3a55a7b4363eb3977f50&name_0=PR&name_1=Stress%20test%20(arm_debug)
ClickHouse#110970
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
Comment thread tests/docker_scripts/upgrade_runner.sh Outdated
# Same capture wrapper as in stress_runner.sh: redirect, not a pipe, because the script leaves
# clients holding its stdout and a pipe reader waits for those too.
: > /tmp/stress_script.log
set +e

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai I think a lot of this code can be deduplicated

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in da3a17e: the block is now run_capturing_output in stress_tests.lib, so this runner is 4 lines where it was 36. Details in the thread on stress_runner.sh.

Comment thread tests/docker_scripts/upgrade_runner.sh Outdated
# The mirror ends with the script, but descendants inherit its stdout and can still
# append. Only a failure row embeds those bytes, so only it pays the settle wait; the
# flush is what puts them on the console either way.
if [ "$stress_script_exit_code" -ne 0 ]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai the branches here look identical, you can simplify this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Gone with the dedup in da3a17e: the status branch is a single append_script_result_row call in stress_tests.lib now, in both runners.

Comment thread tests/docker_scripts/stress_runner.sh Outdated
# past those bytes and never print them. Only `tail` writes to this pipe, so unlike a
# pipe around the script itself it cannot be held open by an inherited descriptor.
exec 3>&1
mirrored_bytes=$(tail -n +1 -f --pid="$stress_script_pid" /tmp/stress_script.log \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵️
@groeneai Reviewed a00d437 and ran the wrapper block from both runners against a stub. One reproducible defect, one structural ask, then I'm happy to merge this.

1. The console mirror is lost when the job's stdout is a regular file

exec 3>&1
mirrored_bytes=$(tail -n +1 -f --pid="$stress_script_pid" /tmp/stress_script.log \
    | tee /dev/fd/3 | wc -c)

tee /dev/fd/3 does not dup fd 3 — it open()s the path, which resolves through /proc/self/fd to the underlying file and yields a new file description with its own offset. The parent's fd 1 offset stays where it was, so the parent's later writes overwrite the mirrored bytes.

mirror form stdout = pipe stdout = regular file
tee /dev/fd/3 (this branch) both lines mirror lost — only the parent's bytes survive
tee -a /dev/fd/3 both lines mirror lost — append does not help, the parent still writes from its own offset
tee >(cat >&3) both lines both lines, in order

Full wrapper run, failure path, stub with a grandchild that prints at 8 s: piped stdout gives 84 bytes and all four lines; > console.log gives 46 bytes beginning at the flush, with line one and traceback: RuntimeError boom gone — while mirrored_bytes=52 still reports them as shown, so the offset bookkeeping then skips them in the flush too.

Minimal probe:

#!/bin/bash
printf 'AAA-from-tee\n' > /tmp/src.log
exec 3>&1
x=$(cat /tmp/src.log | tee /dev/fd/3 | wc -c)   # vs. tee >(cat >&3)
exec 3>&-
printf 'BBB-from-parent\n'

bash probe.sh | cat keeps both lines; bash probe.sh > o.log keeps only BBB-from-parent.

In CI the container's stdout is a pipe, so the CI path is unaffected — which is why every validation arm passed. It bites ./stress_runner.sh > log 2>&1, i.e. the local-reproduction workflow this PR exists to serve. One line in each runner: | tee >(cat >&3) | wc -c. Residual nit worth a comment: cat in the process substitution may not have flushed before the parent's next write, so a small interleaving race remains at the boundary — far better than total loss.

2. Please deduplicate the block into stress_tests.lib

stress_runner.sh:305-349 and upgrade_runner.sh:131-174 are byte-identical apart from the wrapped command: 35 lines of fd juggling, an errexit window, an EXIT trap and offset arithmetic, in two copies. The earlier pipe form of this same block cost a 2h09m Stress test (amd_tsan) timeout, so drift here is expensive — and the fix above has to be applied twice precisely because the block was not factored out.

The lib is sourced rather than executed, so set +e/set -e inside a function affects the caller's shell and trap is global. Something like run_capturing_output <capture-path> <cmd...>, returning the command's status, should carry the whole block.

I'd like this in before merge rather than as a follow-up.

3. Coverage

My objection was to a harness that sources the runner and drives it with a stub, and that still stands. But three of the five new lib functions — script_failure_info, flush_capture, drain_capture — are pure: file in, string out, no server, no docker, no runner-sourcing. Covering just those pins the encode/offset/truncation logic, which is the part most likely to break silently, without reintroducing what I asked you to drop. Your own note that inverting the exit-code comparison and pointing tee at /dev/null now both leave the suite green is the argument for it.

4. Smaller items, none blocking

  • set -ex is active in both runners, so drain_capture's poll emits roughly 10 trace lines/sec for up to 30 s into the job console, interleaved with the mirrored capture. set +x around the loop would keep it readable.
  • mirrored_bytes=${mirrored_bytes//[^0-9]/} yields "" when wc -c produced nothing, and finalize_capture's ${mirrored_bytes:-0} then re-prints the entire capture to the console. Fold the default into the sanitizer line instead of relying on each call site.
  • The truncation marker counts lines (awk END{print NR} / tail -n), but right(s, $FAILURE_TAIL_MAX_BYTES) then cuts bytes, so a row can say "last 30 of 200 lines" while showing 12. Also, the Escaped rule expands as it encodes, so the cell can reach roughly 6 KB against a constant named ..._MAX_BYTES=3000.
  • /test_output/stress_script.log is the whole capture, unbounded, and on a failing run those bytes are already in the job console log — a tail-capped artifact would be cheaper.
  • exec 3>&1 clobbers fd 3 without saving it. Nothing in the three files uses fd 3 today, so it is fine; a comment would keep it that way.

Checked and sound

set -e restoration is correct — both runners are set -ex at the top, so errexit really was on. Neither file has a pre-existing EXIT trap, so the new one clobbers nothing, and it does cover start_server 10 || { …; exit 1; } at stress_runner.sh:326. wait after the command substitution returns the script's status, and exit-code propagation held for 0 and 1. escaped_tail's Escaped rule escapes tabs — unlike the pre-existing escaped() — so the row stays four cells and read_test_results' len(line) == 4 check is satisfied; its csv.reader quotechar cannot trigger because the cell always starts with " script exit code: ". drain_capture honours its 15 s grace and 30 s ceiling (measured 15 s on the failure path, with the late 8 s child recovered into both console and artifact). Trap-body failures cannot replace the job status.

Happy to re-review as soon as 1 and 2 are in.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai are you going to look at this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Sorry for the delay. Both are in, at da3a17e.

1. The mirror. Fixed as you suggested, | tee >(cat >&"$mirror_fd") | wc -c. Your probe is now a test parametrized on what stdout is: mutating it back to tee /dev/fd/N reddens the regular_file arm and leaves pipe green, which is your table exactly. I used a named fd rather than 3 so nothing here can clobber a caller's descriptor, which also covers your last item under 4.

2. Deduplicated. The block moved into stress_tests.lib as run_capturing_output <capture-path> <cmd...>, returning the wrapped command's status with errexit still off, plus append_script_result_row for the row. Each runner is now 4 lines where it was 36 lines. Fixing the mirror once rather than twice is the immediate proof of your point.

3. Coverage. ci/tests/test_stress_capture_lib.py, 40 tests: the three pure helpers, and the wrapper driven by a stub, no server, no docker, no runner sourced. Two properties are load-bearing and every test I had would have stayed green without them, so both now have a test confirmed to redden under the mutation it describes:

  • a descendant that outlives the drain and is reaped only after the wrapper returns, bounded by timeout. Restoring the direct-pipe form exits 124 there. That is the regression that cost the 2h09m amd_tsan timeout.
  • the wrapped command's status is not the runner's: upgrade_runner.sh's allow-list exits 0 after a failing script, so reading the trap's own $? drops the artifact on the run that most needs it. That mutation now fails too.

Also || true on the wrapped-command line made $? read zero and emitted an OK row for a failed stress script, with every runner guard green, because that is the one line they skip by design. Guarded now, in both runners.

4. set +x around the poll via local -; the ${...:-0} default folded into the sanitizer; the truncation marker reports whichever limit bit, in its own unit (last 3000 of 15090 bytes vs last 30 of 200 lines), which was also wrong about the count. Not done: the tail-capped artifact. It is a size question independent of this change and you marked it non-blocking, so say the word if you want it here rather than separately.

Residual, unchanged: a writer slower than the settle wait reaches the console but not the row's info cell. No worse than master on any channel master had.

…e mirror

Review feedback on the capture wrapper this PR adds to the two stress runners.

The mirror used `tee /dev/fd/3`, which does not duplicate fd 3: tee `open()`s the
path, and for a regular-file stdout that resolves to a second file description
with its own offset, so the shell's later writes overwrite the mirrored bytes.
CI redirects the container's stdout to a pipe, where the two forms behave the
same, which is why every arm passed; a local `./stress_runner.sh > log 2>&1`,
the reproduction workflow this reporting exists to serve, lost the mirror
entirely. Mirroring through a process substitution writing to a duplicated
descriptor keeps it in both shapes. Measured with the shipped block driven
against a stub whose grandchild prints late: with stdout a regular file the old
form kept 153 bytes and dropped the first two lines from the console, the new
form keeps all 191 in both shapes.

The block was byte-identical in `stress_runner.sh` and `upgrade_runner.sh` apart
from the command it wrapped, so the mirror fix would have had to be applied
twice. It now lives in `stress_tests.lib` as `run_capturing_output`, which
returns the wrapped command's status with errexit still off, exactly as the
inline window did. Each runner keeps three lines instead of thirty-four.

The truncation marker counted lines while `escaped_tail` cuts bytes, so a row
could read "last 30 of 200 lines" and show eleven, and a capture cut from 15030
bytes to 3000 was reported as untruncated. It now names whichever limit bit, in
that limit's unit. `drain_capture`'s poll runs with xtrace off, scoped by
`local -`, instead of tracing about ten lines a second over the mirrored output.
The `wc -c` sanitizer folds in its own default rather than leaving each reader to
guard an unset offset.

`ci/tests/test_stress_capture_lib.py` covers the three pure helpers -- file in,
string out, no server, no docker, no sourcing of a runner. Every assertion was
checked against a mutant: reporting lines where bytes were cut, `wc -l` for the
line count, an off-by-one flush offset, a flush that does not advance, an ignored
grace floor, an unbounded wait, a leaked xtrace, a dropped `Escaped` rule and a
head-instead-of-tail cut each turn it red.

Exit codes 0, 1, 42 and 143 still propagate, a passing run still leaves no
artifact, and the EXIT trap still recovers post-settle bytes on the early exits
after the wrapper without replacing the status the job reports.
Review of the previous commit found three things.

The wrapper itself had no coverage: breaking the mirror, the exit-code polarity,
the artifact gate or the `EXIT` trap left every test green. Now that the block is
a library function rather than a copy inside each runner, covering it needs only a
stub command, not a harness that sources a runner. Six cases were added, over both
stdout shapes.

`test_drain_capture_waits_for_a_late_writer` asserted nothing. With a 2 s grace
the drain returned at 3 s, before the writer's 6 s sleep, and the late byte was
only on disk by the time Python read the file because `subprocess.run` collects
output and so waits for the writer's inherited pipes to close. A no-op drain
passed it. The write is now scheduled inside the grace window and the capture is
snapshotted in the shell the instant the drain returns.

The `EXIT` trap comment claimed a caller exiting with a different status would be
reported with that status. It would not: `captured_exit_code` is assigned once
from `wait` and no caller reassigns it, so the trap always sees the wrapped
command's status. That is the behaviour the artifact gate wants -- a later failure
of the runner's own does not make the capture worth uploading -- so the comment
was wrong, not the code.

Each of the fifteen assertions was then checked against a mutant of the code it
covers: the mirror opened as a path, the mirror pointed at `/dev/null`, an
inverted exit-code comparison, a swallowed status, errexit restored too early, a
dropped artifact copy, a dropped final flush, a line-unit truncation marker,
`wc -l` for the line count, an off-by-one flush offset, a flush that does not
advance, an ignored grace floor, an unbounded wait, a leaked xtrace, a dropped
`Escaped` rule and a head-instead-of-tail cut. All fifteen turn the suite red.

Two of those mutants survived the first attempt and the tests were fixed rather
than the finding argued: the late-output delay now sits between the two graces, so
it pins which grace a failing run gets, and the early-exit case writes past the
drain ceiling, so the trap is provably what recovers it. That case also needed
`exec >` instead of a `{ ... } > file` group -- a group's redirection is undone
before the shell's EXIT trap runs, which made the trap's flush look lost when it
was the harness at fault. The runners are redirected by the job the same way.
…dget

Second review round on the same change.

The result-row branch was still duplicated: it was byte-identical in both runners,
and nothing covered it, so inverting either runner's success predicate would have
reported a failing stress job as a pass with every test green. It moves to
`append_script_result_row`, alongside the wrapper. Each runner's whole capture and
reporting sequence is now six lines, down from forty-one, and both branches of the
row are covered -- status column, the reason in the info cell, four fields on one
line, and appending rather than truncating a results file earlier stages wrote to.

The tests spent 217 seconds in real sleeps, against a 600-second timeout that
covers all forty-six files in `ci/tests`. They now rewrite the drain constants in
their own copy of the library rather than waiting the production 5/15/30 seconds,
and only the one case that has to tell the two graces apart uses a wide gap; the
rest use a narrow set. 78 seconds, and `test_the_production_timing_constants` reads
the shipped file directly, so relaxing a real constant still fails -- verified by
raising the production timeout to 300 and the grace to 60, each of which turns it
red.

The full matrix is now twenty-three mutants, none surviving: the mirror opened as a
path or pointed at /dev/null, an inverted exit-code comparison, a swallowed status,
errexit restored too early, a dropped EXIT trap, a dropped artifact copy, a dropped
final flush, an ignored grace floor, an unbounded wait, a leaked xtrace, a
line-unit truncation marker, `wc -l` for the line count, an off-by-one flush
offset, a flush that does not advance, a dropped `Escaped` rule, a
head-instead-of-tail cut, an inverted row predicate, a row without its reason, a
truncating row on either branch, and two relaxed production constants.

shellcheck is unchanged on both runners and one finding better on the library.
Third review round, both gaps in the tests rather than the code.

The encoder-failure guard had no coverage: ignoring `escaped_tail`'s status and
accepting its partial output would have stayed green, and partial output carries
raw newlines, which splits the row so `read_test_results` drops both halves. Two
cases now drive it with a broken encoder -- output then a nonzero status, and a
clean status with no output -- and assert the explicit diagnostic, that the row is
still one line of four fields, and that none of the partial output leaked in.
Ignoring the status, dropping the empty-output check and removing the diagnostic
each turn them red.

The runners' call sites were also uncovered. They are checked statically rather
than by sourcing a runner and driving it with a stub: that harness shape was
rejected in review, and the runners reach these lines only after installing
packages and starting a server. What is left in each is two library calls, a `$?`
read and a `set -e`, so the failure modes are drift between the two copies and a
path mismatch, both visible in the text. Seven cases assert that each runner wraps
and reports only through the library, that no copy of the replaced block remains,
that the status is read from `$?` with errexit restored on the next line, that both
helpers get the same capture path, that the capture stays out of the
wholesale-uploaded directory, and that the two runners' sequences are identical
apart from the command being wrapped.

Mutating the runners confirms they discriminate: deleting the caller's `set -e`,
reading a constant instead of `$?`, pointing the row at a different capture,
removing the wrapper, and moving the capture into `/test_output` each turn them
red. 35 tests, 80 seconds.
The wrapper tests could not detect reintroducing either defect they exist to
guard. Every stub closed its output within seconds, so a direct pipe -- the form
that cost a 2h09m Stress test (amd_tsan) timeout -- would still have finished
inside the harness timeout and stayed green. And the only early-exit case paired
a failing script with a failing job, while upgrade_runner.sh's allow-list exits
0 after a failing script, so reading the trap's own $? instead of the wrapped
status would have dropped the artifact on the run that most needs it.

Add a descendant that outlives the drain and is reaped only after the wrapper
returns, bounded by timeout so a waiting reader fails by name; the real 1/0
status pair; and a passing script whose late output must still reach the console.
Each was confirmed to redden under the mutation it describes.
…holder

The wrapped command is excluded from every runner guard, because it is what
legitimately differs between the two runners. That left the line where a status
suffix does the damage uncovered: `|| true` there makes the following `$?` read
zero and emits an OK row for a failed stress script, with all seven runner guards
still green. Reject status-transforming suffixes on that line, in both runners.

The descriptor-holder test also leaked its `sleep 600`. It is reparented to init
when the timed shell exits, so parent-based cleanup could not find it; record the
PID and kill it from a trap that also covers the timeout path.
…re-reason

The only conflict was in the module-level constant block at the top of
stress_tests.lib, where both sides appended: master added
START_SERVER_READY_TIMEOUT and this branch added the seven FAILURE_TAIL_*
and FAILURE_DRAIN_* tunables. Both are kept; neither side's constant is
referenced by the other, and START_SERVER_READY_TIMEOUT remains live at
its only consumer, start_server's ready_timeout default.

The remaining master hunks in stress_tests.lib, stress_runner.sh and
upgrade_runner.sh auto-merged (the analyzer/window-view config drop-ins,
report_start_failure, and the "kill -s 0 || return 0" fix).
ClickHouse#115650 removed ci/tests/ and the "CI Tests" job from master. Nothing on
master executes that directory any more: outside ci/tests/ itself the only
remaining references are the doc examples in ci/praktika/cache.py, and
ci/defs/ has no ci_tests job config at all. A file added there merges
without a conflict because this branch forked before the removal, so the
suite would have shipped as 783 lines that no job can run.

The reviewer's only request about this directory on this PR was to remove a
test file from it, which is the same disposition.

The helpers keep their coverage as the local validation arms recorded in the
PR description: each arm extracts the real wrapper block from the runner by
content anchor and drives it through the real read_test_results, and the
suite is retained out of tree as evidence rather than as coverage this
branch ships.
The library runs under `set -ex`, and script_failure_info composes the row
in four traced steps (the encoded assignment, the emptiness test, the inner
printf and the info assignment). Each one expands the payload, so a failure
reason up to FAILURE_TAIL_MAX_BYTES was echoed to stderr four extra times on
top of the row and the console mirror, which is the opposite of what a
capped, single-copy failure cell is for.

Measured with a marker payload and a stub caller: five occurrences on stderr
before, one after, and re-removing these two lines restores four, so the
suppression is what carries it. The remaining occurrence is the printf in
append_script_result_row, which traces the row it is appending.

Same `local -` idiom already used by drain_capture, so the caller's own
xtrace setting is restored on return.
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (d37d2ea3fbb5) to clear the conflict. The only conflicting hunk was the
module-level constant block in stress_tests.lib: master added START_SERVER_READY_TIMEOUT,
this branch added the FAILURE_TAIL_* and FAILURE_DRAIN_* tunables. Both are kept, and
START_SERVER_READY_TIMEOUT is still live at its only consumer, start_server's
ready_timeout default.

I also dropped ci/tests/test_stress_capture_lib.py. #115650 removed ci/tests/ together with
the CI Tests job, so nothing on master executes that directory: outside ci/tests/ itself the
only references left are the doc examples in ci/praktika/cache.py, and ci/defs/ has no
ci_tests job config. This branch forked before that removal, so the file merged with no
conflict and would have shipped as 783 lines no job can run. That is the same disposition you
asked for on ci/tests/test_stress_job.py here. Those arms still run against the tree out of
band and are listed under Validation as evidence rather than as coverage this branch ships.

One behaviour change while I was in the file: script_failure_info composes the row under the
library's set -ex, so every step expanded the payload into the trace. With a marker payload and
a stub caller, stderr carried 5 copies before and 1 after, the remaining one being the printf
in append_script_result_row that traces the row it appends. Suppressed with the same local -
idiom drain_capture already uses.

The diff against master is now the three tests/docker_scripts/ files, +209/-6.

Comment thread tests/docker_scripts/stress_tests.lib Resolved
`script_failure_info` runs after the wrapped script has already failed, and it
encodes the captured tail with `clickhouse local` from the installed package,
which is the binary the job is stressing. The call was unbounded, so a wedged
encoder blocked both runners at the point that is meant to explain the failure,
and the job reported a timeout with no `Test script failed` row at all.

Measured against the shipped library with a stub `clickhouse` on PATH: before,
`append_script_result_row` never created the results file; after, the row is
written with four tab-separated fields and the reason cell degrades to
`script exit code: 7 (could not encode the captured output)`, the branch that
already existed for a nonzero encoder status.

`--kill-after` is load bearing rather than decoration: against a stub that
ignores TERM, a bare `timeout 3` waited the child's full 120 seconds, and
`various_checks.sh` already refuses `timeout --signal` without it for that
reason. The form mirrors `stress_runner.sh:221`. The 60 second bound is about
300x the measured cost of the encode (0.19s over five runs of a debug build),
so a slow encoder still yields the reason instead of losing it to a tight bound.
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 27c390e

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

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) The log scan hits a background mutation that retries forever with Code: 47 UNKNOWN_IDENTIFIER on a duplicated analyzer scope list. Not caused by this diff, which changes only tests/docker_scripts/*: the identical signature (same three loggers, same all_1_1_1_2 part, same collapsed scope list) is on 30 distinct PRs over 30 days and on 0 true-master runs. #115962 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are aggregator rollups of the row above, not independent results.

170 check-runs completed, 1 red. Test script exit code is OK in that same Upgrade check, so the reporting path this PR adds worked on the run that flagged the log scan.

Session id: cron:our-pr-ci-monitor:20260905-200140

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants