Repository navigation
Push tuple element predicates into Parquet and ORC subcolumn reads - #113383
alexey-milovidov merged 20 commits into
Conversation
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.
Internal second-model review (click to expand)Every change here went through an independent review round before publication: a cold code
Independently verified in the final round and reported clean: the capability gate is applied at Session id: cron:clickhouse-review-slot-10:20260804-185800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-10:20260804-185800 |
|
cc @al13n321 @KochetovNicolai, could you review this? Filter pushdown was lost for |
|
Workflow [PR], commit [7d6ab6e] Summary: ✅
AI ReviewSummaryThis PR extends Missing context / blind spots
Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 305/335 (91.04%) · Uncovered code |
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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_officialFlagged queries (2 of 22)
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
|
CI finish ledger — 3128949Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Neither is PR-caused: this PR touches Parquet/ORC tuple-subcolumn pushdown and the analyzer, 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.
Test-only follow-up: 04707 was consuming 84% of the 180s stateless budget
The cost was harness overhead, not coverage. Each of the 14 labels ran two client invocations: the So the query now reports its own read-row count: Measured on one debug binary and server, arms interleaved to cancel box-load drift: p50 7.05s to Both oracles stay pinned, verified by mutation: disarming the flattened-name ambiguity guard in Two settings pins were considered and dropped after measuring that they change nothing here, The 180s constant is untouched, the PR body and changelog are unchanged, and the test takes no Internal second-model review (click to expand)Independent cold review of the resulting code plus an independent second-model pass, adjudicated
The two out-of-scope source findings are disclosed here rather than filed: both are non-firing Session id: cron:clickhouse-review-slot-50:20260805-135300 |
Pre-PR validation gate (click to expand)
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.
|
Pushed
Renaming the variable to One correction worth recording: quoting the key ( Verified both directions against real jq 1.6 and jq 1.7:
Post-fix stdout under jq 1.6 is byte-identical (md5 Two things this does not fix, to be clear about scope:
|
CI finish ledger — a65f25fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
This is the only failure on this head. Fix-presence probe for the owner, by content rather than commit distance: this head's Gates: (a) 175 check-runs, 0 queued/in_progress/pending/waiting; (b) Session id: cron:our-pr-ci-monitor:20260806-050000 |
|
This PR is too large, forget it |
|
Leaving it as it stands then, no split. CI restarted on the reopened head |
CI finish ledger - a65f25fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
None of these is PR-caused: this PR touches Parquet/ORC tuple-subcolumn pushdown and the analyzer, #114326 is merged but not in this build, so a re-run picks it up. Verified from the run itself
#113397's fix is genuinely absent from this build, so this red is not evidence against it: Gates: (a) 351 check-runs, 0 incomplete non-exempt; (b) Session id: cron:our-pr-ci-monitor:20260812-063000 |
…ess hung check
CI finish ledger - 7762cb3Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All other 175 checks are green or skipped (161 success / 14 skipped / 1 failure). This supersedes the ledger for 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)
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units681 translation units recompiled, 6749 s compile time in total, 681 of them have a recent master baseline. |
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.
CI finish ledger - 8db4d5dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task CI is fully finished on this head and there are no failures to own: 163 successful checks,
The previously reddening 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.
|
🕵 Pushed 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 |
CI finish ledger for 7d6ab6eCI 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
Session id: cron:our-pr-ci-monitor:20260815-180000 |
…-tuple-subcolumn-pushdown
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
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
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Filter pushdown now works for
Tuplesubcolumns in Parquet and ORC files. A predicate such asWHERE tup.1 = 555555overfile(),s3()orurl()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/StorageObjectStoragereturnfalsefromsupportsOptimizationToSubcolumns, sotupleElement(tup, 1)was never rewritten totup.1; the pass also accepted onlyTableNode, skipping table functions. That blanketfalsekeeps #106147 fixed (NOT_FOUND_COLUMN_IN_BLOCKon.nullin PREWHERE), so rather than flipping it this adds a narrowsupportsOptimizationToTupleElementSubcolumnsvirtual defaulting to the existing one, with a{Tuple, tupleElement}-only allow-list.04303_object_storage_prewhere_isnotnull_subcolumnpasses unmodified. Source identity also moves to the table-expression node: everyfile()resolves to the same_table_function.fileID, so two such sources shared a key. Accepting table functions generally also makesformat(),values()andview()eligible for the other transformers; those storages already answersupportsSubcolumns(), so the default covers them.ORC's search argument builder resolved top-level names only, so any dotted name emitted
YES_NO_NULLwhile the read path in the same file resolved them recursively. Resolving recursively also reaches the flattened-Nesteddescent, which rewrites the type it is given, so the builder keeps the key's own type: an array-typed predicate over a flattenedNestedleaf 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 passesinitKeyConditionOncea 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 (unwrappingNullable/LowCardinality/Array), which refuses Map.keys/.values: they useSubstreamType::TupleElementbut have no per-element statistics.Measurements (100k rows, one row group / stride per 10k)
WHERE tup.1 = 55555WHERE id = 55555(control)WHERE tup.1 = 55555WHERE id = 55555(control)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-leveltup.2.1stays 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::flattendoes not descend aNullable(Tuple). #109741 (open) rewrites that helper for theArrowspelling.Version info
26.8.1.1477(included in26.8and later)