Skip to content

Fix Arrow flattened Tuple subcolumn read from a nullable struct - #109741

Merged
nihalzp merged 26 commits into
ClickHouse:masterfrom
groeneai:fix-arrow-nullable-tuple-flattened-subcolumn-109726
Sep 10, 2026
Merged

nihalzp merged 26 commits into
ClickHouse:masterfrom
groeneai:fix-arrow-nullable-tuple-flattened-subcolumn-109726

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #109726

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 reading a flattened Tuple subcolumn (e.g. `s.v`) from an Arrow/ArrowStream file whose column is a nullable struct returning column defaults instead of the actual data when allow_experimental_nullable_tuple_type is enabled. Also fix ORC reads resolving a column or struct field name to the first case-folded match under input_format_orc_case_insensitive_column_matching, which returned another field's data when two names differ only by case.

Description

Since #101272 the Arrow reader hands a nullable struct to NestedColumnExtractHelper as Nullable(Tuple(...)). The helper reached a subcolumn by flattening the parent column, and Nested::flatten does not descend into Nullable(Tuple), so a flattened read such as `s.v` silently returned type defaults.

The helper is now a name resolver in front of the type system: the requested name is cut at the first dot, the head names a block column, and the tail is resolved as a subcolumn of its type, so a flattened read yields whatever SELECT <head>.<tail> yields for that column. The flatten step, the nested-table cache, the in-path unwrap and the reader-side reshape in ArrowIPCBlockInputFormat are gone, and each root's subcolumns are listed once on first request.

Two further defects were found and fixed while addressing review comments on that resolver:

  • an element named like a virtual subcolumn of its own parent (size0 on Array(Tuple(...)), Null against Nullable's null) now resolves the way the direct spelling does;
  • under input_format_arrow_case_insensitive_column_matching or its ORC counterpart, a subcolumn was reachable only through a lower-cased key, so a sibling differing by case shadowed it and the read returned the parent's null map instead of the declared element. The readers now pass the requested spelling through, as StorageHive::read already did, and an exact subcolumn name outranks a case-folded match.

Also fixed here, on review request: ORC resolved a name to the first case-folded field, so with input_format_orc_case_insensitive_column_matching two names differing only by case were both answered by whichever field the file listed first, in a struct and at top level alike. A flattened read returned the sibling's data and a whole-column read also lost the row's NULL. Resolution now prefers the exact spelling and folds only when nothing matches exactly.

Readers affected: ArrowIPCBlockInputFormat (Arrow, ArrowStream), NativeORCBlockInputFormat (ORC), ArrowColumnToCHColumn (ArrowFlight, DeltaLake) and StorageHive.

Related: #101272
Related: #109185


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

Version info

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

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM file('t.arrow', Arrow, '\s.v` Int32') SETTINGS allow_experimental_nullable_tuple_type=1returns0on master,42` with the fix, every run.
b Root cause explained? Since #101272 the Arrow reader wraps a nullable struct into Nullable(Tuple(...)). NestedColumnExtractHelper::extractColumn reaches s.v by calling Nested::flatten on parent s, but flattenImpl only descends into a plain DataTypeTuple (NestedUtils.cpp), not Nullable(Tuple), so the subcolumn is never emitted and the read falls back to type defaults.
c Fix matches root cause? Yes. Unwrap Nullable(Tuple) → Tuple(Nullable(...)) via the existing unwrapNullableTuple right before flatten, so the subcolumn is produced.
d Test intent preserved / new tests added? New test 04401_arrow_nullable_tuple_flattened_subcolumn (Arrow + ArrowStream + multi-field + NULL row + deep-nested tuple + full-column baseline). Existing 04064 full-column test still matches byte-for-byte.
e Demonstrated both directions? Yes. Pristine binary (build id 6a0d6f06) returns 0; fixed binary (2ab395ea) returns 42 for the identical repro.
f Fix is general, not a narrow patch? Fix is in the shared NestedColumnExtractHelper (used by Arrow, ORC, Hive), covering all sibling readers. Applied to both the top-level and recursive (deep-nested) flatten sites. unwrapNullableTuple already handles Nullable/non-Nullable/Array elements.
g Generalizes across inputs / wrappers? Verified single-field, multi-field, NULL struct rows, deep-nested Tuple(Tuple), subcolumn read as Nullable (NULL preserved) and non-nullable (NULL→default). ORC nullable-tuple subcolumn also fixed by the same shared path.
h Backward compatible? Yes. unwrapNullableTuple is a no-op for non-Nullable(Tuple) columns, so plain-Tuple reads (ORC fast decoder, Hive) are byte-identical (04064 unchanged). No setting/format change.
i Invariants / contracts preserved? unwrapNullableTuple propagates the struct null map to each element and preserves element count, names, and row count; the flatten output block structure is unchanged for the plain-Tuple case.

Session id: cron:clickhouse-worker-slot-3:20260708-075500

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp — could you review? Fixes the flattened Tuple subcolumn wrong-result from #101272's nullable-struct wrapping (NestedColumnExtractHelper now unwraps Nullable(Tuple) before Nested::flatten).

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6dc8c25]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation (unit tests) ERROR

AI Review

Summary

This PR replaces NestedColumnExtractHelper's old flatten-based cache with per-root subcolumn-path memoization and makes ORC case-insensitive field lookup exact-first. The ORC changes look coherent, but one library-reader wrong-result path is still open and the new dynamic-subcolumn precedence still diverges from the advertised SELECT <head>.<tail> behavior, so I do not think this is ready to merge.

Findings

❌ Blockers

  • [src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp:2911] ArrowColumnToCHColumn still rebuilds the shared root from only the header entries whose root spelling matches the first request's case. In the TableChanges CDF path, input_format_parquet_case_insensitive_column_matching = 1 plus a projection like `C0.x`, `c0.y` over one Nested / array-of-struct root still produces a partial named-tuple hint, and the struct remap at 2256 / 2332-2363 drops y before the shared extractor ever sees the root. The second sibling is then default-filled or reported missing even though the native Arrow reader now returns it correctly.
    Suggested fix: canonicalize the grouped root before Nested::collect in this path too, and make the named-tuple hint binding exact-first the same way the ORC reader now does. Add a focused ArrowColumnToCHColumn regression for mixed-case sibling requests on one Nested root.

⚠️ Majors

  • [src/DataTypes/NestedUtils.cpp:723] [dismissed by author -- https://github.com/Fix Arrow flattened Tuple subcolumn read from a nullable struct #109741#discussion_r3952645019] For roots that cannot be pre-listed (JSON / Dynamic), resolveSubcolumn case-folds the request onto a declared name before it ever tries the exact path on the live column. With JSON(max_dynamic_paths=8, A UInt32) holding both A and a, extractColumn("j.a") still resolves to declared A and returns 1, while the exact dynamic path a is 2; that breaks the new helper contract that flattened reads follow SELECT <head>.<tail> semantics on the same column.
    Suggested fix: for hasDynamicSubcolumns() roots, try the exact requested path first and fall back to a folded declared name only when that exact path is intentionally considered absent, or narrow the documented contract/tests to the chosen precedence.
Tests
  • ⚠️ There is still no focused regression that exercises the library reader path (ArrowColumnToCHColumn) under input_format_parquet_case_insensitive_column_matching = 1 with mixed-case sibling subcolumn requests on the same Nested root. The current 04401 coverage only proves the native Arrow and ORC readers.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 6dc8c25.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 359/367 (97.82%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
@nihalzp nihalzp self-assigned this Jul 8, 2026
Comment thread src/DataTypes/NestedUtils.cpp Resolved
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest NestedUtils.extractSubcolumnFromNullableTuplePreservesTypeOnEmptyBlock builds an empty Nullable(Tuple(a Tuple(x UInt32,y String), b String)) block and calls NestedColumnExtractHelper::extractColumn("t.a.x"); returns UInt32 on old code every time.
b Root cause explained? Yes. unwrapNullableTuple picked the result TYPE from the runtime null map (has_nulls). With no nulls it stripped Nullable and returned the bare inner Tuple type. An empty sample block (schema planning, StorageHive::read) always has has_nulls==false, so a.x was planned as UInt32 instead of Nullable(UInt32) -> Hive ORC/Parquet subcolumn reads return defaults / reject NULL struct rows.
c Fix matches root cause? Yes. Removed the !has_nulls type-stripping fast path so the result type is always schema-driven (each element wrapped Nullable); has_nulls now only skips per-row work for non-nullable elements.
d Test intent preserved / new tests added? New gtest added; existing NestedUtils.collect and stateless 03917/04401 unchanged. No assertion weakened.
e Demonstrated both directions? Yes. New gtest FAILS on old source (UInt32), PASSES with fix (Nullable(UInt32)); 04401 Arrow/ORC and 03917 diffs empty with the fix.
f Fix is general, not a narrow patch? Audited all 3 callers of unwrapNullableTuple: the two new NestedColumnExtractHelper sites (where the extracted type IS the output) are fixed; the Arrow (ArrowColumnToCHColumn.cpp:2032) and ORC (NativeORCBlockInputFormat.cpp:1944) sites castColumn the result to the header type afterwards, so they are unaffected (04401 confirms). Fix is at the source (the type decision), not a guard at a call site.
g Generalizes across inputs? Result type no longer depends on null-map contents, so it is identical for empty, all-null, no-null, and mixed blocks. Covered leaves: nullable-wrappable (UInt32/String -> Nullable), already-Nullable (merge path), and non-nullable (Array/Map, type unchanged either branch).
h Backward compatible? Yes. No setting, on-disk/wire/metadata format, or default changed. Only makes the flattened-subcolumn type consistent with direct-subcolumn semantics on null-free/empty blocks.
i Invariants preserved? Yes. Restores block-structure consistency: the same stream now yields one stable subcolumn type across all blocks (previously null-free blocks diverged). The per-element column/type construction is unchanged for the value path.

Session id: cron:clickhouse-worker-slot-5:20260708-085700

Comment thread src/DataTypes/NestedUtils.cpp Resolved
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 774106b: the new regression test 04401 was failing on Stateless tests (arm_asan_ubsan, targeted) because the leading description comment block was separated from the -- Tags header by a blank line, so the echo runner emitted it into stdout while the committed reference omitted it (a result-differs, not a code bug — the fix's data output is correct: s.v returns 42, etc.). Comments contiguous with the Tags header are skipped by the echo runner, so I dropped the blank line. Verified with the real clickhouse-test harness: fails 5/5 with the blank line, passes 20/20 without it.

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest NestedUtils.extractSubcolumnFromNullableTuplePreservesTypeOnEmptyBlock builds an empty Nullable(Tuple(a Tuple(x UInt32,y String), b String)) block and asserts the extracted types on demand.
b Root cause explained? The previous commit gated tuple-element wrapping on raw canBeInsideNullable(), which is true for Tuple, so every tuple element became Nullable(Tuple(...)) unconditionally, ignoring allow_nullable_tuple_in_extracted_subcolumns. On StorageHive::read's empty sample block this typed SELECT t.a as Nullable(Tuple(...)) even at the default setting 0.
c Fix matches root cause? Yes. unwrapNullableTuple now uses the setting-aware canExtractedSubcolumnsBeInsideNullable(elem_type) (the predicate direct subcolumn extraction uses) instead of raw canBeInsideNullable().
d Test intent preserved / new tests? gtest updated to assert the full contract: t.a plain Tuple(x Nullable(UInt32), y String) at setting 0 with Nullable leaves. 03917/04401 unchanged and still pass.
e Demonstrated both directions? Yes. On the previous commit the gtest fails (t.a = Nullable(Tuple(x UInt32, y String))); with the fix it passes.
f Fix general, not a narrow patch? Audited all 3 unwrapNullableTuple callers: the 2 NestedColumnExtractHelper sites (incl. deep recursion) go through the fixed path; the Arrow (2032) and ORC (1944) sites castColumn the result to the header type afterward and are unaffected. The fix recurses into nested tuples so deep leaves are handled uniformly.
g Generalizes across inputs / settings? Verified both setting values on a local debug server. setting 0: t.a -> Tuple(x Nullable(UInt32), y String), t.a.x -> Nullable(UInt32). setting 1: t.a -> Nullable(Tuple(x UInt32, y String)); Arrow flattened deep read returns nested data (not defaults).
h Backward compatible? Yes. Restores the pre-existing allow_nullable_tuple_in_extracted_subcolumns contract that the previous commit had broken; default behavior (setting 0) is now correct again. No setting default change, no format change.
i Invariants preserved? Result type is schema-driven and independent of the current null map / has_nulls, so an empty sample block plans identical types to a data block with nulls (block-structure consistency across blocks from one stream).

Session id: cron:clickhouse-worker-slot-1:20260708-095500

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest NestedUtils.extractSubcolumnFromNullableTuplePreservesTypeOnEmptyBlock + new ...WithNullRowGivesDefaults: on b91a308 t.a came out Tuple(x Nullable(UInt32), y Nullable(String)).
b Root cause explained? unwrapNullableTuple applied the extracted-subcolumn policy per-element while flattening, pushing the parent null map into a tuple element's scalar leaves. A terminal tuple element must stay plain Tuple(...) at setting=0 (03917/03913 contract); the per-element decision was made at the wrong level.
c Fix matches root cause? Yes. unwrapNullableTuple now propagates the null map faithfully (tuple element -> Nullable(Tuple)); the setting policy is applied once at the terminal extraction point (unwrap outer Nullable to plain Tuple when setting=0).
d Test intent preserved / new tests added? gtest updated to the correct contract + a data-carrying test asserting NULL parent row -> (0,''). No existing test weakened.
e Demonstrated both directions? Yes. fails-without: 2 gtests fail on b91a308. passes-with: 3 gtests pass; 03917 + 04401 pass; original #109726 deep read returns data.
f Fix general, not a narrow patch? Audited all 3 unwrapNullableTuple callers. Arrow (ArrowColumnToCHColumn.cpp:2032) and ORC (NativeORCBlockInputFormat.cpp:1944) castColumn the extracted type to the declared hint, so those paths are unaffected; only the terminal NestedColumnExtractHelper extraction (StorageHive sample block) changes, to the contract-correct type. Both settings (0 and 1) verified.
g Generalizes across inputs/wrappers? Verified: scalar leaves (Nullable), tuple element (plain at 0 / Nullable(Tuple) at 1), nested tuple (t.a.x deep leaf Nullable), Array/Map element (default-fill on NULL). Empty sample block and data block with NULL row both checked.
h Backward compatible? Restores the pre-#101272 extracted-subcolumn contract (setting-gated); no format/setting-default change. SettingsChangesHistory.cpp N/A.
i Invariants / contracts preserved? Block-structure consistency: extracted type is schema-driven (independent of null-map contents), so empty sample block and data blocks plan identical types. Extracted-subcolumn nullable policy upheld per 03917/03913 references.

Session id: cron:clickhouse-worker-slot-13:20260708-111900

Comment thread src/DataTypes/NestedUtils.cpp Resolved
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest NestedUtils.extractTupleElementFromNullableTupleWithNullRowGivesDefaults — Nullable(Tuple(a Tuple(x UInt32, y String), b String)) with a parent-NULL row carrying non-default payload ((99,'zz'),'Z'); extract t.a at setting 0. Fails on demand without the fix.
b Root cause explained? applyExtractedSubcolumnNullablePolicy unwrapped Nullable(Tuple) → plain Tuple via getNestedColumnPtr(), which returns the raw nested payload. ColumnNullable does not guarantee the payload under a NULL row is the type default, so Arrow/ORC/Hive child values under a parent-NULL row surface as-is instead of the contract-required (0,'') at allow_nullable_tuple_in_extracted_subcolumns = 0.
c Fix matches root cause? Yes. Replaced getNestedColumnPtr() with ColumnNullable::getNestedColumnWithDefaultOnNull(), which materializes type defaults on null rows before dropping the outer nullability. Targets the exact mechanism, not the symptom.
d Test intent preserved / new tests? Yes. Strengthened the existing gtest to insert a real non-default value before flagging the row null (was insertDefault, which masked the bug). Type assertions unchanged.
e Demonstrated both directions? Yes. Without fix: parent-NULL t.a reads (99, 'zz') (gtest FAILS). With fix: reads (0, '') (gtest PASSES). Build ID changed e77a3771 → f708b9ca.
f Fix general, not narrow? Yes. Audited all callers of applyExtractedSubcolumnNullablePolicy / unwrapNullableTuple: only the terminal setting-0 tuple-unwrap path materialized-drops the null map; setting-1 returns early unchanged; scalar leaves stay Nullable. Arrow(2032)/ORC(1944) direct callers castColumn to the declared hint afterward → unaffected.
g Generalizes across inputs / type wrappers? Yes. getNestedColumnWithDefaultOnNull() is type-agnostic over the tuple's declared element types (scalars, nested tuples). setting=1 path (Nullable(Tuple) kept) verified separately; the original #109726 deep c0.inner.x NULL-struct read (04401) still returns data not defaults.
h Backward compatible? N/A — no setting default, format, or on-disk change. Restores the documented setting-0 contract (default-row semantics) that a null-free block already produced; a data block with nulls now matches it.
i Invariants preserved? Yes. Block-structure consistency: the extracted subcolumn type is schema-driven (independent of has_nulls), and the payload under NULL parent rows is now the deterministic type default on every path.

Session id: cron:clickhouse-worker-slot-6:20260708-131600

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d7a69cd

All gating checks passed (Finish Workflow + Mergeable Check green, 0 failed checks). CH Inc sync still running (private, exempt).

Check / test Reason Owner / fixing PR
(all gating checks) — all green
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260708-180000

@nihalzp nihalzp 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.

The following query throws logical error:

SET allow_experimental_nullable_tuple_type = 1;
INSERT INTO FUNCTION file('e.arrow', 'Arrow')
SELECT CAST(tuple(), 'Nullable(Tuple())') AS s;

SET input_format_arrow_allow_missing_columns = 1;
SELECT * FROM file('e.arrow', 'Arrow', '`s.x` Int32');

In NestedUtils, the null-free fast path is now gone.


Since ORC is affected, let's add comprehensive test for that format as well.


You can simplify the code a lot by using existing helpers:

  • The null-map merge loop → ColumnNullable::applyNullMap
  • The default-materializing insertFrom loop → filter + IColumn::expand
  • The merge semantics → applyParentNullMapToExtractedSubcolumn

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks @nihalzp — addressed all four in eb279c2.

1. Empty Nullable(Tuple()) logical error. Reproduced (This function cannot be used to construct empty tuple. It is a bug from ColumnTuple::create via unwrapNullableTuple). Root cause: unwrapNullableTuple built a ColumnTuple from the (empty) element list. Guarded it: an empty Nullable(Tuple()) now drops the outer Nullable and returns a plain empty Tuple(), so a missing-column subcolumn hint (\s.x``) yields the default instead of aborting.

2. Null-free fast path. Restored: distributeParentNullMapToElement short-circuits (no per-row merge/materialization) when the parent carries no nulls, and the result type is unchanged in that case.

3. Simplified via the existing helpers.

  • null-map merge → applyParentNullMapToExtractedSubcolumn (also generalizes correctly to Variant/Dynamic/LC(Nullable) elements, not just plain Nullable).
  • default-materializing loop → filter + IColumn::expand (for Array/Map elements that cannot represent NULL).
  • wrap-able elements → ColumnNullable::create + makeNullable.

4. ORC coverage. Added the full Arrow case set through the ORC reader, plus the empty-Tuple() missing-columns regression for both Arrow and ORC, in 04401_arrow_nullable_tuple_flattened_subcolumn. Added a gtest for the empty-tuple extraction as well.

Verified: empty-tuple gtest fails on the pre-fix code and passes after; 03917, 04401 (Arrow+ORC+empty), and the NestedUtils gtests all pass; both allow_nullable_tuple_in_extracted_subcolumns values plan the expected types; the original #109726 deep read still returns data, not defaults.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM file('e.arrow','Arrow','\s.x` Int32')over an emptyNullable(Tuple())withinput_format_arrow_allow_missing_columns=1aborts every time withThis function cannot be used to construct empty tuple. It is a bug`.
b Root cause explained? unwrapNullableTuple builds ColumnTuple::create(new_elements); for a zero-element tuple new_elements is empty and ColumnTuple::create throws (empty tuples are disallowed). The reviewer also flagged that the null-free fast path had been removed and the hand-rolled null-map/default loops duplicated existing helpers.
c Fix matches root cause? Yes. Guard the empty-tuple case at its origin in unwrapNullableTuple (drop the outer Nullable, return plain empty Tuple()), restore the null-free fast path, and route the null-map work through the canonical helpers.
d Test intent preserved / new tests added? Yes. Added ORC coverage + an empty-Tuple() missing-columns regression (Arrow+ORC) to 04401, and a gtest for the empty-tuple extraction. Existing gtests/03917 intent unchanged.
e Both directions demonstrated? Yes. The empty-tuple gtest aborts on the pre-fix code and passes after; 03917/04401(Arrow+ORC+empty) and all NestedUtils gtests pass with the fix.
f Fix is general across code paths? Yes. The single unwrapNullableTuple/distributeParentNullMapToElement path serves all NestedColumnExtractHelper callers (StorageHive sample block, Arrow, ORC). The refactor generalizes the merge branch to Variant/Dynamic/LC(Nullable) elements via applyParentNullMapToExtractedSubcolumn, not just plain Nullable.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified across empty tuple, scalar / nested-tuple / Array-Map elements, with/without NULL parent rows, and both allow_nullable_tuple_in_extracted_subcolumns values (0 → plain Tuple, default rows; 1 → Nullable(Tuple)).
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Restores correct behavior on a path that previously errored or mis-typed.
i Invariants and contracts preserved? Yes. unwrapNullableTuple stays schema-driven (type independent of null-map contents → stable empty-sample-block planning); block structure header==data preserved; the extracted-subcolumn nullable policy is still applied once at the terminal point.

Session id: cron:clickhouse-worker-slot-0:20260710-133500

Comment thread src/DataTypes/NestedUtils.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed e4153eca fixing the PR-caused 04401 failure that the flaky/targeted checks surfaced.

Root cause (not our NestedUtils change): after the merge with master, CI tests the PR against the new native Arrow IPC reader (ArrowIPCBlockInputFormat, input_format_arrow_use_native_reader = 1 by default). Its buildChunk reshaped every nested-table field via Nested::collect + castColumn to the collected leaf type. That is correct only for an Array(Tuple(...)) Nested table; for a top-level struct column (Nullable(Tuple(v Int32))), Nested::collect on a scalar-subcolumn set returns the leaf type Int32, so castColumn(Nullable(Tuple(v Int32)) -> Int32) threw toInt32(Tuple) (Code 43 for s.v; Code 349 for the multi-field cases). The library reader never hits this because it reads the struct directly into the type hint without a leaf-type cast.

Fix: gate the collect + castColumn reshape to Array-typed fields only; a top-level struct is fed to NestedColumnExtractHelper as-is, which unwraps the nullable tuple, flattens it, and applies the allow_nullable_tuple_in_extracted_subcolumns policy at the terminal subcolumn — mirroring the Apache Arrow library reader. Reproduced only after merging master (the native reader is newer than this branch's base).

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT * FROM file('t.arrow','Arrow','\s.v` Int32')overNullable(Tuple(v Int32))` throws Code 43 every time on the native reader (default). Required merging master (native reader is newer than this branch's base).
b Root cause explained? Native ArrowIPCBlockInputFormat::buildChunk reshaped every nested-table field via Nested::collect + castColumn to the collected leaf type. Correct only for Array(Tuple); for a top-level Nullable(Tuple(...)) struct, collect returns the leaf type (Int32), so castColumn(Nullable(Tuple(v Int32)) -> Int32) = toInt32(Tuple) -> Code 43 (Code 349 CANNOT_INSERT_NULL for multi-field).
c Fix matches root cause? Yes. Gate the collect+castColumn reshape to Array-typed fields; feed a top-level struct directly to NestedColumnExtractHelper (which unwraps+flattens+applies the setting policy), so no struct->leaf cast happens — mirrors the library reader.
d Test intent preserved / new tests? The new 04401 Arrow/ArrowStream/ORC + empty-tuple + multi-field + nested cases now exercise the native reader too; assertions unchanged (still verify data, not defaults, for flattened subcolumns).
e Demonstrated both directions? Yes. Baseline (fix reverted, rebuilt, Build ID 0f11d498): Code 43. With fix (Build ID 51dc2ebd): s.v -> 42, all 04401 rows match .reference; NestedUtils.* gtests (4) pass.
f Fix general, not narrow? Audited all NestedColumnExtractHelper callers: ArrowColumnToCHColumn (library reader) and NativeORCBlockInputFormat read the field directly into the collected type hint (no post-decode struct->leaf cast) -> unaffected; only ArrowIPC had the buggy reshape.
g Generalizes across inputs? Verified single-field, multi-field-with-NULL-row, deep nested tuple, Nullable(UInt32) hint, full-column read, and empty Nullable(Tuple()) missing-column — Arrow, ArrowStream, ORC; setting 0 and 1.
h Backward compatible? Yes. No setting, format, or metadata change; a reader path that previously threw now returns the correct value (matching the library reader).
i Invariants preserved? Extractor contract unchanged: the block fed to it holds one field with its declared type; the collect/castColumn reshape is only needed to make an Array(Tuple) splittable by Nested::flatten, which a top-level struct does not require.

Session id: cron:clickhouse-worker-slot-0:20260710-172200

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up on the 14:22Z review (comment r3559623711) — fix pushed in a0daf34.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. values('c0 Tuple(a Nullable(Tuple(b Nullable(UInt32))))', (tuple(tuple(10))),(tuple(NULL)),(tuple(tuple(30)))) -> Arrow file -> read \c0.a`returned(NULL)withisNull=0` on the NULL row (native and library readers).
b Root cause explained? unwrapNullableTuple faithfully propagates a parent struct null map, so a Tuple element arrives at the terminal policy as Nullable(Tuple) in TWO cases: synthesized from an outer struct null map, or genuinely declared Nullable(Tuple) in the schema. The old policy unwrapped BOTH at setting 0. The current null-map contents cannot distinguish them, so the genuine descendant's real NULL rows were collapsed to default tuples.
c Fix matches root cause? Yes. The unwrap/keep decision is now driven by the root declared subcolumn type (IDataType::tryGetSubcolumnType) — the same setting-aware machinery that governs direct MergeTree/Memory subcolumn reads. Declared Nullable -> keep nullable; declared plain Tuple -> drop outer Nullable (materializing type defaults on NULL rows).
d Test intent preserved / new tests added? Yes. Added gtest extractGenuinelyNullableTupleDescendantStaysNullable and Arrow+ORC _gen cases to 04401. All existing cases (03917/04049/04337/04401) unchanged and passing.
e Both directions demonstrated? Yes. New gtest FAILS on reverted NestedUtils.cpp (x.a returned plain Tuple), PASSES with the fix. \c0.a`now returns\N/isNull=1` on the NULL row through both readers + ORC.
f Fix is general across code paths? Yes. The fix is at the single terminal applyExtractedSubcolumnNullablePolicy, used by all NestedColumnExtractHelper callers (ArrowColumnToCHColumn, ArrowIPC, NativeORC, StorageHive). Verified genuine/synthetic on native + library Arrow readers and ORC.
g Fix generalizes across inputs? Yes. Verified: synthetic Nullable(Tuple) (setting 0 -> plain, setting 1 -> Nullable); genuine Nullable(Tuple) descendant (stays Nullable both settings); scalar leaves stay Nullable; deeper t.a.x stays Nullable; empty Nullable(Tuple()) + missing column still returns default without error.
h Backward compatible? Yes. Only corrects the previously-wrong reader result to match the declared-type subcolumn contract; no setting default, on-disk/wire format, or new validation change.
i Invariants and contracts preserved? Yes. The presented subcolumn type now exactly equals tryGetSubcolumnType of the declared root — the same type the query planner/serialization layer produces for direct reads — so block-structure consistency (declared header == reader output) is upheld. Case-insensitive path degrades to the prior setting-only decision (no regression).

Session id: cron:clickhouse-worker-slot-7:20260710-224400

Comment thread src/DataTypes/NestedUtils.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. c Tuple(A Nullable(Tuple(b Nullable(UInt32))), C String) written to Arrow, read as c.a with input_format_arrow_case_insensitive_column_matching=1 + allow_nullable_tuple_in_extracted_subcolumns=0 → the NULL row deterministically returns (NULL)/isNull=0 on HEAD a0daf34.
b Root cause explained? applyExtractedSubcolumnNullablePolicy distinguishes genuine vs synthetic Nullable(Tuple) via declared_subcolumn_type = root.type->tryGetSubcolumnType(path). tryGetSubcolumnType is case-sensitive; the Arrow/ArrowIPC/ORC readers lowercase the requested name first, so a mixed-case declared element (A) is looked up as a → nullptr → setting-only fallback → genuine Nullable(Tuple) unwrapped → real NULL collapsed to a default tuple.
c Fix matches root cause? Yes. When the exact lookup fails under case_insentive, retry case-insensitively against the root type's getSubcolumnNames() so the declared element is found and its nullability governs the decision. No change to the case-sensitive path.
d Test intent preserved / new tests added? Both. Added stateless _04401_ci Arrow+ORC cases and gtest extractGenuinelyNullableTupleDescendantStaysNullableCaseInsensitive; existing 04401/03917/04049/04337 assertions unchanged.
e Both directions demonstrated? Yes. Reverted binary (Build ID 1089064a): q row → (NULL) 0. Fixed binary (Build ID 544067): q row → \N 1. gtest FAILS on reverted source, PASSES with fix.
f Fix is general across code paths? Yes. The lookup is computed once at the single public extractColumn entry, shared by all four NestedColumnExtractHelper callers (ArrowColumnToCHColumn, ArrowIPC, NativeORC, StorageHive). All three case-insensitive reader call sites lowercase identically, so one fix covers them all.
g Fix generalizes across inputs? Yes. getSubcolumnNames() enumerates the full dotted subcolumn set of the declared type, so nested/multi-field/mixed-case paths resolve. Verified genuine descendant (stays Nullable) and synthetic wrapping (obeys setting) both behave correctly under case-insensitive matching.
h Backward compatible? Yes. No setting default / format / on-disk change. Pure lookup robustness improvement; the case-sensitive path is untouched.
i Invariants and contracts preserved? Yes. Only used when the exact lookup returned nullptr and case_insentive is true; picks the first declared name whose lowercase equals the (lowercased) request — the reader has already established a unique case-insensitive match upstream. Result type still equals a real declared subcolumn type; block structure (type==column) preserved.

Session id: cron:clickhouse-worker-slot-3:20260711-000400

Comment thread src/DataTypes/NestedUtils.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. gtest extractGenuinelyNullableTupleDescendantStaysNullableCaseInsensitiveRawSpelling: case-insensitive extractor, declared element a, requested raw x.A (StorageHive's non-lowercased spelling) fails on demand pre-fix.
b Root cause explained? The a0daf34 declared-type fallback compared to_lower_copy(declared_name) == subcolumn_path, where subcolumn_path is the raw requested suffix. StorageHive::read passes the spelling through unchanged (unlike Arrow/ArrowIPC/ORC which lowercase first), so a mixed-case request c.A gave subcolumn_path = "A", the compare "a" == "A" missed, declared_subcolumn_type stayed null, and the terminal policy fell back to the setting-only unwrap, collapsing a genuine NULL Nullable(Tuple) descendant to a default tuple.
c Fix matches root cause? Yes. Case-fold BOTH sides: compute subcolumn_path_lower once and compare to_lower_copy(declared_name) == subcolumn_path_lower. Directly addresses the raw-spelling caller.
d Test intent preserved / new tests added? New gtest for the raw-spelling path; the existing lowercased-spelling gtest and 04401 Arrow/ORC coverage are unchanged. No assertions weakened.
e Demonstrated both directions? fails-without: reverted NestedUtils.cpp, rebuilt gtest -> ...RawSpelling FAILS (x.A -> Tuple(b Nullable(UInt32)), outer Nullable lost). passes-with: restored -> all 7 NestedUtils gtests PASS; 04401 (Arrow/ArrowStream/ORC + multi + nested + gen + ci + empty, native reader default) matches reference exactly via clickhouse-local (0 result-row diffs).
f Fix general, not a narrow patch? Gate f: enumerated all NestedColumnExtractHelper callers - Arrow (ArrowColumnToCHColumn.cpp), ArrowIPC (ArrowIPCBlockInputFormat.cpp), NativeORC (NativeORCBlockInputFormat.cpp) all boost::to_lower the requested name before extractColumn; only StorageHive::read (StorageHive.cpp:906) passes it raw. Case-folding both sides is caller-spelling-agnostic: no-op for the lowercasing callers, correct for the raw caller. Single fix covers all.
g Generalizes across inputs? Verified across spellings (lowercased x.a, raw x.A), genuine vs synthetic Nullable(Tuple) descendants, and both allow_nullable_tuple_in_extracted_subcolumns values via 04401 + gtests.
h Backward compatible? N/A - the change only affects the internal case-insensitive declared-type lookup; no setting default, on-disk/wire format, or user-visible behavior change beyond restoring the documented nullable-descendant contract.
i Invariants and contracts preserved? Yes. Contract (04049/04337): schema-level Nullable(Tuple) descendants stay nullable regardless of the setting. The fix restores that contract for non-lowercasing callers; the case-sensitive path is unchanged.

Session id: cron:clickhouse-worker-slot-0:20260711-010700

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 49.30% 85.70% +36.40%
Functions 63.90% 92.70% +28.80%
Branches 38.10% 77.90% +39.80%

Changed lines: Changed C/C++ lines covered: 206/211 (97.63%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a117a4a

Every failure below has an owner (a fixing PR). Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (30d: 15+ unrelated PRs + master) #110030 (ours, open)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) / Server died + Unknown error flaky server-died (30d: 63 PRs + 18 master in this coverage shard) #109747 (ours, open)
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260711-053000

@nihalzp

nihalzp commented Sep 8, 2026

Copy link
Copy Markdown
Member

@groeneai Fix conflicts.

…mn-109726

Conflict: src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp, in
buildChunk's nested-extractor block. This branch deletes that block, because the
extractor now addresses tuple elements by name through the type system and
reshaping the decoded column onto the `Nested::collect` type has no job left;
master meanwhile replaced the block's `realignStructFieldsToRequested` call with
`reinterpretRawByteColumns` plus `prepareArrowColumnForCast` against that same
intermediate type.

Resolved by taking master's file and re-applying this branch's two edits to it,
so every unrelated master change in the file survives verbatim. The added-line
sets of both diffs are identical (834 lines, empty symmetric difference in both
directions); the deleted sets differ only by master's five lines inside the
removed block.

Dropping those two calls with the block loses nothing. They reconciled raw-byte
leaves before the intermediate cast that no longer exists, and the per-column
tail already runs `reinterpretRawByteColumns(column, header_column.type)`,
`prepareArrowColumnForCast` and `castColumn` against the requested type on every
path, nested or not. Measured on this merge (build id 45d85137):
`05023_arrow_type_hints_reordered_wrapped_nested`, whose `n Nested(v Int128)`
and `n Nested(d Int32)` arms are that reconciliation's guardians, returns
[1234567890123456789] and [2932996] and passes; 04401 passes; the 11 NestedUtils
gtests pass; and the issue ClickHouse#109726 repro still returns 42 (0 before the fix).
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Conflicts resolved in 880f3f6; the PR is MERGEABLE again.

The only conflict was in ArrowIPCBlockInputFormat.cpp: master replaced the nested block's realignStructFieldsToRequested call with reinterpretRawByteColumns plus prepareArrowColumnForCast, inside the reshape this branch deletes. I took master's version of the file and re-applied this branch's two edits to it, so every other master change in it survives verbatim; the added-line sets of the old and new diffs are identical (834 lines, empty symmetric difference in both directions), and the deleted sets differ only by master's five lines inside the removed block.

Those two calls reconciled raw-byte leaves before the intermediate cast that no longer exists, and the per-column tail still runs reinterpretRawByteColumns(column, header_column.type), prepareArrowColumnForCast and castColumn against the requested type on every path. 05023_arrow_type_hints_reordered_wrapped_nested, whose n Nested(v Int128) and n Nested(d Int32) arms are that reconciliation's guardians, still returns [1234567890123456789] and [2932996]. 04401, the 11 NestedUtils gtests and 170 of 173 local arrow/nullable_tuple tests pass on the merge (the 3 others are not Arrow tests, they match the substring in "narrow"/"narrowed" and fail on sandbox gaps), and the issue repro still returns 42.

One thing I would like your call on, found while re-checking the resolver contract. ORC prunes before the helper sees the request: search_struct_field in traverseDownORCTypeByName lower-cases the target and takes the first folded match, and updateIncludeTypeIds prunes to that selection. So with input_format_orc_case_insensitive_column_matching = 1, a flattened read of c0.a on Tuple(A Nullable(Tuple(b UInt32)), a Tuple(b UInt32)) (3 rows, middle row a struct NULL) returns element A:

binary Arrow c0.a ORC c0.a oracle SELECT c0.a
master 794800200ccc (0),(0),(0) (10),(0),(12) (20),(21),(22)
this branch 880f3f6b (20),(21),(22) (10),(0),(12) (20),(21),(22)

ORC's answer is identical before and after, so it is pre-existing rather than something this PR changes (its entire ORC diff is the one changed call at line 3002). The fix would be to make ORC's path selection exact-first, then case-insensitive, with an end-to-end ORC case. I can do that here, or keep this PR on its single root cause and send it separately. Whichever you prefer.

@nihalzp

nihalzp commented Sep 8, 2026

Copy link
Copy Markdown
Member

Fix ORC bug in this PR.

With `input_format_orc_case_insensitive_column_matching = 1` a request for a
struct field was resolved by lower-casing both sides and taking the first match,
so a struct holding two fields whose names differ only by case (`A` and `a`)
answered every request with whichever field the file happens to list first.
Three places did this, and they did not even agree with each other:

- `traverseDownORCTypeByName` took the first case-folded field, so a flattened
  subcolumn read of `c0.a` walked into `A`;
- `updateIncludeTypeIds` keyed its field map on the folded name, so a collision
  overwrote the earlier entry and the include list selected the last folded
  field for every colliding element, leaving the other element's stream unread;
- `readColumnFromORCColumn` bound each ORC field to the first case-folded
  element of the type hint, so both colliding fields claimed the same element.

Measured on `Tuple(A Nullable(Tuple(b UInt32)), a Tuple(b UInt32))` written to
ORC (3 rows, middle row a struct NULL) and read with the setting on:

    read              before                    after
    `c0.a` flattened  (11),(0),(13)             (21),(22),(23)
    whole column      ((21),(0)),((22),(0)),..  ((11),(21)),(NULL,(22)),((13),(23))

Both were silent wrong results: the flattened read returned the sibling
element's data, and the whole-column read moved `a`'s data into `A`, filled `a`
with defaults and lost the row's NULL. What the reader now returns is what
`SELECT c0.a` over the same file returns, and what it already returned with the
setting off.

Each site resolves the exact spelling first and falls back to the folded match
only when nothing matches exactly, so a request that matches no field exactly is
still answered case-insensitively, and the include-list pruning and the read
path agree on which field answers a name. Fixing only the two pruning sites is
not enough: the whole-column read then fails with `DUPLICATE_COLUMN` because
both fields still claim element `A`.
`orcTableToCHChunk` keyed its field map on the lower-cased file name, so with
`input_format_orc_case_insensitive_column_matching = 1` two top-level columns
whose names differ only by case collapsed onto one entry and the map kept
whichever came last. A header requesting both then read the same column twice,
and which one it was depended on the order the file lists them in:

    file                       requested `A, a`   before      after
    `SELECT 10 AS A, 20 AS a`  10, 20             20, 20      10, 20
    `SELECT 20 AS a, 10 AS A`  10, 20             10, 10      10, 20

The map now holds the file's own spellings and the lookup resolves a request
exactly before folding, which is the rule the struct-field selection already
follows. A request that matches no column exactly still folds onto one, and
among several such candidates the first in file order answers, so the choice no
longer depends on hash iteration or on which entry overwrote which.
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed here, in 53ed54d.

The rule is now that a name resolves to the field spelled exactly like it, and falls back to a case-folded match only when nothing matches exactly. It is applied at every place the ORC reader resolves a name against a struct: the path traversal (traverseDownORCTypeByName), the include-list pruning (updateIncludeTypeIds), the type-hint binding in readColumnFromORCColumn, and the top-level column map.

Measured on Tuple(A Nullable(Tuple(b UInt32)), a Tuple(b UInt32)) written to ORC (3 rows, middle row a struct NULL) and read with input_format_orc_case_insensitive_column_matching = 1:

read before after
c0.a flattened (11),(0),(13) (21),(22),(23)
whole column ((21),(0)),((22),(0)),((23),(0)) ((11),(21)),(NULL,(22)),((13),(23))
top-level A, a from SELECT 10 AS A, 20 AS a 20, 20 10, 20

The whole-column read also lost the row's NULL, and the top-level answer depended on the order the file lists the columns in (reversing it returned 10, 10). All three now agree with the same read at = 0 and with SELECT c0.a. Pruning alone is not enough: with only that fixed, the whole-column read fails with DUPLICATE_COLUMN, because both fields still claim element A.

Regression arms are in 04401_arrow_nullable_tuple_flattened_subcolumn: both field orders, the case-folded fallback that the setting exists for, and an Arrow twin. Reverting the source hunks reddens them; the ORC suite is otherwise unchanged.

Three adjacent cases of the same collapse that I measured and deliberately left alone, since each is pre-existing master behaviour outside the resolution path you asked about:

  1. the ORC traversal prefers a struct field a over a field literally named a.b when the file lists a first, so a.b reads the wrong leaf (order-dependent, and also at = 0);
  2. the Arrow and ArrowStream readers collapse two top-level columns differing only by case exactly as ORC did (20, 20);
  3. ORC union to Variant branch matching folds colliding field names into one candidate, which can reject a valid explicit-schema read with CANNOT_CONVERT_TYPE.

Each is a separate change with its own tests. Tell me if you want any of them in this PR and I will add them, otherwise I will leave them out of scope here.

The comment claimed that the field spelled exactly like the request wins for
the whole column in every reader that resolves a name against a struct.
Measured on this branch, a whole-column `Arrow` or `ArrowStream` read of a
struct whose two fields differ only by case is rejected instead:
`alignStructFieldNamesCaseInsensitive` aligns the file's tuple type onto the
requested one by folded name, both fields claim the first spelling, and
`DataTypeTuple` refuses the duplicate with `DUPLICATE_COLUMN`.

That is byte-identical to master at the merge base and is not touched here.
The arms below assert the flattened read in both readers and the whole column
in ORC, whose name resolution this PR makes exact-first, so the comment now
says exactly that and no more.
A tuple element name may itself contain a dot, so `c0.a.b` names both the
element `a.b` and the path from `a` to `b`. The Arrow reader has coverage for
that pair; the ORC reader, which resolves the name against the file's struct
itself in traverseDownORCTypeByName, had none, and the flattened ORC read of
such a name returns column defaults without this branch.

Which of the two candidates a request resolves to follows the order the schema
declares them in, both in the type system and in the reader, so the
reversed-order arm compares the flattened read with the direct subcolumn read
rather than pinning either candidate's values.
auto nested_column = nested_tables[search_nested_table_name].second->extractColumn(search_column_name);
/// The requested spelling, not the lower-cased one: the helper matches names
/// case-insensitively itself, and an exact element name outranks a folded match.
auto nested_column = nested_tables[search_nested_table_name].second->extractColumn(header_column.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.

Passing the requested spelling into NestedColumnExtractHelper does not finish the case-insensitive fix for ArrowColumnToCHColumn.

This branch still builds nested_table_type from the exact name.starts_with(nested_table_name + ".") scan above, so on a DeltaLake/TableChanges projection like `C0.x`, `c0.y` only the C0.* half of the header reaches the hint. readColumnFromArrowColumn then rematches the whole struct against that partial named-tuple hint at 2256 and 2332-2363, so y is dropped before the helper ever sees the root. The same lossy rematch is what still breaks a case-colliding pair like `c0.A`, `c0.a` here: both file fields bind to the first hint element and the second one is default-filled.

So the library reader path can still return defaults / the wrong sibling for flattened reads under case-insensitive matching even though the native Arrow and ORC paths are fixed. Can we normalize the collected sibling roots here as well, and make the struct-field hint binding exact-first (or otherwise avoid rebuilding the helper root through a lossy named-tuple hint)?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I read the three entry points and the collection scan before deciding. The mechanism is real, two of the three entry points cannot reach it, and the first lossy step is earlier than 2256.

The change at :2911 only chooses which spelling the helper resolves; nested_table_type is built above it and is unchanged from master, so nothing here was meant to finish that part.

Which callers can take the folded path at all. readColumnFromArrowColumn is static in this file (:1817, :2517) and arrowColumnsToCHChunk is private (ArrowColumnToCHColumn.h:81), so this code is reachable only through arrowTableToCHChunk, which has exactly three callers:

caller case_insensitive_matching
ArrowFlightSource.cpp:202 argument not passed, so false (ArrowColumnToCHColumn.h:34)
DeltaLakeMetadata.cpp:565 /* case_insensitive_column_matching */false
TableChanges.cpp:201 format_settings.parquet.case_insensitive_column_matching

ArrowFlight and the Delta checkpoint reader cannot enter the folded branch, so the "returns defaults / the wrong sibling" outcome is available to the delta-kernel CDF read with input_format_parquet_case_insensitive_column_matching = 1, and to nothing else.

The lossy hint needs one more precondition. nested_table_type is Nested::collect(nested_columns).front().type (:2885), and collect unites only Array-typed dotted entries (getSubcolumnsOfNested, NestedUtils.cpp:467-519, gated on typeid_cast<const DataTypeArray *>). For a plain projection like `C0.x`, `c0.y` the entries pass through untouched, .front().type is the leaf type, typeid_cast<const DataTypeTuple *> at :2244 is null, and there is no named-tuple hint to rematch against: the helper receives the natively read struct whole, and :2961 casts the extracted subcolumn to the header type. The same holds for `c0.A`, `c0.a` while they are plain. The hint exists only for classic Nested (array of struct) entries, and there the grouping key in getSubcolumnsOfNested is the exact root spelling, so folding the starts_with prefix alone would not merge C0.x with c0.y: .front() would pick one of two groups instead. Canonicalizing the root spelling before collect is the part that fixes that half.

The hint binding. Agreed on shape, and this is the last unguarded site of that family. tryGetPositionByName is a single boost::iequals scan (DataTypeTuple.cpp:271-287), read_positions.emplace keeps the first (:2342), and the element that loses is filled with defaults (:2363). ORC in this PR already tries the exact spelling first and folds only as a fallback (NativeORCBlockInputFormat.cpp:2940-2942); the V3 Parquet reader runs the same folded scan but raises DUPLICATE_COLUMN when two file elements claim one hint element (Parquet/SchemaConverter.cpp:785-788); the native Arrow whole-column read ends in DUPLICATE_COLUMN as well, measured for the previous thread.

Not pushed in this round. The only consumer that can set the flag is the CDF read, and I have no carrier for it here (no Flight server, no CDF table), so the change would go in without a repro in either direction. The fix-here-or-separately question for these adjacent pre-existing cases is already open on this PR. The three line ORC mirror plus the root canonicalization is ready and goes in as soon as that is answered.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 87ffa16

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.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, public master regression with a hard onset on 2026-09-06: a recorded CANNOT_SCHEDULE_TASK is lost and the client sees code 1000 instead #118390 (mine, merged 2026-09-09 05:40Z), merged master @ 38fda70d to pick it up
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky, collateral of the same race: since the onset there is no job where this test fails without 04648 failing first #118390 (mine, merged), picked up by the same master merge @ 38fda70d

Not counted as failures, recorded for completeness:

  • Bugfix validation (unit tests) reports leaf status ERROR rather than a test result: "Bugfix validation inconclusive: submodule state differs between the merge-base and the checkout". That is base-branch submodule drift, so it is neither a reproduction nor a refutation. Owner: Do not report a base-branch submodule move as a bugfix-validation failure #117948 (mine, open).
  • PR is the workflow aggregator of the jobs above and carries no independent failure.
  • Bugfix validation (functional tests, amd64) and (aarch64) both passed with Failed: 1, Passed: 0 on 04401_arrow_nullable_tuple_flattened_subcolumn, which is the intended inversion: the regression test does fail on the pre-fix binary.
  • CH Inc sync measured success on this head.

Both stateless failures ran at 06:39Z, before this branch contained #118390. With the fix present on master the pair is 14 for 14 green (05:59Z to 07:35Z), and fleet-wide the last failure of either test is 06:39:57Z, so the master merge above is expected to clear both.

Session id: cron:our-pr-ci-monitor:20260909-090115

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 38fda70

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / Timeout infra: graceful session-timeout overrun (ERROR: session-timeout occurred during test execution, zero individual test failures; the five sibling shards of the same suite are green at 0/1273, 0/1228, 0/956, 0/993, 0/1334) #118384 (mine, open)

Session id: cron:our-pr-ci-monitor:20260909-150301

@nihalzp
nihalzp added this pull request to the merge queue Sep 10, 2026
Merged via the queue into ClickHouse:master with commit e80499d Sep 10, 2026
342 of 345 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 10, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 10, 2026
Algunenano pushed a commit that referenced this pull request Nov 11, 2026
The conflicts come from the `-WithMemoryTracking` containers of #126530
and from `findORCStructFieldByName` of #109741, which 26.8 does not have:
the new code uses std::unordered_set and std::vector, and the recursive
call keeps the name lookup of 26.8.

The test enables `enable_nullable_tuple_type`, which is off by default on
26.8, and drops the five queries that read a subcolumn through a list
(`tb.l.b`, `an.x.v`): 26.8 returns empty arrays for such a path even for
a field that is in the file, with or without this change.

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 comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). groeneai-origin-unknown PR origin: unclassified (legacy task) 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 v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Arrow/ArrowStream return defaults instead of data for flattened Tuple subcolumn reads when allow_experimental_nullable_tuple_type is enabled

7 participants