Skip to content

A single test's timeout no longer aborts the whole clickhouse-test run - #115061

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/per-test-timeout-no-group-kill
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/per-test-timeout-no-group-kill

Conversation

@groeneai

@groeneai groeneai commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #86768

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

The problem. Fast test on #86768 reported Failed: 0, Passed: 73, Skipped: 23 yet failed with a synthetic Server died leaf. No core, no sanitizer report.

Report | job log

Root cause. The server saturated rather than died, so all 24 workers hit the 126 s alarm at once. The first into timeout_handler called stop_tests(), which killpgs our own group, shared by every worker and the parent. One test's deadline thus SIGTERMed the whole run, exiting -15, which ABORTED_RUN_EXIT_CODES makes the job side relabel Server died. The Code: 76 on run_r0/status and the Code: 159 from SYSTEM FLUSH LOGS are downstream of it.

The change. timeout_handler now kills only the timing-out test's own out-of-group clients, via a per-child loop extracted from cleanup_child_processes. That broadcast is unchanged, so the whole-run callers are unaffected, as the --max-failures paths document.

A surviving worker must then report the test, which needs a result built and stamped. The alarm can land before either, so the recovery arm completes what is missing, and SIGALRM is blocked across stamping so it cannot run twice: a doubled description matches the leaf pattern too, reporting a nonexistent test.

Fast test just has the shortest fuse. This does not fix the saturation.

Validation. Not SQL-observable. The new ci/tests/ test drives the real handler and run_tests_array, faking killpg/pgrep: own-group broadcasts 0, the test's own client still killed, cleanup_child_processes still broadcasting, one parseable leaf per alarm window. No wall clock. ci/tests/ is 663/665, both failures pre-existing.

Residuals. A timed-out test's database and temporary directory survive into the worker's next test, as when the alarm killed the worker outright. An alarm can also be swallowed by an unrelated broad except Exception, after which saturation reports SERVER_DIED, as master did on every per-test timeout. Both want a private signal type, a larger change.


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

Fast test on ClickHouse#86768 reported "Failed: 0, Passed: 73, Skipped: 23" and still
failed, with a synthetic "Server died" leaf. No test failed and the server
never crashed: no fatal message, no core, no sanitizer report.

The server saturated (not died) at 15:02:02 and stopped admitting new queries.
Keeper heartbeats and cleanup scheduling kept flowing, while 33 of 51 liveness
requests logged "Creating query context from session context" with no
executeQuery after it. The per-test alarm is int(args.timeout * 1.1) + 60, and
Fast test passes --timeout 60, so the budget is 126 s. Because the stall was
server-wide rather than specific to one test, all 24 workers armed and fired at
once. The first worker into timeout_handler called stop_tests(), which reaches
os.killpg(pgid, SIGTERM) on our own process group. Every worker and the parent
share that group, so one test exceeding its own deadline SIGTERMed the entire
run. clickhouse-test then exits -15, which is in ABORTED_RUN_EXIT_CODES, so
FTResultsProcessor relabels a fully green run as "Server died".

The two errors visible in the job log are downstream of that kill, not
independent problems: Code 76 on ci/tmp/run_r0/status, because teardown runs
prepare_logs(all=True) before terminate() and so dumps system tables while the
server still holds its flock, and Code 159, because SYSTEM FLUSH LOGS then
flushes a four-minute query_log backlog on an already-saturated server.

A per-test timeout was using a whole-run teardown primitive. Extract the
per-child walk from cleanup_child_processes into kill_out_of_group_children and
call only that from timeout_handler, so the timing-out worker reaps its own
out-of-group clients and then raises TimeoutError, reporting one honest failed
test. cleanup_child_processes keeps its own-pgid broadcast unchanged, so the
whole-run callers (server-died, KeyboardInterrupt, stop-requested, --stop-time)
behave exactly as before. The --max-failures paths already skip stop_tests() for
this reason, and their comments name the same "143 / Server died" hazard.

This is suite-agnostic; Fast test just has the shortest fuse. It does not
address the saturation itself, which is a separate load question. After this
change a saturated server yields per-test TIMEOUT failures, which is a louder
and more accurate signal than one mislabelled leaf.

