Skip to content

Fix the TopK query condition cache key collision of c UInt8 and cU Int8, and build the File TopK key with SipHash - #127688

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:topk-plan-hash-length-prefix
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:topk-plan-hash-length-prefix

Conversation

@groeneai

@groeneai groeneai commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results of ORDER BY ... LIMIT and GROUP BY ... LIMIT queries with the query condition cache for TopK (use_query_condition_cache_for_top_k): when the name and type of one key column ran into the same string as those of another, for example c UInt8 and cU Int8, the query could reuse the cache entries of the other column and skip rows of its result.

Description

Follow-up to #122127 (comment) and #127745 (comment).

On 26.10.2.103-stable, with default cache and TopK settings, SELECT c FROM t ORDER BY c DESC LIMIT 3 after SELECT cU FROM t ORDER BY cU DESC LIMIT 3 returns 1, 1, 1 instead of 200, 200, 200: on a File(Parquet) table, and on MergeTree with a WHERE that stays out of PREWHERE. topKPlanHash, the TopK part of these keys, hashed the column name and type name without their lengths, so both gave the bytes cUInt8. The salt of GROUP BY ... LIMIT had the same defect: GROUP BY c ORDER BY c DESC LIMIT 2 returns [1] instead of [200, 199] when the WHERE stays a separate filter. 26.9.25.15 returns the right rows.

Changes:

  • topKPlanHash prefixes the column name, the type name and the collation locale with their lengths. The File, data lake and MergeTree TopK keys all take this hash.
  • The GROUP BY ... LIMIT salt (optimizeGroupByTopK.cpp) prefixes its column names and type names the same way.
  • ReadFromFile::makeTopKQueryConditionCacheKey builds the key with one SipHash, like ReadFromObjectStorageStep, instead of four boost::hash_combine, including the hive partition columns from Cover hive partition columns in the TopK query condition cache key of file #127745. The file list is prefixed with its count.
  • The two queryConditionCacheSettingsSalt(s) ^ fileFormatPruningSettingsSalt(s) become one SipHash in queryConditionCacheHashForFiles.

The MergeTree TopK salts still use boost::hash_combine (8 calls in 5 files that must nest alike on write and read); left as is.

Validation: the new test fails on master in 80 of 80 randomized runs (its GROUP BY arm in 10 of 10 without that fix) and passes with the fix in 50 of 50; reverting only the topKPlanHash change makes it fail again. The test of #127745 passes, and fails when the hive columns are left out of the key. The query condition cache and TopK stateless tests pass.


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

… TopK key

`topKPlanHash` salts every TopK query condition cache key: the File key,
the data lake key (`FormatTopKFilterInfo::plan_hash`) and the MergeTree
TopK salts (`TopKFilterInfo::condition_hash`). It fed the sort column name
and the type name to SipHash back to back, without their lengths, so
`c UInt8` and `cU Int8` were the same bytes ("cUInt8"). The two TopK plans
then shared one cache key, and `ORDER BY c DESC LIMIT 3` reused the "no row
of the result here" entries that `ORDER BY cU DESC LIMIT 3` had recorded
against its own threshold, skipping the row group / granule with the top
values of `c`. Measured on a `File(Parquet)` table, and on MergeTree with a
WHERE kept as a separate filter (its entries are keyed by the WHERE hash
and the TopK plan hash). Prefix the name, the type name and the collation
locale with their lengths, as `getTableIdForFileEntries` does.

The weak combinations asked about in ClickHouse#122127 are replaced as well, though
they were not a practical collision (their inputs are SipHash values, and
the Boost 1.90 `hash_combine` mixer is a bijection):
- `ReadFromFile::makeTopKQueryConditionCacheKey` builds the key with one
  SipHash over the condition hash, the plan hash, the files and the table
  name, like `ReadFromObjectStorageStep::makeTopKQueryConditionCacheKey`,
  instead of three `boost::hash_combine`.
- `queryConditionCacheSettingsSalt(s) ^ fileFormatPruningSettingsSalt(s)`
  (in `FormatFilterInfo::computeConditionHash` and in the no-filter branch
  of the File TopK key) becomes one SipHash, `queryConditionCacheHashForFiles`.

The MergeTree TopK salts keep `boost::hash_combine`: their writers and
readers in five files must nest it identically.

