Repository navigation
Fix Logical error 'clock' in EXPLAIN ANALYZE over a streaming read nested in a subquery - #110935
Conversation
…sted in a subquery EXPLAIN ANALYZE rejects streaming (FROM ... STREAM) reads before execution in rejectStreamingForExplainAnalyze. The check used extractTableExpressions with recursive=true, which only recurses into the join tree of QUERY/UNION nodes, so a streaming read nested in a WHERE/PREWHERE IN subquery or a CTE slipped through and reached execution. Its pipeline splices in a source built from a transient nested query plan that StepWallClockRegistry::populateFromPlan never walked, so chassert(clock) in ExecutionThreadContext::executeTask fired in debug/sanitizer builds; release builds did not assert but hung forever because the streaming read never completes. Walk the whole query tree instead of only join-tree table expressions, so a streaming read anywhere in a subquery is rejected with NOT_IMPLEMENTED like a top-level one. Found by the AST fuzzer (STID 2508-3665). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-0:20260718-094500 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-0:20260718-094500 |
|
cc @Fgrtue @george-larionov — could you review this? It broadens |
|
Workflow [PR], commit [c0d3fce] Summary: ✅
AI ReviewSummaryThis PR correctly fixes the original Findings
Final Verdict
|
CI finish ledger — 506a7b3Every failure below has an owner. This PR's diff is
Session id: cron:our-pr-ci-monitor:20260718-163000 |
Fgrtue
left a comment
There was a problem hiding this comment.
It looks right to me. The traversal is correct, the chosen class for visitor is also fine.
…n-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
…ai/fix-explain-analyze-streaming-subquery-clock
CI finish ledger - 7607212Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Fast test, Style check and Bugfix validation (functional + unit) are green on this head, so neither failure is caused by this PR's diff. Session id: cron:our-pr-ci-monitor:20260726-163000 |
|
Investigating... |
…ai/fix-explain-analyze-streaming-subquery-clock
The query-tree walk added earlier cannot see a streaming read reached through a view: an ordinary view stays an opaque `TableNode` unless `analyzer_inline_views` is enabled (off by default), and a parameterized view is always a `StorageView` backed `TableNode` whose inner SELECT is planned separately in `StorageView::readImpl`. So `EXPLAIN ANALYZE SELECT * FROM v`, where `v` is `... FROM t STREAM`, still reached the streaming read and aborted with `Logical error: 'clock'` in debug/sanitizer builds (the server dies), instead of returning `NOT_IMPLEMENTED`. Check the built query plan as well, walking it exactly the way `StepWallClockRegistry::populateFromPlan` does (children plus `getChildPlans`). That walk reaches every step which can be timed, including the ones spliced in from a view's inner plan, and a read absent from the plan cannot be timed and so is not rejected. This keeps a folded `EXISTS` subquery over a streaming read working: with `execute_exists_as_scalar_subquery = 1` (the default) it folds to a constant at analysis, no streaming source reaches the plan, and `EXPLAIN ANALYZE` still succeeds. Regression coverage added for an ordinary view, the same view with `analyzer_inline_views = 1`, and a parameterized view. Reported by the automated reviewer on ClickHouse#110935. Co-Authored-By: Claude Opus 5 <[email protected]>
|
I don't think that this is a good solution anymore. I don't like the fact that there are more cases arising in which it can appear that Streaming Queries are not covered. I think even though semantically EXPLAIN ANALYZE for Streaming Queries doesn't make sense, we could still mark the processors in the "local plan" that are created in the processors with some step that still exists in the plan. This is semantically senseless, but senseless doesn't mean wrong (like making const rvalue reference in c++). I will prepare fix in other PR and then close this one. @groeneai don't do anything |
|
Understood, I will leave this to you and not touch the branch. Your direction is the better one, and it removes the completeness problem my patch has: once the spliced processors carry a step that exists in the plan, there is nothing left to enumerate. One implementation detail that is not obvious from reading the code, in case it saves you time. The generic retag you describe already exists, at
Reproducers, if you want them as acceptance criteria. On a debug build without either fix, these two abort with The original fuzzer shape is a streaming read reached through Two things I measured that neither approach changes, so they are not regressions of yours: a STREAM read used as a scalar subquery or as an Do you want me to close #110935 now, or leave it open until your PR is up so the reproducers and the test stay linkable? |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 26/29 (89.66%) · Uncovered code |
|
Okay, CI is green, I'll merge this first and then do another fix, a proper one |
|
Sounds good. I confirmed green independently on One pointer for the follow-up rather than a repeat: the mechanism note in my previous comment is why the generic retag at |
…utations The test intermittently timed out on Fast test and Fast test (arm_darwin) with the client hitting its 60s budget on one of the mutations_sync=2 ALTERs: Code: 159. DB::Exception: Timeout exceeded: elapsed 60052.163029 ms, maximum: 60000 ms. (TIMEOUT_EXCEEDED) Those are the two jobs whose tests/config/users.d/limits_fast.yaml pins max_execution_time: 60, and both run on every PR. It is a blocking wait rather than a slow run: over 30 days the maximum passing duration is 7.51s on Fast test and 13.59s on arm_darwin against a 60s cap, the 12-59s band is empty, and both failures sit exactly at the cap. Root cause. StorageReplicatedMergeTree::mutate creates the mutation znode, schedules mergeSelectingTask and waits. That task asks CompactionStatistics::getMaxSourcePartBytesForMutation, whose pool guard at CompactionStatistics.cpp:155 reads the server-global BackgroundMergesAndMutationsPoolTask gauge, so it is driven by the other tests running in parallel rather than by this test. On refusal StorageReplicatedMergeTree.cpp:4525 returns AttemptStatus::Limited, no MUTATE_PART entry is created, and waitMutationToFinishOnReplicas just spins. What turns a transient refusal into a 60s stall is the reschedule block at :4576-4585. Limited matches neither the divide branch (EntryCreated/NeedRetry) nor the multiply branch (CannotSelect), but the jitter multiply new_sleep_ms *= uniform_real_distribution<Float32>(1.f, 1.1f) is unconditional, so every refusal ratchets the sleep upward. Measured over 20 consecutive Limited attempts: 5052 -> 15389 ms, mean ratio 1.0607, 3.05x overall, starting from the merge_selecting_sleep_ms floor rather than the ceiling. And there is no wake-up for "pool slots freed" - the only merge_selecting_task->schedule() sites are :4588, :5689, :7152 and :8491, and :8491 (from mutate) has already fired. So the blocker clears in milliseconds while the assigner sleeps ever longer, and the client's 60s budget expires first. Fix: set number_of_free_entries_in_pool_to_execute_mutation = 0 on this test's table. At 0 the condition max_tasks_count - occupied >= 0 is always true, so getMaxSourcePartBytesForMutation can never return 0 for pool reasons and the Limited return becomes unreachable for this table - the mutation is assigned on the first attempt, with no dependence on how long the backoff sleeps. 0 is always legal: MergeTreeSettings.cpp:2489 rejects only values greater than background_pool_size * background_merges_mutations_concurrency_ratio. This is the same remedy already applied to the same starvation in 03518_alter_logical_race.sh, and 18 other stateless tests set this setting for the same purpose. I did not pin the sleep ceiling instead: that bounds the symptom and permanently increases ZooKeeper polling for the table, whereas removing the refusal changes no interval. The reproduction confirms the distinction - with the fix the backoff still reaches its 60s ceiling and the ALTER completes in 0s, so a saturated sleep alone is harmless. No no-random-* tag is needed: none of the five relevant settings appears among the 61 MergeTreeSettingsRandomizer keys, so the runner cannot move them. Verified with a server whose pool is 26 while the setting stays at its default of 20 and 7 slots are held by unrelated tables, so 26 - 7 = 19 < 20 and the real guard fires. A/B on one binary, same fixture: without the setting Code: 159 at 61s, with it success at 0s. Through clickhouse-test with normal randomization the current version fails and the fixed version passes in 6.6s. Per-arm log counts scoped to each arm's table: "there are not enough free threads for mutations" 20 -> 0, "current attempt status: Limited" 20 -> 0, recheck spins 60 -> 0. --test-runs 50 under sustained pool pressure: 50/50. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110935&sha=bbc9355f428946983e9f5687ed8c6b25e5d14adf&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 Related: ClickHouse#110935
…e_tree Follow-up to the previous commit on this branch. The one-line test fix (`number_of_free_entries_in_pool_to_execute_mutation = 0`) is unchanged and still correct; this commit only fixes how the failure was described, plus the in-tree comment that carried one of the wrong claims. Three corrections. 1. The previous commit message quoted a client-side `TIMEOUT_EXCEEDED` exception as the CI failure. That text is in no artifact of either failing job: it was a fragment of a truncated `play.clickhouse.com` reply that leaked into a scratch file during the failure harvest, and the version string embedded in it is the one that query server reports, not the 26.6.1.1 and 26.8.1.1 of the failing jobs. What the artifacts do contain is the runner verdict [ 2086 / 12705] 02899_restore_parts_replicated_merge_tree: [ FAIL ] 60.16 sec. Reason: Timeout! Killing process group 64263 with the blocking `mutations_sync=2` ALTER named in the process list, and then server-side, after the kill Code: 341. DB::Exception: Mutation is not finished because table shutdown was called. It will be done after table restart. (UNFINISHED) (version 26.8.1.1) ... TCPHandler: Processed in 59.129 sec. 2. The expiring 60 s budget is not a server-side `max_execution_time`. It is `clickhouse-test --timeout 60`, the only `--timeout 60` in `ci/` (`ci/jobs/fast_test.py:378`), enforced by `proc.wait(args.timeout)` at `tests/clickhouse-test:3516` and the process-group kill at `:695`. That is also the simpler explanation of why only the two Fast test jobs manifest this: every other stateless job leaves the 600 s default. `tests/config/users.d/limits_fast.yaml`, which would pin `max_execution_time: 60`, is never installed at all - `tests/config/install.sh:273-275` gates its symlink on `[[ $(is_fast_build) == 1 ]]`, but `is_fast_build` only returns an exit code and prints nothing, so the substitution is always empty. The failing job's own trace shows `++ return 1` / `+ [[ '' == 1 ]]`, and `limits_fast` appears nowhere in it. That substitution bug is a separate concern and is not touched here. Consistently, the durations compared in the previous message are the runner's per-test wall clock (`test_duration_ms`), not query durations. 3. The in-tree comment repeated the same `max_execution_time` claim on its last line, so it was a source-visible defect rather than only a description one. It is now three lines carrying just the durable reason - isolation from global merges/mutations pool contention - with literal names in inline code blocks; the incident-level detail lives in the commit messages and the PR description. Also corrected: 12 further stateless tests set this setting to 0 for the same purpose (18 files mention it, but 3 are reference fixtures and 2 of the remaining tests set an illegal value expecting `BAD_ARGUMENTS`); and CI does not run at the shipped default of 20 - `tests/config/config.d/merge_tree.xml:4` overrides it to 8 server-wide, which is the value in the failing job's `max_tasks_count (32) - occupied (25) < ... (8)` line. The reproduction uses the stricter default of 20 by shrinking the pool instead. No behaviour change: the only non-comment edit in the previous commit is untouched, and the comment-stripped test file is byte-identical to it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110935&sha=bbc9355f428946983e9f5687ed8c6b25e5d14adf&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 Related: ClickHouse#110935
Related: #110668
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
Logical error: 'clock'(in debug/sanitizer builds the server dies; an infinite hang in release builds) when runningEXPLAIN ANALYZEover a query with a streaming (FROM ... STREAM) read that is not a plain top-level table expression: nested in a subquery (for example insideWHERE ... IN (...)or a CTE), or hidden behind an ordinary or parameterized view.EXPLAIN ANALYZEnow rejects such queries withNOT_IMPLEMENTED, the same way it already rejects a top-level streaming read.Description
EXPLAIN ANALYZEdoes not support streaming reads and rejects them up front inrejectStreamingForExplainAnalyze. The check enumerated table expressions withextractTableExpressions(query_tree, recursive=true), which only recurses into the join tree ofQUERY/UNIONnodes. AFROM ... STREAMread living outside the join tree (in aWHERE/PREWHEREINsubquery, or a CTE) slipped past the check and reached execution. Its pipeline splices in a source built from a transient nested query plan that the per-step wall-clock registry (StepWallClockRegistry::populateFromPlan) never walked, sochassert(clock)inExecutionThreadContext::executeTaskfired in debug/sanitizer builds; release builds do not assert but hang forever because the streaming read never completes.The fix walks the whole query tree (a
ConstInDepthQueryTreeVisitor) instead of only join-tree table expressions, so a streaming read anywhere in a subquery is rejected with the sameNOT_IMPLEMENTEDerror as a top-level one.Found by the AST fuzzer (STID 2508-3665): report https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110705&sha=b886cba9cb881d23290434cd01b18d2799f6cb2f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
Regression coverage added to
04538_explain_analyze_stream_read.sql.Streaming reads behind a view (added during review)
The automated reviewer pointed out that the query-tree walk cannot see a streaming read reached through a view: an ordinary view stays an opaque
TableNodeunlessanalyzer_inline_viewsis enabled (off by default), and a parameterized view is always aStorageViewbackedTableNodewhose inner SELECT is planned separately inStorageView::readImpl. Confirmed:EXPLAIN ANALYZE SELECT * FROM v, wherevis... FROM t STREAM, aborted the server withLogical error: 'clock', for both an ordinary and a parameterized view.The rejection is therefore also applied to the built query plan, walked exactly the way
StepWallClockRegistry::populateFromPlanwalks it (children plusgetChildPlans). That reaches every step which can be timed, including the ones spliced in from a view's inner plan. Because a read which is not in the plan cannot be timed, it is not rejected, so a foldedEXISTSover a streaming read keeps working: withexecute_exists_as_scalar_subquery = 1(the default) it folds to a constant at analysis andEXPLAIN ANALYZEstill succeeds.Regression coverage extended with an ordinary view, the same view under
analyzer_inline_views = 1, and a parameterized view.Not addressed here, because they are not specific to
EXPLAIN ANALYZEand are not theclockerror: a STREAM read used as a scalar subquery, or as anINset, blocks indefinitely, but it blocks identically with noEXPLAINat all and even under plainEXPLAIN, which never executes (measured; no fatal, server alive). That is a property of draining a STREAM source rather than ofEXPLAIN ANALYZE.