Skip to content

Fix std::out_of_range when a space-filling curve is not a key column - #114233

Merged
al13n321 merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-space-filling-curve-not-key-column
Aug 20, 2026
Merged

al13n321 merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-space-filling-curve-not-key-column

Conversation

@groeneai

@groeneai groeneai commented Aug 10, 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):

Fix std::out_of_range: map::at: key not found when a MergeTree key expression contains a mortonEncode or hilbertEncode call that is not itself a key column, for example ORDER BY mortonEncode(hilbertEncode(x, y), x, y) or PARTITION BY mortonEncode(x, y) % 4.

Description

KeyCondition::getAllSpaceFillingCurves walks every action of the key-expression DAG and looks up each curve node in key_columns with at(). key_columns holds only top-level key columns, so a curve nested inside another expression is an intermediate node whose result_name is absent, and the lookup throws out of KeyCondition's constructor.

Such a table accepts CREATE and INSERT, then rejects almost every read. On released 26.7.4.14 with ORDER BY mortonEncode(hilbertEncode(x, y), x, y), SELECT *, SELECT count() WHERE x = 5 and SELECT sum(y) all fail with Code: 1001 and ALTER TABLE ... DELETE with Code: 341; only a bare count() works. Debug and sanitizer builds abort instead. It reproduces on 25.8.30.12 (LTS), 26.6.3.28 and 26.7.4.14, so it is not new.

A curve is only ever consumed through key_column_pos as a key column index, so one that is not a key column cannot participate in curve-aware key analysis at all. Rather than catch the failed lookup, the fix restricts the enumeration to curve nodes that are key columns, using the key_columns.find form already used at the five other lookups here. Line 1386 was the file's only unconditional at() on key_columns.

Three construction sites reach that line and are all fixed: the primary/sorting key, the partition key, and minmax/set skip indexes. Nothing that worked before changes: for ORDER BY mortonEncode(x, y), and for a nested curve that is also a key column, EXPLAIN indexes = 1 is byte-identical before and after, so curve pruning is preserved.

Found by the AST fuzzer on an unrelated PR that does not touch this code: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113022&sha=03db3c42bad3adf593a621b427aa706d7d81e966&name_0=PR&name_1=AST%20fuzzer%20%28amd_tsan%29. No related open issue found.

Not addressed here: INDEX i mortonEncode(x, y) TYPE minmax, where the curve is the index key column, fails Code: 10 NOT_FOUND_COLUMN_IN_BLOCK both before and after. There the lookup succeeds and the failure is downstream, a different defect.

Version info

  • Merged into: 26.8.1.1727 (included in 26.8 and later)
  • Backported to: 26.7.6.30, 26.6.5.71, 26.3.33.22

KeyCondition::getAllSpaceFillingCurves iterates every action of the
key-expression DAG and looked up each curve node in key_columns with at().
key_columns holds only the top-level key columns, so a mortonEncode or
hilbertEncode call that sits in a non-key-column position of the key
expression is an intermediate DAG node whose result_name is absent, and the
lookup threw std::out_of_range out of KeyCondition's constructor.

Such a table accepts CREATE and INSERT, then rejects almost every read with
Code: 1001, and cannot be mutated (Code: 341); debug and sanitizer builds
abort instead. Reproduced on 25.8.30.12 LTS, 26.6.3.28 and 26.7.4.14, so it
is not new. Found by the AST fuzzer on an unrelated carrier PR.

A curve description is only ever consumed through key_column_pos as a key
column index, so a curve that is not a key column cannot participate in
curve-aware key analysis at all. Restrict the enumeration to curve nodes
that are key columns instead of catching the failed lookup. This was the
only unconditional at() on key_columns in the file; the five other lookups
already use find() with an end() check.

Three construction sites reach that line and are all fixed: the primary and
sorting key, the partition key, and minmax/set skip indexes. Nothing that
worked before changes: for a plain curve key, and for a nested curve that is
itself a key column, EXPLAIN indexes = 1 is byte-identical before and after,
so curve pruning is preserved rather than silently downgraded.
…mization tag

The source fix is unchanged. The test gains a fifth arm asserting that curve
pruning still applies to a nested curve that is itself a key column: the three
failure arms assert count() = 11, which an absent curve also returns via the
safe-degradation paths, and the only previous pruning arm used a non-nested key,
so an over-broad membership filter could have disabled curve pruning for the
whole nested-but-valid class with every arm still green.

The no-random-merge-tree-settings tag is replaced by an explicit
index_granularity on the two EXPLAIN-arm tables. The arms assert presence of a
FUNCTION_ARGS_IN_HYPERRECTANGLE element, which randomized granule counts and
physical layout do not affect, so the remaining tables keep exercising
randomized MergeTree settings on the read path this fix touches.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open findings)

An independent model reviewed this change cold against the repository review checklist, twice: once
on the first candidate and again on the revision. Round 2 returned no findings. Verdicts below.

# Sev Finding Verdict
❌ major No test arm could observe an over-broad membership filter. The three failure arms assert count() = 11, which an absent curve still returns via the safe-degradation paths, and the only pruning arm used a non-nested key. A filter that wrongly rejected a nested curve that is a key column would have silently disabled curve pruning for that whole class with every arm green. AGREE, fixed. Added a fifth arm on ORDER BY (hilbertEncode(x, y), mortonEncode(hilbertEncode(x, y), x)) asserting the has args in plan substring, which is emitted only for a matched space-filling curve. It returns 1 with the fix, 0 under analyze_index_with_space_filling_curves = 0 (so it can fail), and 1 on a pristine binary too, since this shape already worked.
⚠️ nit The test carried a blanket no-random-merge-tree-settings tag, which disables all randomized MergeTree settings for a read-path fix. AGREE, fixed. Tag removed; instead index_granularity is pinned in the DDL of only the two plan-asserting tables. A fresh 50-run randomized pass is green, and system.query_log confirms randomization was genuinely live (52 distinct injected CREATE shapes on the unpinned tables) while the pinned tables saw 8192 on 51 of 51 runs.
⚠️ major The description cited the carrier pull request by number, which would post a cross-reference onto an unrelated third party's pull request. AGREE, fixed. The description now links only the CI report.
💡 nit The second clause of the added comment partly restates the continue below it. Not changed. The first clause states the invariant that is not evident from the code, and the block is two comment lines against four code lines.

Also checked and cleared: all four consumers of the curve list degrade safely on a reduced set
(fall-through, 0uz, Unknown, Unknown), so skipping a curve can cost pruning but cannot produce
wrong results; every other key_columns lookup in the file already used find, and line 1386 was
the only unconditional at(); all eight KeyCondition construction sites were enumerated and the
three that reach this line are covered by the three failure arms.

Not addressed, disclosed for completeness: INDEX i mortonEncode(x, y) TYPE minmax, where the curve
is itself the index key column, fails Code: 10 NOT_FOUND_COLUMN_IN_BLOCK both before and after this
change. There the lookup succeeds and the failure is downstream, so it is a separate pre-existing
defect and this change neither helps nor harms it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% not a percentage. CREATE TABLE t (x UInt32, y UInt32) ENGINE=MergeTree ORDER BY mortonEncode(hilbertEncode(x,y),x,y) then SELECT count() FROM t WHERE x>=10 AND x<=256 AND y>=20 AND y<=30: rc=134 (SIGABRT, debug) on master, 11 with the fix. Note the abort writes zero bytes to stderr.
b Root cause explained? Yes. getAllSpaceFillingCurves iterates every action of the key-expression DAG and did key_columns.at(node->result_name) unconditionally, but key_columns holds only top-level key columns. A curve in a non-key-column position is an intermediate DAG node, so the lookup throws std::out_of_range out of KeyCondition's constructor and escapes ReadFromMergeTree::buildIndexes.
c Fix matches root cause? Yes, and it restricts the enumeration rather than catching the throw. key_column_pos is consumed only as a key column index (verified at all four consumers), so a curve that is not a key column cannot participate in curve-aware analysis at all. Corroborating: a nested curve that is also a key column already worked before this change.
d Test intent preserved / new tests added? New stateless SQL test 04860_space_filling_curve_not_a_key_column, 5 arms: one per carrier (sorting key, partition key, skip index) plus two EXPLAIN indexes = 1 pruning-preservation assertions, for a plain curve key and for a nested curve that is itself a key column. No test weakened or removed. Parallel-safe, no no-parallel tag, and no no-random-* tag either: index_granularity is pinned in the DDL of just the two plan-asserting tables, so randomized MergeTree settings still exercise the read path on the other three.
e Both directions demonstrated? Yes. With the fix reverted and rebuilt (Build ID back to the pristine a1cb40f9...), the server itself aborts on the test's first query with signal 6 and the getAllSpaceFillingCurves frame in the log; with the fix (51b6775a...) the test passes, 50/50 randomized runs green.
f Fix is general across code paths? Yes. After the change no unconditional key_columns.at() remains in the file (all seven lookups are find/contains). There is exactly one curve-enumeration site and no sibling copy. All three construction sites that reach it, primary/sorting key, partition key, and minmax/set skip index, were each measured fixed; shared KeyCondition covers MergeTree, ReplicatedMergeTree and SharedMergeTree.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured on the fixed binary: Nullable argument, constant argument, 3-argument outer curve, nested-curve-that-is-also-a-key-column, empty table, single row, and UInt64 max values all return the correct result. Eight distinct aborting key shapes (curve-in-curve, same-curve, 3-level, +1, % 1024, toString, partition key, skip index) all fixed. Type wrappers are not a real dimension: the lookup key is a DAG node result_name string. LowCardinality in the key is rejected at DDL identically before and after, so that is pre-existing validation.
h Backward compatible? Yes. No setting default change, so no SettingsChangesHistory.cpp entry; no new setting, no serialization or format change, no experimental gate. Every previously-succeeding query returns an identical result with a byte-identical EXPLAIN indexes = 1 plan. Rejecting such DDL at CREATE time was considered and rejected as backward-incompatible: these tables exist since 25.8 and hold data.
i Invariants and contracts preserved? Invariant: every entry of key_space_filling_curves describes a curve that is a key column of this key expression. The continue runs before the description is constructed, so no partially-populated entry can be pushed, and the pre-existing guards below it (non-INPUT child clears arguments; 2 == arguments.size()) are untouched. No lock, allocation, or error path is involved.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @hanfei1991, could you review this? KeyCondition::getAllSpaceFillingCurves walked every action of the key-expression DAG and looked each curve node up in key_columns with at(), so a mortonEncode/hilbertEncode call that is an intermediate node rather than a key column threw std::out_of_range out of the constructor and made such tables almost unreadable since 25.8. Since key_column_pos is only ever used as a key column index, the fix restricts the enumeration with find instead of catching the failed lookup.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f43c6db]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb

AI Review

Summary

This PR fixes KeyCondition::getAllSpaceFillingCurves so mortonEncode/hilbertEncode nodes that are only intermediate DAG values are skipped instead of being looked up as top-level key columns. I traced that invariant through the current KeyCondition construction and space-filling-curve consumers, and I did not find a correctness, compatibility, or coverage issue in the current diff.

Final Verdict

✅ No new issues found in the current patch.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.00% +0.00%

Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f43c6dbdf with master e8e5486ca (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
Binary Master PR Δ
programs/clickhouse-stripped 691.01 MiB 688.02 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f43c6db

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
Stress test (amd_tsan) / Hung check failed, possible deadlock found one already-cancelled DROP TABLE prometheus (is_cancelled: 1, elapsed 970 s) never returns from DatabaseCatalog::waitTableFinallyDropped; the DROP DATABASE ... SYNC teardown then convoys behind it on the DDL guard #113397 (external, open), issue #113954

Owner resolved from hung_check.log rather than by test name: the processlist head carries the
DROP TABLE prometheus + waitTableFinallyDropped + getDDLGuard frames that #113397 addresses,
with a negative control confirming no unrelated token matches the same scan.

175 jobs, 0 incomplete, 0 dropped, 155 green, 19 skipped. Config Workflow and Finish Workflow
both succeeded, last completion 2026-08-11T04:18:54Z.

Not caused by this PR: the diff is confined to the space-filling-curve path in KeyCondition, which
no frame in the hung processlist touches.

Session id: cron:our-pr-ci-monitor:20260811-060000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@al13n321 al13n321 self-assigned this Aug 20, 2026
@al13n321
al13n321 enabled auto-merge August 20, 2026 00:44
@al13n321
al13n321 added this pull request to the merge queue Aug 20, 2026
Merged via the queue into ClickHouse:master with commit 8d5be60 Aug 20, 2026
180 of 182 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 Aug 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t (x UInt32, y UInt32) ENGINE = MergeTree ORDER BY x PARTITION BY mortonEncode(x, y) % 4;
INSERT INTO t VALUES (5, 5);
SELECT count() FROM t WHERE x = 5;
-- Code: 1001. DB::Exception: std::out_of_range: map::at: key not found. (STD_EXCEPTION)
-- Same with ORDER BY mortonEncode(hilbertEncode(x, y), x, y). Expected: 1.

▶ Run on ClickHouse Fiddle

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

CC component owner: @CurtizJ @alexey-milovidov

Analysis metadata

comp-mergetree · Severity P2 · Finding phase_d_pr114233

  • Verified against master build 6c8e5b1397b5 (aarch64)
  • Could not test: master
Introducing change: not identified
  • The one boundary found was rejected — PR only updates Docker base images (libssl3t64 CVE fix) and cannot affect ClickHouse query execution logic for space-filling curves in KeyCondition. — a coincidental boundary, not the cause.
  • Walked 6 release(s) below the supported window: still reproduces down to 25.2.
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

@al13n321 could you apply v25.8-must-backport to this PR? That is the only action needed; the robot opens the backport PRs from there.

Why that exact label: the version-specific form marks the oldest release to reach and expands to every newer active branch. Running select_backport_branches from tests/ci/cherry_pick_branches.py against the currently active release branches (the open release PRs: 25.8, 26.3, 26.5, 26.6, 26.7) gives ['25.8', '26.3', '26.5', '26.6', '26.7'], so one label covers all five and no inactive branch is targeted.

Verification I ran, since the earlier triage comment could not check master:

  • Fixed on master. The published master build is 90a20ccf81cd and git merge-base --is-ancestor 8d5be603139a1 90a20ccf81cd returns 0, so the merge is in that binary. Both shapes now return 1.
  • Still broken on all five, on their latest published binaries: 26.7.5.4, 26.6.4.4, 26.5.8.4, 26.3.20.8, 25.8.31.10 all abort Code: 1001 std::out_of_range for PARTITION BY mortonEncode(x, y) % 4 and for ORDER BY mortonEncode(hilbertEncode(x, y), x, y). Each branch still carries the unguarded key_columns.at(action.node->result_name).
  • The port is clean. The net change is 3 files, +50/-1, and git apply --check succeeds against all five branch indexes. I also checked the applied tree on 25.8, 26.3 and 26.7: the guard, the find() lookup and the test all land together, so no half-applied shape. No settings history entry is involved, and test number 04860 is free on every branch.

Only the primary key path is user visible on a bare count(); the partition key and minmax/set skip index carriers hit the same line, so an affected table fails ordinary SELECT and ALTER ... DELETE too.

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @al13n321 — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed real, and pre-existing rather than caused or changed by #114233.

I hit this while working on #114233 and disclosed it in that PR's description as out of scope: for a skip index the key_columns lookup succeeds and the failure is downstream, so the fix does not touch it either way.

Re-verified today on master at 7e1c82b (contains this PR's merge) and on published 26.3.21.8: both mortonEncode(x, y) TYPE minmax with WHERE x = 5 and hilbertEncode(x, y) TYPE set(100) with WHERE y = 5 fail identically on both builds. The root cause matches what I read at trunk; line numbers have moved to KeyCondition.cpp:3114 (the unguarded sample_block.getByName) and :1417 (registration).

One correction to the open risks: the Iceberg site is not reachable. ManifestFilesPruning.cpp:137 builds its expression from ActionsDAG(const NamesAndTypesList &), which only calls addInput, so that DAG holds INPUT nodes exclusively, while getAllSpaceFillingCurves matches ActionType::FUNCTION only. No curve can be registered there.

Not closing #115829, since the finding is not wrong. One note for whoever fixes it: the guard needs to be narrow enough to leave primary-key curve pruning alive. On master today ORDER BY mortonEncode(x, y) with a predicate on x and y still prunes to 1/123 granules, and that path shares the same registration.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 22, 2026
…oss-type-set-exactness-nonnullable

The sole conflict is the accurateCastOrNull target guard in
tryPrepareSetColumnsForIndex. Master's side is taken and this branch's local
setIndexKeyTypeSupportsAccurateCastOrNull is deleted.

Master reached the same fix through ClickHouse#115152 and ClickHouse#114233, which export
canBeAccurateCastOrNullTarget from CastOverloadResolver.h and call it at three
guards. That is what the local helper's own commit message asked for: the
throwing validator and the predicate now share one implementation instead of
mirroring each other by hand, so they cannot drift.

The two forms are not equivalent and master's is narrower. For a Nullable key
type the local helper recursed into the nested type and could proceed, while
master keeps the outer canBeInsideNullable test, which DataTypeNullable does not
override and therefore answers false. Master declines there, exactly as the
pre-fix guard did, so taking master's side removes a widening this branch had
introduced rather than losing coverage.

The five predicates carrying this PR's contract are untouched and still absent
from master.
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #114233 to 26.7: Fix std::out_of_range when a space-filling curve is not a key column
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 8, 2026
Backport #114233 to 26.6: Fix std::out_of_range when a space-filling curve is not a key column
al13n321 added a commit that referenced this pull request Sep 8, 2026
Backport #114233 to 26.3: Fix std::out_of_range when a space-filling curve is not a key column
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 11, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
STOR: mortonEncode/hilbertEncode inside a key expression -> exc std::out_of_range.
Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/114233.PROD263.txt).
Upstream patch unchanged, with its test(s): 04860_space_filling_curve_not_a_key_column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

6 participants