Skip to content

Explain analyze estimate and actual cost - #114792

Merged
Fgrtue merged 37 commits into
masterfrom
explain-analyze-estimate-cost
Sep 10, 2026
Merged

Fgrtue merged 37 commits into
masterfrom
explain-analyze-estimate-cost

Conversation

@Fgrtue

@Fgrtue Fgrtue commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Related: #110839
Related: #110668
Related: #110892

Changelog category (leave one):

  • Improvement

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

EXPLAIN ANALYZE now shows more information about estimation for joins.


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

Version info

  • Merged into: 26.9.1.1130 (included in 26.9 and later)

Fgrtue and others added 19 commits July 9, 2026 19:48
Split out the in-development work-intervals collection (collect_work_intervals /
WorkInterval / work_intervals) from the Join statistics work so it can live in
its own branch/PR. This feature is not yet wired to a setting or an output
consumer.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 14, 2026, 11:20 AM

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3bc3004]

Summary: ✅


AI Review

Summary

This PR wires join-order estimates and actual join metrics into EXPLAIN PLAN / EXPLAIN ANALYZE, which is the right direction, but the exposed contract is still misleading in three important cases. I would not merge it as-is because users are being asked to trust numbers that are still wrong for non-ALL joins, WITH TOTALS, and fully matching FULL JOINs.

Findings

⚠️ Majors

Tests
  • ⚠️ Add an EXPLAIN ANALYZE ... WITH TOTALS regression that proves Output rows: actual and Cost: actual ignore the totals row.
  • ⚠️ Add a focused non-ALL regression (LEFT ANY, LEFT SEMI, LEFT ANTI, plus keep_logical_steps = 1) so the explain output cannot silently fall back to ALL-join estimates again.
  • ⚠️ Add a FULL JOIN regression with full key overlap; it should prove the exposed Output rows lower bound is max(left_rows, right_rows), not the sum.
Final Verdict

⚠️ Changes requested.

LLVM Coverage Report

Measured on commit 3bc3004.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 486/506 (96.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3bc30044f with master 8782a8213 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 07c5bfb53; 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

125 object files changed (+257.34 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/AnalyzePlanStats.cpp.o 119.14 KiB 172.96 KiB +53.81 KiB (+45.17%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinBranchCosts.cpp.o new 49.98 KiB +49.98 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinStatsAnalyzer.cpp.o 59.12 KiB 90.62 KiB +31.50 KiB (+53.29%)
src/CMakeFiles/clickhouse_common_io.dir/IO/S3/Requests.cpp.o 217.34 KiB 238.06 KiB +20.72 KiB (+9.53%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinEstimation.cpp.o new 18.73 KiB +18.73 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinStep.cpp.o 242.17 KiB 258.87 KiB +16.70 KiB (+6.90%)

717 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

799 translation units recompiled, 6538 s compile time in total, 797 of them have a recent master baseline.

Job report

Comment thread docs/reference/statements/explain.mdx Resolved
@Fgrtue

Fgrtue commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@m-selmi thank you for the review! I was thinking on whether is should add your suggestion about tag the estimated filters on table scans with their estimates/selectivities too in this PR. I decided that probably that would be better to do it separately, as it will be touching different parts of the code. I'll take a note on that one though for the future.

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026

MetricGroup output{MetricGroupKey::Output, {}};
output.metrics.emplace_back(MetricKey::Estimated, optionalQuantity(estimation.output_rows));
output.metrics.emplace_back(MetricKey::Actual, context.io.output_rows);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

context.io.output_rows is the step-level port counter, not "rows produced by the main join stream". collectIOStats sums every output port that crosses a step boundary, and hash-join pipelines install a separate JoiningTransform on the totals stream (QueryPipelineBuilder::joinPipelinesRightLeft, lines 724-733). On that path JoiningTransform::transform emits joinTotals rows without calling join->joinBlock, so the per-side matched-row report stays on main-stream semantics while this Actual row count grows by the totals row.

That also leaks into q-error below, and into Cost: actual because computeJoinBranchCosts feeds the same io_stats.output_rows into joinMatchedOutputRows. As soon as the join step propagates totals (for example from a joined subquery with WITH TOTALS), the new estimate-vs-actual metrics are wrong by one. Please either exclude the totals port from this accounting or derive the "actual output rows" from the same matched/unpaired counters used for the join-side metrics.

fraction over the join conditions is used.
- `Output rows` — the estimated number of rows the join produces:
`<selectivity> * <left_rows> * <right_rows>` for an inner join, floored at `<left_rows>` for
`LEFT`, at `<right_rows>` for `RIGHT`, and at `<left_rows> + <right_rows>` for `FULL`, because an

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FULL join output rows are not floored at left_rows + right_rows. When rows match, one left row and one right row collapse into the same output row, so a perfectly matching FULL JOIN between two 100-row inputs can legitimately produce 100 rows, not 200. This text now codifies the estimator's current behavior, so after this PR EXPLAIN PLAN / EXPLAIN ANALYZE will expose a systematically too-large Output rows estimate and q-error for fully matching FULL joins. Please floor FULL joins at max(left_rows, right_rows) and keep this explanation in sync.

@Fgrtue

Fgrtue commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

@groeneai

Copy link
Copy Markdown
Collaborator

The failure is a master regression, not from your diff.

Stress test (arm_tsan) at 3bc30044 aborts the server on a LOGICAL_ERROR, which is why the job is red with no individual test listed as failing:

Logical error: 'Input nodes size mismatch in dag:
0 : INPUT () (no column) Int64             __table1.deleted
1 : INPUT () (no column) String            __table1.a
2 : INPUT () (no column) Nullable(Nothing) __table1.b
3 : INPUT () (no column) String            __table3.a
4 : INPUT () (no column) String            __table3.c
5 : FUNCTION (1, 3) (no column) UInt8             equals(__table1.a, __table3.a) [equals]
6 : FUNCTION (2, 4) (no column) Nullable(Nothing) equals(__table1.b, __table3.c) [equals]
Output nodes: 0 1 2 3 4 5 6 0
, expected: [__table1.b, __table1.a], [__table3.a, __table3.c]'

at JoinExpressionActions.cpp:138, from optimizeJoin.cpp:1448 chooseJoinOrder.

It comes from #114817, merged to master 2026-09-09 08:56 UTC. Your head predates that: compare/9ce67d62...3bc30044 is diverged with behind_by=1055, so the regression reached this run only through the merge commit CI builds, and the job started 2026-09-09 23:12 UTC. Breadth since that merge, from default.checks: 15 occurrences over 10 check flavours, spread across 13 pull requests (yours among them) plus one MasterCI run (d8d2f994, AST fuzzer arm_asan_ubsan).

Mechanism: resolvePlannerOnlyFilters rebuilds a FilterStep with remove_filter = true, using a surviving conjunct's result_name as the filter column. collectFilterConjuncts unwraps aliases, so that conjunct can be a column of the step's own output header, the __filter<name> wrapper push-down had added precisely so the removal could not hit the stream column. FilterTransform then erases it, and because the pass replaces node.step, no updateInputHeader reaches the parent JoinStepLogical, which still holds an input node for it. In your dump that column is __table1.deleted: five inputs against the expected two plus two keys.

A fix is already open, #119106, so there is nothing to create and nothing to change on your side. It re-establishes the alias at the rebuild site. It also carries a deterministic reproducer on default settings if you want to confirm independently:

SELECT deleted, b, c
FROM (SELECT 'v' AS b, toNullable('x') AS a, 1 AS deleted) AS q
INNER JOIN (SELECT 'x' AS a, 'w' AS c) AS s ON q.a = s.a
WHERE deleted AND (c != b);

@Fgrtue
Fgrtue added this pull request to the merge queue Sep 10, 2026
Merged via the queue into master with commit ba9fc17 Sep 10, 2026
344 of 345 checks passed
@Fgrtue
Fgrtue deleted the explain-analyze-estimate-cost branch September 10, 2026 13:45
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
case MetricKey::Actual: return "actual";
case MetricKey::EstimatedNDV: return "estimated (NDV)";
case MetricKey::ActualCartesian: return "actual (cartesian)";
case MetricKey::QError: return "q-error";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice to see that we now have q-error, which is the only relevant error metric in DMBS.

@clickhouse-gh clickhouse-gh Bot added comp-explain EXPLAIN and query profiling output: EXPLAIN PLAN / PIPELINE / AST / SYNTAX / ESTIMATE, pretty EXP... and removed comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-explain EXPLAIN and query profiling output: EXPLAIN PLAN / PIPELINE / AST / SYNTAX / ESTIMATE, pretty EXP... pr-improvement Pull request with some product improvements 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.

5 participants