Skip to content

Fix skip index, sorting key and partition key computed from the wrong column for a subcolumn name two columns share - #127527

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/key-and-index-subcolumn-registered-owner
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/key-and-index-subcolumn-registered-owner

Conversation

@groeneai

@groeneai groeneai commented Oct 23, 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 skip indexes, sorting keys and partition keys over a subcolumn whose name another column also claims (for example j.m.keys: the keys of a Map column `j.m` and the path m.keys of a JSON column j). Inserts, merges and mutations computed them from the other column, so merges failed with Unexpected return type from materialize, inserts were rejected, or queries using the index or key returned wrong results. Also fixed vertical merges that failed with Not found column or subcolumn when the partition key used a subcolumn, or a key or index used a JSON path whose name starts with another column's name.

Description

On 26.8.18.2, a table with `j.m` Map(String, String), j JSON(`m.keys` Array(LowCardinality(String))) and INDEX i j.m.keys TYPE bloom_filter returns 0 instead of 200 rows for WHERE has(j.m.keys, 'a'), and OPTIMIZE fails with Unexpected return type from materialize (a debug abort). Found by the AST fuzzer on #127482 (not caused by it): report.

Key and index expressions are typed against the table's ColumnsDescription, which registers such a name under one column, and queries read it from that column. The MergeTree write path instead took the first block column whose name is a prefix and which has the remainder as a subcolumn, so it used j's path.

Now a registered subcolumn is taken only from the column it is registered under when computing the sorting key, skip indexes, the partition key and its min-max index on insert, merge, mutation and TTL GROUP BY re-sorting; merges and mutations read that column. Unregistered names keep the old resolution, except in vertical merges (below).

In parts written before the fix, a merge or MATERIALIZE INDEX rebuilds skip indexes but not the sort order or partition; such tables need their data reinserted (INSERT INTO new SELECT * FROM old).

Vertical merges now also read the owner of a subcolumn partition key when they can remove rows, and take a JSON path in a key or index from the column whose type has it. This fixes Not found column or subcolumn for PARTITION BY t.a, PARTITION BY j.p.:Int64 and j.m.p.:Int64 beside a j UInt8 column.

The test fails on master and passes with the fix; builds that revert the insert min-max, mutation, merge min-max or TTL GROUP BY sites each fail their arm. 50 randomized runs and 122 related subcolumn/JSON key and index tests pass.


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

groeneai and others added 2 commits October 23, 2026 00:36
…d under

Sorting key, skip index and partition key expressions are typed against the
table's columns description, where a subcolumn name claimed by two columns
(the keys of Map `j.m` and the typed or dynamic path `m.keys` of JSON `j` are
both `j.m.keys`) belongs to the column it is registered under, and queries
read it from that column. The MergeTree write path materialized such an input
from the block by a shortest-prefix walk instead, so it took `j`'s path:

- a merge wrapped the result in `materialize` and aborted with
  `Unexpected return type from materialize. Expected Array(String). Got
  Array(LowCardinality(String))` (AST fuzzer, STID 1611-37da);
- an insert, mutation or `TTL GROUP BY` failed (`Unexpected type Dynamic of
  bloom filter index`, `Bad cast from type DB::ColumnDynamic to
  DB::ColumnArray`, `Sort order of blocks violated`) or, with equal types,
  silently built the index, primary key, partition and its min-max index from
  the other column, so queries using them returned wrong results.

Now a subcolumn that the columns description registers is taken from the
column it is registered under (and only from it) when computing the sorting
key, skip indexes and the partition key and its min-max index on insert,
merge, mutation and `TTL GROUP BY` re-sorting, and the merge and the mutation
place that column among the ones they read. Names the description does not
register keep the previous resolution.

Placing the owner of a min-max index input in a row-reducing merge also fixes
vertical merges of a ReplacingMergeTree partitioned by any subcolumn
(`PARTITION BY t.a`), which failed with `Not found column or subcolumn t.a in
block` because the subcolumn's column was gathered, not merged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a comment in MutateTask.cpp that restates the lambda below it.

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 review (1 nit).

# Sev Finding Verdict Evidence / action
1 ❌ ALTER UPDATE of j.m on a Wide part keeps a stale index on j.m.keys DISAGREE (out of scope: separate PR) The mutation never selects the index for rebuild (exact-name match in StorageInMemoryMetadata::getColumnDependencies), so nothing is computed from any column. It reproduces the same way for a single-column subcolumn index (t.a, m.keys) with and without this PR. That is #121018, fixed by the open #112717.
2 💡 The text index, projection part and optimize_on_insert pass-throughs have no arm of their own noted, not blocking Same one-argument change as the tested sites; the PR description no longer claims per-site coverage.

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

Session id: cron:clickhouse-review-slot-9:20261023-004500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The CI table (j.m Map, typed JSON j, bloom_filter on j.m.keys), two inserts and OPTIMIZE FINAL abort a debug master build every time with Unexpected return type from materialize. Expected Array(String). Got Array(LowCardinality(String)) at ExpressionActions.cpp:897 from MergeTask.
b Root cause explained? Key and index expressions are typed against ColumnsDescription, which registers j.m.keys under one column, and queries read it from that column. The write path took the first block column whose name is a prefix and which has the remainder as a subcolumn (j + m.keys), so it indexed the other column.
c Fix matches root cause? Yes. The write path resolves a registered subcolumn through the same ColumnsDescription (only from its registered column, no fallback) and merges/mutations read that column. No guard at the throw site.
d Test intent preserved / new tests added? New 05447_key_and_index_subcolumn_registered_by_one_of_two_columns.sql, one arm per changed site: skip index (horizontal and vertical merge, untyped JSON), sorting key, partition key, UPDATE rewrite, old part, TTL GROUP BY, min-max after a row-reducing merge, DELETE, vertical ReplacingMergeTree.
e Both directions demonstrated? Master: every arm fails (abort, rejected insert, or wrong count). Fix: all pass. Two builds that each revert a group of sites fail exactly the arms of the reverted sites.
f Fix is general across code paths? Insert (sorting key, skip indexes, optimize_on_insert, projection parts), partition value and min-max, merge (placement, index step, text index check, sorting key step, min-max), mutation (index step, placement for old parts, min-max) and TTL GROUP BY re-sorting. Projections and TTL expressions keep the query read rule.
g Fix generalizes across inputs (params/datatypes/wrappers)? Typed JSON path of a different type and of the same type, untyped JSON in either column order, Map keys, a Tuple element; wide, compact and packed parts; horizontal and vertical merges; ReplacingMergeTree; UPDATE, DELETE, MATERIALIZE INDEX.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Output changes only for a name two columns claim (and for vertical row-reducing merges with a subcolumn partition key, which failed before). Old parts keep their values until merged.
i Invariants and contracts preserved? When one column claims a name, the registered column is the one the previous resolution found, so results are unchanged. The extracted subcolumn is cast to the registered type (a no-op outside an in-flight MODIFY COLUMN).

Session id: cron:clickhouse-impl-slot-6:20261022-235800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @Algunenano, could you review this and add the can be tested label so CI runs? Key and index expressions are typed and queried through ColumnsDescription, but the MergeTree write path resolved a subcolumn name that two columns register (j.m.keys: Map j.m keys vs the JSON path m.keys of j) by a prefix walk over the block; it now takes a registered subcolumn only from its registered column.

@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a02bb5d]

Summary: ✅


AI Review

Summary

Reviewed #127527 at a02bb5d61cffc9b59b060e76157d36b4b048064d. The change makes MergeTree key and skip-index inputs use the registered subcolumn owner and fixes dynamic partition-key inputs in vertical merges. No actionable findings remain. The earlier migration request is addressed by the revised reinsertion guidance: upgrading parts written by 26.8.18.2 confirmed that ordinary merges cannot repair their sorting or partitioning, while reinserting into new tables repairs both. The regression check for the earlier dynamic-owner finding passes with the PR binary.

Missing context / blind spots
  • ⚠️ The CI run held the full suite, including sanitizer and bugfix-validation jobs, behind the earlier review-thread gate. A full rerun is still needed. The Fast test passed the added 05447_key_and_index_subcolumn_registered_by_one_of_two_columns regression; focused local checks also passed for index ownership, sorting, and dynamic partition keys in vertical merges.
Final Verdict

✅ Approve — no new inline findings; existing resolved threads need no changes.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 23, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 23, 2026
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
A merge that can remove rows recomputes the partition min-max index in the
horizontal stage, so the column a partition key subcolumn comes from must be
merged, not gathered. Only registered subcolumns were resolved to their
column, so a dynamic JSON path such as `PARTITION BY j.p.:Int64` left `j` in
the gathering stage and a vertical ReplacingMergeTree merge failed with
`Not found column or subcolumn j.p.:Int64 in block`. Fall back to the column
the name is a subcolumn of, as the other key columns of the merge do.

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

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a02bb5d61 with master 4eada96ac (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.

Compile time of recompiled translation units

1159 translation units recompiled, 8561 s compile time in total, 1158 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.1 s

Job report

groeneai and others added 2 commits October 23, 2026 23:09
Under the ParallelReplicas configuration the read step is nested inside the
parallel replicas plan, so every EXPLAIN line starts with a `│` tree prefix
that `trim` keeps. Strip it the same way other EXPLAIN-based tests do.

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

The vertical merge places a key, skip index or partition key subcolumn by
the column it comes from. A name that is not a registered subcolumn fell
back to the shortest column-name prefix, whatever its type, so with columns
`j UInt8` and `j.m JSON` the JSON path `j.m.p.:Int64` was attributed to `j`,
`j.m` stayed in the gathering stage, and the merge failed with
`NOT_FOUND_COLUMN_IN_BLOCK`. Resolve it with
`ColumnsDescription::tryGetColumnOrSubcolumn`, which keeps the registered
owner first and then takes the first prefix whose type has that dynamic
subcolumn, the same column the block lookup reads it from.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dex-subcolumn-registered-owner

Resolve conflicts: master moved the partition min-max index to
`MergeTreePartMinMaxIndex` (its `update` takes the registered owner here), and
`splitAndModifyMutationCommands` now resolves index input columns with its own
type-aware `getColumnNameInStorage`, which already takes a registered subcolumn
from its registered owner, so this branch's lambda is dropped in favour of it.

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

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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