Skip to content

TopN dynamic filtering for the Memory engine - #123787

Merged
alexey-milovidov merged 8 commits into
masterfrom
memory-topk-filter
Oct 7, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
memory-topk-filter

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

TopN dynamic filtering (use_top_k_dynamic_filtering) for the Memory engine.

ReadFromMemoryStorageStep implements supportsTopKDynamicFilter and setTopKFilter, the generic interface that tryOptimizeTopK already uses for Parquet files. The source evaluates __topKFilter as the first of its in-source filter steps (before the row policy and the PREWHERE steps). With compress = true, a block where no row is within the running threshold is skipped after only the sort column is decompressed. The other columns are read only for the remaining rows.

The motivation is ClickBench Q24–Q27 (... ORDER BY EventTime LIMIT 10) on the clickhouse-memory entry (ClickHouse/ClickBench#1590). On a local 10M-row subset of hits (Memory SETTINGS compress = true), Q24 SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10 takes 0.318 s → 0.152 s with max_threads = 8, and 0.152 s → 0.107 s with max_threads = 24. The filter only helps once a thread has read its first block and a threshold exists, so the gain grows with the number of blocks per thread. The 100M-row benchmark table has about 1200 blocks.

The source also re-checks that the PREWHERE and the row policy do not depend on the set of rows they see (rowNumberInBlock, rand, ...). optimizePrewhere can move such a condition into PREWHERE after tryOptimizeTopK has checked the plan.

EXPLAIN actions = 1 shows TopN filter column: ... on the ReadFromMemoryStorage step.

Related: ClickHouse/ClickBench#1590

Changelog category (leave one):

  • Performance Improvement

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

Queries with ORDER BY ... LIMIT n over Memory tables use TopN dynamic filtering: rows that cannot get into the result are dropped while reading, before the other columns are read (or decompressed, with compress = true).

🤖 Generated with Claude Code


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

Version info

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

alexey-milovidov and others added 2 commits October 3, 2026 22:58
`ReadFromMemoryStorageStep` now implements `supportsTopKDynamicFilter` and
`setTopKFilter`, so `tryOptimizeTopK` arms it for `ORDER BY ... LIMIT n` like it
does for Parquet files. The source evaluates `__topKFilter` as the first of its
in-source filter steps: for a table with `compress = true`, a block where no row
is within the running threshold is skipped after decompressing only the sort
column, and the other columns are read only for the remaining rows.

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

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d570173]

Summary: ✅


AI Review

Summary

This PR adds source-side TopN dynamic filtering for the Memory engine, so rows that cannot enter the query’s ORDER BY ... LIMIT top-K are dropped before the rest of the columns are read, with extra value for compress = 1. After reading the current diff, the resolved thread, and the surrounding code paths, I did not find any remaining correctness, safety, or rollout issues that look actionable in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit d570173.

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: 34/39 (87.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... labels Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds TopN dynamic filtering only to reads from Memory-engine tables (ReadFromMemoryStorageStep). ClickBench and TPC-H read MergeTree tables, so none of the benchmark queries run the new code. The three flagged ClickBench improvements (Q11 -15.2%, Q30 -15.5%, Q31 -15.0%) are almost the same size, and each lands just below master's normal range. That pattern fits a quieter benchmark run, not an effect of the PR, so all three are downgraded to not sure. No regressions were flagged.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 11 not_sure 191 162 -15.2% <0.0001 The PR only adds TopN filtering to Memory-engine reads, and ClickBench reads a MergeTree table. The -15.2% median sits just below master's normal range.
⚠️ 30 not_sure 233 197 -15.5% <0.0001 This GROUP BY/ORDER BY LIMIT query reads MergeTree, not Memory, so the new source filter never runs. The -15.5% sits at the bottom edge of master's range.
⚠️ 31 not_sure 286 244 -15.0% <0.0001 The query reads MergeTree, so the Memory-engine TopN change is not on its path. The -15.0% matches the shift seen on Q11 and Q30, which points to a quieter run.

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: 0b5fa672-51d4-4fb7-b8d1-72e8d7618988
  • MIRAI run: 0c92e0b8-7287-491f-8009-dfcfe8374b95
  • PR check IDs:
    • clickbench_3504633_1791276946
    • tpch_adapted_1_official_3504645_1791276946
    • tpch_adapted_1_official_3504676_1791276946
    • tpch_adapted_1_official_3504690_1791276946

alexey-milovidov and others added 2 commits October 5, 2026 09:57
…eadFromMemoryStorage`

The materialized CTE is read from a `Memory` table, which now supports TopN dynamic filtering, so `EXPLAIN` shows `TopN filter column` for the `ORDER BY c DESC LIMIT 1` branch.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123787&sha=latest&name_0=PR&name_1=Fast%20test
PR: #123787

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

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d570173b9 with master b5446bfff (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 59c4d18fa; 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.

Compile time of recompiled translation units

10 translation units recompiled, 48 s compile time in total, 10 of them have a recent master baseline.

Job report

alexey-milovidov and others added 4 commits October 6, 2026 06:53
…th a `DEFAULT` expression

Blocks written before `ALTER TABLE ... ADD COLUMN` expose the default of the type
inside the source, while the query sees the `DEFAULT` expression evaluated above it,
so the threshold filter could drop rows that belong to the top-K. Gate such columns
the same way as `StorageMemory::supportedPrewhereColumns`.

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

@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.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit c20a83f Oct 7, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the memory-topk-filter 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-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... 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.

2 participants