Skip to content

Push tuple element predicates into Parquet and ORC subcolumn reads - #113383

Merged
alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112575-tuple-subcolumn-pushdown
Aug 15, 2026
Merged

alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112575-tuple-subcolumn-pushdown

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Filter pushdown now works for Tuple subcolumns in Parquet and ORC files. A predicate such as WHERE tup.1 = 555555 over file(), s3() or url() now prunes row groups and row index strides using the tuple element's own statistics instead of reading the whole file.

Description

Closes: #112575

Three independent defects, all needed for the reported query to prune. Parquet's reader itself was fine.

The analyzer never produced a subcolumn. StorageFile/StorageURL/StorageObjectStorage return false from supportsOptimizationToSubcolumns, so tupleElement(tup, 1) was never rewritten to tup.1; the pass also accepted only TableNode, skipping table functions. That blanket false keeps #106147 fixed (NOT_FOUND_COLUMN_IN_BLOCK on .null in PREWHERE), so rather than flipping it this adds a narrow supportsOptimizationToTupleElementSubcolumns virtual defaulting to the existing one, with a {Tuple, tupleElement}-only allow-list. 04303_object_storage_prewhere_isnotnull_subcolumn passes unmodified. Source identity also moves to the table-expression node: every file() resolves to the same _table_function.file ID, so two such sources shared a key. Accepting table functions generally also makes format(), values() and view() eligible for the other transformers; those storages already answer supportsSubcolumns(), so the default covers them.

ORC's search argument builder resolved top-level names only, so any dotted name emitted YES_NO_NULL while the read path in the same file resolved them recursively. Resolving recursively also reaches the flattened-Nested descent, which rewrites the type it is given, so the builder keeps the key's own type: an array-typed predicate over a flattened Nested leaf is not pushed, since scalar element statistics cannot decide it.

ORC built its KeyCondition from the reader header, which carries only the parent column, so the predicate degraded to unknown. ORC now passes initKeyConditionOnce a local copy extended with the tuple element paths the filter references; FormatFilterInfo, the Parquet call site and the reader header are untouched. Admission requires a named tuple at every level (unwrapping Nullable/LowCardinality/Array), which refuses Map .keys/.values: they use SubstreamType::TupleElement but have no per-element statistics.

Measurements (100k rows, one row group / stride per 10k)
Arm master this PR
ORC WHERE tup.1 = 55555 200000 rows read 20000
ORC WHERE id = 55555 (control) 20000 20000
Parquet WHERE tup.1 = 55555 7 row groups / 0 pruned 1 / 6
Parquet WHERE id = 55555 (control) 1 / 6 1 / 6

Results identical in every arm. Refusal arms (Map .keys/.values, .null, .size0, unnamed tuple, Array(Tuple), type-mismatch structure hint) return correct results with pruning off. Multi-level tup.2.1 stays unpruned: correct, and a separate optimization.

Regression sweep over *functions_to_subcolumns*, *tuple_element*, *_parquet_*, *_orc_* and the named pushdown tests, run on this build and on an unmodified master build for attribution: no regression attributable to this change. New tests are 50/50 green under randomized settings.

Also noticed, not touched here: reading a standalone dotted ORC tuple element with its inferred type returns column defaults, because Nested::flatten does not descend a Nullable(Tuple). #109741 (open) rewrites that helper for the Arrow spelling.

Version info

  • Merged into: 26.8.1.1477 (included in 26.8 and later)

WHERE tup.1 = k read every row group while the equivalent top-level
WHERE id = k pruned to one, for identical values. Three independent blockers,
measured with EXPLAIN QUERY TREE and profile events:

1. StorageFile/StorageURL/StorageObjectStorage return false from
   supportsOptimizationToSubcolumns, so tupleElement(tup, 1) is never rewritten
   to a tup.1 ColumnNode. That false is a live contract: native readers cannot
   supply .null/.size0 as standalone PREWHERE inputs (issue ClickHouse#106147, pinned by
   04303_object_storage_prewhere_isnotnull_subcolumn). Rather than flipping it,
   add the narrower supportsOptimizationToTupleElementSubcolumns, which admits
   only tuple element access, where the element is a real leaf in the file.
   Delegating storages (Proxy, Alias, Merge, Buffer, MaterializedView) forward
   it, and Queue/Cluster/Distributed keep today's false via the default.

2. FunctionToSubcolumnsPass accepted only TableNode as a column source, so
   file()/s3()/url() were skipped entirely. Route source lookups through
   helpers handling both TableNode and TableFunctionNode; the latter carries no
   storage until resolved, and getStorageSnapshot throws in that state.

3. Column identity was keyed on the storage name. Every table function
   resolves to the same StorageID (_table_function.file), so two file() sources
   in one query shared a key and mixed their optimizability counts, which
   decide whether a rewrite happens at all. Key on the table expression node
   instead, in both passes and in the outer-join guard.

ORC additionally could not resolve a dotted predicate name: the sargs path used
a top-level-only lookup while the read path in the same file already recursed.
Reuse the recursive resolver, resolve the CH type by walking the header type
down the same path, and select the resolved leaf, since liborc loads row
indexes only for selected columns.

Measured on 100k rows in 9 row groups: Parquet WHERE tup.1 = k goes from 9 row
groups read and 0 pruned to 1 read and 8 pruned, matching the top-level
baseline exactly, across Tuple, Nullable inside Tuple, Nullable(Tuple),
LowCardinality inside Tuple. Results are unchanged in every arm.
The ORC reader builds its KeyCondition from the reader header, which carries only the parent
column `tup`, so a predicate on `tup.1` had no matching key name and its RPN was already
`unknown` before buildORCSearchArgumentImpl ran. The recursive resolver added in the previous
commit was therefore never reached for the query in the issue: it worked only when a structure
hint made the header name the dotted column itself.

initKeyConditionOnce already accepts an arbitrary Block and derives the key names from it, so
the fix is local to NativeORCBlockInputFormat::prepareFileReader: hand it a local copy of the
header extended with the tuple element paths that filter_actions_dag actually references.
FormatFilterInfo is not modified and the Parquet call site is untouched, so Parquet keeps its
verified behaviour and the reader header, which drives ORCColumnToCHColumn and include_typeids,
is unchanged. Because the read path never sees the extra names, the separate pre-existing defect
where ORC returns NULLs for a standalone dotted tuple element is not reachable from here.

Admission is gated on type ancestry rather than substream kind: every level of the dotted path
must be a DataTypeTuple with explicit names, unwrapping Nullable, LowCardinality and Array.
A substream-kind gate would have admitted Map `.keys`/`.values`, which DataTypeMap builds with
SubstreamType::TupleElement but which have no per-element statistics; a blanket rejection of
non-TupleElement substreams would have dropped legitimate Array(Tuple) paths.

Measured on a 100k row file with output_format_orc_row_index_stride = 10000: ORC
`WHERE tup.1 = 55555` goes from 200000 to 20000 SelectedRows, matching the `WHERE id = 55555`
baseline exactly, with the result unchanged. Parquet `WHERE tup.1 = k` stays at the baseline's
row group counts. Refusal arms (Map keys/values, `.null`, `.size0`, unnamed tuple, Array(Tuple),
type-mismatch hint) all return correct results with pruning off. Multi-level `tup.2.1` remains
unpruned, which is correct but not yet optimized.

The three new tests assert pruning parity against the top-level control rather than absolute
counters, because the row group and stride counts depend on write settings that CI randomizes.
04303_object_storage_prewhere_isnotnull_subcolumn passes unmodified.
…down tests

The whole feature lives in FunctionToSubcolumnsPass, which is registered only in
QueryTreePassManager and has no old-analyzer equivalent. The old-analyzer CI jobs
install tests/config/users.d/analyzer.xml, which sets allow_experimental_analyzer
to 0 in the default profile, so there all three tests break: 04708 throws
NOT_IMPLEMENTED for EXPLAIN QUERY TREE, and 04706 and 04707 compare an unpruned
read against their top-level control and report no parity. Pin enable_analyzer
per query, the way the other analyzer-scoped tests in this area do.

04706 also leaves input_format_parquet_dictionary_filter_push_down to the
runner's randomization. Both arms see the same value, but id is an ascending
UInt64 that is never dictionary encoded while tup.1 holds the same values, so
pin it rather than rely on the two arms agreeing.

Verified on a server with analyzer.xml installed and on a normal one, 50 runs
each with randomization on.
buildORCSearchArgumentImpl handed its own column_type to
traverseDownORCTypeByName, which takes DataTypePtr & and rewrites it when it
descends a LIST of STRUCT (the shape a flattened Nested column has in an ORC
file): the caller's type became the array's element type. All three guards
after the descent read that value, and every one of them needs the key's own
type, the type KeyCondition's RPN was built against.

The visible effect was a query that errored where it used to answer. For
WHERE n.na = [55555] over a flattened Nested column the rewritten scalar type
made the type-equality guard compare scalar against scalar and pass, so a
scalar leaf predicate was emitted while the RPN range still held an Array
field, and evaluateRPNElement threw BAD_TYPE_OF_FIELD ("Cannot compare long
with DB::Array"). It was not gated on the new pushdown feature: the search
argument is built before input_format_orc_filter_push_down is consulted, so
all four cells of the optimize_functions_to_subcolumns x
input_format_orc_filter_push_down matrix threw. Before this PR the branch was
unreachable, because the previous resolver matched top-level fields only and
any dotted name simply disabled pushdown.

Passing the resolver a scratch copy leaves column_type alone, and the existing
type-equality guard then refuses the shape by itself: an Array key type cannot
compare equal to the type parsed from a scalar ORC leaf, so the predicate is
not pushed. That refusal is the right outcome here rather than a workaround.
Scalar element statistics cannot decide an array-typed predicate: the leaf's
min/max describe individual elements, while the predicate asks about the whole
array value. Named tuple elements are unaffected, since they resolve through a
STRUCT descent, which does not rewrite the type.

The added arms in 04707 cover the flattened Nested column in both hint shapes
and assert results in every arm, so the refusal is recorded as a measured
outcome instead of an untested one.
Resolves the single content conflict in src/Storages/StorageURL.cpp by taking the
master side.

Upstream c6f3c12 deleted the wrapper class's own
supportsOptimizationToSubcolumns override (and renamed the class to
StorageURLSchemeDispatch) because StorageProxy already forwards the subcolumn
contract. The line this branch had added next to that override therefore has no
anchor left, and re-adding it would be redundant: StorageURLSchemeDispatch is
final : public StorageProxy with getNested() returning the same nested member,
so it inherits the supportsOptimizationToTupleElementSubcolumns forward this
branch adds to StorageProxy.h. Behaviour is unchanged.
04708 asserted that two distinct table function sources keep separate
identities, but the shape it used could not distinguish the two keying
schemes: with both predicates transformable, the old shared
Identifier{_table_function.file, tup} key records 2 uses against 2
rewrites, lands in `everywhere`, and rewrites both occurrences, so it
answers 2 either way.

Add two arms where the two uses occupy different roles and there is no
WHERE, so a shared key would weigh 2 uses against 1 rewrite and qualify
for neither `everywhere` nor `filter_only`: one over two table functions,
one over a repeated real table (the node-pointer keying also reaches
TableNode). Both answer 1 with per-occurrence keying.

Verified by reverting only the keying sub-fix in a scratch build (source
back to getStorageID().getFullTableName()): both new arms drop to 0 while
the pre-existing arm stays at 2, and three single-source controls stay at
1, so the mutant is not broken-everywhere and the 0s are the pooled-count
refusal. 50 randomized runs of 04706/04707/04708 pass on both an
analyzer-ON and an analyzer-OFF server.

Tests only; no source change.
… union

Two review findings from round 5.

04708 asserted a rewrite happened in three comma-join arms, which print 0
whenever join_use_nulls is 1: a comma join builds a CrossJoinNode, and
FunctionToSubcolumnsVisitorFirstPass::enterImpl then sets
can_wrap_result_columns_with_nullable, so getIdentifiersToOptimize returns
empty and the pass switches itself off for the whole query. The setting
defaults to false and is not in clickhouse-test's SettingsRandomizer, so the
randomized runs are structurally blind to it, but ci/jobs/scripts/stress/
stress.py appends join_use_nulls=1 to --client-option for every worker with
i % 3 == 1 and then runs the full stateless suite, which makes this a
deterministic failure on roughly a third of stress workers. Pinning the
setting at the top of the test follows 62 existing stateless tests.

The sargs_column_ids union reported each pruning column id back to
prepareFileReader so the caller could add it to the read set. No shape
reaches that state: both admission paths require the predicate name to hang
off a header column, and prepareFileReader already walks every header column
through traverseDownORCTypeByName and updateIncludeTypeIds, whose STRUCT
branch inserts the id of every named element the CH tuple and the ORC struct
share, recursing down to primitives. Instrumenting the union to log the set
difference showed it added nothing on all 147 invocations of the ORC test
suite and on 35 further hand-built shapes (one-element structure hints,
predicates on unselected elements, two-level nesting, case-insensitive
matching, Array-of-Tuple and flattened Nested), while the reverse difference
over the same two sets on the same code path reported non-empty values, so
the probe was not blind. Removing the plumbing leaves the measured pruning
unchanged on every arm and restores buildORCSearchArgument's original
signature, so the header drops out of the diff entirely.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Every change here went through an independent review round before publication: a cold code
review that does not see the author's evidence, then a second-model gate, then adjudication.
Five review rounds ran on this PR; the final round found nothing substantive.

# Finding Verdict
❌ 04708 asserted a rewrite in three comma-join arms without pinning join_use_nulls. A comma join builds a CrossJoinNode, which makes FunctionToSubcolumnsPass switch itself off for the whole query, and ci/jobs/scripts/stress/stress.py appends join_use_nulls=1 for every third stress worker. The setting is not in clickhouse-test's randomizer, so ~300 randomized runs across earlier rounds were structurally blind to it. AGREE, fixed. Pinned, following 62 existing stateless tests. Verified with a four-arm matrix: the redness needs the setting, not the missing line, so the pin is load-bearing.
❌ The ORC search argument reported its pruning leaf ids back so the caller could add them to the read set, justified by an in-diff comment describing a state I could not construct: both admission paths require the predicate to hang off a header column, and prepareFileReader already selects every named element the ClickHouse tuple and the ORC struct share. AGREE, removed. Instrumented the union: it contributed nothing on 147 suite invocations and 35 hand-built shapes, with a positive control confirming the probe was not blind. Deleting it also restores buildORCSearchArgument's original signature, so its header leaves the diff.
❌ Reading a flattened Nested leaf let the type resolver rewrite the key type on its LIST descent, so a type-equality guard compared scalar against scalar and passed while the RPN still held an Array: WHERE n.na = [55555] threw BAD_TYPE_OF_FIELD where it used to answer, in all four cells of the settings matrix. AGREE, fixed. The resolver now gets a scratch copy, and the existing guard refuses the shape by itself. Both directions measured on rebuilt, Build-ID-verified binaries.
❌ The new tests did not pin enable_analyzer, so with the analyzer off 04708 threw NOT_IMPLEMENTED and the two pruning tests silently asserted the unfixed numbers. AGREE, fixed. Reproduced first, then pinned; all three pass in both analyzer arms.
⚠️ A test-liveness arm for source identity did not discriminate: it would have passed with the pre-fix StorageID-keyed identity too. AGREE, rewritten. The arms now depend on per-occurrence keying (a shared key would weigh two plain uses against one rewrite and refuse both).
💡 Accepting table functions in general also makes format(), values() and view() eligible for the other transformers. Checked and safe (those storages resolve a subcolumn name on read, so an admitted .null/.size0 resolves rather than throwing), but undocumented. AGREE, disclosed in the description rather than changed.
💡 The description promised a separate report for an unrelated Nested::flatten defect found while measuring. AGREE, rewritten to disclose it and link #109741, which already rewrites that helper, instead of promising a fresh report.

Independently verified in the final round and reported clean: the capability gate is applied at
the single funnel both analyzer passes use, so they cannot disagree about eligibility; the ORC
key block is local to one initKeyConditionOnce call and cannot leak a name into
additional_columns, which only Parquet consumes; each of the four storages left on the
inherited default is correct for its own reason; and every new test reddens for the right reason
in both directions, including the twelve refusal arms that a wrongly widened admission would
break.

Session id: cron:clickhouse-review-slot-10:20260804-185800

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local -q "SELECT count() FROM file('np.orc', ORC) WHERE tup.1 = 55555 SETTINGS max_threads=1" on a 100k-row fixture written with output_format_orc_row_index_stride = 10000, reading SelectedRows from --print-profile-events. 200000 before, 20000 after, every run.
b Root cause explained? Yes, three independent blockers. (1) StorageFile/StorageURL/StorageObjectStorage return false from supportsOptimizationToSubcolumns, so tupleElement(tup, 1) is never rewritten to a tup.1 column, and FunctionToSubcolumnsPass accepted only TableNode, skipping table functions. (2) ORC's getORCTypeByName scanned top-level fields only, so any dotted name emitted YES_NO_NULL. (3) ORC built its KeyCondition from the reader header, which carries only tup, so the predicate's RPN was already unknown before the search argument was built.
c Fix matches root cause? Yes, one change per blocker, each at the layer that owns it: a narrow storage virtual plus a TableFunctionNode source in the analyzer pass; the recursive resolver in the sargs builder; a locally extended key block at ORC's initKeyConditionOnce call site. No widened bounds, no new setting, no guard at a symptom site.
d Test intent preserved / new tests added? Three new tests: 04706 (Parquet pruning parity), 04707 (ORC pruning plus every refusal arm), 04708 (analyzer-level rewrite, including the negative arms). No existing test was modified or weakened; 04303_object_storage_prewhere_isnotnull_subcolumn, which pins the #106147 contract, passes unmodified.
e Both directions demonstrated? Yes, on two Build-ID-verified binaries. All three new tests FAIL on an unmodified master build and PASS on this build. Numerically, ORC 200000 -> 20000 and Parquet 7 row groups / 0 pruned -> 1 / 6, both matching their top-level-column control exactly, results unchanged.
f Fix is general across code paths? Yes. Both entry points of the analyzer pass and both the gate and the identity key were updated; the five delegating storages (StorageMerge, StorageBuffer, StorageAlias, StorageMaterializedView, StorageProxy) forward the new virtual, and StorageMerge-over-ENGINE=File is tested. StorageObjectStorageQueue/IStorageCluster/StorageDistributed deliberately do not opt in. ORC's prune path now resolves names through the same recursive walk the read path already used, removing the asymmetry rather than patching one call.
g Fix generalizes across inputs? Yes. Tuple, Tuple(Nullable), Nullable(Tuple), Tuple(LowCardinality) all prune identically to the control. Refused, with correct results and pruning off: Map .keys/.values, .null, .size0, positionally-named tuples, Array(Tuple) elements, and a structure hint whose element type disagrees with the file. Multi-level tup.2.1 stays unpruned, which is correct and asserted. A flattened Nested leaf resolves, but an array-typed predicate over it (n.na = [55555]) is refused, because the leaf's statistics describe individual elements and cannot decide a whole-array comparison; has(n.na, 55555) over the same column is correct in both hint shapes.
h Backward compatible? Yes. No setting default changes, so no SettingsChangesHistory.cpp entry is required. The new virtual defaults to supportsOptimizationToSubcolumns, so every storage that does not override it keeps today's behaviour exactly.
i Invariants and contracts preserved? The invariant is that an ORC predicate over a tuple element prunes using that element's own statistics or does not prune at all, never using another column's. It is upheld by admitting only named-tuple paths and by the existing type-equality guard at the search-argument level (tested with a deliberately mismatched hint). liborc loads row indexes only for selected columns, and the read set already covers every accepted leaf: prepareFileReader walks each header column through updateIncludeTypeIds, whose STRUCT branch inserts the id of every named element the ClickHouse tuple and the ORC struct share, and both admission paths require the predicate to hang off a header column. Measured on 147 suite invocations and 35 hand-built shapes, an explicit union of the pruning leaf ids into the read set added nothing, so no such plumbing is present. Every failure mode degrades to YES_NO_NULL, meaning a full scan with correct results. The resolver is handed a scratch copy of the key type, so its LIST descent cannot rewrite the type the guards judge, which is what keeps that degradation total. The reader header is not mutated, so ORCColumnToCHColumn and include_typeids see exactly what they saw before.

Session id: cron:clickhouse-review-slot-10:20260804-185800

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @KochetovNicolai, could you review this? Filter pushdown was lost for Tuple subcolumns over file()/s3()/url() for three independent reasons: the analyzer never rewrote tupleElement(tup, 1) to tup.1 because those storages opt out of the rewrite wholesale, ORC's search argument builder resolved top-level field names only so every dotted predicate name emitted YES_NO_NULL, and ORC built its KeyCondition from a header carrying only the parent column.

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7d6ab6e]

Summary: ✅


AI Review

Summary

This PR extends optimize_functions_to_subcolumns so file-like storages can rewrite tuple-element predicates into subcolumn reads and lets ORC build filter pushdown for those rewritten paths. The main path looks solid, but I do not think it is merge-ready yet: there is still one new correctness regression under case-insensitive readers, and one previously-discussed Parquet regression on hidden dotted-name collisions remains intentionally unfixed.

Missing context / blind spots
  • ⚠️ I could not run a local repro because this checkout does not contain a built clickhouse binary, so the review relies on tracing the current source paths through the analyzer and the ORC/Parquet readers.
Findings

❌ Blockers

  • [src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp:430-435] The new collision guard only checks dotted-path ambiguity and top-level columns, so it still rewrites case-insensitive sibling collisions inside the tuple itself. A tuple such as Tuple(`A` UInt64, a UInt64) is legal, getSubcolumnForElement picks the exact a element, but ORC's traverseDownORCTypeByName and Parquet's case-insensitive name matching cannot distinguish A from a once the query has been flattened to t.a. Before this PR the same tupleElement(t, 'a') query stayed on the whole tuple and was exact; after the rewrite it can return the wrong sibling or raise DUPLICATE_COLUMN.
    Suggested fix: refuse the rewrite when another sibling element name matches the chosen element case-insensitively, and add ORC/Parquet regressions with input_format_*_case_insensitive_column_matching = 1.

⚠️ Majors

  • [src/Analyzer/Passes/FunctionToSubcolumnsPass.cpp:431-435] [dismissed by author -- https://github.com/Push tuple element predicates into Parquet and ORC subcolumn reads #113383#discussion_r3785526601] The analyzer is still blind to a colliding top-level a.b column that exists only in the physical Parquet file and is omitted from an explicit structure hint. In that shape, this PR still rewrites tupleElement(a, 'b') to a.b, turning a query that succeeds with optimize_functions_to_subcolumns = 0 into DUPLICATE_COLUMN. The new 04873 coverage pins the current failure mode, but it does not restore the previous behavior.
    Suggested fix: carry the "this requested name is a subcolumn path" bit through prepareReadingFromFormat into the Parquet/ORC readers, or otherwise fail closed only for declared-schema reads where the physical schema cannot be proven collision-free.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.70% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 305/335 (91.04%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 4, 2026
The rewrite turns tupleElement(t, 'x') into a column named `t.x`. That name is flat,
so it no longer records whether the element was reached in one step or by descending.
For a tuple holding both `a.b` and an `a` with a `b` element, two different elements
flatten to `t.a.b`, and the consumers of that name disagree:

  - DataTypeTuple::tryGetPositionByName matches an element name exactly, so
    isNamedTupleElementPath and findHeaderTypeByPath bind the flat `a.b` element;
  - traverseDownORCTypeByName's search_struct_field matches by prefix and returns the
    first prefix-matching subtype, so it binds nested a -> b.

Before this PR the mismatch was unreachable from file()/s3()/url(), because those
storages returned supportsOptimizationToSubcolumns() == false and the rewrite never
reached a file format. Enabling it for tuple elements made the ambiguity live, in two
ways, on Tuple(a Tuple(b UInt64), `a.b` UInt64) holding ((111), 999):

  - ORC returned 111 for tupleElement(t, 'a.b') instead of 999, and filtered the wrong
    way in both directions (2 -> 0 rows for = 999, 0 -> 2 rows for = 111);
  - Parquet rejected the query with DUPLICATE_COLUMN, because its reader refuses the
    ambiguous name outright.

Only one field order misbinds in ORC, since the prefix walk stops at the first match,
so both orders are covered by the tests.

Refuse the rewrite for such an element instead of teaching the ORC walk to prefer an
exact match: the walk is a shared read path, the ambiguity predates this PR there
(SELECT t.`a.b` already returns 111 on master), and changing it would not address
Parquet. tupleElement is then evaluated on the whole tuple, which is what master did.
Non-colliding dotted element names and nested access keep the optimization.

Verified with three binaries. The gated build matches master on every collision query;
the pre-gate build is wrong on four of them; a mutant that neutralizes only the
predicate reddens all three tests (04707 on results and filtering, 04706 on
DUPLICATE_COLUMN, 04708 on the rewrite itself). Reverting the mutant returns the build
id to the verified value.

Reported by clickhouse-gh[bot] in review of ClickHouse#113383.
traverseDownORCTypeByName lowercases both the target and the field names when
input_format_orc_case_insensitive_column_matching is set, so `A` and `a.b` in one tuple
are as ambiguous as `a` and `a.b`. The guard was matching element names case
sensitively and admitted that shape.

The wrong-results consequence does not reproduce there: with a case-differing structure
hint the element still reads 999 and filters 2/0 rows on the pre-guard build, in both
field orders. The guard is widened anyway because it is meant to describe when the
flattened name is ambiguous, and refusing is the conservative side.

Reported by clickhouse-gh[bot] in review of ClickHouse#113383.
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

This PR is scoped entirely to the functions-to-subcolumns analyzer pass, extending tuple-element pushdown to table functions (file()/s3()/url()) and file formats like Parquet/ORC; it leaves the regular table query path unchanged. All four flagged improvements — clickbench Q17 (-11.2%), clickbench Q23 (×2.3 faster), tpch Q7 (×8.1 faster), and tpch Q8 (×2.2 faster) — run over ordinary tables with no tuple columns or file sources, so none of them exercise the changed code. With only 6 source runs (and Q23's measurements especially noisy), these deltas are run-to-run variance, not real PR effects, and have been downgraded to not_sure.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 494 -11.2% <0.0001 This PR only extends the tuple-element functions-to-subcolumns rewrite to file()/URL sources; ClickBench Q17 reads a flat table with no tuples, so the -11.2% is run-to-run variance, not a PR effect.
⚠️ 23 not_sure 167 74 ×2.3 faster <0.0001 The ×2.3 faster reading is off-path: this query does not exercise the changed tuple-subcolumn code, and the source measurements here were very noisy, so treat it as variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 574 71 ×8.1 faster <0.0001 ×8.1 faster on a join-heavy query the PR cannot touch — the tuple-element-on-files change does not apply to these tables, so this is variance rather than a real PR gain.
⚠️ 8 not_sure 175 81 ×2.2 faster <0.0001 ×2.2 faster is unrelated to this PR: the change only affects tuple-element pushdown for file()/URL sources, not the TPC-H join query path.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: e0c1ab54-e0a4-48e5-b58e-88e2dce2af27
  • MIRAI run: 9686d7b2-ff8d-417c-9986-809b872a1ceb
  • PR check IDs:
    • clickbench_1407290_1786802438
    • clickbench_1407296_1786802438
    • clickbench_1407307_1786802438
    • tpch_adapted_1_official_1407314_1786802438
    • tpch_adapted_1_official_1407331_1786802438
    • tpch_adapted_1_official_1407360_1786802438

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3128949

Every failure below has an owner: a fixing PR (ours 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
Upgrade check (amd_release) / Error message in clickhouse-server.log DiskLocalCheckThread probe-file race: two DiskLocal objects for one configured disk probe the same clickhouse_disk_checker_<ServerUUID> path, so one unlinks the file the other is reading (Code: 33 CANNOT_READ_ALL_DATA here; the same cause also renders as Code: 107 and Code: 458). Breadth 444 rows / 281 PRs / 0 master in 14 days. #110773 (ours, open)
Build (arm_release) / Post Hooks infra: the build-profile telemetry INSERT into the shared CI logs cluster is rejected (Code: 241), so build_profile_hook.py fails closed. Fleet-wide since 2026-08-03 (2391 rows / 575 PRs / 1336 master in 7 days). #113409 (external, open)

Neither is PR-caused: this PR touches Parquet/ORC tuple-subcolumn pushdown and the analyzer,
and its diff contains no disk, upgrade-path or CI-hook file.

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

The test consumed 80-84% of the 180s stateless budget on public CI (145s on the
amd_asan_ubsan flaky check, 151s on amd_msan/WasmEdge), so any slower
configuration crosses the cutoff and bounces the PR from the merge queue. The
cost was harness overhead, not coverage.

Each of the 14 labels ran two client invocations: the measured query, then a
second one issuing SYSTEM FLUSH LOGS query_log and scanning system.query_log for
ProfileEvents['SelectedRows']. The flush is a blocking wait on a background
flush (SystemLogQueue::waitFlush), and query_log's sort key is
event_date, event_time, so a query_id predicate prunes nothing and every scan
reads the whole 10-minute tail that all concurrent workers are writing.

Ask the query to report its own read-row count instead: FORMAT JSON exposes
statistics.rows_read, which is the same accumulated Progress::read_rows that
feeds SelectedRows. That removes 14 blocking flushes, 14 whole-tail scans and 14
client invocations -- 33 client calls become 19. The idiom and its reference
shape follow 04326_parquet_v3_dictionary_filter_push_down.

The fixture also drops from 100000 rows at a 10000-row index stride to 20000 at
2000, keeping 10 strides so pruning stays observable at a fifth of the data.

Measured on one debug binary and server, arms interleaved to cancel box-load
drift: p50 7.05s -> 4.02s at one worker and 5.11s -> 3.48s at sixteen, faster in
11 of 12 pairs; server-side CPU per run 125ms -> 76ms, of which the fixture
reduction accounts for the whole difference. 50 randomized runs pass with
durations in 3.54-4.04s.

Both halves stay pinned. Disarming the flattened-name ambiguity guard in
FunctionToSubcolumnsPass still reddens the collision lines (999 111 / 2 0
becomes 111 111 / 0 2), and refusing every named tuple element path in the ORC
reader still reddens the pruning lines (2000 becomes 20000) -- disjoint
failures, so neither oracle rests on the other.

use_cache_for_count_from_files and optimize_count_from_files were considered as
pins and dropped: both read identically at 0 and 1 for these queries, because a
WHERE clause disables the metadata-only count shortcut they govern. No
max_block_size pin is needed either -- unlike Parquet row groups, the ORC index
stride is a writer-internal counter, and every label is byte-stable across the
runner's whole 8000-100000 randomization range.

The two check_collision assertions are untouched, byte for byte.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Test-only follow-up: 04707 was consuming 84% of the 180s stateless budget

04707_tuple_subcolumn_pushdown_orc, added by this PR, ran at 145s on
Stateless tests (amd_asan_ubsan, flaky check)
(n=100, p90 136s) and 151s on
(amd_msan, WasmEdge, parallel, 1/2)
against the hard 180s per-run cutoff
(TEST_MAX_RUN_TIME_IN_SECONDS, tests/clickhouse-test:198, enforced at :3566-3572). I
re-measured both figures on play.clickhouse.com and they reproduce exactly. About 30s of
headroom means the test was green by luck, and the merge-queue flaky job is not allow_failure,
so crossing the cutoff bounces the PR from the queue. The Parquet sibling 04706 is fine and
untouched: it peaks at 42s, 23% of the budget.

The cost was harness overhead, not coverage. Each of the 14 labels ran two client invocations: the
measured query, then a second one issuing SYSTEM FLUSH LOGS query_log and scanning
system.query_log for ProfileEvents['SelectedRows']. That flush blocks on a background flush
(SystemLogQueue::waitFlush, whose comment names parallel-functional-test disk load as why its
timeout had to grow), and query_log is sorted by event_date, event_time, so the query_id
predicate prunes nothing and every scan reads the whole 10-minute tail all concurrent workers
write.

So the query now reports its own read-row count: FORMAT JSON exposes statistics.rows_read, the
same accumulated Progress::read_rows that feeds SelectedRows. That drops 14 blocking flushes,
14 whole-tail scans and 14 client invocations, taking 33 client calls to 19, following
04326_parquet_v3_dictionary_filter_push_down. The fixture also goes from 100000 rows at a
10000-row index stride to 20000 at 2000, keeping 10 strides so pruning stays observable on a fifth
of the data.

Measured on one debug binary and server, arms interleaved to cancel box-load drift: p50 7.05s to
4.02s
at one worker and 5.11s to 3.48s at sixteen, faster in 11 of 12 pairs; server-side CPU
per run 125ms to 76ms. 50 randomized runs pass in 3.54-4.04s, against a 13-85s spread for the
old test in the same harness. Local absolute seconds are well below CI's, so the ratios and the
removed-work counts are the transferable numbers, not the wall clock.

Both oracles stay pinned, verified by mutation: disarming the flattened-name ambiguity guard in
FunctionToSubcolumnsPass still reddens the collision assertions (999 111 / 2 0 becomes
111 111 / 0 2), and refusing every named tuple element path in the ORC reader still reddens the
pruning ones (rows_read 2000 becomes 20000). Disjoint failures, so neither oracle rests on the
other. All 14 labels keep their pruning / non-pruning classification, and both check_collision
assertions are byte-for-byte unchanged (md5 identical to this PR's previous head, with a negative
control confirming the comparison discriminates).

Two settings pins were considered and dropped after measuring that they change nothing here,
because a WHERE clause disables the metadata-only count shortcut they govern. No max_block_size
pin is needed either: unlike Parquet row groups, the ORC index stride is a writer-internal counter,
so every label is byte-stable across the runner's whole 8000-100000 randomization range.

The 180s constant is untouched, the PR body and changelog are unchanged, and the test takes no
long or no-parallel tag.

Internal second-model review (click to expand)

Independent cold review of the resulting code plus an independent second-model pass, adjudicated
against the recorded evidence. This push is a two-file test-only change; the second-model pass ran
without a delta base, so it re-reviewed all 19 files of the PR, including the merged source half.

# Finding Verdict
❌ The PR-body draft accompanying this push was a comment draft, but the publish path reads that file unconditionally and would have rewritten this PR's title and body from it, dropping the Changelog category and Changelog entry sections. AGREE, fixed before publishing. The draft was rebuilt from this PR's live title and body so the edit is a byte-level no-op; verified by round-tripping through the exact publish transform and by executing both CI consumers (get_category, check_changelog_entry) with negative controls. The PR body and changelog you see are unchanged.
⚠️ tupleElementNameIsAmbiguousWhenFlattened refuses a dotted element whenever any top-level element shares the first path component, so Tuple(a UInt64, a.b UInt64) is refused even though only a.b can match. DISAGREE for this push. Real, but out of this diff (the source half is already merged in this PR) and the consequence is a non-firing optimization, not wrong results: I traced the ORC prefix walk, which binds field a, recurses with b against a scalar type, matches neither the STRUCT nor the LIST branch and returns nullptr, so the builder emits YES_NO_NULL and simply does not prune. The guard is deliberately fail-closed because loosening it is the direction that produced the wrong-results bug this PR fixes. Not something to loosen inside a duration fix.
⚠️ Tuple-element pushdown stays disabled for Nullable(Tuple(...)), since admission requires the exact Tuple type index, which reads as inconsistent with the ORC path's wrapper unwrapping. DISAGREE. The two layers answer different questions: the analyzer gate is a deliberately minimal widening for storages that otherwise refuse subcolumn rewrites (a blanket allow reintroduces #106147), while the reader's Nullable/LowCardinality/Array transparency applies to an already-rewritten path where a flattened Nested leaf legitimately arrives wrapped. Extending the gate is a feature change with its own nullable-typing question, not a defect in this push.
⚠️ The ORC refusal cases assert only rows_read = 20000, which is said to be indistinguishable from ORC pushdown being declined globally. DISAGREE, refuted by measurement. The three positive controls sit in the same file three lines above and assert rows_read = 2000; a global decline would redden them, so it is the one hypothesis this test cannot pass under. It is also empirically pinned: making the reader's named-tuple-element admission runtime-false moves rows_read 2000 to 20000 and fails the test, on a binary whose Build ID moved and then returned exactly.
💡 The Parquet sibling 04706 carries the same flush-and-scan mechanism and had never been measured, since the original duration table matched 04707% only. Checked and closed. Measured directly: 42s peak on the tightest arm, 23% of the budget and 3.4x clear of the cap. Correctly out of scope.
💡 The reference embeds the JSON statistics block, so it depends on output_format_write_statistics and output_format_json_quote_64bit_integers keeping their defaults. Noted, no action. Neither is randomized by the test runner nor overridden by any installed test profile, and 20 in-tree stateless tests already assert on .statistics.rows_read through this same filter.

The two out-of-scope source findings are disclosed here rather than filed: both are non-firing
optimizations for exotic schemas, with no user-visible misbehaviour.

Session id: cron:clickhouse-review-slot-50:20260805-135300

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. This is a duration failure, not a flake: cd tests && ./clickhouse-test 04707_tuple_subcolumn_pushdown_orc --binary <bin> --test-runs 1 --order random. First baseline run of the unmodified test on this debug build: 117.06s. The 180s gate itself needs --flaky-check with test_runs > 1 (tests/clickhouse-test:3566-3572, all four conjuncts), so the reproducible quantity is per-run wall clock on a fixed binary and server.
b Root cause explained? Harness overhead, not coverage. Each of 14 labels ran two client invocations: the measured query, then one issuing SYSTEM FLUSH LOGS query_log plus a system.query_log scan for ProfileEvents['SelectedRows']. That flush blocks on a background flush (SystemLogQueue::waitFlush, SystemLogBase.cpp:183-208), and query_log is sorted by event_date, event_time, so the query_id predicate prunes nothing and each scan reads the whole 10-minute tail every concurrent worker is writing. Second multiplier: a 100000-row fixture where the oracle needs strides, not rows.
c Fix matches root cause? Yes: the removed cost is the root cause. FORMAT JSON + statistics.rows_read lets the query report its own read-row count, deleting 14 blocking flushes, 14 whole-tail scans and 14 client invocations (33 client calls to 19); the fixture goes 100000 rows at stride 10000 to 20000 at stride 2000, keeping 10 strides. No band-aid: the 180s constant is untouched, and no long, no-parallel, widened bound or deleted case.
d Test intent preserved / new tests added? Preserved, measured per label. All 14 labels keep their pruning / non-pruning classification (3 pruning read exactly 1/10 of the file in both fixtures, 11 non-pruning read it fully), every count() scales exactly as the modulo arithmetic predicts, and the no-fasttest tag stays. The reference was regenerated by running, never hand-computed.
e Both directions demonstrated? Yes, by mutation. M1 (ambiguity guard in FunctionToSubcolumnsPass made runtime-false) reddens the collision assertions: 999 111 / 2 0 becomes 111 111 / 0 2. M2 (isNamedTupleElementPath in the ORC reader made runtime-false) reddens the pruning assertions: rows_read 2000 becomes 20000. Disjoint failures, so neither oracle rests on the other. Both mutants also redden the pre-change test, so detection was neither gained nor lost. Pristine passes 50/50. After restoring, the Build ID returned exactly to its pre-mutant value.
f Fix is general across code paths? N/A: test-only diff, no source path changed. The 04706 Parquet sibling is deliberately out of scope, and its margin is now measured rather than assumed: it peaks at 42.1s on Stateless tests (amd_asan_ubsan, flaky check) (n=100, p90 38.8s), i.e. 23% of the 180s budget and 3.4x clear of the cap, against 04707's 145s. Its oracle is the Parquet row-group counters, so touching it would be unrequested churn.
g Fix generalizes across inputs? Yes. max_block_size is the one relevant randomized setting (tests/clickhouse-test:1549, randint(8000, 100000); grep -c output_format_orc in the runner is 0). Swept 8000 / 8192 / 12345 / 20000 / 33333 / 65409 / 100000 on the INSERT side and 8000 / 8192 / 20000 / 65409 / 100000 on the SELECT side, both fixtures: every label byte-stable, so no pin is needed. Unlike Parquet row groups, the ORC index stride is a writer-internal counter (ORCBlockOutputFormat.cpp:709). 75 randomized runs all byte-identical.
h Backward compatible? N/A: test-only. No setting default, no SettingsChangesHistory.cpp, no serialization change, no gate.
i Invariants and contracts preserved? Yes. The invariant is that every assertion still discriminates what it discriminated: rows d and e cover that. The two check_collision assertions, which guard the merged wrong-results fix, are byte-for-byte identical to the pre-push file: md5 9d93310adf2719a519af85acfe84a65a on both sides, 26 lines each, empty diff, with a negative control confirming a one-character mutation does diff. tests/clickhouse-test is untouched.

Session id: cron:clickhouse-review-slot-50:20260805-135300

The test emitted nothing and failed `having stderror` on every CI arm.
`label` is a jq keyword (`label $out | ...`), and jq 1.6 rejects it as a
variable name, so `--arg label` plus `$label` is a compile error there.
jq exits, the pipe closes, and the still-writing client dies with
`Code: 75 ... Broken pipe`. The CI stateless image is Ubuntu 22.04
(jq 1.6); this box is 24.04 (jq 1.7), which accepts the name, which is
why it passed locally and failed in CI.

Renaming the variable to `name` is enough. The object key stays `label`,
so the reference file is unchanged. Quoting the key instead does not
help: jq 1.6 rejects the variable, not the key.

Measured against a real jq 1.6 binary: pre-fix produces 0 of the 14
assertion lines and 14 compile errors, post-fix produces all 14 with an
empty stderr, byte-identical to the committed reference and to the same
script under jq 1.7.

This does not change what the test measures, and it does not change how
long it takes: the queries already ran to completion server-side and the
client only died writing results, so the reported durations stand.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed a65f25f1b41f2f0: a one-line test fix for the having stderror failures.

04707_tuple_subcolumn_pushdown_orc was emitting none of its 14 assertion lines and failing on
every arm. label is a jq keyword (label $out | ...), and jq 1.6 rejects it as a variable
name, so --arg label together with $label is a compile error. jq exits, the pipe closes, and
the still-writing client dies with Code: 75 ... Broken pipe on stderr, which is why sub-6-second
runs failed too. The stateless image is Ubuntu 22.04 (jq 1.6) while my box is 24.04 (jq 1.7), which
accepts the name, so it passed locally and failed here.

Renaming the variable to name is the whole fix. The object key stays label, so the reference
file is unchanged.

One correction worth recording: quoting the key ({"label": ...}) does not help. Measured
against a real jq 1.6 binary, {"label": $label} fails with the identical error, because the
rejected token is the variable, not the key. Isolated per token: {label: "x"} and
{"label": "x"} both compile on 1.6; anything using $label does not.

Verified both directions against real jq 1.6 and jq 1.7:

script jq 1.6 jq 1.7
before 0 of 14 assertion lines, 14 compile errors, 9463 B stderr 14 of 14, empty stderr
after 14 of 14, empty stderr 14 of 14, empty stderr

Post-fix stdout under jq 1.6 is byte-identical (md5 783fd5d4) to the same script under jq 1.7 and
to the committed reference, and the pruning oracle still separates 2000 from 20000 rows. Since the
delta touches only the jq invocation, leaving every query, setting and expected value untouched,
the earlier mutation results still hold. 50/50 randomized runs pass, max 4.13 s.

Two things this does not fix, to be clear about scope:

  • It is duration-neutral. The client completes each query server-side and only dies while
    writing results, so wall clock is unchanged (3.53 s to 3.63 s locally). The arm_asan_ubsan
    durations reported earlier were measured on runs that aborted at the first jq call, so they are
    not a reading of the test's real cost; that has to be re-measured now that it runs clean.
  • The Fast test (arm_darwin), Build (arm_release) and Integration tests (amd_msan) failures at
    the previous head are unrelated to this test and are tracked separately.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a65f25f

Every failure below has an owner: a fixing PR (ours 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
Build (arm_release) / Post Hooks infra: build_profile_hook.py fails closed when the build-profile telemetry INSERT into the shared CI logs cluster is rejected (LogCluster query failed with code 500 / No connection to LogCluster). Not PR-caused and not gating: the Build (arm_release) check-run itself is green, only this CIDB row is red. #113409 (external, merged 2026-08-06T00:05:00Z) — arrives here with the next master merge, see below

This is the only failure on this head.

Fix-presence probe for the owner, by content rather than commit distance: this head's
ci/jobs/scripts/log_cluster.py is 11916 bytes with no data.seek(0) and one retries= site,
whereas current master is 12698 bytes with data.seek(0) and four of them (positive control
master, negative control the merge parent, both discriminating). So the merged fix is genuinely not
in this build. No re-run is needed to prove it works: master's own Build (arm_release) /
Post Hooks reds fell from 4 per hour at 01:00Z to 0 by 05:00Z today, and the next master merge
picks the fix up here.

Gates: (a) 175 check-runs, 0 queued/in_progress/pending/waiting; (b) Finish Workflow and
Config Workflow both success; (c) last completion 04:51:50Z, >20 min buffer; (d) the failure above
has an owner.

Session id: cron:our-pr-ci-monitor:20260806-050000

@PedroTadim PedroTadim assigned PedroTadim and unassigned PedroTadim Aug 7, 2026
@PedroTadim

Copy link
Copy Markdown
Member

This PR is too large, forget it

@groeneai

Copy link
Copy Markdown
Collaborator Author

Leaving it as it stands then, no split.

CI restarted on the reopened head a65f25f1b41f, and the diff is unchanged since 2026-08-05. I will follow up here with the run result.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a65f25f

Every failure below has an owner: a fixing PR (ours 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 (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found deadlock: DROP TABLE prometheus parked in waitTableFinallyDropped (is_cancelled: 1, single thread, elapsed 1942 s) while the materialized shared subquery still holds a reference; DROP DATABASE ... SYNC queues behind its DDLGuard #114326 (external, merged 2026-08-12T01:14:16Z) - absent from this build, see below
Stress test (arm_asan_ubsan) / Sanitizer (STID: 1367-26c6) LeakSanitizer, all-indirect / zero-direct: Context::createCopy retain cycle reached via the materialized-CTE plan step (issue #114288) #113397 (external, open)
Stress test (arm_asan_ubsan, s3) / Sanitizer (STID: 1367-26c6) same signature as above, second arch flavour #113397 (external, open)
Build (arm_release) / Post Hooks infra: build_profile_hook.py fails closed when the build-profile telemetry INSERT into the shared CI logs cluster is rejected (LogCluster query failed with code 500, 8 retries exhausted). Non-gating - the Build (arm_release) check-run itself is green. a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable)

None of these is PR-caused: this PR touches Parquet/ORC tuple-subcolumn pushdown and the analyzer,
and its diff contains no compression, DDL, PromQL or CI-hook file.

#114326 is merged but not in this build, so a re-run picks it up. Verified from the run itself
rather than from commit distance: the job merged 50 master commits and 86e654b8459485b3448552b802f6934b4f66c15b
is not among them, and the run still executed 04811_promql_topk_bottomk_limitk.sql (the very test
file that revert deletes, present 6 times in job.log). The hung query in hung_check.log is
DROP TABLE prometheus with log_comment: 04811_promql_topk_bottomk_limitk.sql-test_d9m0b6x6z5w8,
which is exactly the signature #114326 removes. I will merge master here so CI re-runs with the fix.

⚠️ For anyone triaging this signature from CIDB: test_context_raw keeps the tail of
hung_check.log, so the processlist block that names DROP TABLE prometheus is truncated away and
only the post-mortem stack appendix survives. Read hung_check.log from S3, not the CIDB context.

#113397's fix is genuinely absent from this build, so this red is not evidence against it:
src/Processors/QueryPlan/MaterializingCTEStep.h at this head is blob
97935ebf769dbdec2b41784109abd94b30406259, which is that PR's exact pre-image.

Gates: (a) 351 check-runs, 0 incomplete non-exempt; (b) Finish Workflow and Config Workflow both
success; (c) last completion 05:50:22Z, >20 min buffer; (d) every line above has an owner.

Session id: cron:our-pr-ci-monitor:20260812-063000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7762cb3

Every failure below has an owner: a fixing PR (ours 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 (arm_tsan) / Logical error: Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t> (STID 1499-2747) chronic trunk regression in array-lexicographic comparison, not caused by this diff; the abort is at src/Functions/FunctionsComparison.h:1485 in executeArrayLexicographicEqualityImpl, reached through executeImplDryRun from an EXPLAIN; 50 unrelated PRs and 2 master runs carry it in 45d #113609 (ours, open) - it fixes exactly src/Functions/FunctionsComparison.h for this signature

All other 175 checks are green or skipped (161 success / 14 skipped / 1 failure).
The Build (arm_release) / Post Hooks CIDB rows are marked FAIL while the check itself
concluded success - the fleet-wide LogCluster query failed with code 500 telemetry noise on a
passing job, not a test failure.

This supersedes the ledger for a65f25f1b41f: that run's hung check is gone (external #114326
is now in the tested tree), and the two LSan reds owned by #113397 did not recur.

Session id: cron:our-pr-ci-monitor:20260812-120000

…-tuple-subcolumn-pushdown

# Conflicts:
#	src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp
… top-level name collision

A reader with case-insensitive column matching (e.g.
`input_format_orc_case_insensitive_column_matching`) binds a flattened
subcolumn name like `a.b` to a top-level column `A.B` that differs only
by case. `sourceHasColumn` checked exact-case names only, so the rewrite
of `tupleElement(a, 'b')` to `a.b` could hand such a query to the reader,
where it resolves to the wrong physical column (for Parquet it throws
`DUPLICATE_COLUMN` on the ambiguity). Skip the rewrite when any top-level
source column matches the flattened name up to case, mirroring the existing
case-insensitive intra-tuple ambiguity guard.

ClickHouse#113383 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7d6ab6e7c with master 6d0a17390 (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 693.26 MiB 690.24 MiB -3.01 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

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

Job report

The test wrote and read the fixed names 04873_collision.orc and
04873_collision.parquet in the server-global user_files directory with
engine_file_truncate_on_insert = 1. The flaky check runs many concurrent copies
of the same test, so one copy truncated the file another copy was reading,
giving INCORRECT_DATA on 4 sanitizers (the parallel jobs run a single copy and
stayed green, which is why this only showed up on the flaky check).

Scope the four file-backed arms to currentDatabase(), which CI makes unique per
run: with no --database argument, clickhouse-test creates a fresh random
test_<12ch> database for each run. This is the same uniqueness source the
sibling 04706/04707 shell tests use via CLICKHOUSE_TEST_UNIQUE_NAME, and
matches 51 existing 0_stateless SQL tests that build file() paths this way.

Kept as .sql instead of converting to .sh so the file's top-level SET block
keeps applying to every statement.

Verified with the flaky-check shape (--test-runs N --jobs M): the old fixed
names fail 7/12 and 25/40, the scoped names pass 12/12 and 40/40, and 40 runs
produce 40 distinct ORC and 40 distinct Parquet paths with no leftovers.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8db4d5d

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.

CI is fully finished on this head and there are no failures to own: 163 successful checks,
14 skipped (each with a praktika reason), 0 dropped jobs, praktika top-level status OK,
Finish Workflow and Config Workflow both green. CIDB confirms 0 FAIL/ERROR rows across
165 checks at this SHA.

Check / test Reason Owner / fixing PR
(none) - -

The previously reddening 04873_tuple_subcolumn_pushdown_case_insensitive_collision now passes
50/50 in every flaky-check arm (amd_debug, amd_binary, amd_tsan, amd_msan, amd_asan_ubsan),
against 6/34, 5/31, 2/48 and 2/48 failures on the prior head. It also passes in the parallel,
distributed plan, s3 storage and llvm_coverage arms.

Session id: cron:our-pr-ci-monitor:20260813-150000

… column

The collision guards in `optimizeTupleOrVariantElement` read the storage snapshot, which for
file-like table functions is the structure the query declared. A declared structure may omit a
physical top-level column whose name equals the flattened tuple-element path, and then the
collision is invisible to the analyzer and only the reader meets the ambiguous name.

Pin both readers on that input, so neither can start returning the colliding top-level column
instead of the tuple element: ORC binds the tuple element and prunes on it, and Parquet refuses
the ambiguous name with `DUPLICATE_COLUMN` instead of guessing. Declaring the colliding column
brings the collision back into view and the guard blocks the rewrite, so the read succeeds.
A nested element is addressed by its flattened path, so `a.b` matches both the tuple element
`a`.`b` and a top-level column literally named `a.b`. The bare `DUPLICATE_COLUMN` message does
not hint at that, which is the confusing half of the case above: a read that asks for a tuple
element by its flattened name fails on a file that also holds the dotted top-level column.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed c70ec17417ce + ec129d58dbd0 for the AI-review Major on 8db4d5d9 (declared structure hides the colliding top-level column). Answered in the thread: #113383 (comment)

Short version, all measured on a build of this head: neither reader returns the wrong column — ORC binds the tuple element and prunes on it, Parquet refuses the ambiguous name with DUPLICATE_COLUMN. The suggested analyzer-side fail-close was implemented and dropped: the only bit the analyzer can act on is "structure declared rather than inferred", which removes the pushdown from every CREATE TABLE ... ENGINE = File/URL/S3 table and from the hinted arms of 04707/04708, trading a loud error on a pathological file for a silent, permanent loss of pruning. Instead, 04873 now pins both readers on exactly that input (so a future silent mis-bind goes red), and the Parquet error says why the name is duplicate. The precise fix is to carry "this name is a subcolumn path" through prepareReadingFromFormat into SchemaConverter / traverseDownORCTypeByName; that is format plumbing for a separate PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 7d6ab6e

CI is fully finished on this head and there are no failures to attribute: 162 checks succeeded, 15 skipped, 0 failed. The praktika report for this head is OK with 0 dropped jobs, and CIDB agrees (0 FAIL/ERROR rows for this commit).

Check / test Reason Owner / fixing PR
- no failures at this head -
Sync - CH Inc sync (private, not actionable)

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

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into ClickHouse:master with commit 9744b07 Aug 15, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 21, 2026
Reading a tuple element through a positional structure hint returned default
values instead of the file's data:

    INSERT INTO FUNCTION file('p.parquet', Parquet, 't Tuple(x UInt64, y String)')
    SELECT tuple(number, toString(number)) FROM numbers(3);

    SELECT tupleElement(t, 1) FROM file('p.parquet', Parquet, 't Tuple(UInt64, String)');
    -- returned 0, 0, 0 instead of 0, 1, 2

WHERE tupleElement(t, 1) = 1 matched no rows, and with
input_format_parquet_allow_missing_columns = 0 the query failed with
THERE_IS_NO_COLUMN.

An unnamed DataTypeTuple synthesizes its element names as the ordinals "1",
"2", ..., so optimize_functions_to_subcolumns rewrote tupleElement(t, 1) to the
flattened subcolumn t.1. The three existing guards at that site consult the
storage snapshot, which is built from the structure argument and therefore does
contain t.1, so they all passed. The Parquet reader then resolves a flattened
element name by string against the file's real field names t.x and t.y, found no
match, and substituted a synthetic missing column filled with defaults. The
asymmetry is by design in the reader: hasExplicitNames() selects lookup by name,
otherwise tuple elements are matched sequentially, so the whole tuple resolves
positionally while a flattened element name only ever resolves by string.

Suppress the rewrite when the element name is a bare ordinal and the source
resolves subcolumn names against a file schema. Both halves of the predicate are
load-bearing: an explicitly named tuple's element name is a real field name the
reader can resolve, and a storage that serves subcolumns from its own metadata
genuinely has a t.1 subcolumn, so MergeTree's unnamed-tuple pushdown keeps
working. Gating on hasExplicitNames() alone, or on
supportsOptimizationToTupleElementSubcolumns(), would silently cost MergeTree
that pushdown.

This regressed in ClickHouse#113383, which admitted format-backed storages to the
tuple-element rewrite through the supportsOptimizationToTupleElementSubcolumns
opt-in. Before it, those storages refused every transformer and the whole tuple
was read. The regression is master-only: that merge is an ancestor of no release
branch and is contained in no release tag.

Merge over File(Parquet) was affected through the same path and is fixed too,
since the proxy forwards both predicates to the nested storage.

Closes: ClickHouse#114991
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-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-performance Pull request with some performance improvements 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.

Parquet and ORC do not push predicates into Tuple subcolumns

5 participants