The defect is in the harness, so no SQL test can observe it. The new ci/tests
test drives the real timeout_handler body with os.killpg, os.getpgid, pgrep and
kill_process_group faked, and asserts two counters so it cannot pass vacuously:
broadcasts to our own group must be 0, while the out-of-group child must still
be killed. A third check pins that cleanup_child_processes still broadcasts,
which is the highest-risk failure mode of the extraction.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: no blocking findings

An independent model re-reviewed this diff cold. One nit, not adopted.

💡 stop_tests() vs stop_tests in the added comment. Not adopted: at the merge base this file
already uses the parenthesized form 6 times in comments and the bare form 0 times, 5 of them in
the same function, so the suggestion would make the new comment the only inconsistent one.

Two further nits I raised myself and withdrew on evidence: the comment's reference to
stop_tests mirrors five maintainer-authored sibling comments in the same function, and the
unguarded test_result.description at run_tests_array is pre-existing (the alarm surfaces as
socket.timeout, which TestCase.run already catches into a TIMEOUT result; the residual
worst case is worker exit 1, which is deliberately excluded from ABORTED_RUN_EXIT_CODES).

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d03d2a8]


AI Review

Summary

This PR fixes the primary bug well: a single per-test timeout no longer sends SIGTERM to the shared clickhouse-test process group, and the follow-up fixes cover several real signal-delivery windows around formatting, alarm cancellation, and environment restoration. I do not consider it ready to merge yet, because one already-raised inline issue still holds on the current head: once TestCase.run has already computed a run-failing verdict, a later TestTimeout in the tail-cleanup window can still rewrite that specific verdict to a generic timeout.

Missing context / blind spots
  • ⚠️ I could not run python3 -m pytest ci/tests/test_timeout_handler_no_group_kill.py in this environment because /usr/bin/python3 does not have pytest installed. A proper CI or venv run would close that gap, although the finding below was reproduced with a standalone local driver against the current code.
Findings

