Skip to content

Add the executed query plan to system.query_log - #123059

Merged
Manerone merged 57 commits into
ClickHouse:masterfrom
Manerone:qpp-m2-logging
Nov 17, 2026
Merged

Manerone merged 57 commits into
ClickHouse:masterfrom
Manerone:qpp-m2-logging

Conversation

@Manerone

@Manerone Manerone commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Related: #111748

Adds a query_plan column of the native JSON type to system.query_log, holding the plan the query actually executed together with its per-step runtime statistics. It is filled when the log_query_plans setting is enabled, and is empty for QueryStart rows, since no plan exists at that point.

Shape of the document

{Version, Root, Output, ExecutionTimeNs, MaxThreads, Nodes[]}

Nodes is flat, each node naming its children by id, rather than nested. SQL cannot walk arbitrary nesting, so a tree would make aggregation by step type across queries impossible. Each node carries its type, id, description, details, per-step statistics, and — for a ReadFromMergeTree — what index and projection analysis decided.

A query decides how much text its own plan contains: a large IN list, a long alias and a folded constant are all rendered into it. log_query_plans_max_size bounds the whole document, one mebibyte by default and zero to disable. The plan is rendered into a buffer of that size, so the limit bounds what rendering allocates and not only what is stored — the capture runs with the memory tracker blocked, so that matters as much as the row does. A plan that does not fit is not stored truncated, because half a document is not a plan; the column holds the reason instead, as {"Error": ...}.

A step's own description and details are separately cut to query_plan_max_step_description_length, as they are everywhere else they are exposed.

How it is captured

The plan is read on the way out of QueryPlan::buildQueryPipeline, once the plan has been optimized and the pipeline built. That is the first moment the index analysis and the lazily built child plans exist, and the last moment the plan does. Only the pretty names are read beforehand, because building the pipeline moves each step's ActionsDAG into the ExpressionActions and the names are derived from them.

One walk of the plan feeds both readings, so the captured document and the per-step clocks cannot disagree about the shape. The statistics are read after the query has run, from the pipeline's processors.

sequenceDiagram
    autonumber
    participant EQ as executeQuery
    participant ISQA as InterpreterSelectQueryAnalyzer
    participant QP as QueryPlan
    participant C as QueryPlanLogCapture
    participant PIPE as QueryPipeline
    participant QL as system.query_log

    EQ->>C: canCapturePlan(context, ast, internal)
    Note right of C: false -> declineCapture(reason), at trace level
    EQ->>ISQA: setPlanLogCapture()

    ISQA->>QP: buildQueryPipeline(log_capture)
    QP->>QP: optimize()
    QP->>QP: buildPrettyNamesPerPlan()
    Note right of QP: while the ActionsDAGs<br/>are still on the steps
    QP->>PIPE: updatePipeline(), step by step
    Note right of PIPE: ActionsDAGs move into ExpressionActions here
    QP->>QP: PlanWalk::of(plan)
    QP->>C: capturePlanStructure(walk, pretty_names)
    Note right of C: the plan is optimized and its child<br/>plans are built: the last moment<br/>it is worth reading
    QP->>PIPE: setStepProfiler(StepProfiler(walk))

    PIPE-->>PIPE: execution
    Note right of PIPE: the processors stamp their clocks

    EQ->>C: captureStatistics(pipeline)
    Note right of C: takes the StepProfiler back off the pipeline
    EQ->>QL: attachQueryPlan(): FlatJSONPlanRenderer writes the document
    QL-->>QL: query_plan
Loading

A query that asks for its plan and does not get one says why through declineCapture, at trace level, rather than logging an empty column silently.

Changelog category (leave one):

  • New Feature

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

Added a query_plan column to system.query_log, containing the query plan that was executed with its per-step runtime statistics, serialized as JSON. Enabled with the log_query_plans setting.


Workflow [PR]
Sync PR [sync-upstream/pr/123059]

Version info

  • Merged into: 26.11.1.2565-master (included in 26.11 and later)

Records the plan a query actually ran, with its runtime statistics, in a new
`query_plan` column of the native `JSON` type on `system.query_log`, filled when
`log_query_plans` is on.

The document is flat: `{Version, Root, Output, Nodes[]}`, where each node names
its children by id. Flat rather than nested because SQL cannot walk arbitrary
nesting, so a tree would make aggregation by step type across queries
impossible. Serialization lives in its own `capturedPlanToJSON` rather than
inside `QueryPlan::explainPlan`, which continues to serve `EXPLAIN json = 1`
unchanged.