Iceberg and Delta Lake tables cannot hit the collision: none of their type
names ends with another one. 26.9.25.15 does not show it on MergeTree; the
File TopK cache (ClickHouse#122064) is in the 26.10 branch.

Related: ClickHouse#122127 (comment)

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test only checks results, so it would also pass if the TopK cache declined (05454_...sh) DISAGREE Fails on master 80/80 and with only the topKPlanHash change reverted 10/10, so the cache path is engaged; same result-only shape as 05427_...sh.
2 💡 The no-filter branch of ReadFromObjectStorageStep::makeTopKQueryConditionCacheKey does not include fileFormatPruningSettingsSalt, unlike its filter branch and the File key DISAGREE (out of scope) Key completeness, not hash strength, in other code; left as is.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261024-054400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: the new test fails on master in 80 of 80 randomized runs, both arms in each run.
b Root cause explained? topKPlanHash hashed the column name and type name without lengths, so c UInt8 and cU Int8 gave one TopK plan hash and one cache key, and the second query reused the first one's entries.
c Fix matches root cause? Yes: the hash itself prefixes its strings with their lengths; it feeds all TopK keys.
d Test intent preserved / new tests added? New test 05454_query_condition_cache_top_k_plan_hash_collision (File and MergeTree arms); no existing test changed.
e Both directions demonstrated? Master fails, fix passes 50/50 (100/100 with -j 16); reverting only the hash change fails again; renaming cU to cV passes on master.
f Fix is general across code paths? Yes: the File, data lake and MergeTree keys all take the hash from topKPlanHash.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: type wrappers are part of the type name; the collation locale is prefixed too.
h Backward compatible? (maintainer-approved exception only) Yes: the cache is in memory only; no setting, format or persisted value changes.
i Invariants and contracts preserved? Yes: every writer and reader of these keys goes through the changed functions; the cache-hit tests pass.

Session id: cron:clickhouse-impl-slot-4:20261024-032500

@clickhouse-gh

clickhouse-gh Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2a4f284]

Summary: ✅


AI Review

Summary

The PR fixes deterministic TopK query condition cache collisions by length-prefixing column names, type names, and collation locales, and builds the File TopK key with a single SipHash. The current diff and surrounding cache readers and writers show no actionable findings. The regression covers File, MergeTree, and GROUP BY and passed 27 targeted ASan/UBSan runs plus bugfix validation at 03c1778656f07fb019ac8f91ede07b08a8651f4a.

Missing context / blind spots
  • ⚠️ At review time, stateless tests and bugfix validation for current head 2a4f2848f95e220c5a41d0cf26c88cc1d0025a5b were pending. Their completion will confirm validation after the latest merge. No local build or server was available to rerun the regression.
Final Verdict

✅ Approve. No changes requested; current-head CI remains pending.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai, could you review this and add the can be tested label so CI runs? topKPlanHash hashed the sort column name and its type name without their lengths, so ORDER BY c (UInt8) and ORDER BY cU (Int8) shared one TopK query condition cache key and the second query returned wrong rows; the hash now length-prefixes them, and the File TopK key is one SipHash.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 24, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 65d2bda

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): the master this head was tested on says use_query_condition_cache_for_time_conditions became true in 26.10, while the 26.10 release ships false (same 1 / 0 row on many other PRs today). The fix is absent from the tested merge commit #127687 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #127687 (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head, apart from the Config Workflow / Pre Hooks rows of the earlier attempts, which only reported the missing can be tested label.

Session id: cron:our-pr-ci-monitor:20261025-140005

groeneai and others added 2 commits October 30, 2026 08:30
…o the File TopK SipHash

Resolves the conflict with ClickHouse#127745, which added the hive partition columns
to the File TopK query condition cache key as a fourth `boost::hash_combine`
of a separate SipHash. They now go into the same single SipHash as the rest
of the key (name and type name, each length-prefixed), so the key has no
`boost::hash_combine` left.

The file list is now followed by more variable-length fields in that one
stream, so it is prefixed with its count to keep the encoding unambiguous.

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

`tryAttachDynamicFilter` in `optimizeGroupByTopK.cpp` streamed the first ranked
key and every grouping key as name and type name without their lengths, so
`GROUP BY c` (`UInt8`) and `GROUP BY cU` (`Int8`) produced the same salt. With
the `WHERE` kept as a separate filter, its query condition cache entry is keyed
by the plain predicate and this salt only, so `GROUP BY c ORDER BY c DESC
LIMIT 2` after the same query by `cU` reused the granules emptied by the `cU`
boundary and returned `[1]` instead of `[200, 199]` (measured on master and on
26.10.2.103-stable with the cache and TopK settings at their defaults).

Same fix as `topKPlanHash`; the test gets a `GROUP BY` arm.

Found by the second-model review of the ClickHouse#127745 conflict resolution.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Oct 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2a4f2848f with master c4830992f (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.67, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.9 s 12.1 s +8.1 s (+204%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.6 s +5.3 s (+230%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +87.0 s (+6%) in total before that adjustment.

Job report

Conflict in src/Formats/FormatFilterInfo.cpp only: master changed the
parameter of ColumnMapper::setStorageColumnEncoding to ColumnNameToFieldId
next to the new queryConditionCacheHashForFiles; both kept.

ReadFromFile::makeTopKQueryConditionCacheKey merged cleanly and still builds
the key with one SipHash (hive partition columns, paths.size(), no
boost::hash_combine). The object-storage TopK key that master added since
the last merge already takes top_k_filter->plan_hash, so it gets the
length-prefixed topKPlanHash as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants