Repository navigation
Add the executed query plan to system.query_log - #123059
Conversation
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]>
|
Workflow [PR], commit [66d0bd8] Summary: ✅
AI ReviewSummaryAdds an opt-in Findings❌ Blockers
Missing context / blind spots
Final VerdictStatus: ❌ 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. |
|
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. |
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]>
system.query_logsystem.query_log
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes688 object files changed (+835.18 KiB total), 6 added.
711 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 units3565 translation units recompiled, 23016 s compile time in total, 3559 of them have a recent master baseline. Translation units without a recent master baseline:
|
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]>
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]>
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]>
What this addsA The difference from 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
When the capture runsThe profiler lives on the query 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
The capture is split across two moments, and neither of them can move. The plan is taken after 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
Why there is a
|
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]>
`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]>
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]>
`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]>
bab51f5
…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]>
|
@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? |
|
@devcrafter it will be done in the future, right now we are setting up the basic infrastructure. |
|
@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. |
|
@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. |
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]>
Related: #111748
Adds a
query_plancolumn of the nativeJSONtype tosystem.query_log, holding the plan the query actually executed together with its per-step runtime statistics. It is filled when thelog_query_planssetting is enabled, and is empty forQueryStartrows, since no plan exists at that point.Shape of the document
Nodesis 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 aReadFromMergeTree— what index and projection analysis decided.A query decides how much text its own plan contains: a large
INlist, a long alias and a folded constant are all rendered into it.log_query_plans_max_sizebounds 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'sActionsDAGinto theExpressionActionsand 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_planA 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a
query_plancolumn tosystem.query_log, containing the query plan that was executed with its per-step runtime statistics, serialized asJSON. Enabled with thelog_query_planssetting.Workflow [PR]
Sync PR [sync-upstream/pr/123059]
Version info
26.11.1.2565-master(included in26.11and later)