`QueryPlanProfiler` captures the plan before the pipeline is built, because
building it moves each step's `ActionsDAG` into its `ExpressionActions`, and
reads the statistics afterwards from the pipeline's processors. What it keeps is
a `CapturedPlan`: owned values, no pointers into a plan or pipeline that the
logging path outlives.

A query that asks for its plan and does not get one says why, through
`declineCapture`, rather than logging an empty column silently.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [66d0bd8]

Summary: ✅


AI Review

Summary

Adds an opt-in JSON query plan and per-step runtime statistics to system.query_log. Reviewed head 66d0bd8e7cad48ab9732666444d00bcba7b2f961, including all prior discussion. Secret masking, allocation bounds, and several diagnostic correctness/coverage concerns remain. These already have review threads; no duplicate inline comments were posted.

Findings

❌ Blockers

  • src/Processors/QueryPlan/Profiling/Render/FlatJSONPlanRenderer.cpp:303 — The new log column bypasses query_masking_rules. Captured literals, descriptions, output expressions, and conditions are serialized without SensitiveDataMasker, whereas the query text is masked. A literal redacted from query can therefore be persisted in query_plan. Apply masking to user-derived text before serialization, preserving structural identifiers, and cover a matching literal. [dismissed by author -- https://github.com/Add the executed query plan to system.query_log #123059#discussion_r4165262878] Deferring masking still exposes secrets when this feature is enabled.

⚠️ Majors

  • src/Processors/QueryPlan/Profiling/Capture/CapturedPlan.cpp:211; src/Processors/QueryPlan/Profiling/Render/FlatJSONPlanRenderer.cpp:303 — The document limit does not bound capture/render allocations. Output, index/projection text, and string-valued join metrics retain full values. Rendering then constructs an owning JSONBuilder tree, copying those strings before writing any bytes to the bounded buffer. For example, SELECT repeat('0123456789', 1000000) AS x FROM numbers(1) FORMAT Null still copies the expanded value under MemoryTrackerBlockerInThread, even with a small log_query_plans_max_size. Enforce a common budget while producing/capturing text and stream rendering without first duplicating the whole document. The new size test checks stored bytes only. Existing thread.

  • src/Processors/QueryPlan/Profiling/Capture/CapturedPlan.cpp:37 — Already truncated descriptions can invalidate the entire plan. IQueryPlanStep::setStepDescription cuts bytes before capture. A MergeTree table named é in database default, with query_plan_max_step_description_length = 9, leaves default. followed by byte 0xC3; the early return preserves it. JSONString writes it unchanged, the default SimdJSONParser rejects it, and QueryLogElement::appendToBlock replaces the plan with {}. Truncate safely at the original cut and handle arbitrary byte strings before JSON serialization; add a description-boundary regression. [dismissed by author -- https://github.com/Add the executed query plan to system.query_log #123059#discussion_r4562578443] The size limiter does not repair invalid UTF-8.

  • src/Storages/StorageMerge.cpp:863 — Optimizer-generated descriptions disappear from captured Merge child plans. getChildPlanOptimizationSettings leaves max_step_description_length at zero, so optimizations such as mergeExpressions erase synthesized descriptions through setStepDescription. The top-level interpreter supplies the configured limit, but these newly exposed child plans do not receive it. Propagate the limit to child optimization settings and assert a nonempty optimized child description. [dismissed by author -- https://github.com/Add the executed query plan to system.query_log #123059#discussion_r4144577422] The current child-settings constructor still leaves this field unset.

  • src/Storages/StorageView.cpp:399 — A visible sealed view reports zero statistics as an opaque logged leaf. Logging always omits the child plan, but processors are attributed to ReadFromSealedView only when show_plan is false. With show_plan = true, their inner step IDs have no matching captured node. For a SQL SECURITY NONE view selecting number FROM numbers(10) WHERE number > 0, the leaf reports zero output rows and no stages despite producing nine rows. Aggregate the omitted subtree into the opaque leaf without exposing its internals. [dismissed by author -- https://github.com/Add the executed query plan to system.query_log #123059#discussion_r4565972017] Deferring attribution leaves recorded execution statistics incorrect.

  • src/Storages/StorageView.cpp:416 — The logging-specific sealed-view privacy boundary has no regression coverage. Existing privacy tests check EXPLAIN and processors_profile_log; none exercises query_plan or its pretty-name prepass. Add a stateless case with a SQL SECURITY DEFINER view containing a scalar subquery over a private table, queried with log_query_plans = 1 by an invoker granted only access to the view. Assert that the logged opaque leaf exists and private values/inner steps are absent; also cover show_plan = true. [dismissed by author -- https://github.com/Add the executed query plan to system.query_log #123059#discussion_r4586595162] Existing tests cannot detect a disclosure through this new column.

Missing context / blind spots
  • ⚠️ No local ClickHouse executable/build was available. The retained repros were verified by tracing the current capture, renderer, parser, and processor-attribution code; focused runtime regressions would provide independent confirmation.
Final Verdict

Status: ❌ Block. Apply secret masking before persisting plans. Bound allocations before materializing diagnostic text, preserve valid JSON text, correct child descriptions and sealed-view statistics, and add the focused privacy regression coverage described above.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 30, 2026
@Manerone
Manerone marked this pull request as ready for review September 30, 2026 11:38
@Manerone Manerone self-assigned this Sep 30, 2026
@Manerone Manerone added the can be tested Allows running workflows for external contributors label Sep 30, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 30, 2026
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
@Manerone

Copy link
Copy Markdown
Contributor Author

cc @rschu1ze original PR is too large, I broke it into two new PRs. This one and another that I will create after this one is merged.

Informing you in case you want to add this to the JOINs project as well.

Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
The plan carries the same literals the `query` column does -- a filter's
constants reach `Details` -- so an operator relying on `query_masking_rules`
needs it masked too. Running `SensitiveDataMasker` over every string of the
rendered document was the first attempt at that, and it is the wrong shape:
`Root`, every `Node Id` and the `Children` references are strings such as
`Expression_12`, so a rule matching digits collapses distinct steps onto one id
and the flat `Nodes` array stops describing a graph.

Masking the plan properly means masking the user-derived text -- descriptions,
details, index conditions, output column names -- and leaving the structural
ids and step types alone. That is a feature of its own, so take it out of this
change rather than ship a version that can corrupt the document it protects.

Until it lands, a plan logged on a server with masking rules configured can
contain literals the `query` column hides. The setting is off by default.

`JSONBuilder::transformStringValues` goes with it: the masker was its only
caller.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Manerone Manerone changed the title Milestone 2 - Add the executed query plan to system.query_log Add the executed query plan to system.query_log Sep 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 66d0bd8e7 with master 8bcbbbe48 (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

688 object files changed (+835.18 KiB total), 6 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Capture/CapturedPlan.cpp.o new 135.50 KiB +135.50 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Render/FlatJSONPlanRenderer.cpp.o new 115.03 KiB +115.03 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Capture/QueryPlanLogCapture.cpp.o new 75.63 KiB +75.63 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Capture/PlanIndexStats.cpp.o new 64.27 KiB +64.27 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryLog.cpp.o 296.40 KiB 353.28 KiB +56.88 KiB (+19.19%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Analysis/PlanAnalysisSnapshot.cpp.o new 44.52 KiB +44.52 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinStep.cpp.o 308.64 KiB 350.57 KiB +41.92 KiB (+13.58%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Capture/PlanWalk.cpp.o new 36.49 KiB +36.49 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Profiling/Analysis/AnalyzePlanStats.cpp.o 236.31 KiB 271.27 KiB +34.96 KiB (+14.79%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/BlockNestedLoopJoinStep.cpp.o 249.06 KiB 276.35 KiB +27.29 KiB (+10.96%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/QueryPlan.cpp.o 627.53 KiB 650.88 KiB +23.35 KiB (+3.72%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromMergeTree.cpp.o 2.72 MiB 2.70 MiB -22.35 KiB (-0.80%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/IQueryPlanStep.cpp.o 160.73 KiB 181.05 KiB +20.32 KiB (+12.64%)

711 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

3565 translation units recompiled, 23016 s compile time in total, 3559 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/Profiling/Capture/CapturedPlan.cpp: 12.3 s

Job report

Manerone and others added 2 commits October 1, 2026 08:59
Making the capture walks side-effect-free switched `buildPrettyNamesPerPlan` to
`getBuiltChildPlans` outright, but the profiler is only one of its three
callers. The other two render whole plans, and `QueryPlan::explainPlan`
descends through `getChildPlans` as it goes -- so the prepass stopped covering
child plans the renderer then materialises and prints.

Give it the same parameter `StepWallClockRegistry::populateFromPlan` already
takes, for the same reason. The profiler asks for the plans a step already
holds, because building one there would make capturing a plan change the work
the query does. `EXPLAIN` and `explainPlan`'s own fallback keep the original
traversal, since materialising those plans is what they are for.

No output changes: `explainPlan` rebuilds names for any plan missing from the
registry, which covered the gap. This restores the split the two walks should
have shared from the start rather than relying on that fallback.

Co-Authored-By: Claude Opus 5 <[email protected]>
Master reorganised the profiling code into `Processors/QueryPlan/Profiling/`
and replaced `StepWallClockRegistry` with `StepProfiler`, which this branch had
been changing at the same time. Master's structure wins throughout; what is
kept from here is what the plan column actually needs.

`AnalyzeStepsStats` already separated analysis from rendering -- `analyzeStep`
produces a format-neutral `AnalyzedStepData` and `renderStep` is one consumer of
it -- so splitting it into a collector and two printers, as this branch had
done, bought nothing. That split is dropped, along with the four file renames
that came with it, and replaced by making `analyzeStep` public and adding the
two getters the capture needs.

Three changes are carried across:

  - `hasCollectedMetrics` moves to `StepAnalyzeInfo.h`. Both renderers had their
    own copy and could have disagreed about when a group counts as collected.
  - `StepStatsContext` moves from the data model to the analyzer header, where
    its only users are.
  - `StepProfiler` takes `only_built_child_plans`. Its constructor walks
    `getChildPlans()`, which builds plans a step does not already hold, so
    attaching the clocks would otherwise change the work a logged query does.
    `EXPLAIN` wants those plans and passes false.

The executor changes here are dropped entirely: they existed to serve a
string-keyed registry, and master keys by step pointer and leaves the elapsed
time to the caller, so the profiler now measures it directly.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Manerone and others added 3 commits October 1, 2026 13:57
Resolving the conflict at the top of the file added master's
`AnalyzePlanStats.h`, and a second include further down was then rewired to the
same header. Caught by `readability-duplicate-include` in the tidy build.

Co-Authored-By: Claude Opus 5 <[email protected]>
The denominator of every time share is how long the query executed, and after
the merge it was being taken on the query-finish path: the span ran from
instrumenting the pipeline to `finalizeQueryPipelineBeforeLogging`. That
brackets the whole thing -- the wait before the client starts reading, and the
serializing and sending afterwards -- so every share came out understated. It
is also the problem review raised against an earlier version of this code,
which the branch had fixed and the merge undid.

`StepProfiler` keeps the timestamp it is constructed with and gains
`markExecutionFinished`, which `PipelineExecutor::finalizeExecution` calls. That
is the executor's own end-of-execution hook, so it runs for the stepping and
the batch paths alike, and on the exception path. The profiler reads both the
origin and the duration back off it rather than reading the clock itself.

`extractWorkIntervals`'s parameter is renamed: it was shadowing the new member,
and it is not the same value. `EXPLAIN ANALYZE` rebases intervals against its
own stopwatch, not against the profiler's construction.

On a pulling pipeline the span still contains the stalls between the client's
reads, so this is a tighter bound rather than a clean execution time. What that
denominator should be is a separate question.

Co-Authored-By: Claude Opus 5 <[email protected]>
All six conflicts come from one upstream change, which gave
`IQueryPlanStep::getChildPlans` a `for_explain` flag so a sealed view can hide
its plan from users without the privilege to see it. This branch had extended
the same method with `getBuiltChildPlans`, the variant that reports only the
child plans a step has already built, so that capturing a plan does not change
the work a query does.

The two are orthogonal and every resolution keeps both: the overrides take the
flag and keep reporting their built child plans, and the two call sites that
choose between the variants pass the flag on the `getChildPlans` side.

`ReadFromSealedViewStep` overrides only `getChildPlans`, so the captured plan
walk, which goes through `getBuiltChildPlans`, stops at a sealed view. Record
why that must stay so: the captured plan lands in `system.query_log`, which is
readable beyond the user who ran the query.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Interpreters/QueryPlanProfiler.cpp Resolved
Manerone and others added 3 commits October 2, 2026 13:02
The methods sat in neither declaration nor call order, and the header and the
implementation disagreed with each other, so following what the profiler does
to a query meant jumping around both files.

Both now read in the same order: the static entry points that decide whether a
query is profiled at all, then capturing the plan and the statistics, then
attaching the profiler to the pipeline, then finishing, then rendering.
`getMaxDescriptionLength` moves up to the entry points, being an accessor
rather than a step of the lifecycle, and the private `capture` stays with the
two methods that share it.

No behaviour change: the implementation file is the same text in a different
order.

Co-Authored-By: Claude Opus 5 <[email protected]>
`StepStatisticsJSONPrinter` described itself as the sibling of
`StepStatisticsASCIIPrinter`, which no longer exists: the text rendering of the
same analysis is `AnalyzeStepsStats::renderStep`.

The `CapturedPlan` comments were wrong in a way that invites a bug. They said
the capture walks the child plans a step owns through `getChildPlans`, while it
walks `getBuiltChildPlans`. The difference is the point of that method:
`getChildPlans` builds the child plans of `ReadFromMerge` and
`LazyReadReplacingFinalStep` when asked, so capturing through it would make
observing a plan change what the query does. Say which one the walk calls, and
why it has to be that one.

Also write the remaining two mentions as `getChildPlans` rather than
`getChildPlans()`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Manerone

Manerone commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

What this adds

A query_plan column on system.query_log, of type JSON, holding the plan that the logged query actually executed, annotated with per-step runtime statistics. It is filled only when log_query_plans is enabled, and is always empty on QueryStart rows, because no plan exists at that point.

The difference from EXPLAIN ANALYZE is that EXPLAIN ANALYZE runs the query a second time, so it reports a plan and timings for a different execution than the logged one. The captured plan is the one that execution ran, taken in place. The second difference is that every value is written raw, nanoseconds and rows and bytes as numbers rather than 4.04 ms or 142.86 thousand, so the column can be aggregated by a query. That is the point of storing a JSON document rather than the rendered plan text.

SET log_query_plans = 1;
SELECT ...;
SYSTEM FLUSH LOGS;

SELECT query_plan FROM system.query_log WHERE type = 'QueryFinish' ORDER BY event_time DESC LIMIT 1;

When a plan is captured

QueryPlanProfiler::canEnableProfiler decides this once, early in executeQueryImpl, before the interpreter is built. Every rejection other than "the setting is off" is reported through declineCapture, which logs at TRACE saying why, so a user who turned the setting on and got no plan can find out the reason instead of guessing.

Condition Why it declines
log_query_plans = 0 Feature off. Silent, no log line.
Internal query It writes its own system.query_log row marked is_internal; only client-issued queries are captured.
log_queries = 0 There is no row to attach the plan to, so capturing would be pure cost.
Not INITIAL_QUERY Each shard of a distributed query logs its own row; the plan is captured on the initiator.
Not a SELECT Only SELECT plans are captured.
allow_experimental_analyzer = 0 The old analyzer cannot produce a plan to capture.
make_distributed_plan = 1 Distributed plans are not supported yet.

When the capture runs

The profiler lives on the query Context and is handed to the interpreter. It has a five-call protocol, and the order is enforced with chassert in debug builds.

sequenceDiagram
    participant EQ as executeQueryImpl
    participant P as QueryPlanProfiler
    participant I as InterpreterSelectQueryAnalyzer
    participant X as PipelineExecutor

    EQ->>P: canEnableProfiler
    Note over EQ: context->enablePlanProfiler<br/>interpreter->setPlanProfiler
    I->>I: query_plan.optimize
    I->>P: captureQueryPlan, takes ownership
    Note over P: builds PrettyNamesPerPlan<br/>while the ActionsDAGs are still in the steps
    P-->>I: reference to the owned plan
    I->>I: buildQueryPipeline on that plan
    I->>P: instrumentPipeline, attaches a StepProfiler
    X->>X: query runs
    X->>P: markExecutionFinished, stamps the end
    EQ->>P: captureStatistics, pipeline still alive
    EQ->>P: finish, snapshot taken, running state dropped
    EQ->>P: render, JSON for the query_log row
Loading

The capture is split across two moments, and neither of them can move.

The plan is taken after query_plan.optimize, so the recorded shape is the one that ran rather than the pre-optimization shape, and before buildQueryPipeline, because building the pipeline moves each step's ActionsDAG into its ExpressionActions, and deriving the pretty column names reads those DAGs.

The statistics are read after execution, and while the pipeline is still alive, because they come from its processors.

Why the profiler owns the plan

captureQueryPlan takes the plan by value and hands back a reference, and the interpreter then builds the pipeline from the profiler's copy rather than its own. The reason is that PrettyNamesPerPlan is keyed by const QueryPlan * and looked up as find(this) at render time, so the names have to be built on the very object that will later be rendered. Letting the interpreter keep its own plan and copying would break that lookup.

Why there is a CapturedPlan

The query_log row is written well after the plan and pipeline are gone. captureStatistics runs, and then query_pipeline.reset() happens a few lines later, long before attachQueryPlan renders anything.

So the profiler does not keep the plan around to render later. At capture time it copies out everything it will need into a CapturedPlan and a flat std::vector<CapturedStep>. These hold strings and numbers only, with no pointers back into the plan, the pipeline or the steps, so they remain valid once all three are gone, and the JSON is produced from them afterwards.

flowchart LR
    subgraph alive["while the query runs"]
        QP["QueryPlan"]
        PL["QueryPipeline"]
        SP["StepProfiler"]
    end
    subgraph snap["survives into logging"]
        CP["CapturedPlan, strings and numbers,<br/>no pointers back"]
    end
    QP --> CP
    PL --> CP
    SP --> CP
    CP --> J["JSON for system.query_log"]
Loading

CapturedPlan carries no formatting decisions of its own, though the only renderer of it today is the JSON one.

Where the statistics come from

The per-step numbers are not computed by this feature. They come from AnalyzeStepsStats, the same analyzer EXPLAIN ANALYZE uses. Its analyzeStep produces an AnalyzedStepData, which carries no formatting decisions, and the two renderers are two readings of that one value.

flowchart TD
    AS["AnalyzeStepsStats::analyzeStep"] --> ASD["AnalyzedStepData"]
    ASD --> R1["AnalyzeStepsStats::renderStep, text, for EXPLAIN ANALYZE"]
    ASD --> R2["StepStatisticsJSONPrinter::toJSON, JSON, for system.query_log"]
Loading

The plan column therefore cannot drift from EXPLAIN ANALYZE: there is one analysis, and a metric added to it appears in both.

Query-level timing comes from the StepProfiler, which stamps its start at construction and is told to stamp the end by PipelineExecutor::finalizeExecution calling markExecutionFinished. So ExecutionTimeNs is the executor's own span and does not include whatever the query-finish path does afterwards.

Shape of the document

{
  "Version": 1,
  "Root": "<id of the root node>",
  "Output": ["col1", "col2"],
  "ExecutionTimeNs": 3412887,
  "MaxThreads": 8,
  "Nodes": [
    {
      "Node Type": "Aggregating",
      "Node Id": "Aggregating_4",
      "Description": "...",
      "Details": ["..."],
      "Statistics": { "Stages": [ { "Name": "...", "GroupId": 0, "WallClockTimeNs": 0, "Processors": 8 } ] },
      "Indexes": { },
      "Children": ["Expression_5"]
    }
  ]
}

Nodes is a flat array and parent/child links are ids in Children, rather than a nested tree. That is deliberate: a consumer can unnest the array and aggregate across steps or across queries without having to walk a recursive structure in SQL.

Version is there so a consumer can tell which shape it is reading; it is 1 in this PR.

Indexes is present only for a ReadFromMergeTree. The index-analysis types were lifted out of ReadFromMergeTree into PlanIndexStats so that CapturedStep does not have to depend on the storage engine.

Behaviour on the logging path

Both capture and render run after the client has already received its result. An exception escaping either one would fail a query that had already succeeded, so both catch everything and log it instead. render degrades in two steps: first to a document containing only an Error key, and if even that fails, to an empty string, which leaves the column at its default empty JSON object rather than something invalid.

Both also run under MemoryTrackerBlockerInThread, so producing diagnostics cannot push a query over its memory limit.

finish is idempotent, which is what the failure path relies on. A query that succeeds finishes on the pipeline path; a query that threw before its pipeline completed never gets there, and attachQueryPlan finishes it at logging time instead, capturing the plan alone with no statistics.

Two conflicts, both from upstream rearranging code this branch had touched.

`InterpreterExplainQuery` hoisted the pipeline, the step profiler and the
execution time out of the `EXPLAIN ANALYZE` block and wrapped the rest in a
`ThreadGroupSwitcher` scope. The only thing this branch contributed there was
passing `only_built_child_plans` to the `StepProfiler` explicitly, and that
parameter defaults to false, so upstream's call already says the same thing.
Taken as upstream wrote it.

`PipelineExecutor` moved under `Runtime/V1` behind the new `IExecutor`
interface, and the release of the CPU slots became a `SCOPE_EXIT` so that the
output formats can write their epilogue before the slots go back. The call to
`markExecutionFinished` stays ahead of that `SCOPE_EXIT`: the epilogue of
`Parquet` or `ORC` is real work, and counting it would make the plan logged for
such a query look slower than the work it did. Say so in a comment, because the
two are now adjacent and the order between them is the whole point.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Fgrtue Fgrtue self-assigned this Oct 5, 2026
Manerone and others added 3 commits November 13, 2026 14:12
`check_catch_all` suppresses its warning when the `catch (...)` block carries a
comment containing the word `Ok`. Rewording the comment dropped the word, so the
check started reporting the block as one that silently swallows an exception.

Co-Authored-By: Claude Opus 5 <[email protected]>
A query decides how much text its own plan contains. A large `IN` list, a long
alias or a folded constant are all rendered into it, and the capture runs with
the memory tracker blocked, so one query could make a server allocate and store
an arbitrarily large row.

Capping each carrier of text separately did not hold: `Output` was bounded, and
the input column names a join reports in its statistics were still not. There is
no reason to believe that was the last one.

So the limit is on the document instead. `log_query_plans_max_size`, one
mebibyte by default, zero to disable. The plan is rendered into a
`MemoryWriteBuffer` of that size, which throws rather than allocate the chunk
that would cross it, so the limit bounds what rendering allocates and not only
what is stored. A plan that does not fit is not stored truncated, because half a
document is not a plan; the row holds the reason instead.

The per-step cut by `query_plan_max_step_description_length` stays as it was,
now at a UTF-8 boundary.

`SELECT repeat('0123456789', 1000000) AS x FROM numbers(1)` stored a
ten-megabyte row. It now stores 99 bytes, with no configuration.

Co-Authored-By: Claude Opus 5 <[email protected]>
A session setting that is neither in the frozen baseline of
`03999_stateless_settings_history` nor present in `system.settings_changes` is
reported by that test and by the `settings_changes_history` style check, so that
`compatibility` keeps working.

The previous value is the same as the new one: the `query_plan` column is new in
this version, so there is no earlier behaviour for `compatibility` to restore,
and the setting bounds what one query can make a server allocate and store.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
Manerone and others added 2 commits November 16, 2026 09:21
The test asserts that optimization folds a `Join`-engine right side into a
`FilledJoin`. With parallel replicas it does not: the table is read as
`ReadFromMemoryStorage` and joined by a plain `Join`, and the plan gains a
`ReadFromRemoteParallelReplicas` and a `Union`, so there is no `FilledJoin` to
find.

Failed in `Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel)`
only; the same configuration with `AsyncInsert` in place of `ParallelReplicas`
passed, which is what identifies parallel replicas rather than s3 or the
architecture.

Co-Authored-By: Claude Opus 5 <[email protected]>
Master had moved under the same files this branch rewrites. Three changes on its
side account for every conflict: `modernize-use-nodiscard` was enabled,
`-WithMemoryTracking` containers were applied to `src/Processors/QueryPlan`, and
a per-side q-error was added to `EXPLAIN ANALYZE`.

Most conflicts were the same shape. Master's side is the profiling design this
branch replaces - keyed by `const IQueryPlanStep *` and walking the live plan -
with memory-tracking containers applied to it. The resolution keeps the id-keyed
design and carries the memory tracking onto every container that survives:
`StepWallClocks`, `CardinalityByJoinStep`, the `AnalyzeStepsStats` maps,
`TimeIntervalsByStep`, `timing_by_step`, `joins_below`,
`step_to_thread_intervals` and `steps_by_scope`. Master's `collectPostOrder` and
`collectPlanSteps` are dropped: both walk the live plan, which
`PlanAnalysisSnapshot::stepsInPostOrder` replaces.

`ReadFromMergeTree.h` needed more than a choice between the two sides. This
branch moved the index and projection structs into
`Profiling/Capture/PlanIndexStats.h`, so master's container change had to be
applied there instead. `used_keys` stays a plain `std::vector<std::string>`, as
master has it: it is filled from `KeyCondition::Description::used_keys` and
`StatisticsPartPruner::getUsedColumns`, which return `Names`.

`JoinAnalysisInputs::input_columns` is now a `VectorWithMemoryTracking` to match
the return type of `collectJoinInputColumns`. That file merged without a
conflict, so nothing marked the mismatch.

`[[nodiscard]]` is on every `makeAnalyzer` declaration, including the ones no
conflict touched.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
`modernize-use-nodiscard` is enabled since the merge with master, and the check
wants the attribute on every const member function that returns a value and has
no side effects. The profiling headers had it on `makeAnalyzer` alone.

Also drops a duplicate `Common/MapWithMemoryTracking.h` in `StepProfiler.h`,
left by the merge: the include arrived from master and the `<map>` it replaced
was swapped for the same header.

Co-Authored-By: Claude Opus 5 <[email protected]>
@Manerone
Manerone added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit bab51f5 Nov 17, 2026
378 of 379 checks passed
@Manerone
Manerone deleted the qpp-m2-logging branch November 17, 2026 11:53
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 19, 2026
…eplicas

In the ParallelReplicas jobs the join runs as the local plan plus
ReadFromRemoteParallelReplicas. j_left is a single coordinator segment, owned
by a remote replica by consistent hash, and DefaultCoordinator does not hand
an owned segment to another replica once its owner has announced. When the
remote announcement reaches the coordinator before the local replica's first
read request, the local replica gets 0 marks and the remote replica does the
whole join. The plan in system.query_log is captured on the initiator only, so
its Join node reports Right.Rows = 0 and UniqueKeys = 0 (and, with
max_threads = 1, no probe stage): 2 of 576 ParallelReplicas runs since the
test was added in ClickHouse#123059, 0 elsewhere.

Pin enable_parallel_replicas = 0 on the two queries whose plans the test
inspects, so the initiator executes the whole join. A query-level setting
beats the job's profile and the runner's injection, and keeps the rest of the
test running in that job.

Locally, on a 3-replica default_parallel_replicas cluster with the CI seed
342504: with the failpoint slowdown_parallel_replicas_local_plan_read and
max_threads = 2 the old test fails 20/20 and the new one passes 30/30; with
max_threads = 1 and no failpoint it failed 14/50 with the exact CI diff and
passes 50/50 now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@devcrafter

Copy link
Copy Markdown
Member

@Manerone Why the query plan is not stored for secondary queries i.e. on remote nodes which execute part of a distributed query, or do we want to support it later?

@Manerone

Copy link
Copy Markdown
Contributor Author

@devcrafter it will be done in the future, right now we are setting up the basic infrastructure.

@Fgrtue

Fgrtue commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

@devcrafter it also depends on what kind of remote execution do you have in mind. Because if you mean parallel replicas remote execution (i.e. https://clickhouse.com/docs/products/cloud/features/infrastructure/parallel-replicas) it is not supported. But if you mean the distributed plan that was added to EXPLAIN here (#126706) -- these kind of plans should be supported soon I think. @Manerone am I right?

Nothing against supporting the parallel replicas though. We just have different remote executions and each of them requires at the moment its own support.

@Manerone

Copy link
Copy Markdown
Contributor Author

@Fgrtue initially I thought we could add the distributed plans once we can collect the execution statistics as well. But now that you mentioned, we could start by having only the plan without statistics.

Once I merge this work with the structures created on #126706 I will do this. Maybe the same can be done for parallel replicas.

@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
diegomestre2 pushed a commit to diegomestre2/ClickHouse that referenced this pull request Nov 24, 2026
Mask every text of the captured plan that can carry user data with
`query_masking_rules`, as values, before the JSON document is rendered:
step descriptions and details (before they are cut to length), output
column names, index and projection descriptions and conditions, string
statistics such as join input columns, and the error text.

Store no plan for a query in which the plan could show what the `query`
column hides in a form masking cannot catch: a query with secret
arguments, a query in which a masking rule matches its text or a query
parameter of the session, and a query in which a subquery is replaced by
its result. The last one is to be lifted once the plan is logged without
such values.

Related: ClickHouse#123059

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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.

4 participants