Skip to content

Fix optimize_functions_to_subcolumns rewriting onto the wrong subcolumn - #115777

Merged
Avogar merged 2 commits into
masterfrom
fix-optimize-functions-to-subcolumns-name-collision
Sep 9, 2026
Merged

Avogar merged 2 commits into
masterfrom
fix-optimize-functions-to-subcolumns-name-collision

Conversation

@Avogar

@Avogar Avogar commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Related: #115632
Related: #115394

optimize_functions_to_subcolumns rewrites a function to a subcolumn of its argument
(length(arr) to arr.size0, isNull(n) to n.null, mapKeys(m) to m.keys, ...) and
hardcodes the type that subcolumn has. It only checked that a subcolumn with that name exists,
which is wrong in two independent ways, both giving wrong results.

A Tuple element or a JSON path can claim the name with the same type, and declaration order
decides which one a read returns:

CREATE TABLE t (c Tuple(`a.size` UInt64, `a` String)) ENGINE = Memory;
INSERT INTO t VALUES ((99, 'abc'));

SELECT length(c.a) FROM t SETTINGS optimize_functions_to_subcolumns = 0;  -- 3   correct
SELECT length(c.a) FROM t SETTINGS optimize_functions_to_subcolumns = 1;  -- 99  wrong

The same shape affects empty, notEmpty, isNull, isNotNull, count, mapKeys,
mapValues, mapContains and m['key'].

An enclosing Nullable wraps the subcolumn without changing which substream it is - c.a is a
bare Array while c.a.size0 is Nullable(UInt64), because Array cannot be inside Nullable.
Only length lacked the guard the other rewrites already had:

CREATE TABLE t (c Nullable(JSON(`a` Array(Int64)))) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES ('{"a":[1,2]}'), (NULL);

SELECT length(c.a) FROM t SETTINGS optimize_functions_to_subcolumns = 0;  -- 2, 0   correct
SELECT length(c.a) FROM t SETTINGS optimize_functions_to_subcolumns = 1;  -- 2, \N  wrong

To tell these apart, subcolumn resolution now reports the substreams path identifying the
resolved subcolumn, not just its data (getSubcolumnData becomes getSubcolumnInfo).
Subcolumns resolved from the data get a synthesized path too, so all of them are identifiable
the same way. The optimizer asks the serialization owning the substream whether the resolved
subcolumn is the one the rewrite means, and additionally requires the exact type; neither check
catches the other's case. Subsumes subcolumnIsNullableInStorage and nestedTypeHasNullSubcolumn.

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 from optimize_functions_to_subcolumns. A Tuple element or a JSON path named like an automatic subcolumn claimed it, so for example length(c.a) on Tuple(`a.size` UInt64, `a` String) returned the element instead of the length; empty, notEmpty, isNull, isNotNull, count, mapKeys, mapValues, mapContains and m['key'] were affected the same way. Separately, length on an Array or Map inside a Nullable (for example Nullable(JSON(`a` Array(Int64)))) returned NULL instead of 0 for a NULL row.


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

Version info

  • Merged into: 26.9.1.1084 (included in 26.9 and later)

`optimize_functions_to_subcolumns` rewrites a function to a subcolumn of its
argument (`length(arr)` to `arr.size0`, `isNull(n)` to `n.null`, `mapKeys(m)` to
`m.keys`, ...) and hardcodes the type that subcolumn has. It only checked that a
subcolumn with the constructed name exists, which is wrong in two independent
ways, both giving wrong results:

* Subcolumn names are flat, so a `Tuple` element or a `JSON` path can claim the
  name with the same type. ``Tuple(`a.size` UInt64, `a` String)`` exposes
  `a.size` twice, and declaration order decides which one a read returns, so
  `length(c.a)` returned the element instead of the length of `a`. The same
  shape affects `empty`, `notEmpty`, `isNull`, `isNotNull`, `count`, `mapKeys`,
  `mapValues`, `mapContains` and `m['key']`.
* An enclosing `Nullable` wraps the subcolumn without changing which substream
  it is. ``Nullable(JSON(`a` Array(Int64)))`` exposes `c.a` as a bare `Array`
  but `c.a.size0` as `Nullable(UInt64)`, so `length(c.a)` returned NULL instead
  of 0 for a NULL row. Reachable only because `Array` and `Map` cannot be inside
  `Nullable`.

To tell the cases apart, subcolumn resolution now reports the substreams path
that identifies the resolved subcolumn, not just its data:
`IDataType::getSubcolumnData` and `getDynamicSubcolumnData` become
`getSubcolumnInfo` and `getDynamicSubcolumnInfo` and return a `SubcolumnInfo`
holding both. Subcolumns resolved from the data rather than from the static
enumeration get a synthesized path as well, so every resolved subcolumn is
identifiable the same way: a `Map` key is `MapKeyValue`, a JSON path is
`ObjectTypedPath`/`ObjectDynamicPath`, a `Dynamic` type subcolumn is
`DynamicData` + `VariantElement`, and the JSON subcolumns built from many paths
at once get `ObjectDistinctPaths`/`ObjectSubObject`/`ObjectCombinedPath`.
Resolving through `Array` and `Nullable` contributes `ArrayElements` and
`NullableElements`, so a dynamic resolution produces the same path the static
enumeration would.

The optimizer then asks the serialization that owns the substream whether the
resolved subcolumn is really the one the rewrite means, and additionally
requires the exact type. Neither check catches the other's case. This subsumes
the two one-off guards `subcolumnIsNullableInStorage` and
`nestedTypeHasNullSubcolumn`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20ae2b3]

Summary: ✅


AI Review

Summary

This PR hardens optimize_functions_to_subcolumns by validating the resolved SubstreamPath and type before rewriting, and it adds solid end-to-end regressions for flat-name collisions and outer Nullable wrappers. The remaining blocker is that the new common validation still ignores case-insensitive top-level shadowing for most dotted rewrites, so supported ORC/Parquet/Arrow modes can still return the wrong column.

Findings

❌ Blockers

  • [src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp:199] canOptimizeToExpectedSubcolumn only rechecks exact-case resolution from the declared structure. With input_format_{orc,parquet,arrow}_case_insensitive_column_matching = 1, a top-level column like A.SIZE0 / A.NULL / A.KEYS / V.INT64 still shadows the rewritten a.size0 / a.null / a.keys / v.Int64, but only the tupleElement path currently calls sourceHasColumnCaseInsensitive. That leaves wrong-result rewrites for the automatic .size / .size0 / .null / .keys / .values / key_* optimizations, and for variantElement, whenever the file schema exposes a colliding dotted column that differs only by case.
    Suggested fix: move the sourceHasColumnCaseInsensitive guard into the common dotted-name check (or apply it to every rewrite site, including variantElement) so every synthesized <column>.<subcolumn> is blocked when a case-insensitive top-level match exists.
Final Verdict

Changes requested: the exact-case/path validation looks good, but the case-insensitive shadowing invariant is still only enforced for tupleElement, so the PR still leaves wrong-result rewrites in supported input-format modes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 337/351 (96.01%) · 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 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 20ae2b351 with master 6e4e77ec8 (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 704.50 MiB 701.50 MiB -3.00 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.

Object file sizes

323 object files changed (+105.88 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/DataTypeObject.cpp.o 587.20 KiB 604.66 KiB +17.46 KiB (+2.97%)
src/CMakeFiles/dbms.dir/Analyzer/Passes/FunctionToSubcolumnsPass.cpp.o 349.71 KiB 366.18 KiB +16.46 KiB (+4.71%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

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

Job report

`optimizeTupleOrVariantElement` still only checked that a subcolumn with the
constructed name exists, so a sibling element flattening to the same name won
when it was declared first:

    Tuple(`t.a` UInt64, t Tuple(a UInt64))
      tupleElement(c.t, 'a')        off = 1, on = 99

    Tuple(`t.Int64` UInt64, t Variant(Int64, String))
      variantElement(c.t, 'Int64')  off = 7, on = 99

`tupleElementNameIsAmbiguousWhenFlattened` does not cover this: it only looks at
whether the element name itself contains a dot, not at the parent path plus the
element name. Reversing the declaration order makes both correct, because the
nested element then wins the first exact match.

Check the resolved substreams path here as well, through
`SerializationTuple::isElementSubcolumn` and
`SerializationVariant::isElementSubcolumn`. The element name is part of the
check: both candidates end in a `TupleElement`, and only the name tells
`TupleElement("t.a")` from `TupleElement("a")`. `QBit` delegates to its nested
`Tuple` serialization, so the same predicate covers it.

Unlike the rewrites that hardcode a type, these take the element type from the
type definition, where an enclosing `Nullable` legitimately wraps it in storage,
so `canOptimizeToExpectedSubcolumn` now takes the expected type optionally and
only the path is checked for them.

Also pin `optimize_functions_to_subcolumns` in the test before the block that
asserts the rewrites still fire: those queries read it from the session, and CI
randomizes it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
GetColumnsOptions(GetColumnsOptions::All).withRegularSubcolumns(), subcolumn_name);
return actual && actual->type->isNullable();
}
auto resolved = storage_snapshot->tryGetColumn(GetColumnsOptions(GetColumnsOptions::All).withSubcolumns(), subcolumn_name);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

canOptimizeToExpectedSubcolumn now filters exact-case flat-name collisions, but it still does not block case-insensitive top-level shadowing. sourceHasColumnCaseInsensitive is only used in the Tuple branch below, so with input_format_{orc,parquet,arrow}_case_insensitive_column_matching = 1 a schema like A.SIZE0 UInt64, a Array(UInt64) or V.INT64 UInt64, v Variant(Int64, String) will still rewrite to a.size0 / v.Int64 and let the reader bind that dotted name to the top-level column instead of the intended subcolumn. I think the iequals guard needs to live in the common dotted-name check (or be applied at every rewrite site), not only on tupleElement.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@serxa serxa self-assigned this Sep 7, 2026

@serxa serxa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Avogar
Avogar added this pull request to the merge queue Sep 9, 2026
Merged via the queue into master with commit 8c0af4c Sep 9, 2026
177 checks passed
@Avogar
Avogar deleted the fix-optimize-functions-to-subcolumns-name-collision branch September 9, 2026 22:15
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 9, 2026
Avogar added a commit to groeneai/ClickHouse that referenced this pull request Sep 11, 2026
Avogar added a commit that referenced this pull request Sep 11, 2026
`optimize_functions_to_subcolumns` name collision (#115777) merged into master
after this branch was cut, so its files exist on both sides. Master's versions win
there, including the `memory-engine` tag added to
`04935_optimize_functions_to_subcolumns_name_collision` afterwards.

`IDataType::getSubcolumnInfo` keeps this branch's body, which delegates to
`SubcolumnResolution::findSubcolumn`; master's inline implementation and its
`makeSubcolumnInfo` helper are superseded by `subcolumnResolution.cpp`, which
populates the same `substreams_path`.

In `IMergeTreeDataPart::getCompressionCodecForPart` the two sides changed adjacent
lines: master added a warning when no data file is found, this branch takes the
naming scheme from the part. Both are kept.

`MergeTreeData.cpp` loses both conflicting includes: master dropped
`absl/container/inlined_vector.h` and this branch made
`boost/container_hash/hash.hpp` unused by removing `collect_nested` from the
part-columns interning key.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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 v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants