Skip to content

Honor a break-mode timeout while building child plans of a Merge table - #113642

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-merge-plan-break-mode-timeout
Aug 9, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-merge-plan-break-mode-timeout

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A SELECT from a Merge table that exceeds max_execution_time with timeout_overflow_mode = 'break' now stops building query plans for the remaining matched tables, instead of running full query analysis for every matched table before stopping. The query still finishes without an error, as that mode documents.

Description

Follow-up to #113415, which added a cancellation checkpoint to the per-child loop in ReadFromMerge::createChildrenPlans but discarded checkTimeLimit's return.

checkTimeLimit signals a timeout two ways. For KILL QUERY and timeout_overflow_mode = 'throw' it throws, gated on the killed flag. For 'break' it returns false instead, and a break deadline never sets that flag, so the existing checkpoint cannot alter control flow and the loop keeps analysing every remaining matched table.

This stops the loop on the false return and truncates selected_tables to the plans built, keeping the two aligned 1:1 as ReadFromMerge documents. The stop is a break rather than a throw because that is what the setting declares (Settings.cpp: "stop executing the query and return the partial result, as if the source data ran out"), so the query stays silent and successful. No new error code, and KILL QUERY and throw mode are unaffected.

The behaviour change is confined to that mode. The deadline is shared with the pipeline, so such a query has already exceeded its execution-time budget: the saving is analysis work, not rows.

Validated with a new stateless test that paces the loop with a PAUSEABLE failpoint instead of timing it. Pre-fix the break arm fails: all 4 children are planned and the loop pauses at a second child. With the fix it stops after the first, and the client still exits 0 with empty stderr. Four mutants each redden only their own arm: reverting the guard, deleting the failpoint, and either direction of the truncation. Reverting it aborts in initializePipeline with std::out_of_range; over-truncating leaves the pipeline empty, which every other assertion accepts, so both directions are pinned. 50/50 runs pass (p50 26.1 s); the test opts out of settings randomization, so that is the only meaningful arm.

groeneai and others added 3 commits August 6, 2026 04:12
Follow-up to ClickHouse#113415, which added a cancellation checkpoint to the per-child
loop in ReadFromMerge::createChildrenPlans but discarded checkTimeLimit's
return value.

checkTimeLimit signals a timeout two different ways. For KILL QUERY and
timeout_overflow_mode = 'throw' it throws from throwProperExceptionIfNeeded,
which is gated on the killed flag. For 'break' it instead returns false:
ExecutionSpeedLimits::handleOverflowMode returns false for OverflowMode::BREAK,
and CancellationChecker::cancelTask calls cancelQuery only for THROW, so a
break-mode deadline never sets that flag. The checkpoint therefore could not
alter control flow in that mode and the loop kept running full query analysis
for every remaining matched table past the deadline.

The stop is a break rather than a throw because timeout_overflow_mode declares
break as "stop executing the query and return the partial result, as if the
source data ran out". A throw would contradict that, and the note above
max_execution_time already concedes that a query "currently cannot stop during
query analysis", which is exactly this loop, so this makes the documented break
semantics reachable in a place the docs exempt rather than adding a new error.

Leaving the loop early breaks the 1:1 alignment between getSelectedTables() and
the child plans that ReadFromMerge documents, and initializePipeline is the sole
positional consumer of it (child_plans->at(i) bounded by selected_tables.size()),
so the non-const caller truncates selected_tables to the plans actually built.
A one-sided shrink is not representable: reverting only the truncation aborts in
initializePipeline with std::out_of_range from vector::at. Per-child resources
are pushed only for children that built, so dropping the trailing tables drops
nothing still referenced, and truncating to empty reuses the NullSource path a
Merge table matching nothing already takes.

The other plan-time sites that also discard the false return
(JoinOrderOptimizer::checkLimits, and part selection in
MergeTreeDataSelectExecutor) are deliberately left alone: they belong to other
subsystems, and truncating part selection would be wrong results rather than a
smaller result.

The test paces the loop with a PAUSEABLE failpoint instead of timing it, which
is what makes a deterministic stateless test possible here. The KILL QUERY arm
is a control for the half ClickHouse#113415 already fixed and stays green without this
change. The row count cannot serve as the oracle, because the same elapsed
budget that stops the plan build has also stopped the pipeline, so both outcomes
return zero rows; the test counts how many children were planned instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
The test synchronises on a PAUSEABLE failpoint against its own two-second
max_execution_time budget, and the cancellation checkpoint is evaluated before
the pause on every iteration including the first. If server-side startup has not
reached the first child within that budget, the guard fires with zero children
planned, selected_tables truncates to empty, initializePipeline takes its
NullSource path, and the first SYSTEM WAIT FAILPOINT PAUSE times out, so the
test reports a failure on a correct binary. The runner randomizes dozens of
settings that move analysis and planning cost, among them max_threads and
optimize_read_in_order, and the file pinned none of them.

Add no-random-settings. No coverage is lost: the changed code path is reached
only with timeout_overflow_mode = 'break', which the runner never randomizes,
and the test pins both timeout settings in its own query, so randomization was
never exercising the behaviour under test.

Also relax the control assertion from an exact count to a lower bound and prune
the system.text_log read with the usual event_date and event_time predicate.
The witness is unchanged: it is the inequality between the children planned by
the timed-out query and by the control.

Co-Authored-By: Claude Fable 5 <[email protected]>
The break-mode assertions only observe that the loop stopped, not how much of
selected_tables survived. Truncating it to empty instead of to the plans built
keeps both containers aligned, so nothing aborts: ReadFromMerge::initializePipeline
takes its early NullSource return, and the wait still times out, the client still
exits 0 with empty stderr, and the child counter still reads one, because that
counter is logged after the break. So discarding the planned child shipped green.

Assert ProfileEvents['SelectedParts'] instead. ReadFromMergeTree::initializePipeline
increments it while building a child's pipeline, before any row is read, which is
the only observable that separates the two truncation widths here: the retained
prefix cannot be observed through rows, since the same deadline has already
stopped the pipeline and both outcomes read zero rows.

Measured on the shipping binary: break arm 1, control 4, deterministic over
repeats. A lower bound is asserted rather than an equality because the number of
parts is not the property under test. The mutant that over-truncates reddens this
assertion alone and leaves the four existing break-arm assertions green.

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

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Before publishing I reviewed this change cold (independently of the notes written while
implementing it) and then ran an independent reviewer over the result, in three rounds.
Findings and verdicts:

# Finding Verdict
⚠️ The test could not distinguish "kept the child plans built before the deadline" from "threw them away". Every assertion was satisfied by truncating selected_tables to empty instead of to the built prefix: both containers stay aligned so nothing aborts, initializePipeline takes its existing NullSource path, and the child-count witness is unaffected because the log line it counts is emitted after the break. Agreed and fixed: the test now also asserts ProfileEvents['SelectedParts'] >= 1 for the timed-out query. That counter is incremented inside ReadFromMergeTree::initializePipeline, i.e. while a retained child's pipeline is built, so it is non-zero exactly when the planned prefix survives. Measured before the assertion was written (retained prefix: SelectedParts = 1 with read_rows = 0), and a mutant replacing resize with clear() reddens that one line and nothing else.
⚠️ The new test permitted randomized query settings that can invalidate its own synchronization. The test needs the query to reach the first failpoint pause before its max_execution_time = 2 budget elapses. The guard is checked before the pause on every iteration including the first (StorageMerge.cpp:766 then :770), so if server-side analysis has not reached child 1 within 2 s, the guard fires with zero children planned and the first SYSTEM WAIT FAILPOINT ... PAUSE times out, failing the test on a correct binary. 43 of the 224 settings the runner randomizes plausibly move that startup cost, including max_threads (which draws 32 with p=0.03). Agreed and fixed: added no-random-settings. Coverage loss is nil by measurement: the changed path is reached only with timeout_overflow_mode = 'break', which the runner never randomizes, and the test pins both timeout settings in its own query, so randomization was never exercising the behaviour under test.
⚠️ The system.text_log control could fail on a correct binary. The witness counts log rows per query_id, and the control asserted the un-timed-out query planned exactly 4 children. CI randomizes the async logger, whose queue drops messages when full (OwnSplitChannel.cpp:336-345, clearing query_id on the replacement warning at :351), so a single dropped line would fail the control. Agreed and fixed: the control now asserts "at least 4", which stays loud and stays non-vacuous because the witness is the inequality break_planned < control_planned. Also added the standard event_date/event_time predicate to that read: text_log is partitioned by month and 47 of the 56 stateless tests reading it prune, where this one did not.
⚠️ Two figures in this PR's own description were stale or wrong. It said "three mutants, one per changed line" (there are four, and the fourth is the one pinning the retention assertion above, which is not a per-line revert), and quoted a p50 measured on a superseded revision of the test. Agreed and fixed before publishing: the description now says four mutants and names both directions of getting the truncation width wrong, and quotes this tree's own 50/50 figure (p50 26.1 s, range 25.5-28.3 s).
💡 max_execution_time's documentation note says the timeout "currently cannot stop ... during query analysis". Noted, not changed. The note is a general caveat and remains true for the plan-time sites this change deliberately does not touch (joinOrder.cpp:464, MergeTreeDataSelectExecutor.cpp:1066, MergeTreeDataPartWriterOnDisk.cpp:298, DistributedPlanExecutor.cpp:1301), each of which still discards the return value. Editing that prose is a separate concern from this fix.

Two claims raised during review were withdrawn after I re-derived them, rather than acted on:

  • A claim that the witness log line is unavailable in some CI flavours, on the grounds that the
    stress job lowers the logger level. It does the opposite: Poco's priority enum is
    ascending-verbosity, with PRIO_TEST below PRIO_TRACE
    (base/poco/Foundation/include/Poco/Message.h:55-57), so that rewrite makes logging more
    verbose and the LOG_TRACE line is still captured. The jobs that remove text_log.xml
    outright do not run stateless tests.
  • A claim that the guard could fire spuriously in CI. It cannot on the default path:
    timeout_overflow_mode defaults to throw, the runner randomizes neither it nor
    max_execution_time, and the stress profile pins it to throw. The intersection of the
    stateless tests that set timeout_overflow_mode with those using a Merge table is empty,
    so no existing reference can shift.

The two-sided truncation was checked against every reader of the two containers, not just the
one the fix was written for: initializePipeline is the only strictly positional consumer, the
four in-file consumers guard on isInitialized(), and the two consumers in
optimizeReadInOrder.cpp already bound-check their index. The shrink is a correct prefix-shrink
because the per-child loop has no continue, its single emplace_back is the loop's last
statement, and its catch rethrows, so the plans built are exactly a prefix of the tables
selected. Reverting only the truncation aborts with std::out_of_range from vector::at, and
over-truncating instead drops the planned children silently, so both width directions are pinned
by mutants rather than argued.

Session id: cron:clickhouse-review-slot-10:20260806-092700

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test 04763_kill_query_merge_table_plan on a binary carrying only the failpoint registration (his guard as merged, return value discarded) fails deterministically: 4 of 4 children get planned and the loop pauses at a second child. The PAUSEABLE failpoint paces the loop rather than timing it, so nothing depends on machine speed.
b Root cause explained? QueryStatus::checkTimeLimit calls throwProperExceptionIfNeeded (which throws only when the killed flag is set) and then returns limits.checkTimeLimit(...). ExecutionSpeedLimits::handleOverflowMode returns false for OverflowMode::BREAK, and CancellationChecker::cancelTask calls cancelQuery only for THROW. So a break-mode deadline never sets the killed flag, nothing throws, and the checkpoint added by #113415 discards the false, leaving the per-child loop uninterruptible for that one mode.
c Fix matches root cause? Yes. It consumes the exact value that was being discarded, at the site that discarded it, and then restores the invariant the early exit breaks. The change in src/ is not a widened bound, a tag or a size reduction. The stop is a break rather than a throw because timeout_overflow_mode declares break as "return the partial result, as if the source data ran out". (The new test does carry no-random-settings; that is a property of the test, not of the fix, and is justified in row d.)
d Test intent preserved / new tests added? New test added; nothing existing was weakened. The KILL QUERY arm is a control covering the half #113415 already fixed, and it stays green on the pre-fix binary, so the test isolates the break-mode delta. The test carries no-random-settings because its synchronization needs the two-second deadline not to elapse before the first child reaches the failpoint, and randomized settings change how much analysis precedes that pause; no coverage is lost, because the changed path is reached only with timeout_overflow_mode = 'break', which the runner never randomizes, and the test pins both timeout settings in its own query.
e Both directions demonstrated? Yes, on Build-ID-verified binaries with a per-arm server restart. Pre-fix f09db596831cbad9: FAIL, both break assertions red. With the fix f7670b41b69eab4d: OK, 50/50 runs pass (p50 26.1 s). Four mutants each redden their own arm and nothing else: reverting the guard (946bf10e47192f85), reverting the truncation (75641fcb1436c933), deleting the pauseFailPoint call (3d3bfdad1683a379), and over-truncating with selected_tables.clear() instead of resize (f1b0b8a30e3e601b). The last one is why the test also asserts ProfileEvents['SelectedParts']: it keeps both containers aligned, so it aborts nothing and every other assertion stays green, but it silently discards the children the query did plan.
f Fix is general across code paths? Every checkTimeLimit site in src/ was enumerated (git grep -n checkTimeLimit -- src/: 99 lines across 49 files, of which 76 are checkTimeLimit( call expressions). Only this one is changed. StorageReplicatedMergeTree.cpp and FillingTransform.cpp already consume the false; the other plan-time sites (joinOrder.cpp, MergeTreeDataSelectExecutor.cpp) belong to different subsystems, and truncation there would be wrong results rather than a smaller result, so widening was deliberately not done.
g Fix generalizes across inputs? Not an input-shaped change: no data type, column wrapper or serialization format is involved. The guard is per matched child table and is independent of column types and of how many tables match. The empty case is covered: if the first child is already past the deadline, selected_tables truncates to empty and initializePipeline takes its existing NullSource path.
h Backward compatible? No setting is added or changed, so no SettingsChangesHistory.cpp entry, no serialization version and no experimental gate. It is a behaviour change for timeout_overflow_mode = 'break' over a Merge table: previously every matched table was planned, now only the tables planned before the deadline are. No rows are lost either way, because the same deadline has already stopped the pipeline (measured read_rows = 0 on both binaries): the saving is analysis work. Stated in the PR body and the changelog entry. KILL QUERY and throw mode are unaffected. Excluding the test added here, 17 stateless tests assign timeout_overflow_mode (grep -lE 'timeout_overflow_mode *=' tests/queries/0_stateless/*.{sql,sh}) and none of them uses a Merge table, so no existing test observes the change.
i Invariants and contracts preserved? The invariant is the documented 1:1 alignment between getSelectedTables() and the child plans. initializePipeline is the only positional consumer (child_plans->at(i) bounded by selected_tables.size()), so both containers are truncated together in the non-const caller, on the statement immediately after the assignment, with no early return in between. Both directions of getting the width wrong are covered by mutants: reverting the truncation aborts with std::out_of_range from vector::at inside initializePipeline, and over-truncating to empty drops the planned children, which the SelectedParts assertion catches. Per-child resources are pushed only for children that built, so nothing still referenced is dropped, and the break sits before the loop body's try.

Session id: cron:clickhouse-impl-slot-7:20260806-081400

@groeneai

groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @tavplubix, could you review this? It is a follow-up to #113415: checkTimeLimit returns false rather than throwing under timeout_overflow_mode = 'break', so the checkpoint added there could not stop the per-child loop in that mode, and truncating selected_tables alongside child_plans keeps the two aligned for the positional reader in initializePipeline.

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@PedroTadim PedroTadim self-assigned this Aug 8, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [764c8db]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Cannot start clickhouse-server FAIL cidb IGNORED
Check failed FAIL cidb IGNORED

AI Review

Summary

This PR makes ReadFromMerge honor max_execution_time with timeout_overflow_mode = 'break' between child-table plan builds, truncates selected_tables to the planned prefix so downstream table/plan consumers stay aligned, and adds a deterministic failpoint-based stateless test for both the KILL QUERY and 'break' paths. I did not find new correctness, safety, performance, or coverage issues in the current code.

Final Verdict

✅ Looks good to merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 764c8db18 with master 7a9ada8cf (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 56c386405; 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 689.45 MiB 686.33 MiB -3.13 MiB (-0.45%)

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

22 translation units recompiled, 33 s compile time in total, 8 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 764c8db

CI is fully finished on this head: 175 check-runs, 0 queued or in progress, Config Workflow
and Finish Workflow both success. 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 (amd_msan) / Cannot start clickhouse-server the restart phase aborts loading metadata with Code: 669 NAMED_COLLECTION_DOESNT_EXIST while attaching 04320_url_engine_dispatch_partition_and_format_test_3_n, an ENGINE = URL(named_collection) table left behind by another test; a missing collection makes the whole ATTACH fatal at startup instead of deferring the error to query time fixing PR #110529 (ours, open)

Not caused by this pull request. The diff touches src/Storages/StorageMerge.cpp,
src/Common/FailPoint.cpp and one stateless test, none of which is on the attach path, and the
offending table belongs to an unrelated test. Over 30 days this exact startup abort appears in
9 rows across 8 distinct pull requests with 2 master hits, so it is a trunk condition rather than
something reachable from this change.

Stress test (amd_msan) is the only red; the other nine Stress test flavours on this head are
green, which matches the low per-run rate of the signature. #110529 is not merged yet, so there is
nothing to pick up by merging master.

Session id: cron:our-pr-ci-monitor:20260809-003000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit af10c1c Aug 9, 2026
178 of 180 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
alexey-milovidov added a commit to jh0x/ClickHouse that referenced this pull request Aug 9, 2026
Pulls in the merged fix ClickHouse#113642 for the hung `Stress test (arm_asan_ubsan)` check (uncancellable `ReadFromMerge` child-plan analyzer loop), which was the sole red on this PR.
@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 pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants