Repository navigation
Conversation
Each node now carries a `Details` array holding the lines `EXPLAIN ANALYZE` prints under a step — `Filter column: ...`, `Sort description: ...`, `Limit ...`. The structured `describeActions(JSONBuilder::JSONMap &)` cannot supply them: it rebuilds its output from the step's `ActionsDAG`, which `buildQueryPipeline` has moved out by the time the plan is serialized, and `FilterStep` does not merely print nothing there — it looks its filter column up with `ActionsDAG::findInOutputs`, which throws `UNKNOWN_IDENTIFIER` on the empty remains. `addStepDetails` renders the text form instead, pinned to compact and pretty, the only settings under which the describe methods never read the DAG. The profiler now passes the options `EXPLAIN ANALYZE` itself uses, along with the pretty names captured before the pipeline was built and `query_plan_max_step_description_length`, so `Description` is trimmed and truncated exactly as the text renderer does it and expressions read as the user wrote them rather than as column identifiers. The root node gains an `Output` array, the column list the text form prints above the tree. `EXPLAIN json=1` is unchanged: every addition is behind `pretty` or the presence of statistics, neither of which holds for it. Co-Authored-By: Claude Opus 5 <[email protected]>
# Conflicts: # src/Processors/Executors/Runtime/ExecutionThreadContext.cpp
The style check flags a bare `catch (...)` that neither logs nor rethrows. This one is reached when reporting an earlier failure has itself failed, on the query-finish path of a query that already returned its result: the first exception was logged, and leaving the plan empty costs the row its plan and nothing else, whereas letting this one out would fail a query that succeeded. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [c67817c] Summary: ❌
AI ReviewSummaryThis PR adds a Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit c67817c.
Changed lines: Changed C/C++ lines covered: 1137/1296 (87.73%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes885 object files changed (+1.05 MiB total), 8 added.
718 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units3644 translation units recompiled, 17704 s compile time in total, 3636 of them have a recent master baseline. Translation units without a recent master baseline:
|
Resolved one conflict in src/Core/SettingsChangesHistory.cpp, where master added allow_experimental_trino_dialect at the same position as this branch's log_query_plans entry. Both entries are kept. Co-Authored-By: Claude Opus 5 <[email protected]>
…uery-plans-m2 # Conflicts: # src/Interpreters/executeQuery.cpp
`evaluateScalarSubqueryIfNeeded` folds a single scalar value into the query as
a literal, and the id that pairs a captured sub-plan with the step consuming it
travels on that constant. For an `Array`, `Tuple` or `LowCardinality` result
there is no folded value: the subquery result goes into the query context and
what stays behind is a `__getScalar('<hash>')` call. The id had nowhere to ride,
so the sub-plan was captured and timed but its `ConsumedBy` came out empty, and
the document showed a subquery that scanned a table with nothing saying which
step wanted it.
Attach the id to the hash constant instead, since the hash is the only part of
the subquery left in the query.
Test `05255_query_plan_json_scalar_subquery_get_scalar` covers the `Array` and
`Tuple` carriers next to the folded-literal case; all three now report the step
that reads the value.
Co-Authored-By: Claude Opus 5 <[email protected]>
…ry-plans-m2 Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. - semantic merge fixes in non-conflicting files: src/Processors/QueryPlan/StepIntervalTimings.h, src/Processors/QueryPlan/StepStatisticsASCIIPrinter.cpp, src/Processors/QueryPlan/StepStatisticsAnalyzer.h, src/Processors/QueryPlan/StepStatisticsCollector.cpp, src/Processors/QueryPlan/StepStatisticsJSONPrinter.cpp Also resolved conflicts in: - `src/Processors/Executors/Runtime/ExecutionThreadContext.cpp` - `src/Processors/Executors/Runtime/ExecutionThreadContext.h` - `src/Processors/Executors/Runtime/ExecutorTasks.cpp` - `src/Processors/Executors/Runtime/ExecutorTasks.h` - `src/Processors/QueryPlan/AnalyzePlanStats.cpp` - `src/Processors/QueryPlan/StepStatisticsAnalyzer.cpp` - `src/Processors/QueryPlan/StepStatisticsCollector.h` - `src/Processors/QueryPlan/StepStatisticsModel.h` The split into `StepStatistics*` files keeps master's Time/Concurrency feature, ported into the files that did not conflict. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`recordConsumedSubqueries` matched three step types by `dynamic_cast`: `ExpressionStep`, `FilterStep` and `SourceStepWithFilter`, plus a special case for the deferred `PREWHERE` of `ReadFromMergeTree`. Any other step holding an expression was invisible to it, so a subquery consumed there was captured and timed while its `ConsumedBy` stayed empty, leaving a sub-plan in the document with nothing saying which step wanted its value. `HAVING` over an aggregation with `WITH TOTALS` is one such case: it survives as a `TotalsHavingStep`, which owns its own `ActionsDAG` and is neither an `ExpressionStep` nor a `FilterStep`. Add `IQueryPlanStep::forEachActionsDAG`, modelled on `hasCorrelatedExpressions`, and have the walk ask each step for its expressions instead of guessing from the step type. Besides `TotalsHavingStep`, this also covers `ObjectFilterStep`, `LimitRangeStep`, `JoinStepLogical`, `WindowStep`, `ArrayJoinStep` and the `INTERPOLATE` expression of `FillingStep`, none of which the old walk reached. The `ReadFromMergeTree` special case moves into its own override. Test `05260_query_plan_json_having_subquery` covers a scalar subquery consumed by `HAVING`, which now reports the `TotalsHaving` step as its consumer. Co-Authored-By: Claude Opus 5 <[email protected]>
`getChildPlans` is not an accessor for every step. `ReadFromMerge` resolves the tables it covers and plans a read for each of them when asked, and `LazyReadReplacingFinalStep` builds a whole plan that only `EXPLAIN` ever wants. Walking them therefore does planning work because something looked at the plan, which is why `CreatingSetsStep` already refuses to make that walk: doing it there made the nested subquery of a `SELECT ... WHERE key IN (SELECT ... FROM <merge table>)` run one extra time under automatic parallel replicas. Capturing a plan for `log_query_plans` did make it, in five places: recording the subqueries each step consumes, building the pretty names, capturing the steps themselves, populating the step clocks and computing the join branch costs. The first four run before the pipeline is built. So turning on a setting whose only purpose is to observe a query could change the work that query does. Add `IQueryPlanStep::getBuiltChildPlans`, which reports only the child plans a step already holds, and use it for those five walks. `EXPLAIN` keeps using `getChildPlans`, since materializing the children is exactly what it is asking for; `StepWallClockRegistry::populateFromPlan` is shared between the two and takes a flag to say which it wants. Nothing is lost for `ReadFromMerge`: a set becomes a captured sub-plan only when it was built ahead of time for index analysis, and index analysis over a merge table has already built the children by then. A `LazyReadReplacingFinalStep` child plan is no longer part of a logged plan, because running the query never builds one. Co-Authored-By: Claude Opus 5 <[email protected]>
`forEachActionsDAG` had a default that reported nothing, so a step holding an expression was covered only if someone had remembered to override it. That kept being wrong: `TotalsHavingStep`, then `FillingStep`, then `IEJoinStep` all owned a DAG and answered for none of it, and each one left the subqueries consumed there with an empty `ConsumedBy`. Three different attempts to enumerate the DAG-owning steps by hand each missed a different one, because the lists they were derived from - the `describeActions` overrides, the `hasCorrelatedExpressions` overrides - have their own omissions. Make it pure, so a new step cannot be written without saying which expressions it holds. A step that holds none writes an empty body. Doing this immediately found `PrintTSVStep`, a step declared in a unit test that no enumeration over headers would have caught. `IEJoinStep` now exposes the residual `ON` condition, where the conjuncts beyond the two inequalities live for every join kind except `ALL INNER JOIN`. Test `05261_query_plan_json_ie_join_subquery` covers a scalar subquery in that residual, which now reports the `IEJoin` step as its consumer. Co-Authored-By: Claude Opus 5 <[email protected]>
Adding the `forEachActionsDAG` declarations left an extra `public:` behind in this header, which indents its class body: the declaration went in ahead of the existing specifier, and removing it again -- the step inherits the real implementation from `SourceStepWithFilterBase` and must not hide it -- left the specifier with nothing under it. Caught by `readability-redundant-access-specifiers` in the tidy build. Co-Authored-By: Claude Opus 5 <[email protected]>
Making it pure forced all 70-odd steps that own no expression to write an empty
body, and that is worse than the omission it was meant to prevent. It does not
buy correctness: an author who hits "cannot instantiate abstract class" can
silence it with `{}` just as easily as they can forget to override a default,
so a step that holds a DAG can still report nothing either way.
What it did buy was a new way to be wrong. An empty override on a class whose
base has a real one hides it, and the mechanical pass did exactly that to
`SourceStepWithFilter`, which would have stopped every source step from
reporting its filter and `PREWHERE` expressions - tree-wide, compiling cleanly,
and visible only as missing `ConsumedBy` entries. With no empty overrides to
write, that cannot happen.
Keep the twelve overrides that report something and drop the rest. The comment
on the default now records how a step holding an expression goes unnoticed,
rather than claiming the signature prevents it.
Co-Authored-By: Claude Opus 5 <[email protected]>
Related: #111748
Adds a
query_plancolumn tosystem.query_logholding the plan that was actually executed, with its per-step runtime statistics, serialized as JSON.EXPLAIN ANALYZEalready shows this, but only by running the query a second time, and only to whoever is watching. That makes it useless for a query that has already finished, for one that failed halfway, and for any question spanning more than a single execution — which step type dominates across a workload, whether a plan changed shape after an upgrade, why one tenant's query is slower than the same query for another.Capture is off by default and enabled per query, session or user with the new
log_query_planssetting. OnlySELECTqueries running with the analyzer are captured, and only whenlog_queriesis on as well — the plan is stored on thesystem.query_logrow, so without that row there is nowhere to put it. When a query asks for its plan and one of those conditions rules it out, the reason is written to the log at trace level, so an empty column is never silent.A query that failed during execution is stored with the plan it was running, without statistics: those are collected when the pipeline is finalized, which a failing query never reaches.
The column has the
JSONtype and holds a flat array of nodes, each naming its children by id:{ "Version": 1, "Root": "Expression_7", "ExecutionTimeNs": 8956610, "MaxThreads": 1, "Output": ["number"], "Nodes": [ { "Node Id": "Filter_8", "Node Type": "Filter", "Description": "(WHERE + Change column names to column identifiers)", "Details": ["Filter column: number MOD 7 = 0"], "Children": ["ReadFromSystemNumbers_0"], "Statistics": { "IO": { "InputRows": 1000000, "OutputRows": 142858, "InputBytes": 8000000, "OutputBytes": 1142864 }, "Stages": [ { "Name": "", "GroupId": 0, "WallClockTimeNs": 3665940, "Processors": 1, "ProcessorTimeNs": { "Min": 3664600, "Median": 3664600, "Max": 3664600, "Sum": 3664600 } } ] } } ] }Nothing that a reader can compute from the document is stored in it. A stage carries its wall-clock time, its processor count and the distribution of per-processor times; the share of query time, the average parallelism and the parallelism ceiling are left out, being
WallClockTimeNs / ExecutionTimeNs,ProcessorTimeNs.Sum / WallClockTimeNsandmin(MaxThreads, Processors)respectively. That leaves one place where a measurement can be wrong, and nothing to keep consistent with anything else.EXPLAIN ANALYZEstill prints all three, because there the arithmetic is presentation and a human reading a plan is not going to do it.ExecutionTimeNsis the query's execution time, recorded when the pipeline finishes rather than sampled when the row is written — the gap between the two is unbounded, since a slow client can keep the query-finish path waiting long after the last processor has stopped, and counting it would understate every step.log_query_plansalso switches on the join analyze mode for the captured query, so joins report their own metrics — rows and matches per side, hash table size, spilled bytes, and separatebuildandprobestages. Without it a plan containing a join carried its I/O and timings but none of that. The counting happens in the probe loop, so timings for an instrumented join include it.Versionis written into every plan; it is bumped only when a reader written for the previous version would misread the new one, not when a field is added. Removing a field is such a change, and three were removed during review — version 1 is not bumped for them only because it has never been released, so it still describes the one shape that exists.Enabling the setting makes the captured query collect per-processor timings — the same instrumentation
log_processors_profilesuses — so it is not free. Queries that are not captured are unaffected.Implementation notes
AnalyzePlanStatsis split into three:StepStatsStoragecollects from the pipeline and analyses a step into a plain value,StepStatsPrinterrenders that value as the textEXPLAIN ANALYZEprints, andStepStatsJSONPrinterrenders the same value as JSON. Both renderers read one analysis rather than either of them re-deriving it, andEXPLAIN ANALYZEoutput is unchanged.Serialization lives in its own
queryPlanToJSONrather than insideQueryPlan::explainPlan, which continues to serveEXPLAIN json=1unchanged. It is flat rather than nested because a reader should not have to walk arbitrary nesting to reach a step, and because a sub-plan root is then just another node instead of a second kind of child.The only change to shared execution code is in
PipelineExecutor::finalizeExecution, which now records when execution ended on the plan'sStepWallClockRegistry. That is the one point that knows the pipeline is done, and it costs a single timestamp; the alternative of tracking it per step would have put an atomic on every busy/idle transition.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
You can now see the query plan that was actually executed, together with per-step row counts, byte counts and timings, in the new
query_plancolumn ofsystem.query_log. Enable it with thelog_query_planssetting. UnlikeEXPLAIN ANALYZE, which runs the query again, this records the execution that already happened — including queries that failed partway through — and because the plan is stored as JSON you can query across many executions to find which steps spend the time.Workflow [PR]
Sync PR [sync-upstream/pr/118819]