Skip to content

Milestone 2 - Add the executed query plan to system.query_log - #118819

Closed
Manerone wants to merge 70 commits into
ClickHouse:masterfrom
Manerone:matheus-persist-query-plans-m2
Closed

Manerone wants to merge 70 commits into
ClickHouse:masterfrom
Manerone:matheus-persist-query-plans-m2

Conversation

@Manerone

@Manerone Manerone commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Related: #111748

Adds a query_plan column to system.query_log holding the plan that was actually executed, with its per-step runtime statistics, serialized as JSON.

EXPLAIN ANALYZE already 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_plans setting. Only SELECT queries running with the analyzer are captured, and only when log_queries is on as well — the plan is stored on the system.query_log row, 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 JSON type 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 / WallClockTimeNs and min(MaxThreads, Processors) respectively. That leaves one place where a measurement can be wrong, and nothing to keep consistent with anything else. EXPLAIN ANALYZE still prints all three, because there the arithmetic is presentation and a human reading a plan is not going to do it.

ExecutionTimeNs is 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_plans also 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 separate build and probe stages. 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.

Version is 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_profiles uses — so it is not free. Queries that are not captured are unaffected.

Implementation notes

AnalyzePlanStats is split into three: StepStatsStorage collects from the pipeline and analyses a step into a plain value, StepStatsPrinter renders that value as the text EXPLAIN ANALYZE prints, and StepStatsJSONPrinter renders the same value as JSON. Both renderers read one analysis rather than either of them re-deriving it, and EXPLAIN ANALYZE output is unchanged.

Serialization lives in its own queryPlanToJSON rather than inside QueryPlan::explainPlan, which continues to serve EXPLAIN json=1 unchanged. 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's StepWallClockRegistry. 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):

  • New Feature

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_plan column of system.query_log. Enable it with the log_query_plans setting. Unlike EXPLAIN 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]

Manerone and others added 12 commits September 3, 2026 13:04
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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c67817c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, flaky check) FAIL
05219_query_plan_json_nested_set_subquery FAIL cidb
05219_query_plan_json_nested_set_subquery FAIL cidb
05219_query_plan_json_nested_set_subquery FAIL cidb
05219_query_plan_json_nested_set_subquery FAIL cidb
05219_query_plan_json_nested_set_subquery FAIL cidb
Too many test failures FAIL cidb
Integration tests (amd_llvm_coverage, 1/8) FAIL
test_storage_iceberg_no_spark/test_iceberg_inverted_manifest_bounds.py::test_iceberg_narrow_manifest_bounds FAIL cidb

AI Review

Summary

This PR adds a query_plan JSON column to system.query_log, plus the capture machinery to serialize the executed plan, per-step statistics, and detached subquery plans. I am not approving it in the current state: ordinary distributed execution is still treated as supported even though the serializer only sees the initiator-side wrapper, and one of the new ConsumedBy links can still point at steps that no longer read the scalar subquery value after column pruning.

Findings

❌ Blockers

  • [src/Interpreters/QueryPlanProfiler.cpp:209-210] The new distributed-execution gate still only rejects make_distributed_plan, but ordinary Distributed-table queries still enable profiling on the initiator while ReadFromRemote never exposes the remote shard plans to the capture walk. That means system.query_log.query_plan can still claim to be “the plan that was executed” while omitting the remote scan/filter/join tree that actually did the work. Either reject all unsupported distributed execution paths here, or make capture descend into the remote plans before merge.

⚠️ Majors

  • [src/Interpreters/QueryPlanProfiler.cpp:64-65] ConsumedBy for scalar subqueries is still derived from ActionsDAG::scalar_subquery_ids, but those ids are copied and merged blindly and are never pruned when the corresponding constant is optimized away. A query such as SELECT a FROM (SELECT 1 AS a, (SELECT count() FROM numbers(1)) AS b) can therefore log the surviving projection step as consuming b even though the executed plan no longer reads that scalar value. Recompute scalar-subquery consumers from live output-reachable nodes, or prune the DAG-level ids during unused-action removal.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118819#discussion_r4134737158] Context::enablePlanProfiler still flips JoinAnalyzeMode::Derived on the whole query context, and RecursiveCTESource::buildStepExecutor still builds recursive-member InterpreterSelectQueryAnalyzers on recursive_query_context without attaching the profiler. Joins inside recursive members therefore still pay the analyze bookkeeping even though query_plan only stores the outer ReadFromRecursiveCTEStep, which contradicts the documented “queries that are not captured are unaffected” contract.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118819#discussion_r4024481314] Plan-based parallel replicas are still in the same unsupported state as ordinary distributed execution: the current guard only checks make_distributed_plan, while ReadFromParallelReplicasStep still keeps an inner QueryPlan that the capture walk never traverses. If this mode is intentionally out of scope for log_query_plans, it needs the same fail-closed gate as the rest of distributed execution rather than silently logging only the wrapper step.
Tests
  • ⚠️ Add a focused distributed regression on a real Distributed-table read (not only make_distributed_plan) that proves query_plan is either explicitly declined or includes the remote scan tree.
  • ⚠️ Add a pruning regression such as SELECT a FROM (SELECT 1 AS a, (SELECT count() FROM numbers(1)) AS b) and assert that the scalar subquery is still captured but has no stale ConsumedBy reader after b is optimized away.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    Gate unsupported distributed execution out of log_query_plans (or serialize the remote plans), stop ConsumedBy from reading stale DAG-wide scalar ids, and either scope JoinAnalyzeMode::Derived to actually captured plans or explicitly fail-close unsupported recursive-CTE paths.

LLVM Coverage Report

Measured on commit c67817c.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 1137/1296 (87.73%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 8, 2026
@Manerone Manerone changed the title Matheus persist query plans m2 Milestone 2 - Add the executed query plan to system.query_log Sep 8, 2026
@Manerone Manerone added the can be tested Allows running workflows for external contributors label Sep 8, 2026
@Manerone
Manerone marked this pull request as ready for review September 8, 2026 16:10
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 8, 2026
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c67817c82 with master 35c44d631 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

885 object files changed (+1.05 MiB total), 8 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/StepStatisticsCollector.cpp.o new 148.37 KiB +148.37 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryPlanProfiler.cpp.o new 147.27 KiB +147.27 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/CapturedPlan.cpp.o new 103.22 KiB +103.22 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/QueryPlanToJSON.cpp.o new 60.33 KiB +60.33 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/StepStatisticsJSONPrinter.cpp.o new 59.48 KiB +59.48 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/StepStatisticsASCIIPrinter.cpp.o new 59.41 KiB +59.41 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/PlanIndexStats.cpp.o new 52.70 KiB +52.70 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/StepStatisticsAnalyzer.cpp.o new 52.36 KiB +52.36 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryLog.cpp.o 259.54 KiB 307.33 KiB +47.79 KiB (+18.41%)
src/CMakeFiles/dbms.dir/Interpreters/Context.cpp.o 2.91 MiB 2.93 MiB +22.90 KiB (+0.77%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.32 MiB 2.30 MiB -19.64 KiB (-0.83%)
src/CMakeFiles/dbms.dir/Analyzer/Resolve/evaluateScalarSubqueryIfNeeded.cpp.o 257.56 KiB 273.93 KiB +16.36 KiB (+6.35%)

718 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3644 translation units recompiled, 17704 s compile time in total, 3636 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/CapturedPlan.cpp: 9.0 s
  • src/Processors/QueryPlan/StepStatisticsCollector.cpp: 5.2 s

Job report

Manerone and others added 5 commits September 9, 2026 14:57
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]>
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
Manerone and others added 3 commits September 25, 2026 12:40
`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]>
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
`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]>
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
`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]>
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
`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]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Manerone and others added 2 commits September 29, 2026 15:42
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]>
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
@Manerone
Manerone marked this pull request as draft September 30, 2026 11:30
@Manerone Manerone closed this Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added comp-explain EXPLAIN and query profiling output: EXPLAIN PLAN / PIPELINE / AST / SYNTAX / ESTIMATE, pretty EXP... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 22, 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 comp-explain EXPLAIN and query profiling output: EXPLAIN PLAN / PIPELINE / AST / SYNTAX / ESTIMATE, pretty EXP... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants