Skip to content

Fix wrong ORDER BY ... LIMIT results on Delta Lake tables with column mapping - #130793

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-delta-lake-top-k-column-mapping
Nov 12, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-delta-lake-top-k-column-mapping

Conversation

@groeneai

@groeneai groeneai commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124545
Related: #122109

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 on a Delta Lake table with column mapping when a renamed column has the name that another column is stored under: the top-K dynamic filter (use_top_k_dynamic_filtering) compared the other column against the threshold and dropped rows of the true result.

Description

On 26.10.2.103, SELECT k, k_old FROM deltaLakeLocal(...) ORDER BY k DESC LIMIT 3 SETTINGS max_threads = 1, max_parsing_threads = 1 on a column-mapped table that stores k_old as k and k as v returns 10901, 10900, 10899 instead of 99999, 99998, 99997 (correct with use_top_k_dynamic_filtering = 0).

ReadFromObjectStorageStep::supportsTopKDynamicFilter looked the logical sort column name up in ReadFromFormatInfo::format_header, which DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat fills with physical names. When the logical name k is the physical name of another read column, the lookup finds that column, the filter is armed, and the Parquet reader filters rows and skips row groups by the other column's values. The per-file guard in StorageObjectStorageSource declines only files with a schema transform, which Delta sets only for partitioned tables.

Delta's prepareReadingFromFormat now records the columns it reads under other names in ReadFromFormatInfo::columns_read_under_other_names (from the same snapshot that produced format_header), and supportsTopKDynamicFilter declines the filter for them. Before, the lookup for such a column either missed (TopN off) or found another column (this bug), so no correct pruning is lost; a column stored under its own name keeps TopN. Other storages leave the set empty.

The WHERE pushdown on the same tables has a separate, pre-existing issue (#117666), not changed here.

Test 05620_delta_lake_top_k_dynamic_filtering_column_mapping fails 20/20 on master with randomized settings and passes 50/50 with the fix; a positive control checks that a column stored under its own name still reads fewer rows.


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

Version info

  • Merged into: 26.11.1.2027-master (included in 26.11 and later)

… mapping

`ReadFromObjectStorageStep::supportsTopKDynamicFilter` looked the logical
sort column name up in `ReadFromFormatInfo::format_header`, which
`DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat` fills with physical
names. With column mapping, a renamed column's logical name can be the
physical name of another read column (`k_old` stored as `k`, `k` stored as
`v`), so the lookup found that other column, the TopN filter was armed with
the logical name, and the Parquet reader filtered rows and skipped row groups
by the other column's values. The per-file guard in
`StorageObjectStorageSource` declines only files with a schema transform,
which Delta sets only for partitioned tables.

Delta's `prepareReadingFromFormat` now records the columns it reads under
other names in `ReadFromFormatInfo::columns_read_under_other_names`, from the
same snapshot that produced `format_header`, and `supportsTopKDynamicFilter`
declines the filter for them. For such a column the old lookup either missed
(TopN already off) or found another column (this bug), so no correct pruning
is lost; columns stored under their own name keep TopN. Other storages leave
the set empty. `updateFormatPrewhereInfo` carries the field over.

Closes ClickHouse#124545

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 (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test does not cover the copy of the new set in updateFormatPrewhereInfo (a PREWHERE query) DISAGREE A Delta Lake read never has a PREWHERE: DataLakeConfiguration::supportsPrewhere() is true only for Iceberg, so an explicit PREWHERE fails with ILLEGAL_PREWHERE and optimizePrewhere never moves WHERE. For every other storage the set is empty. The copy only keeps the rebuilt struct from dropping the field.
2 💡 ReadFromFormatInfo::serialize does not carry the new set DISAGREE No in-tree caller; TopN is never armed for a distributed plan (optimizeTopK.cpp, make_distributed_plan).
3 💡 WHERE pushdown has the same name aliasing DISAGREE (out of scope) Separate issue #117666, another consumer; mentioned in the description.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One Parquet file (10 row groups), Delta log with column mapping k_old -> k, k -> v, max_threads = 1, max_parsing_threads = 1: ORDER BY k DESC LIMIT 3 returns 10901, 10900, 10899 on master and on 26.10.2.103. The new test fails 20/20 on master with randomized settings.
b Root cause explained? supportsTopKDynamicFilter looks the logical sort name up in format_header, which Delta fills with physical names; the logical k matches the physical k of k_old, so the Parquet reader filters rows and row groups by k_old. Non-partitioned Delta files have no schema transform, so the per-file guard does not decline.
c Fix matches root cause? Yes. Delta's prepareReadingFromFormat records which columns it reads under other names (same snapshot as format_header), and the step declines TopN for them. No setting pinned, no test weakened.
d Test intent preserved / new tests added? New test 05620_delta_lake_top_k_dynamic_filtering_column_mapping: TopN ON vs OFF on the renamed column, plus a positive control that a column stored under its own name still reads fewer rows.
e Both directions demonstrated? Master: 20/20 FAIL. Fix: 50/50 OK with randomized settings. Same A/B on a direct probe (master 10901..., fix 99999...), Build-IDs differ.
f Fix is general across code paths? Only Delta overrides prepareReadingFromFormat; File, URL, Memory, Iceberg, Hudi and Paimon keep logical names in format_header (set stays empty). Partitioned Delta tables were already declined per file. The WHERE pushdown sibling is #117666, separate and pre-existing.
g Fix generalizes across inputs (params/datatypes/wrappers)? The decline is by name, so type-independent; a Nullable(Int64) variant behaves the same. SELECT * is fixed; a non-renamed sort column keeps TopN, also when read together with a renamed one.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; only a TopN filter that compared the wrong column is no longer armed.
i Invariants and contracts preserved? TopN is armed only when FormatTopKFilterInfo::column_name names the sort column itself in the format's output. updateFormatPrewhereInfo carries the new field; the lazy-materialization info never gets TopN.

Session id: cron:clickhouse-impl-slot-7:20261111-121200

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [37149c2]

Summary: ✅


AI Review

Summary

The PR prevents incorrect ORDER BY ... LIMIT results on column-mapped Delta Lake tables by declining Top-K dynamic filtering when the sort column's logical and physical names differ. Columns stored under their own names retain the optimization. No actionable findings in commit 37149c2da5b7591508d57ca2ac53c9adf0c883b0.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build was available to rerun the regression test. The PR includes a focused regression and positive control, and the author reports 20/20 failures before the fix and 50/50 passes afterward. Functional and bugfix validation remain pending in the latest CI report; completion would provide independent runtime confirmation.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 37149c2da with master 46bd37447 (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.69 (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.8 s 14.9 s +11.0 s (+280%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.7 s +5.4 s (+237%)
Compile time of recompiled translation units

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

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 12, 2026
Merged via the queue into ClickHouse:master with commit e93f4a4 Nov 12, 2026
597 of 601 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
qoega pushed a commit to qoega/ClickHouse that referenced this pull request Nov 12, 2026
…ames

`DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat` renamed the requested columns to their physical names in
place, while iterating over the same `ColumnsDescription`. Under column mapping the physical name of a column can be
the logical name of another one: after `k` is renamed to `k_old` and `v` to `k`, `k_old` is stored as `k`. When `k_old`
comes first, `ColumnsDescription::rename` to the existing `k` makes `modify_key` erase `k_old`, and the loop reads the
freed node. Build a new description with the physical names instead.

Found by the AST fuzzer in the stress test of ClickHouse#120906:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120906&sha=4b935993be52f957f83759b7ea8fa1a133ae82c5&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

Caused by: ClickHouse#130793

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Nov 20, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 127836 124816 Revert "Avoid building stream names and substreams cache keys for every block in MergeTreeReaderWide"
Changelog-revert: 128706 116083 Revert "Fit the insert pipeline and merges into a small server's memory"
Changelog-revert: 128760 128658 Revert "Prewarm macOS code signature verification of the clickhouse binary after linking"
Changelog-revert: 128947 127422 Revert "[GPU] `GDeflate` compression codec on the CPU"
Changelog-revert: 129099 128947 Revert "Revert "[GPU] `GDeflate` compression codec on the CPU""
Changelog-revert: 129310 127149 Revert "Mark a query as cancelled in the process list when its TCP client cancels it"
Changelog-revert: 129311 129310 Revert "Revert "Mark a query as cancelled in the process list when its TCP client cancels it""
Changelog-revert: 129862 129425 Revert "Add 7 tests for coverage gaps in 5 components"
Changelog-revert: 129863 129862 Fix `GLOBAL IN` in projection `WHERE` with parallel replicas; restore coverage tests
Changelog-revert: 129986 122871 Revert "Search long integer slices in 512-byte chunks on AArch64 in `hasAll` and `hasAny`"
Changelog-revert: 130046 129986 Revert "Revert "Search long integer slices in 512-byte chunks on AArch64 in `hasAll` and `hasAny`""
Changelog-revert: 130368 114729 Revert "CI: run the full test suite only when review threads are resolved"
Changelog-revert: 130509 130368 Revert "Revert "CI: run the full test suite only when review threads are resolved""
Changelog-revert: 130531 114923 Revert "Make a table read by a scalar subquery in a CONSTRAINT a loading dependency"
Changelog-revert: 131043 129464 Revert "Sync shared files changed by the private `AmberMap` PR"
Changelog-revert: 131045 130793 Revert "Fix wrong ORDER BY ... LIMIT results on Delta Lake tables with column mapping"
Changelog-revert: 131270 128764 Re-enable the adaptive aggregator for queries generated from PromQL
Changelog-revert: 131424 122826 Revert "Forbid renaming the source of incremental refreshable views"
Changelog-revert: 131562 131454 Revert "Build the symbol index in the background at server startup"
Changelog-revert: 131638 131562 Revert "Revert "Build the symbol index in the background at server startup""
Changelog-revert: 131691 130864 Revert "Use one source instead of N for parallel_inserts of AzureQueue/S3Queue"
Changelog-revert: 131765 119685 Revert "Enable `-mbranch-protection=pac-ret` on ARM"
Changelog-deleted-entry: 116083 [Performance Improvement] [section] * Reduce memory use for `INSERT` and background merges on servers with a few GiB of RAM. Write buffers, insert squashing, the `Parquet` reader and merge selection now scale with `max_server_memory_usage`, avoiding `MEMORY_LIMIT_EXCEEDED` during wide-table inserts and merges that repeatedly fail without reducing the part count. New `MergeTree` settings `max_memory_ratio_to_activate_adaptive_write_buffer` and `merge_memory_estimate_per_source_part_column` control adaptive write buffers and merge selection, respectively; set either to `0` to disable that adjustment. [#116083](#116083) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 119685 [Build/Testing/Packaging Improvement] [raw] * Build the `C` and `C++` code of the ARM binaries with `-mbranch-protection=pac-ret`, which signs the return address so that overwriting it on the stack cannot redirect control flow; the AArch64 `.S` sources that key off `__ARM_FEATURE_PAC_DEFAULT` opt into the same signing. Sanitizer builds are excluded, because the sanitizer runtimes do not strip the signature when they unwind. [#119685](#119685) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 122826 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Forbid renaming the source of incremental refreshable views closes #[#120082](#120082). [#122826](#122826) ([Smita Kulkarni](https://github.com/SmitaRKulkarni)).
Changelog-deleted-entry: 128658 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Prewarm macOS code signature verification of the clickhouse binary after linking. [#128658](#128658) ([Azat Khuzhin](https://github.com/azat)).
Changelog-deleted-entry: 128764 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Disable the adaptive aggregator for queries generated from PromQL. [#128764](#128764) ([Vitaly Baranov](https://github.com/vitlibar)).
Changelog-deleted-entry: 129464 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Sync shared files changed by the private `AmberMap` PR. [#129464](#129464) ([Miсhael Stetsyuk](https://github.com/mstetsyuk)).
Changelog-deleted-entry: 130793 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed wrong results of `ORDER BY ... LIMIT` on a Delta Lake table with column mapping when a renamed column has the name that another column is stored under: the top-K dynamic filter (`use_top_k_dynamic_filtering`) compared the other column against the threshold and dropped rows of the true result. [#130793](#130793) ([Groene AI](https://github.com/groeneai)).
Changelog-deleted-entry: 130864 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Use one source instead of N for parallel_inserts of AzureQueue/S3Queue. [#130864](#130864) ([Azat Khuzhin](https://github.com/azat)).
@clickhouse-gh clickhouse-gh Bot added comp-delta-lake Delta Lake tables: reading Delta metadata through delta-kernel-rs (table snapshots, schema and ty... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
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-delta-lake Delta Lake tables: reading Delta metadata through delta-kernel-rs (table snapshots, schema and ty... pr-bugfix Pull request with bugfix, not backported by default 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.

Wrong ORDER BY ... LIMIT results on column-mapped Delta Lake tables

3 participants