Skip to content

Extend reading in reverse order with FINAL to Merge tables and topKThroughJoin - #118008

Merged
alexey-milovidov merged 19 commits into
masterfrom
reverse-final-merge-topk
Oct 7, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
reverse-final-merge-topk

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Closes: #117961
Related: #115345
Related: #111609

#115345 enabled the read-in-order optimization for FINAL queries that sort in reverse order of the sorting key on ReplacingMergeTree tables, and left two places out: the Merge engine and the topKThroughJoin optimization. This change covers both.

  • ReadFromMergeTree gets canReadInReverseOrder, which holds the check that requestReadingInOrder used inline: without FINAL a reverse read is always accepted, with FINAL only for ReplacingMergeTree with optimize_read_in_reverse_order_final enabled.
  • ReadFromMerge::requestReadingInOrder rejected every reverse order request with FINAL, so SELECT ... FROM merge_table FINAL ORDER BY key DESC LIMIT n read all the data of the children. It now asks every child reading step with canReadInReverseOrder and passes the request on when all of them accept it. The children are asked before any of them is switched to reading in order, so a rejected request leaves the child plans untouched. A Merge table with a child that cannot read in reverse order with FINAL (for example, a CollapsingMergeTree) keeps the previous plan.
  • topKThroughJoin decides whether to inject its own Sort + Limit on the preserved side of a LEFT JOIN, or to defer to the read-in-order optimization through the join. For FINAL it deferred only when all columns of the sort description were ascending, because the second pass rejected every reverse read with FINAL. It now gets the input order that the second pass would request from getInputOrderIfReadInOrderIsUseful (renamed from wouldReadInOrderBeUseful, which returned only a flag) and defers exactly when the second pass accepts that direction: a reverse direction is accepted when canReadInReverseOrder holds. The direction is the one computed for the storage's sorting key, so a descending sorting key read by an ascending sort description is a reverse read, and by a descending one a direct read, which the previous column-based heuristic got wrong in both directions. The same deferral now also applies to a Merge table on the preserved side: ReadFromMerge::canReadInReverseOrder holds the check of the children, and a ReadFromMerge overload of getInputOrderIfReadInOrderIsUseful matches every selected child table the way the second pass does, so Merge ... FINAL LEFT JOIN ... ORDER BY key DESC LIMIT n reads the children in reverse order through the join without an inner Sort + Limit. With parallel replicas, where the Merge read is expanded into its tables later, the explicit Sort + Limit is kept.

Tests: 05192_read_in_reverse_order_final_merge_table covers a Merge table over ReplacingMergeTree children (level-0 duplicates, duplicates across parts, overlapping children with several parts and granules, a descending sorting key, the setting disabled, and a child engine that cannot read in reverse order). 05193_top_k_through_join_final_reverse_order covers the deferral decision of topKThroughJoin for ReplacingMergeTree with the setting on and off, AggregatingMergeTree, a descending sorting key, and a Merge table behind the join, and compares the rows with a plain read. 04234_top_k_through_join_final_desc_gate disables optimize_read_in_reverse_order_final to keep testing the case it was written for.

Changelog category (leave one):

  • Performance Improvement

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

Queries with FINAL that sort in reverse order of the sorting key, such as SELECT ... FROM t FINAL ORDER BY key DESC LIMIT n, now read in order also through Merge tables over ReplacingMergeTree tables, and the topKThroughJoin optimization defers to reading in reverse order below a LEFT JOIN when the table supports it. This extends #115345.

Measured locally (release build, Merge over two ReplacingMergeTree tables of 20M rows each, SELECT k, v FROM m FINAL ORDER BY k DESC LIMIT 10):

optimize_read_in_reverse_order_final rows read bytes read duration
0 43170304 658.73 MiB 554 ms
1 211456 3.23 MiB 4 ms

The LEFT JOIN shape of topKThroughJoin (SELECT a.k, r.v FROM a FINAL LEFT JOIN r ON a.k = r.k ORDER BY a.k DESC LIMIT 10, a a ReplacingMergeTree of 20M rows):

optimize_read_in_reverse_order_final rows read bytes read duration
0 21524712 164.23 MiB 511 ms
1 61672 489.63 KiB 3 ms

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

Version info

  • Merged into: 26.10.1.1718-master (included in 26.10 and later)

…roughJoin

`ReadFromMergeTree` gets `canReadInReverseOrder`, which holds the check that
`requestReadingInOrder` did inline: without `FINAL` a reverse read is always
accepted, with `FINAL` only for `ReplacingMergeTree` when
`optimize_read_in_reverse_order_final` is enabled.

`ReadFromMerge::requestReadingInOrder` rejected every reverse order request
with `FINAL`. It now asks the reading steps of all children with
`canReadInReverseOrder` before switching any of them, and passes the request
on when all of them accept it.

`topKThroughJoin` deferred to the read-in-order optimization through the join
only when all sort columns were ascending with `FINAL`. It now gets the input
order the second pass would request from `getInputOrderIfReadInOrderIsUseful`
(renamed from `wouldReadInOrderBeUseful`) and defers exactly when the second
pass accepts that direction, which also handles descending sorting keys.

Closes: #117961
Related: #115345
Related: #111609

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f422ec5]

Summary: ✅


AI Review

Summary

This PR extends reverse-order read-in-order support for FINAL through Merge tables and brings topKThroughJoin's deferral logic into line with the second-pass read-in-order checks, including the child-plan reset needed to keep _table / _database pruning correct after the probe. I did not find any remaining correctness, safety, or material performance-contract issues in the current diff, and the previously raised Merge / topKThroughJoin review points appear fixed in the code now under review.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f422ec5.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 139/147 (94.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 4, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f422ec594422bb57b51bd47feb25576824be8f92 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR changes when topKThroughJoin defers to read-in-order, adds reverse-order FINAL reads through Merge tables, and moves the existing ReplacingMergeTree reverse-read check into a canReadInReverseOrder() helper without changing what it does. None of the four flagged ClickBench queries (Q18, Q28, Q33, Q34) use a JOIN, FINAL or a Merge table, so the changed code does not run for them. All four stay not_sure: the +7% to +11% slowdowns are either inside master's normal range (Q18, Q28) or borderline with the two tests disagreeing (Q33, Q34). They share a similar 4-6% CPU rise, which points to the run environment rather than this diff, and the envelope-based suppressions match what the diff touches.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 864 952 +10.2% 0.0041 aggregation: This GROUP BY on a single table has no JOIN, FINAL or Merge table, so the changed top-K and reverse-read code never runs. The +10.2% is inside master's normal range.
⚠️ 28 not_sure 1020 1108 +8.6% 0.0041 aggregation: This regex GROUP BY/HAVING query does not use the topKThroughJoin or Merge-table read-in-order paths. The +8.6% is inside master's normal range, and the PR runs were noisy.
⚠️ 33 not_sure 1124 1252 +11.4% 0.0194 aggregation: This is a high-cardinality GROUP BY with ORDER BY count LIMIT, with no JOIN or FINAL. The PR does not change that path, and the two tests disagree about the +11.4%.
⚠️ 34 not_sure 1118 1200 +7.3% 0.0144 aggregation: This GROUP BY URL query has no JOIN, FINAL or Merge table, so the changed optimizer gates do not apply. The +7.3% is borderline, and the two tests disagree.

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
  • StressHouse run: 7e03f0ff-4b22-439a-948e-0491cd0c4dff
  • MIRAI run: 6a5b6152-1508-442a-a266-287c49a8491d
  • PR check IDs:
    • clickbench_85521_1791328859
    • clickbench_85527_1791328859
    • clickbench_85533_1791328859
    • tpch_adapted_1_official_85549_1791328859
    • tpch_adapted_1_official_85556_1791328859
    • tpch_adapted_1_official_85591_1791328859

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
alexey-milovidov and others added 3 commits September 10, 2026 15:54
…bles

The AI review pointed out that the structured docs still said reverse-order
reading with `FINAL` works only for `ReplacingMergeTree`. Update the
`optimize_read_in_reverse_order_final` doc string in `src/Core/Settings.cpp` and
the `ORDER BY` optimization text in `src/Parsers/ParserSelectQuery.cpp`, which is
the source of truth for the autogenerated `order-by.mdx`, to also mention `Merge`
tables over such children.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated to f869061a:

  • Merged master (the branch was 4035 commits behind; the merge was clean).
  • Addressed the AI review's documentation finding (8653e094): the optimize_read_in_reverse_order_final doc string in src/Core/Settings.cpp and the ORDER BY optimization text in src/Parsers/ParserSelectQuery.cpp — the source of truth for the autogenerated order-by.mdx — now mention Merge tables over ReplacingMergeTree children as well. The generated .mdx is untouched.
  • Renumbered the new tests to 05192_read_in_reverse_order_final_merge_table and 05193_top_k_through_join_final_reverse_order (f869061a), because 05076/05077 are claimed by other pending pull requests.
  • Added the performance measurement the review asked for, to the pull request description. Release build, Merge over two ReplacingMergeTree tables of 20M rows, SELECT k, v FROM m FINAL ORDER BY k DESC LIMIT 10: 43170304 rows / 658.73 MiB / 554 ms with the setting off, 211456 rows / 3.23 MiB / 4 ms with it on. The LEFT JOIN shape of topKThroughJoin over a 20M-row ReplacingMergeTree: 21524712 rows / 164.23 MiB / 511 ms → 61672 rows / 489.63 KiB / 3 ms.

ninja clickhouse builds; 05192, 05193, 04506_read_in_reverse_order_final, 04234_top_k_through_join_final_desc_gate and 02564_read_in_order_final_desc all pass locally, and a sweep of the 77 read_in_order / top_k_through_join tests shows no result difference (the 17 local reds are missing test clusters, a missing test.hits and a stale system clickhouse-client, all environment artifacts).

The only red, 04898_distributed_plan_grouping_function in Stateless tests (arm_binary, parallel), is unrelated: the runner's own diagnosis pins it on the randomized index_granularity_bytes 2544 (the EXPLAIN dump reports Granules: 10 instead of 1), it failed the same day on master itself and on #118071, and the fix is already in flight in #118071, which is not merged yet, so merging master cannot clear it here.

alexey-milovidov and others added 3 commits September 18, 2026 02:21
…gh a `Merge` table

`topKThroughJoin` deferred to the second pass of the read-in-order optimization only when the preserved side of the join was a `ReadFromMergeTree`, so with the default `query_plan_top_k_through_join = 1` a `Merge` table with `FINAL` behind a `LEFT JOIN` still got an inner `Sort + Limit` although the second pass can now read its children in reverse order through the join.

- `ReadFromMerge::canReadInReverseOrder` holds the check of the children that `requestReadingInOrder` did inline.
- `getInputOrderIfReadInOrderIsUseful` gets an overload for `ReadFromMerge` that matches every selected child table the same way the second pass does (`buildInputOrderFromSortDescription` for `Merge`).
- `topKThroughJoin` probes a `ReadFromMerge` on the preserved side with them and defers exactly when the second pass would accept the request; with parallel replicas the `Merge` read is expanded later, so the explicit `Sort + Limit` is kept there.

`05193_top_k_through_join_final_reverse_order` now expects no inner sort for the `Merge` table with `topKThroughJoin` enabled.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated to 6d86c6f0:

  • Merged master (3972 commits behind; clean merge). This pulls in Revert "Revert "Proper partition pruning with dates"" #119302, the fix for the only red job: test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch in Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) failed with the logical error key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0 in Iceberg partition pruning, which is unrelated to this change and was fixed there on 2026-09-17.
  • Addressed the AI review's Major (95d48ccc): topKThroughJoin now defers to reading in order through a Merge table on the preserved side of the join. It probes the ReadFromMerge the same way the second pass does (new ReadFromMerge::canReadInReverseOrder and a ReadFromMerge overload of getInputOrderIfReadInOrderIsUseful), so with the default query_plan_top_k_through_join = 1 the Merge ... FINAL LEFT JOIN ... ORDER BY ... LIMIT shape reads the children in reverse order through the join without an inner Sort + Limit. 05193 now pins that plan (plan_merge_topk_on is 1 1) and the setting-off case still injects the sort.
  • Fixed a stale reference to the renumbered test in a comment of 04234 (6d86c6f0).

ninja clickhouse builds; 05192, 05193, 04234, 04506_read_in_reverse_order_final and 02564_read_in_order_final_desc pass locally, and a sweep of 124 top_k_through_join / read_in_order / storage_merge tests has 101 passes and 23 environment-only failures (missing test clusters, test.hits, Keeper), with no result diff.

alexey-milovidov and others added 3 commits September 24, 2026 01:38
…Useful` in `WhatIfProjectionEstimator`

A new caller of `wouldReadInOrderBeUseful`, which this PR renamed, came from master.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…allel replicas may expand it

The probe was skipped whenever the session could use parallel replicas, but only the plan-based
parallel replicas expand a `Merge` read, and only when `parallel_replicas_allow_merge_tables = 1`
and the read is not `FINAL`. In the other cases the second pass still sees the `ReadFromMerge`, so
`topKThroughJoin` now defers there as well (`ReadFromMerge::mayBeExpandedForParallelReplicas`).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Updated to 1ae98d7c:

  • Merged master (3572 commits behind, no textual conflicts). One semantic conflict: master added a new caller of wouldReadInOrderBeUseful in WhatIfProjectionEstimator.cpp, which this PR renamed to getInputOrderIfReadInOrderIsUseful; fixed in a separate commit.
  • Addressed the AI review's Major (parallel-replicas gate on the Merge deferral in topKThroughJoin): the probe is now skipped only when the plan-based parallel replicas may actually expand the Merge read (new ReadFromMerge::mayBeExpandedForParallelReplicas: parallel_replicas_plan_based, parallel_replicas_allow_merge_tables, not FINAL). 05193 covers FINAL with plan-based parallel replicas, parallel_replicas_allow_merge_tables = 0, and the classic parallel replicas.
  • The previous red job (Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel): 03174_exact_rows_before_aggregation, 03262_filter_push_down_view, 01414_push_predicate_when_contains_with_clause) is unrelated: the same three tests failed on 122 PRs and on master until 2026-09-19 and have not failed since, so the merge pulls the fix in.
  • Local: ninja clickhouse OK; 05193, 05192, 04506 and the 04207–04234 top_k_through_join tests pass, 05193/05192 also with randomized settings.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good implementation, I like it.

@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
alexey-milovidov and others added 3 commits October 3, 2026 01:49
…-topk

# Conflicts:
#	tests/queries/0_stateless/04234_top_k_through_join_final_desc_gate.sql
…k_through_join_final_reverse_order`

Master made `query_plan_read_in_order` obsolete; the plan optimization is now gated by `optimize_read_in_order` alone, which the test already sets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… real expandability verdict

`ReadFromMerge::mayBeExpandedForParallelReplicas` judged by the settings and `FINAL` alone, but
`expandMergeReadsForParallelReplicas` also requires every child to be a plain `ReadFromMergeTree`
without a set-building root that `mergeTreeReadCanBeShipped` accepts. When it refuses (for example,
non-replicated children with the default `parallel_replicas_for_non_replicated_merge_tree = 0`), the
`ReadFromMerge` stays in the plan and the second pass can read it in order, but `topKThroughJoin`
still injected the avoidable inner `Sort + Limit`.

The gate now asks the same question as `getExpandableReads`, with the same `mergeTreeReadCanBeShipped`
predicate (no longer `static`). The answer is computed by the new uncached `computeExpandableReads`,
because the first pass can run before the child plans get their last pushed-down filters, and the
cached answer that `applyParallelReplicas` relies on must not be pinned by this earlier probe.

`05193` covers the non-shippable case.

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

Copy link
Copy Markdown
Member Author

🕵 Updated to 7971fb63:

  • Merged master. The one conflict was in 04234_top_k_through_join_final_desc_gate, because master made query_plan_read_in_order obsolete (1be319227b1). I kept the PR's optimize_read_in_reverse_order_final = 0 and dropped the obsolete setting. I also dropped it from 05193 (432d2a53).
  • Addressed the AI review's Major (7971fb63): the Merge deferral in topKThroughJoin now uses the real expandability verdict (getExpandableReads with mergeTreeReadCanBeShipped), not a settings-only approximation. The verdict is computed without caching, so the answer that applyParallelReplicas uses later is not fixed by this earlier probe. 05193 covers non-shippable children (non-replicated, parallel_replicas_for_non_replicated_merge_tree = 0), where it now defers to reading in reverse order.
  • CI on the previous commit was green.

Local: ninja clickhouse OK. 05192, 05193, 04234, 04506 and 02564 pass. 05192 and 05193 also pass in 10 runs with randomized settings. In a sweep of 141 read_in_order / top_k_through_join / Merge tests, the only failures were environment problems: the test.hits dataset is missing, and pandas is not installed. Two timeouts during the parallel sweep passed when rerun alone.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (no conflicts; the PR diff is unchanged, and 05192, 05193, 04234, 04506 pass on the merged tree).

The remaining CI failures on the previous commit are unrelated to this change, which only touches the read-in-order optimization of the query plan:

@groeneai, investigate the json_extract_rapidjson performance failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118008&sha=7971fb63558b5da0f8b27e853fc4d649dbcd5925&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix is in progress for this one. What I measured so far: json_extract_rapidjson #4 is the JSONExtractFloat query over a missing key (rapidjson-5), and the slowdown is a property of the binary, not of the runner. Locally, pinned to one CPU, 3 rounds of 25 runs: 0.177 s with this PR's amd build vs 0.138 s with the reference master build (892f06d) and with another PR's build on the same master base. The read-in-order change is not executed by this query. The same +28-33% hit 9 unrelated PRs today between 05:52 and 13:11 UTC. I'm now localizing what makes this query sensitive to the binary, and I'll follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #123755. The slow binaries run the same instructions as the fast ones but miss the uop cache about 80x more often, mostly in the per-document allocation and freeing of rapidjson's two parse stacks (14-19% of the query's cycles). The PR serves those stacks from a 2 KB buffer inside the parser, which makes json_extract_rapidjson queries #0..#4 13-18% faster. I could not reproduce the layout flip with --shuffle-sections, so I cannot show that the query is now immune to such flips, only that the code where the misses landed is off its hot path.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (392eaf5e, no conflicts, PR diff unchanged). ninja clickhouse builds. 05192, 05193, 04234, 04506 and 02564_read_in_order_final_desc pass locally. 05192 and 05193 also passed 5 runs each with randomized settings.

@groeneai, thanks for tracking the json_extract_rapidjson slowdown down to #123755.

The failures on the previous commit a4a320db are unrelated to this change, which only touches the read-in-order optimization of the query plan:

@groeneai, investigate the 05237_with_expression_alias_scope_descendant, 04825_quantile_deterministic_alter_add_modify_column and 04819_dynamic_aggregate_function_state_version failures linked above and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

All three already have a fixing PR:

Build (amd_fuzzers): the fix was #123738 (merged 2026-10-04 01:14 UTC). Master's job is green from its merge commit 80f00c85 on, before 2132b458468 landed.

alexey-milovidov and others added 2 commits October 6, 2026 01:48
…`optimizeReadInOrder` does

`topKThroughJoin` deferred to the second-pass read-in-order when an arbitrary
single-child chain below the join led to a `ReadFromMergeTree` or `ReadFromMerge`.
But `optimizeReadInOrder`'s `findReadingStep` descends only through expressions,
filters, preliminary `DISTINCT`, set-building steps and suitable joins, so for a
preserved side such as `(SELECT DISTINCT k, src FROM t_merge FINAL)` the deferral
fired, the second pass stopped at the final `DistinctStep`, and neither
optimization applied.

Export `findReadingStepForReadInOrder`, a wrapper over `findReadingStep`, and use
it for the deferral probe, so both passes agree on whether the read is reachable.
Add plan and result checks for a `DISTINCT` subquery on the preserved side.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and addressed the AI review in 8af132e: topKThroughJoin now finds the preserved-side read through findReadingStep (the same traversal as optimizeReadInOrder), so it no longer defers for shapes such as a DISTINCT subquery, which pass 2 cannot see through. New checks are in 05193. The top_k_through_join and read-in-order tests pass locally.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118008&sha=392eaf5e8599cfd7c69b1213835c94a7f5a719a3&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 (sum_map #1, +18%) and provide a fix in a separate PR. If the fix is already in progress, link it here. The query is a plain sumMap aggregation with no ORDER BY, FINAL, Merge table or join, so it does not run any code this PR changes.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

This is the same slowdown as sum_map query 1 on #117136, analyzed in #117136 (comment). In the CPU profiles of query 1 from this job (0.166 s to 0.197 s), Field::operator< called from AggregateFunctionMapBase::add goes from 248 to 318 samples, while the rest of the query goes from 217 to 231.

The fix in progress is #107554, which replaces this Field-based path with typed aggregation. The smaller change I offered in that comment applies here too.

alexey-milovidov and others added 2 commits October 6, 2026 21:07
…ughJoin` probe

`topKThroughJoin` looks for the preserved-side read and probes a `ReadFromMerge` in the
first optimization pass. Both create the child plans (`filterTablesAndCreateChildrenPlans`),
and they are created only once, before the second pass applies the filters to the read
(`applyFilters`). So `getSelectedTables` could not use a filter on `_database` or `_table`,
and the children read tables which the filter excludes.

Drop the child plans which the probe created, so that they are created again when needed.
Child plans that already existed are kept: under `make_distributed_plan`, the children carry
their own verdict on distribution, which recreating them would lose.

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

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

I opened #124340, the smaller change offered above: integer keys are compared inline in the sumMap/minMap/maxMap map, so the sum_map queries no longer call Field::operator< (0.43x to 0.53x of master time locally, same results and state bytes).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit a6f7ca3 Oct 7, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the reverse-final-merge-topk branch October 7, 2026 09:42
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-performance Pull request with some performance 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.

Extend reading in reverse order with FINAL to Merge tables and topK through JOIN

3 participants