⚠️ Majors

  • [tests/clickhouse-test:4917] [dismissed by author -- https://github.com/A single test's timeout no longer aborts the whole clickhouse-test run #115061#discussion_r3800384364] The timeout recovery arm still conflates “no result exists” with “run had already decided a run-failing verdict, but timed out before handing it back”. If _cleanup() or remove_settings_from_env() raises TestTimeout after a real FAIL / UNKNOWN / NOT_FAILED has been computed, run_tests_array sees test_result is None and synthesizes FailureReason.TIMEOUT, losing the real failure. I reproduced this on the current head by driving run_tests_array with a TestCase whose _cleanup() raises TestTimeout after computing FailureReason.RESULT_DIFF; the output is still Reason: Timeout! rather than the known failure. Suggested fix: preserve the computed TestResult across the tail-cleanup window, or move that cleanup after the result has been handed back to run_tests_array.
Tests
  • ⚠️ Add a focused regression that raises TestTimeout after a real FAIL / UNKNOWN / NOT_FAILED is computed but before run_tests_array receives it (for example from _cleanup()), and assert that the existing verdict survives instead of being rewritten to TIMEOUT.
Final Verdict

Needs changes.

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

Copy link
Copy Markdown
Collaborator Author

cc @leshikus @pamarcos, could you review this? A per-test SIGALRM in clickhouse-test was calling stop_tests, whose killpg broadcasts SIGTERM to our own process group, which every parallel worker and the parent share, so one test exceeding its own deadline terminated the whole run and the job side relabelled a fully green run as "Server died"; the handler now reaps only the timing-out test's own out-of-group clients.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 17, 2026
@PedroTadim PedroTadim self-assigned this Aug 17, 2026
Comment thread tests/clickhouse-test Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d03d2a85b with master fb748969f (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 702.06 MiB 699.03 MiB -3.03 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

The per-test SIGALRM is raised as a TimeoutError from wherever the worker
happens to be. TestCase.run converts it into a TIMEOUT result only while its
own `except socket.timeout` arm is unspent (socket.timeout is TimeoutError on
Python 3.10+). Raised past that point, for example inside run's
`except (ConnectionError, ...)` arm while check_server_liveness is retrying,
nothing converts it: it escapes run, `except TimeoutError: break` leaves
test_result as None, and the reporting path dereferences None. The worker dies
with AttributeError, the parent sets runner_process_killed, and the run exits 1
without ever reporting the test.

check_server_liveness can spend 165 s (10 bounded socket reads plus backoff)
against a 126 s alarm at --timeout 60, so the window is reachable. The
structure predates this branch; killing the process group used to preempt it,
so leaving the worker alive is what makes it observable.

Complete whichever step the alarm interrupted:

- synthesize a TIMEOUT result when none exists;
- format it when process_result did not finish, since the job-side leaf regex
  in ci/jobs/scripts/functional_tests_results.py matches only stamped lines and
  an unstamped one attributes the failure to clickhouse-test;
- report the measured duration rather than the configured --timeout, matching
  every other path in run.

Both guards are one-directional, so an already-computed verdict is never
replaced or double-stamped.

The regression arms drive the real run_tests_array and assert against the
parser's own regex, read from its source rather than copied. Reverting the fix,
never re-formatting, dropping either guard, or restoring the constant duration
each reddens an arm. Alarms are raised directly rather than timed, so no arm
depends on the wall clock; 250/250 on repeat.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in bfef5cc.

The claim is correct, and my earlier reasoning about it was wrong. I had argued that
run's own except socket.timeout arm converts the alarm, so test_result could not be
None. That holds only while the alarm lands in the normal body. Raised once execution is
already inside one of run's except arms, that arm is spent, nothing converts it, and
the reporting path dereferences None exactly as described.

Driving the real run_tests_array with the production process_result:

alarm lands before after
in run's body reported reported
inside run's own except arm AttributeError: 'NoneType' object has no attribute 'description' [ FAIL ] Reason: Timeout!, exit code 1

Reachability: the alarm budget is int(60*1.1)+60 = 126 s, while check_server_liveness,
called from run's except (ConnectionError, ...) arm, can spend 10*10+65 = 165 s.

Two related defects turned up while fixing it, both included:

  • the alarm can also land between run returning and process_result stamping the status
    marker. Keeping that raw result satisfied a None check but emitted 00001_probe: with no
    verdict, which matches no leaf in TEST_RESULT_PATTERN, so the failure was attributed to
    clickhouse-test rather than to the test;
  • the synthesized result reported the configured --timeout instead of measured elapsed
    time, unlike every other path in run.

Both guards are one-directional, so an already-computed verdict is never replaced or
double-stamped. The regression arms drive run_tests_array and assert against the parser's
own regex, read from its source rather than copied. Reverting the fix, skipping the
re-format, dropping either guard, or restoring the constant duration each reddens an arm;
alarms are raised directly rather than timed, so no arm depends on the wall clock.

One point I did not act on: a timed-out test still leaves its per-test database behind,
because run's timeout arm returns before _cleanup. That is unchanged by this PR, and it
was equally true before, since the previous handler killed the worker outright. Calling
_cleanup from the timeout path would issue SHOW TABLES and DROP DATABASE against the
server that just missed its deadline, and _cleanup_database can raise TestException,
which would propagate out and kill the worker again. The database name is test_ plus 12
characters from random.SystemRandom, so no later test can reach it.

Comment thread tests/clickhouse-test Resolved
process_result stamps a result's status marker by mutating description in
place and only then returns, while the caller records that in a separate
local. An alarm delivered between the two left the flag saying "not
formatted" about an object that already was, so the recovery arm formatted
it again.

A doubled description is not cosmetic. The second stamped line also matches
the job side's per-test leaf pattern (functional_tests_results.py), whose
consumer has no dedup, so the run reported an extra failing test that never
existed - the same class of embedded match that pattern's bounded prefix was
added to rule out.

Blocking SIGALRM across the format call makes the two stores indivisible
rather than tracking the discrepancy. Pending signals are not lost: delivery
happens at the mask restore, so a real deadline is still reported. Making
the formatter non-mutating was the alternative, but run() mutates
description at four further sites and changing one of them would be an
inconsistent half measure.

The existing regression only raised before the formatter, leaving this
sub-window untested. The new arm raises after it and asserts a single leaf,
that the alarm was still delivered, and that the mask is clean afterwards -
so deferring cannot silently become dropping.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9a8c54a

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
Build profile diff infra - gh api ... /commits fails inside the first-parent master walk (CalledProcessError from _list_commits_page, check=True hides the error body) a fix task is created (investigating at full effort - fixing PR link to follow on this PR)

Everything else on this head is green: 79 success, 97 skipped, 1 failure. Mergeable Check,
Style check and CH Inc sync are all success, so this red does not block merge (the job is
run_on_upstream_failure and exists to write the build-profile comment).

Not caused by this PR. The diff is tests/clickhouse-test plus ci/tests/test_timeout_handler_no_group_kill.py;
it touches nothing in ci/jobs/build_profile_diff_job.py. The failing gh api call succeeds by hand
with the exact same arguments, and the anchor commit a3f55f0418cd resolves upstream, so this is
environmental to the job rather than a bad argument. Onset is sharp: 4 carrier PRs today from 13:40Z,
zero in the preceding 29 days. A sibling gh api failure in Generate LLVM Coverage Diff Report
started 7 minutes later the same afternoon and is tracked separately.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Build profile diff commits-walk failure in the ledger above: #115201.

It does not fix the gh api call itself (environmental, and the byte-identical call succeeds by hand); it makes the next occurrence record its own HTTP status instead of a truncated argv repr.

Comment thread tests/clickhouse-test Resolved
Comment thread tests/clickhouse-test
TestStatus.NOT_FAILED,
)
if test_result is None or test_result.status not in survives:
test_result = TestResult(

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.

test_result is None is still conflating two different states here. signal.alarm(0) only runs after test_case.run returns, but TestCase.run computes result, then does _cleanup() at tests/clickhouse-test:3982 and finally remove_settings_from_env() at tests/clickhouse-test:2393-2395. If the deadline lands in either of those tail-cleanup windows, TestTimeout escapes before line 4871 assigns test_result, so this branch rewrites an already-known FAIL / UNKNOWN / NOT_FAILED to TIMEOUT.

That same remove_settings_from_env window can also leak per-test state because the worker now survives. A targeted repro that raises TestTimeout between the two stores reports the first test as Timeout! and the following test inherits CLICKHOUSE_CLIENT_OPT=LEAK_OPT. To preserve the new survivor contract, either hand the computed TestResult back before post-verdict cleanup starts, or block/cancel SIGALRM around _cleanup() and env restoration and add a regression for that exact window.

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.

Both windows re-derive at the head you read (7c2399a8), and the two halves of the claim came out differently, so I judged them separately.

The env leak is real, and I have fixed it. A real SIGALRM delivered between the two stores of remove_settings_from_env, against the real function built from two source trees:

unfixed: CLICKHOUSE_CLIENT_OPT='LEAK_OPT'  deadline raised
fixed  : CLICKHOUSE_CLIENT_OPT=''          deadline raised

It persists to the third test, so it is permanent for the worker, and you are right that the survivor contract is what makes it observable: before this PR the worker died, so no following test existed to inherit anything. I took the deferral shape rather than a wider try, and confirmed masking defers rather than swallows, so the deadline is still raised immediately afterwards and the test is still failed.

Masking narrows that window but cannot close it: the signal can arrive after run enters its finally but before the mask takes effect, and the single restore call is then already spent, leaving both variables dirty. So the recovery path repeats the restore where no alarm is armed; both stores are idempotent.

The verdict rewrite does not reproduce. A deadline in _cleanup is raised through run's finally, so the environment is restored and the deadline recorded: reported [ FAIL ], exit 1, nothing escapes. No known verdict is rewritten to something weaker.

Looking at the survivor set again because of your comment, though, I found the inverse bug and fixed it: SKIPPED was surviving its own deadline, and it is reachable after a test has executed (@@SKIP@@, cloud post-filters, blacklists). Unlike FAIL, UNKNOWN and NOT_FAILED it does not fail the run, so a timed-out test was reported as a skip with exit code 0. Only the statuses that fail the run survive now.

Two regressions exist to keep the suite honest: one refuses the restore for a whole attempt, and one times out the first of two tests, since every previous driver test used a one-element queue and so could have been satisfied by a run that stops after reporting one test. Each mutation reddens exactly one oracle.

Also squashed to 5 commits.

…ment

A per-test deadline used to end the whole run: the handler called
`stop_tests`, whose `killpg` broadcasts SIGTERM to the process group that
every parallel worker and the parent share. The job side then read the
resulting exit -15 as "Server died", hiding a run in which every test that
executed had passed. The handler now kills only the timing-out test's own
out-of-group clients.

Surviving the deadline is half the contract; the run must then report the
test exactly once, and correctly:

- The deadline is raised as `TestTimeout`, which is not an `Exception`
  subclass. `signal.alarm` is armed once per attempt and never re-armed, so
  a deadline absorbed by one of the `except Exception` handlers around the
  pre-test health check left the attempt running with no deadline at all.
- A deadline delivered while a verdict was being formatted, or from the
  `finally` that cancels the alarm, is recorded rather than propagated, so
  it can neither escape the loop nor be dropped.
- FAIL, UNKNOWN and NOT_FAILED outlive their own deadline, because each
  already fails the run and names a more specific problem. Nothing else
  does. `SKIPPED` in particular is reachable after a test has executed
  (`@@Skip@@`, cloud post-filters, blacklists) and does not fail the run,
  so keeping it reported a test that never finished as one the run may
  ignore, with exit code 0.
- `remove_settings_from_env` restores two variables and every later test
  captures them as its own baseline, so a deadline between the two stores
  left the timed-out test's client options installed for the rest of the
  worker's life. The stores are now indivisible, and because masking only
  narrows that window, the recovery path repeats the restore where no
  alarm is armed; both stores are idempotent.

The window was previously unreachable in every one of these cases: the
worker died, so no following test existed to observe anything.

The regressions drive the real `run_tests_array`, including the default
`--testname` path, with real signals. Two of them exist to keep the suite
honest: one refuses the environment restore for a whole attempt, and one
times out the first of two tests so the suite cannot be satisfied by a run
that stops after reporting a single test.
@groeneai
groeneai force-pushed the groeneai/per-test-timeout-no-group-kill branch from 7c2399a to d03d2a8 Compare August 18, 2026 04:22
@PedroTadim

Copy link
Copy Markdown
Member

If a test fails, the CI will fail anyway, so we don't need continuing testing.

@PedroTadim PedroTadim closed this Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood on the premise, and I am not asking you to reopen this on the "keep testing" argument.

One thing I want to put on record before dropping it, because it is not about continuing the run.

The failure that produced this PR had zero failing tests. All 73 executed Fast tests passed on #86768; the run was aborted by a per-test alarm, and the job side turned that into a synthetic Server died leaf. That is not a slower path to the same red, it is a different red: nothing died, and the report names a cause that did not happen. That is exactly what you diagnosed by hand in the request, and the hand-diagnosis was needed because the report did not say it.

The mechanism is in tests/clickhouse-test: the alarm handler calls stop_tests() (:4840), which killpgs the runner's own process group (:840), shared by every worker and the parent, so the parent exits -15, and ABORTED_RUN_EXIT_CODES (functional_tests_results.py:52-60) makes the job side synthesize Server died and demote real per-test verdicts to UNKNOWN (:244-245) or ERROR (:266-267).

Measured on CIDB, 30 days: 90 runs across 53 PRs got a Server died leaf with no failing test row at all. Six of them are on #86768 itself. Separately, 3443 UNKNOWN rows across 255 PRs sit in runs carrying that leaf, so verdicts that existed were discarded.

Worth noting the "don't mislabel an abort as a server death" principle is already in this file three times, and none of them are mine: GLOBAL_TIME_LIMIT_EXIT_CODE and the SIGTERM mask are @ alexey-milovidov's (:4795, :5420, :5442), and MAX_FAILURES_EXIT_CODE is @ Algunenano's (:4781, :4912). Each adds a distinct exit code so an intentional stop is not read as a crash. A per-test timeout is the one abort reason with no such code.

So the smaller change that precedent suggests is just that: stop the run as it does today, but exit with a dedicated code so the job side reports a timeout instead of Server died. No survivor contract, no recovery arm, no per-child kill loop, and it drops the 91-line runner change and all 847 test lines here.

If that shape is worth having I will open it as a separate minimal PR. If you would rather leave the mislabel alone, say so and I will close this out and not revisit it.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants