Repository navigation
Improve AutoPR observability - #120884
Improve AutoPR observability#120884
Conversation
Every number needed to answer "did this fire, and if not why" was only available
by grepping `optimizeTree` at debug level, which nobody enables in production and
which cannot be aggregated. Reconstructing one run's funnel took 25,614 log lines.
Add eleven ProfileEvents covering the whole decision:
AutoParallelReplicasProbePlansBuilt AutoParallelReplicasNoStatistics
AutoParallelReplicasProbeMicroseconds AutoParallelReplicasStatisticsDrifted
AutoParallelReplicasNodeMatchFailed AutoParallelReplicasCostModelEvaluated
AutoParallelReplicasNoReadFromReplicas AutoParallelReplicasApplied
AutoParallelReplicasNoSelectedRows AutoParallelReplicasRejectedByThreshold
AutoParallelReplicasProbeSkippedByThreshold
`ProbeMicroseconds` is charged from a `SCOPE_EXIT` around the whole probe, so it
counts whether or not the plan is adopted - the probe is paid either way, and on
one run 7263 of 25614 probes ended in an early return that installs no statistics
updater, so they are rebuilt on every execution and can never converge.
`Applied` is the one event that says the optimization changed the query.
`ProbeSkippedByThreshold` and `RejectedByThreshold` are separate on purpose: the
first is the gate working as intended before any work, the second is the probe
already paid for.
`ParallelReplicasQueryCount` is left alone, but its description now warns that
automatic parallel replicas increments it while probing, so a query can carry it
with no replica having done anything: on that run 21449 of 26471 queries carrying
it had `ParallelReplicasUsedCount` = 0.
Two log messages become actionable:
- `Cannot find step with matching hash` - by far the most common reason the
optimization gives up, 4867 times in that run - now prints the hash it wanted,
the step it wanted it for, and every `uniqID=hash` the single-node plan offered.
- the statistics-drift message now prints the hash. Without it there is no way to
tell genuine drift on one plan from two plans sharing a cache entry.
There is also a line for the acceptance itself, which was silent: whether the plan
was replaced could only be inferred by comparing the two numbers in
`The applied formula`.
Verified against a server: each counter matches what `optimizeTree` logged for the
same query across the no-statistics, cost-model, applied, node-match-failure and
threshold-skip paths, and the probe count agrees with the log over a whole run
(10 probes built, 10 logged).
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Follow-up on the review of the previous commit. Terminology: the plan the optimization builds to make its decision is a plan with parallel replicas, not a "probe plan", so the word is gone from the event names and descriptions. `AutoParallelReplicasProbePlansBuilt`, `AutoParallelReplicasProbeMicroseconds` and `AutoParallelReplicasProbeSkippedByThreshold` become `AutoParallelReplicasPlansBuilt`, `AutoParallelReplicasMicroseconds` and `AutoParallelReplicasSkippedByThreshold`. `AutoParallelReplicasNodeMatchFailed`, `AutoParallelReplicasNoReadFromReplicas` and `AutoParallelReplicasNoSelectedRows` are united into a single `AutoParallelReplicasPlanNotSuitable`: from the outside they are one outcome - the plan that was built could not be used to decide. The three log messages are kept, so which case it was is still visible in the server log. `AutoParallelReplicasMicroseconds` is now an umbrella over the whole of `considerEnablingParallelReplicas`, not just the plan build: the two plan traversals above it are not free, and the threshold gate used to return before the stopwatch existed at all, so a query rejected there recorded nothing. Measured on the local harness: a gate rejection now records ~200 us that was previously invisible. Log severities: `DEBUG` is now reserved for the decision the optimization made once it had everything it needed - the cost model formula, the drift detection, the threshold rejection and the plan replacement. Everything explaining why it stopped short is `TRACE`, including the "Cannot find step with matching hash" message, which is both the most frequent one and by far the longest. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…casSkippedEarly` Both this counter and `AutoParallelReplicasRejectedByThreshold` are the same threshold, so naming them both after it says nothing. What separates them is when they fire: this one before any planning work, the other after the cost model has already run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Workflow [PR], commit [79cf84c] Summary: ✅
AI ReviewSummaryThe PR adds outcome counters, separate optimization and plan-building timers, runtime statistics-collection timers, and clearer diagnostics for automatic parallel replicas. Reviewed commit Missing context / blind spots
Final VerdictStatus: ✅ Approve. No required code changes or new inline findings. |
…uildAttempts` The counter is incremented before `query_plan_with_parallel_replicas_builder` is called, so it also counts the case where the builder comes back empty because the query cannot be executed with parallel replicas at all - the old name promised a plan that may not exist. Counting the attempt rather than the result is deliberate: re-planning the query is what costs, and it is paid in full whether or not a plan comes out of it. So the name and the description move to the attempt instead of the increment moving below the null check. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…outcome Five exits past `AutoParallelReplicasPlanBuildAttempts` incremented nothing, so `system.query_log` showed that automatic parallel replicas spent time and tried to build a plan but not why it stopped. The window function over a bare table scan covered by `04502_autopr_input_bytes_estimation_window_function` was one of them; `findReadingStep` returning nothing was another, and that one does not always log on its way out either. All five now increment `AutoParallelReplicasPlanNotSuitable`, which is what they are: no decision could be reached from the plan with parallel replicas. Its description no longer presupposes that a plan was built, since one of the five is the builder coming back empty. `AutoParallelReplicasApplied` moves below `replaceNodeWithPlan`. It claims the plan was replaced, but both `moveSetsFromLocalPlanToReplicasPlan` and `replaceNodeWithPlan` can throw, so a failed query could report `Applied = 1` for a swap that never happened. `tmp/verify_events.sh` grew an arm for the window-function shape and a closure check: over the harness run, 6 build attempts against 6 terminal outcomes, 0 unaccounted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
With `automatic_parallel_replicas_mode = 2`, usable statistics and no drift, the decision is skipped because that mode only ever collects. Nothing was counted on that path, so a repeated mode-2 query showed a build attempt with no terminal outcome - and mode 2 is exactly the lane that exists to collect, so this is its normal steady state rather than a corner case. Counted with a new `AutoParallelReplicasDecisionSkippedByMode` rather than by dropping the attempt counter in mode 2: the plan really is built and matched there, that work costs, and hiding it would leave the statistics-collection lane with no observability at all. `apply_plan_with_parallel_replicas` starts as `mode != 2` and drift is the only other thing that clears it, so the increment sits in the no-drift branch where the flag being false means the mode and nothing else. Drift keeps its own event and is not double counted. `tmp/verify_events.sh` grew a mode-2 arm; the closure check now reads 8 build attempts against 8 terminal outcomes, 0 unaccounted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…anning `AutoParallelReplicasMicroseconds` starts at the top of `considerEnablingParallelReplicas`, but the two exits right below it were counted by nothing, so those queries showed time spent with no reason next to it. `force_use_projection` did not even log. Two events rather than one: the plan-shape exit is by far the most frequent one on a mixed workload and is really the reach of the optimization - how many queries it never gets to consider - which is a number worth trending on its own. Folding it together with a rare setting-driven skip would bury it. Every exit past the mode guard is now counted: `SkippedForcedProjection`, `PlanShapeNotSupported`, `SkippedEarly`, or a build attempt with its terminal outcome. `tmp/verify_events.sh` grew an arm for each. The projection one needs a table that really has a projection - with `force_optimize_projection` on a table without one the query throws and never reaches the optimization, which is how the first version of that arm passed vacuously. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`optimizeTree` enforces `force_optimize_projection_name` against the single-node plan, and only afterwards does `considerEnablingParallelReplicas` get a chance to replace that plan. The candidate it offers is built with projections disabled entirely - `buildQueryPlanForAutomaticParallelReplicas` clears `optimize_projection`, `force_use_projection` and `force_projection_name` - so adopting it would answer a query that demanded a projection with a plan that uses none. The boolean `force_optimize_projection` was already handled; the named variant was not. I could not make it actually happen: in two shapes the candidate was rejected at node matching instead, because a plan reading a projection hashes differently from one reading the table. So this is making an implicit guarantee explicit rather than fixing an observed break - the protection today is an accident of how the hashes are built, and nothing pins it. `AutoParallelReplicasSkippedForcedProjection` now names both settings in its description, and `05227_autopr_forced_projection_name` pins the behaviour: the projection is still used, no candidate is built, and the skip is counted. Ran 10x against a server carrying the real test cluster, no failures. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes119 object files changed (+63.31 KiB total), 0 added.
719 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 units272 translation units recompiled, 2309 s compile time in total, 272 of them have a recent master baseline. Symbol sizes
|
`clickhouse-test` randomizes `optimize_use_projections`, and both forcing settings are gated on it - `QueryPlanOptimizationSettings.cpp` leaves `force_projection_name` empty when projection optimization is off. So on the 5% of runs where it was randomized to 0, nothing was forced, the guard under test never fired, and the assertions came back `0 0 0 1`. That is what the CI run on dc7fa9a hit, across three jobs. Pinned rather than tagged `no-random-settings`: the test needs exactly this one setting held, not the whole randomizer disabled. Verified against the condition itself rather than by luck: with `optimize_use_projections` forced off at session level the test still passes, and without the pin the same run proceeds past the guard instead of stopping at it. 30 randomized runs on top, all green - though those cannot confirm coverage on their own, since `clickhouse-test` only prints the settings it chose when a run fails. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…llelReplicasSkippedDueToSettings` The counter is for the case where the settings a query was given rule the optimization out before it looks at the query at all. A forced projection is the only one today, but naming the counter after it means a new event every time another such setting turns up, when callers want one number for "configuration said no". The description names the forced-projection case as the current instance rather than defining the counter by it, and the log message at the call site stays specific, so which setting it was is still one grep away. Deliberately still a single call site. The three settings checks inside `buildQueryPlanForAutomaticParallelReplicas` (`enable_parallel_replicas`, `parallel_replicas_local_plan`, an unset `cluster_for_parallel_replicas`) are settings-driven too, but they fire after `AutoParallelReplicasPlanBuildAttempts` has already been counted, so folding them in here would mix a pre-planning skip with one inside an attempt and break the closure the funnel check relies on. They stay in `AutoParallelReplicasPlanNotSuitable`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…read `automatic_parallel_replicas_min_bytes_per_replica` is a number somebody has to choose, and nothing said what the queries it turns away would have read. The log line said it for one query at a time, but a log line cannot be aggregated, so there was no way to see the distribution the choice should be made from. `AutoParallelReplicasRejectedBytesPerReplica` records it, and it is the exact decision boundary: with the value it reported for a query, setting the threshold to 4061072 applied the optimization and 4061073 turned it away. Recorded at both checks, not just the late one. The late check is close to unreachable in practice: it needs `input_bytes / replicas` below the threshold while the early gate passed on the compressed estimate, and `input_bytes` is the larger of the two for anything but fixed-width columns, so the early gate gets there first. Sweeping the threshold over a string column found no value that reaches the late check at all. Recording only there would have produced an empty distribution. The two checks size the read differently, so the description says to treat the distribution as approximate. The late log message now prints the total read alongside the per-replica figure. Drop `AutoParallelReplicasDecisionSkippedByMode`: mode 2 is the statistics-collection mode, not one production runs in, so a counter dedicated to it is noise where the events are actually read. The comment in its place records that mode 2 sits outside the attempts-to-outcomes accounting by construction, and the funnel check in the harness now scopes itself to modes 0 and 1. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ejection Recording it only when the byte threshold turned a query away showed one side of the curve: which rejected queries a lower `automatic_parallel_replicas_min_bytes_per_replica` would let through, but nothing about what a higher one would cost. The queries a higher threshold would start turning away are the ones being applied, and those recorded nothing. The cost model now records the size for every query that reaches it, before the decision. The gate before planning keeps its own record, since those queries never reach the cost model. Only its rejected side can be recorded: when a read qualifies the loop stops early, deliberately, because measuring one runs index analysis, so `max_bytes_to_read` is not the largest read on that path. The two sites size the read differently and, measured on a string column, they disagree by nearly 2x rather than the ~40% the existing comment anticipates - 8009994 from the cost model against 4061072 from the gate, for one and the same query. The gate runs first, so its figure is the one that decides how high the threshold can go, and the description says so: read naively, the cost model's larger figure would suggest room to raise the threshold that is not there. Renamed from `AutoParallelReplicasRejectedBytesPerReplica`, which no longer described it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nothing depends on the logger name functionally - no test reads `system.text_log` or filters by `logger_name`, they all assert on `ProfileEvents` - but several comments quoted `optimizeTree` as the source of a message, and the `AutoParallelReplicasPlanNotSuitable` description named it as where to look for which case fired, which is user-facing. `03707`'s comment also said those messages are printed at the debug level, which stopped being true when most of them were demoted to trace. Left alone: the two places that say `optimizeTree` meaning the function in `optimizeTree.cpp` rather than the logger, which are still accurate. The local harness greps the server log by the logger prefix, so it would have reported an empty log column beside every counter rather than failing. Updated too, and while confirming that, taught it to redefine the two clusters the tests use at its own port: `clusters.xml` points every replica at 9000, so against a server anywhere else every parallel-replicas test died with INCONSISTENT_CLUSTER_DEFINITION long before reaching what it asserts. That took the suite from 1 passing to 32. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ings `check-settings-style` collects settings externs with `rg "^\s*extern const .*Settings"`, which matches "Settings" anywhere on the line - including in the variable name. `extern const Event AutoParallelReplicasSkippedDueToSettings;` is a ProfileEvent, but the check took it for a setting, failed to find it in the settings list and reported it as obsolete. That is what the `cpp` style step failed on for fbb0d85. The type is what carries "Settings" in a real declaration (`extern const SettingsUInt64 x;`), so the word right after `const` is what should be matched. Checked rather than assumed: across `src`, `base`, `programs` and `utils` the tighter pattern matches 5223 lines against 5226, and all three it drops are the same false positive - this one, plus two `extern const Event SettingsProfile...` lines in `SettingsProfilesCache.cpp` that carry a `// NOLINT` for exactly this reason. It drops no real declaration, and those two NOLINTs are now redundant. Verified end to end: with the old pattern the check reproduces the CI message locally, with the new one `check_cpp.sh` is silent and exits 0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…st level The trace line says which hash was not found and on which step, which is enough to know the match failed but not why. The list of hashes the single-node plan offered, which it also carried, was a flat unordered dump with no structure - you could see that nothing matched but not where the two plans stopped agreeing. Split in two. The trace line keeps the question - the hash and the step it was looked up for. A test-level line before it prints both plans in EXPLAIN shape with every step's hash next to it. The hashes are bottom-up, so the deepest level at which the two dumps disagree is where the plans actually diverge, and that is the thing worth reading. It pays for itself on the join case that has never matched. Every step from the reads up to and including `Join` hashes identically in both plans (`1008622370744229163`), and the divergence is one level above it, in the wrapping `Expression`: `11702660461138147004` against `17594823321490061594`. One command instead of an inference. `LOG_IMPL` leaves before it touches its arguments when the level is off, so neither plan is walked unless someone asked. Read it with `--send_logs_level test`, since a server logs at trace by default. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The dump printed a step's description in place of its name, so a step with a description looked nothing like the same step under `EXPLAIN`. `explainStep` prints the name and then the description in parentheses when there is one, and now so does this - with `getUniqID`, which is the name plus an instance number, standing in for the name so the trace message below can be tied to a line. Why it is not `QueryPlan::explainPlan` is now written down next to it: the text renderer is file-local to `QueryPlan.cpp` and its entry point takes a `QueryPlan`, where the only thing in hand at this point is a node. The JSON form is public and does carry the step id, but finding the level at which two plans stop agreeing by reading two JSON documents side by side defeats the point. The line is built from the same two accessors `explainStep` uses, and the hash - which `EXPLAIN` has no way to show - is appended. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…rinter The dump added for the failed-match case walked the plan itself, which meant a second plan printer living next to the real one and free to drift from it. It existed only because `EXPLAIN` had no way to show a node's hash. So give it one. `ExplainPlanOptions::step_hashes`, when set, annotates each step with the hash of the node it belongs to, in both the text and the JSON renderers. Nothing in a plan carries these - they come from `calculateHashTableCacheKeys` - so only a caller holding them can supply them, and the option is keyed by step rather than by node so `QueryPlan.h` does not have to know about `QueryPlan::Node` ahead of its own declaration. The automatic parallel replicas dump is now `QueryPlan::explainPlan` with that option set, and the bespoke traversal is gone. `findCorrespondingNodeInSingleNodePlan` takes the two plans rather than their root nodes to reach it; `root` is `*query_plan.getRootNode()` at this point, since `QueryPlan::optimize` passes both. Unset, which is every caller but this one, nothing changes: plain `EXPLAIN` and `EXPLAIN json=1` print exactly what they did, and across the 116 stateless `explain` tests no output mentions a hash. The seven that fail here fail on this machine for want of `test.hits`, of clusters pointing at this server's port, and of ZooKeeper. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds profile events, timers and trace-level logging to automatic parallel replicas, and moves one eligibility check earlier in the code. None of this can make a single-node aggregation faster. The added counters can only add a tiny cost, and only on queries that go through automatic parallel replicas. The two flagged ClickBench improvements, Q33 (-10.0%) and Q34 (-10.1%), are both large GROUP BY queries with noisy history, and both PR medians sit inside master's recent range, so they are downgraded to not sure. No real performance change can be attributed to this PR. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
…nSettings.h` Only the `LoggerPtr` alias is needed there. Related: #120884 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
It timed out (> 180s) in the TSan flaky check: every replica reads the whole build side in the run with the gate disabled. A tenth of the data reaches the same decisions, and the test no longer needs to lift `max_rows_to_read`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120884&sha=latest&name_0=PR Related: #120884 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp
Fgrtue
left a comment
There was a problem hiding this comment.
One main question related to the cases when we log AutoParallelReplicasPlanNotSuitable. I would assume we would want to change the category of such cases to AutoParallelReplicasPlanShapeNotSupported. WDYT?
…t count `buildContext` switches automatic parallel replicas off when `enable_parallel_replicas` is disabled or forced, or `parallel_replicas_mode` is not `read_tasks`, so the optimization never runs and counts nothing, as with `automatic_parallel_replicas_mode = 0`. That also leaves the builder's `enable_parallel_replicas` check unreachable, so it is now an assertion. Related: #120884 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
`AutoParallelReplicasPlanShapeNotSupported` and `AutoParallelReplicasPlanNotSuitable` read alike, yet one is counted before the plan with parallel replicas is built and the other after. Now `AutoParallelReplicasSkippedDueToQuery` sits with `AutoParallelReplicasSkippedDueToSettings` and `AutoParallelReplicasSkippedEarly` before the build, and `AutoParallelReplicasPlansNotComparable` says what went wrong after it. The descriptions say "before" and "after building the plan". Related: #120884 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now declines at a remembered boundary without building the plan with parallel replicas, calling `decideAtBoundary` once without the plan and, when that asks for it, again with it. The funnel events in `decideAtBoundary` are counted only by the call with the plan, so that a query is counted once: a decline without the plan is `AutomaticParallelReplicasDecidedWithoutBuildingPlan`, which master counts in the caller. The new log lines follow the branch's rule (`LOG_TRACE` on `AutoParallelReplicas`), and the plan dump on a failed match moves to the caller, which is the only place that has both plans now. Tests that check the events of a second run pin `automatic_parallel_replicas_remember_boundary = 0`, and `05397_autopr_remembered_read_ambiguous_in_self_join` raises the client log level to `trace`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A query declined at a boundary remembered from an earlier execution counted only `AutomaticParallelReplicasDecidedWithoutBuildingPlan`, so in the steady state, where most declines are of this kind, `system.query_log` could not tell a cost-model decline from a threshold or duplicated-read one. `decideAtBoundary` now counts its events as it returns, and drops them only when it asks for the plan with parallel replicas, since the call with the plan decides again and counts then. 05257, 05332 and 05361 no longer turn the remembered boundary off, and 05257 and 05361 assert that the decision was taken there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…icasStatisticsDrifted` are counted Both were only ever asserted to be zero, so dropping either increment left the tests passing. A projection read makes the two plans not comparable, since the plan with parallel replicas is built without projections, and growing the table past twice the rows of the collected statistics makes the next run drift. Related: #120884 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
`AutoParallelReplicasPlansNotComparable` also counted a plan with parallel replicas in which the planner had turned parallel replicas off by itself, e.g. for too few rows per replica or a correlated subquery. Such a plan has no read from the other replicas, and the query is not one this optimization could improve, so it now counts `AutoParallelReplicasPlanWithoutParallelReplicas`, and `AutoParallelReplicasPlansNotComparable` is left with the limitations of the optimization itself. The case is told from the plan, not from the settings of the nested context, so a plan that does read from the other replicas but has a shape `findTopNodeOfReplicasPlan` cannot handle stays not comparable. #120884 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Instead of buffering the events and dropping them when the call asks for the replicas plan, return before counting anything on those paths: the cost-model predicates are computed up front, and the missing-statistics and drift branches return before their counters when there is no plan yet. Each query still counts its outcome once, and a cached decline still counts its reason. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #120884 to 26.10: Improve AutoPR observability
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improved
automatic_parallel_replicasobservability by adding outcome-specificProfileEvents, split optimization/plan-build timing counters, and runtime statistics-collection timing inquery_log.Workflow [PR]
Sync PR [sync-upstream/pr/120884]
Version info
26.10.1.2502-master(included in26.10and later)26.10.2.4