Repository navigation
Reintroduce EXPLAIN ANALYZE with a fix for the logical error over a streaming read - #110164
alexey-milovidov wants to merge 21 commits into
Conversation
|
Workflow [PR], commit [4f65bdd] AI ReviewSummaryThis PR reintroduces Findings
Tests
Final Verdict
|
|
I'd rather suggest forbidding the running of streaming queries with explain analyze, since it is a concept mismatch. |
Reintroduces the `EXPLAIN ANALYZE` feature (originally #106586) by reverting its revert #110162 (merge commit 178267d, reverted with `-m 1`). The feature was reverted only because of a `Logical error: 'clock'` abort in `EXPLAIN ANALYZE` over a streaming (`FROM ... STREAM`) read in debug and sanitizer builds. The following commit fixes that bug, so the feature can be reintroduced. This restores the query-executor instrumentation (`StepWallClock`, `StepWallClockRegistry`, `AnalyzePlanStats`, per-step wall-clock and per-port data accounting on `IProcessor`, per-stage processor grouping on `SortingStep`/`AggregatingStep`/`JoinStep`), the `ANALYZE` keyword and its handling in `ParserExplainQuery`/`InterpreterExplainQuery`, `StreamLocalLimits::forQueryResult`, and the associated tests and documentation. Related: #106586 Related: #110162 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`EXPLAIN ANALYZE` attributes per-step wall-clock time by looking up each processor's query plan step in a `StepWallClockRegistry` populated from the walked query plan. `ExecutionThreadContext::executeTask` asserted with `chassert(clock)` that every step-attributed processor has a registered clock. That invariant does not hold. A streaming (`FROM ... STREAM`) read expands its pipeline at run time via `expandPipeline` and splices in a source built from a transient nested query plan; the source keeps that plan's `ReadFromMergeTree` step even after the nested plan is destroyed, so its step is not part of the plan walked by `populateFromPlan`, and `find` returns null. In debug and sanitizer builds the `chassert` then aborted with `Logical error: 'clock'` (the failed-expression text). Release builds already handled the null clock gracefully via the following `if (clock)` guard. Remove the assertion and simply skip timing for such processors, matching the release behavior. `AnalyzeStepsStats` already tolerates these steps: it only uses the step pointer as a map key or for identity comparison and never dereferences it, and it prints stats only for steps of the walked plan. Found by the AST fuzzer wrapping a query from `04411_streaming_distinct_in_order` into `EXPLAIN ANALYZE`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ec064681ee99d6f2c0153607a0cb49bb190c30cc&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
d3c6e9d to
bad3f40
Compare
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Restructured: since #110162 (the revert of Regarding the timing concern: this keeps the "do not time runtime-expanded streaming processors" behavior. Forbidding |
…ANALYZE test The regression test only proved that `EXPLAIN ANALYZE` over a streaming read no longer aborts. Strengthen it to assert the chosen behavior structurally, following the pattern of `04312_explain_analyze`: the query summary block is present with all its fields (`Time:`, `Read:`, `Peak memory:`), and the steps of the walked outer plan are rendered and annotated (`ReadFromMergeTree`, `Limit`, per-step `time` and `parallelism` fields). Note that the rows and bytes read by the run-time-expanded snapshot processors still reach the summary `Read:` counters; only their per-step wall-clock attribution is skipped. Verified against a debug build (where the removed `chassert` is active): the test output matches the reference. Co-Authored-By: Claude Fable 5 <[email protected]>
`EXPLAIN ANALYZE` executes the inner `SELECT`, so once a transaction has failed (its state is `ROLLED_BACK`) it must be rejected exactly like the query it wraps. The failed-transaction gate in `executeQueryImpl` treated every `ASTExplainQuery` as a "special" (non-executing) query and let it through, so `EXPLAIN ANALYZE SELECT ...` still planned and executed the inner `SELECT` against the failed transaction even though a plain `SELECT` is rejected there. Exclude `ExplainKind::Analyze` from that exemption. Other `EXPLAIN` kinds do not execute the inner query (they only print a plan) and stay special, as do transaction-control statements so a failed transaction can still be rolled back. Addresses a review finding on the EXPLAIN ANALYZE reintroduction (#110164). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-wall-clock-crash
The style check (`ci/jobs/check_style.py`) rejects any test whose file name contains the substring `fail`, so `04540_explain_analyze_failed_transaction` failed `functional_tests_check`. Rename it to `04540_explain_analyze_rolled_back_transaction`, which describes the same scenario (a `ROLLED_BACK` transaction) without the forbidden word. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-wall-clock-crash
…-wall-clock-crash
|
|
||
| const size_t group = proc->getQueryPlanStepGroup(); | ||
| const UInt64 group_elapsed = proc->getElapsedNs(); | ||
| if (group_elapsed == 0) |
There was a problem hiding this comment.
Skipping group_elapsed == 0 here makes EXPLAIN ANALYZE hide idle processors from both parallelism <avg>/<max> and Time per processor (<n>). For a 16-way stage where only one worker actually sees data, the report becomes parallelism 1/1 with Time per processor (1) instead of showing the 15 zero-time workers, which is exactly the load-skew signal the new processors = 1 mode is supposed to surface.
Please count every processor in the stage, and either include zeroes in the per-processor distribution or at least keep total_num_processors based on the full stage width rather than only the non-zero subset.
|
|
||
| UInt64 read_rows = analyze_thread_group->performance_counters[ProfileEvents::SelectedRows]; | ||
| UInt64 read_bytes = analyze_thread_group->performance_counters[ProfileEvents::SelectedBytes]; | ||
| Int64 peak_memory = analyze_thread_group->memory_tracker.getPeak(); |
There was a problem hiding this comment.
Peak memory is taken from analyze_thread_group, but that child group is created only immediately before executor.execute(). Planning, optimization, and pipeline construction all happen on the outer query thread group, and child groups are parented to that outer memory_tracker, so any peak hit during planning is dropped from the reported header.
That makes EXPLAIN ANALYZE systematically under-report memory for plan-heavy queries even though the header and docs describe peak memory for the whole query. Please read the peak from the outer query group (or otherwise combine planning and execution peaks) here.
Fgrtue
left a comment
There was a problem hiding this comment.
chassert was there way to check in debug build if we undercount the time of execution of different operators. Otherwise EXPLAIN ANALYZE silently might return wrong values, and no one would be able to find this, because it is not something that is easy to track on its own.
I would suggest to leave chassert where it was, and reject STREAMING QUERIES in favor in the way as suggested by @Michicosun in #110077 (comment).
We might not want to keep chassert, because it might eventually break CI. We might choose some other, more silent mechanism, that does not break CI, such as sending a LOG for example. But to me it seems, that it is better to fail loudly so that we can spot the problem early and do revert->fix->merge rather than relying that someone will notice an error and report it as an issue.
Fgrtue
left a comment
There was a problem hiding this comment.
Here is what I would suggest to implement, based on the comment of @Michicosun. I can also do it as a separate fix outside of this PR right after this one merged, if you wish.
| /// A processor can carry a query plan step that is not part of the plan walked by | ||
| /// `populateFromPlan`, so `find` legitimately returns null. This happens for processors | ||
| /// added at run time by `expandPipeline` (lazy reads, streaming reads, external sort, ...): | ||
| /// such a processor may be built from a transient nested query plan and keep that plan's | ||
| /// step even after the nested plan is destroyed. We simply do not time these processors. |
There was a problem hiding this comment.
| /// A processor can carry a query plan step that is not part of the plan walked by | |
| /// `populateFromPlan`, so `find` legitimately returns null. This happens for processors | |
| /// added at run time by `expandPipeline` (lazy reads, streaming reads, external sort, ...): | |
| /// such a processor may be built from a transient nested query plan and keep that plan's | |
| /// step even after the nested plan is destroyed. We simply do not time these processors. | |
| chassert(clock); |
Test `04540_explain_analyze_rolled_back_transaction` failed reproducibly in the `old analyzer` CI job: it used `EXPLAIN SYNTAX SELECT 1`, whose normalized output depends on the analyzer (the new analyzer adds the implicit `FROM system.one`, the old one does not), while the reference was generated under the default (new) analyzer. Switch the "non-executing EXPLAIN stays allowed" check to `EXPLAIN AST SELECT 1`, which dumps the parsed AST before analysis and is therefore byte-identical under both analyzers. `EXPLAIN AST` is still a non-executing `ExplainKind` (not `Analyze`), so it remains exempt from the failed-transaction gate and exercises the same code path. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110164&sha=b42879c4a553859463bec70dcfaea0cd63c0d2f6&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29 PR: #110164 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…-wall-clock-crash
| plan.optimize(optimization_settings); | ||
| planning_ns += watch.elapsed(); | ||
|
|
||
| /// Build the per-plan pretty-names registry now: buildQueryPipeline below moves the ActionsDAGs |
There was a problem hiding this comment.
EXPLAIN ANALYZE still explains the consumed plan after buildQueryPipeline / executor.execute(), but only the pretty names are snapshotted here. That does not preserve the rest of the EXPLAIN PLAN surface: ExpressionStep::transformPipeline and FilterStep::transformPipeline both std::move their ActionsDAG into the pipeline, so compact = 0, actions = 1 loses the action breakdown even though ANALYZE advertises the same display options as EXPLAIN PLAN. Please snapshot the explainable step state before consuming the plan (or explain a cloned plan and stitch the runtime stats into that) instead of caching names only, and add a focused regression for compact = 0.
…-wall-clock-crash
| inner_options.setExplain(); | ||
|
|
||
| auto planning_context = Context::createCopy(getContext()); | ||
| inner_options.max_step_description_length = planning_context->getSettingsRef()[Setting::query_plan_max_step_description_length]; |
There was a problem hiding this comment.
EXPLAIN ANALYZE ... SETTINGS query_plan_max_step_description_length = N still builds and caches the inner plan with the session default here, because inner_options.max_step_description_length is copied before InterpreterSetQuery::applySettingsFromQuery mutates planning_context. Once analyzed_inner_query holds that plan, the later render cannot recover the requested truncation: long step descriptions were already generated at the wrong length.
Please move this assignment after InterpreterSetQuery::applySettingsFromQuery (or read the limit back from planning_context when constructing the inner interpreters), and add a regression that forces a long step description under a tiny query_plan_max_step_description_length.
Co-authored-by: Kirill Kopnev <[email protected]>
Co-authored-by: Kirill Kopnev <[email protected]>
Co-authored-by: Kirill Kopnev <[email protected]>
Co-authored-by: Kirill Kopnev <[email protected]>
…-wall-clock-crash
The last few commits (applying reviewer suggestions to switch the
streaming-read fix from "silently skip timing" to "reject EXPLAIN
ANALYZE over FROM ... STREAM up front") left the build broken:
`rejectStreamingForExplainAnalyze` was defined but never called, and
`extractTableExpressions` was used without including `Analyzer/Utils.h`.
- Add the missing `#include <Analyzer/Utils.h>`.
- Call `rejectStreamingForExplainAnalyze(query_tree)` after the
analyzer/non-analyzer branches in `getAnalyzedInnerQuery`, matching
the suggested placement.
- Fix a stray one-space indent left by the suggestion-commit UI.
- `04538_explain_analyze_stream_read.reference` was not updated to
match the rewritten `.sql` (which now only expects two
`NOT_IMPLEMENTED` errors and no query output) - empty it accordingly.
- Fix a comment that referred to a nonexistent `extractAllTableReferences`
function; the actual function is `extractTableExpressions`.
- Reword a `04540` test comment per the style-check nit ("new analyzer"
-> "the analyzer").
Verified: the two EXPLAIN ANALYZE / STREAM cases in 04538 now correctly
throw NOT_IMPLEMENTED (checked with `clickhouse local`), and a plain
non-streaming EXPLAIN ANALYZE still works.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 764/850 (89.88%) · Uncovered code |
…-wall-clock-crash
…TableFunctionNode.h rejectStreamingForExplainAnalyze uses TableNode::as<>() and TableFunctionNode::as<>(), whose complete type definitions were only reaching this translation unit transitively. Add the explicit includes as suggested in review.
|
@groeneai, two CI failures on
Could you investigate and provide a fix in a separate PR? For (2), since each occurrence's stack is unrecoverable after the fact, a fix likely means addressing the symbolizer's nested-bug/broken-pipe abort itself (as raised in #106591) so future hits are actually diagnosable, and/or opening a fresh tracking issue for the |
|
@alexey-milovidov Both are unrelated to this PR's 1. 2. On the symbolizer meta-point: the |
|
The work started in this PR will be continued in #110668 |
… was reintroduced `EXPLAIN ANALYZE` was reverted from master in ClickHouse#110162 and reintroduced in ClickHouse#110164, so the merge brings back `InterpreterExplainQuery.cpp`, which builds its accounting group with `std::make_shared<ThreadGroup>(outer_thread_group)`. This branch makes the borrowing `ThreadGroup` constructor private so borrowed groups are created only through factories, so the merge does not compile: `calling a private constructor of class 'DB::ThreadGroup'`. Re-add the `createForExplainAnalyze` factory (matching `createForMaterializedView` and `createForFlushAsyncInsertQueue`) and use it at the call site. This is the same change as 9b8462b, which was dropped by the previous merge because master had `EXPLAIN ANALYZE` reverted at the time. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
EXPLAIN ANALYZE(added in #106586) was reverted in #110162 because of aLogical error: 'clock'abort in debug and sanitizer builds when run over a streaming (FROM ... STREAM) read. This pull request reintroduces the feature and fixes that bug, so it can land safely.The first commit reintroduces the feature by reverting #110162 (a
git revert -m 1of the revert merge). It is an exact inverse: the reintroduced tree is byte-identical tomasterright before the revert, so the previously hand-resolved03269_explain_unique_ids.referenceconflict is restored correctly.The second commit fixes the bug.
EXPLAIN ANALYZEattributes per-step wall-clock time by looking up each processor's query plan step in aStepWallClockRegistrypopulated from the walked query plan.ExecutionThreadContext::executeTaskasserted withchassert(clock)that every step-attributed processor has a registered clock. That invariant does not hold: a streaming read expands its pipeline at run time viaexpandPipelineand splices in a source built from a transient nested query plan; the source keeps that plan'sReadFromMergeTreestep even after the nested plan is destroyed, so its step is not part of the plan walked bypopulateFromPlanandfindreturns null. Release builds already tolerated this via the followingif (clock)guard; only thechassertaborted. The fix removes the assertion and simply does not time such processors, matching the release behavior.AnalyzeStepsStatsalready tolerates these steps — it only uses the step pointer as a map key or for identity comparison and never dereferences it, and it prints stats only for steps of the walked plan.Known limitation: runtime-expanded streaming processors are therefore not accounted for in the per-step timing of
EXPLAIN ANALYZE. ForbiddingEXPLAIN ANALYZEfor streaming queries outright is the alternative proposed in #110077.Because
EXPLAIN ANALYZEexecutes the innerSELECT, a follow-up commit also aligns its transaction handling with that behavior: it is now rejected in a failed (ROLLED_BACK) transaction like a plainSELECT, instead of passing through the non-executingEXPLAINexemption (regression test04540_explain_analyze_failed_transaction).Found by the AST fuzzer wrapping a query from
04411_streaming_distinct_in_orderintoEXPLAIN ANALYZE.CI report (revert-triggering failure): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ec064681ee99d6f2c0153607a0cb49bb190c30cc&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Adding
EXPLAIN ANALYZEv1 for examination of query performance using metrics rendered in the familiar query plan format.Documentation entry for user-facing changes