Skip to content

Do not read subcolumns through a view whose declared types differ from its inner query - #113057

Merged
SmitaRKulkarni merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-storageview-supports-opt-to-subcolumns
Aug 5, 2026
Merged

SmitaRKulkarni merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-storageview-supports-opt-to-subcolumns

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Related: #112688
Related: #82058

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed UNKNOWN_IDENTIFIER when selecting from a VIEW whose declared column types differ from the types its inner query produces, for example SELECT sum(length(arr)) FROM v where v declares arr Array(UInt8) over a String column. With the default optimize_functions_to_subcolumns = 1 the optimizer rewrote length(arr) into a read of the arr.size0 subcolumn and forwarded that name into the inner query, which has no such subcolumn.

Description

At default settings the optimizer turned a working query into an error:

CREATE TABLE vstr (arr String) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO vstr VALUES ('[1,2,3,4,5,6]');
CREATE VIEW vw (arr Array(UInt8)) AS SELECT arr FROM vstr;

SELECT sum(length(arr)) FROM vw;
-- before: Code: 47. Unknown expression identifier `arr.size0`
-- after:  6  (already 6 with optimize_functions_to_subcolumns = 0)

StorageView declared supportsSubcolumns() = true with no supportsOptimizationToSubcolumns() override, so it inherited the IStorage default that derives one from the other. FunctionToSubcolumnsPass reads that bit and rewrote length(arr) into a read of arr.size0. Its follow-up type check cannot catch this for a view: it compares the view's declared metadata against a type that came from that same metadata, so a divergence from the inner query is invisible there. readImpl then forwards the rewritten name into the inner query, where it is resolved against the real type and fails.

A view forwards column names to something it does not type-check, so it cannot honour this capability. This adds the missing override returning false, the established pattern here: StorageProxy, StorageMaterializedView, StorageMerge and StorageBuffer all carry one, and StorageView was the last forwarding wrapper without it. Delegating to a target is not possible: an ordinary view has none. Opting out costs no I/O: the rewrite had no payoff through a view (below).

New test 04711_view_no_subcolumn_optimization fails without this change and passes with it. It also pins that a type-consistent view keeps working, that a subcolumn the inner query genuinely lacks is still rejected, and that the optimization still fires on a direct read.

Compatible with #112688: its new pass reads this bit on the inner storage a subquery reads from, not on the wrapper.

Measured payoff of the rewrite through a view: zero

200k rows of Array(UInt8), SELECT sum(length(arr)), SelectedBytes:

arm optimize_functions_to_subcolumns = 1 = 0
through a type-consistent view 6,500,000 6,500,000
direct on the table (control) 1,600,000 6,500,000

Identical through the view; a real saving only on the direct table. EXPLAIN PLAN actions = 1 shows why: the view arm computes getSubcolumn(arr, 'size0') above a ReadFromMergeTree that has no Output: arr.size0, so the whole column is read either way, whereas the table arm's ReadFromMergeTree carries Output: arr.size0. Nothing currently pushes a subcolumn read across the view boundary, so this bit bought no I/O for views and could only cause the error above.

groeneai and others added 2 commits August 3, 2026 01:02
…m its inner query

`StorageView` declared `supportsSubcolumns() = true` and had no
`supportsOptimizationToSubcolumns()` override, so it inherited the
`IStorage` default, which derives the second from the first.

`FunctionToSubcolumnsPass` reads that bit and rewrote `length(arr)` into
a read of the `arr.size0` subcolumn. Its follow-up type check cannot
catch the problem for a view: it compares the view's declared metadata
against a type that came from that same metadata, so a divergence
between the view and its inner query is invisible there.
`StorageView::readImpl` then forwards the rewritten column name into the
inner query, where it is resolved against the real type and fails.

At default settings this made the optimizer turn a working query into an
error:

    CREATE TABLE vstr (arr String) ENGINE = MergeTree ORDER BY tuple();
    INSERT INTO vstr VALUES ('[1,2,3,4,5,6]');
    CREATE VIEW vw (arr Array(UInt8)) AS SELECT arr FROM vstr;
    SELECT sum(length(arr)) FROM vw;
    -- Code: 47. Unknown expression identifier `arr.size0` in scope
    --          SELECT arr.size0 FROM (SELECT arr FROM default.vstr)

A view forwards requested column names to something it does not
type-check, so it cannot honour this capability. Opt out with an
override returning false, which is the established pattern here:
`StorageProxy`, `StorageMaterializedView`, `StorageMerge`,
`StorageBuffer` and `StorageURLSchemeDispatch` all carry such an
override, and `StorageView` was the last forwarding wrapper without one.
Delegating to a target table is not possible: an ordinary view has no
target, only an inner query.

Opting out costs no I/O, because through a view this rewrite had no
payoff. On 200k rows of `Array(UInt8)`, `sum(length(arr))` reads
6,500,000 bytes through a type-consistent view with the setting both on
and off, versus 1,600,000 reading the table directly. `EXPLAIN PLAN
actions = 1` shows why: through a view the size is computed above a
`ReadFromMergeTree` that has no `Output: arr.size0`, so the whole column
is read either way, whereas the direct read carries that output.
Nothing currently pushes a subcolumn read across the view boundary.

The second consumer of the bit,
`DistanceTransposedPartialReadsPass`, was verified to lose no
correctness: a QBit `L2DistanceTransposed` through a type-consistent
view returns identical results before and after.

The new test pins the setting per query rather than using a
`no-random-settings` tag: the runner randomizes
`optimize_functions_to_subcolumns`, and an injected 0 would otherwise
silently disarm the row that must fail without this change.

Co-Authored-By: Claude Fable 5 <[email protected]>
The test asserted behaviour of FunctionToSubcolumnsPass without pinning the
analyzer. That pass exists only in the analyzer, and the `old analyzer`
stateless job (ci/defs/job_configs.py, added to every PR workflow) disables it
in the server default profile via tests/config/users.d/analyzer.xml, where a
query-level SETTINGS clause cannot restore it. Measured there: the row that
must fail without the source fix returns the post-fix value on an unfixed
binary, and the EXPLAIN row returns 0 against a reference of 1, so the test
would have gone red on its own PR while also being unable to detect the bug it
exists for. A session-level SET keeps the test executing in that job, which a
no-old-analyzer tag would not, and it overrides the profile because
enable_analyzer is an alias of allow_experimental_analyzer.

The two EXPLAIN rows grepped plan text without pinning
explain_query_plan_default, whose pretty default renders a different shape
since 26.7, and one of them is an assert-absent oracle that any format change
would satisfy. Pin legacy and pair that row with a positive control over the
same plan, so a substring that simply failed to render cannot look like the fix
working: the control holds in both arms while the absent-oracle is 0 before the
fix and 1 after it.

Test-only. src/Storages/StorageView.h is unchanged.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 3 gate runs) — 4 findings agreed and fixed, 1 disagreed with evidence

Before publishing I ran an independent cold review plus a separate second-model gate on this
change, adjudicated every finding, and bounced the fix rounds back for implementation. Summary
for reviewers; the source fix itself drew zero findings in either gate round.

❌ Agreed and fixed

The new test was analyzer-blind and would have failed this PR's own CI. 04711 pinned
optimize_functions_to_subcolumns per query but not enable_analyzer.
FunctionToSubcolumnsPass is analyzer-only (its old-analyzer counterpart was deleted in
d7de2ae0c9c37e9), and the old analyzer stateless job forces allow_experimental_analyzer=0
in the server default profile via tests/config/users.d/analyzer.xml, which a query-level
SETTINGS clause cannot restore. In that job the reddening row would have gone vacuous and the
arr.size0 plan assertion would have returned 0 against a reference of 1. Fixed with
SET enable_analyzer = 1, then re-proved: with the CI profile symlinked in and
getSetting('enable_analyzer') asserted false, the pinned test body still fails Code: 47 on
a pre-fix binary, so it stays armed in the very job that would have blinded it. SET was chosen
over a no-old-analyzer tag deliberately, to keep real coverage there.

An assert-absent EXPLAIN oracle could pass for the wrong reason. The row asserting the view
arm's plan does not mention arr.size0 is satisfied by any rendering change, and
explain_query_plan_default changed default in 26.7. Fixed by pinning 'legacy' and adding a
positive control over the same plan text, so a plan that merely failed to render cannot
masquerade as the fix working: the absent-oracle reads 0 pre-fix / 1 post-fix while the control
reads 1 in both arms.

Missing visible issue linkage. The Related: lines sat inside the template's HTML comment
block, which GitHub does not render, so this PR would have published with no visible linkage.
Hoisted into the body.

⚠️ Disagreed, with evidence

"The test is non-deterministic under randomized parallel-replica settings." The injection
mechanism is real (clickhouse-test sets cluster_for_parallel_replicas = 'parallel_replicas'
in about a quarter of runs), but two necessary steps of the failure fail. First, it was already
exercised: the 100 randomized runs ran against a server config that defines that cluster exactly
as CI does, so roughly 25 of them carried the injection and all 100 passed; an earlier failure
cluster was traced to a local config with no remote_servers (Code: 701), not to this test.
Second, the injected bundle uses automatic_parallel_replicas_mode = 2, which is documented as
statistics collection only, with switching to parallel-replica execution disabled. Adding
no-parallel-replicas would have removed genuine coverage, so the specific settings the test
depends on are pinned instead.

💡 Noted, not blocking

The test pins explain_query_plan_default, which exists only from 26.7. That is irrelevant to
this PR (no backport is requested), but a backport of the test to an older release branch would
need that line adapted.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% at default settings, no server needed: clickhouse local with CREATE TABLE vstr (arr String) ... ; CREATE VIEW vw (arr Array(UInt8)) AS SELECT arr FROM vstr; SELECT sum(length(arr)) FROM vw raises Code: 47 UNKNOWN_IDENTIFIER on arr.size0. Not a probabilistic repro.
b Root cause explained? Yes. StorageView declares supportsSubcolumns() = true with no supportsOptimizationToSubcolumns() override, so it inherits the IStorage.h:176 default that derives one from the other. FunctionToSubcolumnsPass gates on that bit (:753, chained :815) and rewrites length(arr) to arr.size0; its follow-up type check at :757 is vacuous for a view because both sides read the view's own declared metadata. readImpl then forwards the rewritten column name into the inner query, where it resolves against the real String type and fails.
c Fix matches root cause? Yes, it corrects the capability predicate that lied, at the layer designed for it. Not a band-aid: no widened bound, no no-random-* tag, no guard at the crash site. Four rejected alternatives are recorded (re-deriving the bit from the inner query needs a ContextPtr and can throw, so it is the wrong layer for a const non-throwing predicate; special-casing views inside the pass duplicates knowledge StorageView owns; widening to isView() would regress StorageMaterializedView, which legitimately delegates; flipping the IStorage default is backward-incompatible for every storage now getting true).
d Test intent preserved / new tests added? Yes. New stateless test 04711_view_no_subcolumn_optimization; no existing test weakened or removed. Verified no existing stateless test asserts subcolumn optimization over a plain VIEW, so there is no reference-file fallout being papered over, and the eight tests of the subcolumn-optimization family pass untouched. Parallel-safe, no no-parallel tag. Every assertion pins the settings it depends on per query (optimize_functions_to_subcolumns) plus session pins for enable_analyzer and explain_query_plan_default, and the assert-absent EXPLAIN row is paired with a positive control over the same plan text so a vanished substring cannot masquerade as the fix working. Nine neighbours of the subcolumn family pass; 04401_predicate_pushdown_view_over_distributed_union_all cannot run in this sandbox (-- Tags: shard, needs a replica on port 9000) and fails identically on a pristine pre-fix master server, so it is environmental.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Pre-fix (shared master-debug snapshot): Code: 47. Post-fix (Build ID 4cc360335c1013bd093dad20fd1fe895ac053fe4, asserted equal to the server's buildId() before every verdict): 6. Pre-fix with optimize_functions_to_subcolumns = 0 also returns 6, proving the optimizer is the cause. Re-proved after the settings pin: the pinned test body still fails Code: 47 on the pre-fix binary under the adverse randomized injection, so the reddening row cannot be silently disarmed. Re-proved a second time after the analyzer pin, against a server carrying the old analyzer CI profile (tests/config/users.d/analyzer.xml symlinked into users.d/, getSetting('enable_analyzer') = false): the pinned body still fails Code: 47 on the pre-fix binary there, i.e. the test stays armed in the one CI job that would otherwise have made it vacuous.
f Fix is general across code paths? Yes. Both pass gates are covered (:753 plain and :815 chained, the latter verified live: sum(toUInt64(length(arr))) through a mistyped view returns 3). The second consumer of the bit, DistanceTransposedPartialReadsPass.cpp:119, was checked empirically rather than assumed: a QBit L2DistanceTransposed through a type-consistent view returns byte-identical results pre- and post-fix, so it merely declines an optimization with no correctness delta. Exhaustive sweep: of the 21 storages reporting supportsSubcolumns() = true, the 12 without an override are all self-reading storages that produce their own columns, so none forwards names to a differently-typed schema; every forwarding wrapper already had an override and StorageView was the last one missing. StorageMaterializedView is safe structurally, verified empirically not inferred (a TO MV cannot declare a divergent column list: Code 62 SYNTAX_ERROR). StorageWindowView already reports false, so an override there would be dead code, and it is documented out of scope (one root cause per PR).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured live through mistyped views, all correct post-fix: Nullable element wrapper 3, LowCardinality(String) element wrapper 2, chained-function form 3, empty-array boundary 0, parameterized view ({kk:UInt8}) 9, Nullable/.null path via isNull 0. Two cases are unreachable by construction rather than untested: Array(LowCardinality(UInt8)) is refused at CREATE VIEW (Code 455 SUSPICIOUS_TYPE_FOR_LOW_CARDINALITY) and a Map-declared view over a String target is refused at read (Code 53 TYPE_MISMATCH). Wrapper-stripping asymmetry is structurally not a dimension here: the fix is a flat false on one class and branches on no type.
h Backward compatible? (maintainer-approved exception only) Yes, nothing at risk. No new setting, no setting default changed, no serialization or metadata format change, so no SettingsChangesHistory.cpp entry applies. The only behavioural delta is an error becoming the correct result. Re-verified against today's origin/master (248 commits ahead of the branch base): IStorage.h:176 is byte-identical and StorageView.h still carries no override, so the change applies cleanly.
i Invariants and contracts preserved? Yes. The change is a const, non-throwing, context-free predicate returning a literal, so there is no lifetime, resource, concurrency or error-path surface and no crash/restart re-entry path (nothing is persisted). It restores the invariant that a storage may report supportsOptimizationToSubcolumns() == true only if the rewritten subcolumn name is resolved against the same schema that was analyzed, and both consumers were verified to behave correctly when it returns false (see f).

Session id: cron:clickhouse-impl-slot-46:20260803-001900

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @pufit @SmitaRKulkarni, could you review this? StorageView declared supportsSubcolumns true with no supportsOptimizationToSubcolumns override, so it inherited the IStorage default and FunctionToSubcolumnsPass rewrote length(arr) into a read of arr.size0, a name that readImpl then forwards into the inner query where it does not resolve, turning a working query into UNKNOWN_IDENTIFIER at default settings.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [99cd761]

Summary: ✅


AI Review

Summary

This PR makes StorageView fail closed for supportsOptimizationToSubcolumns(), which is the correct contract for a wrapper that analyzes against the view schema but executes against an inner query with potentially different physical column types. Tracing the current code through FunctionToSubcolumnsPass, DistanceTransposedPartialReadsPass, StorageView::readImpl, the existing inline-view/type-conversion tests, and the new deterministic regression test did not surface any remaining correctness or coverage gaps in the patch.

Final Verdict

✅ No blocking or major issues found.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.40% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.60% -0.10%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 99cd761

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 CI telemetry infra: build_profile_hook.py INSERT into build_time_trace rejected with LogCluster query failed with code 500; the enclosing Build (arm_release) job is itself success, so nothing is gated and no result in this PR is affected a fix task is created (investigating at full effort — fixing-PR link to follow here)

All 174 other checks completed without failure (Finish Workflow and Config Workflow both green).

The one red is not attributable to this PR's diff: it fires inside a build post-hook that uploads
compile-time telemetry, and its breadth over the last three days is 690 rows across 165 distinct
PRs with 249 of them on master, so it appears on PRs whose diffs have nothing in common with this
one.

Session id: cron:our-pr-ci-monitor:20260803-123000

@SmitaRKulkarni

Copy link
Copy Markdown
Member

Currently it seems fine to turn off optimization instead of throwing error for views. But if we want to support optimization we should fix the name. I think we need different approach then this (#87205).
cc @Avogar

@SmitaRKulkarni
SmitaRKulkarni added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit 263e89b Aug 5, 2026
181 checks passed
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review and the merge.

That matches what I measured: through a view the rewrite has no payoff today, so declining it costs nothing. On 200k rows of Array(UInt8) at ~25 elements per row, SelectedBytes for a subcolumn read:

read bytes
sum(arr.size0) direct on the table 1,610,204
sum(arr.size0) through a view 6,613,856
whole arr column, control 6,614,632

So through a view a subcolumn read already costs a full column read: the plan computes getSubcolumn(arr, 'size0') above a ReadFromMergeTree that reads the whole column. The bit bought no I/O for views and could only produce the UNKNOWN_IDENTIFIER. It reproduces the same way for a view declared with SELECT * and for a subquery over a view.

I agree the general fix is the name derivation rather than 87205's approach, which addressed splitting names that contain a dot (it resolved 82058, the same user-visible symptom through a view from that different cause).

On direction, one correction to my own PR description, which was loose here. The subcolumn pushdown in #112688 reads this capability bit on the storage that the inner projection of a subquery reads from. When that is a real table, this change does not affect it. When the subquery reads from a view, that storage is the view itself, so it declines there too, and I believe that is correct: pushing arr.size0 into the view's projection forwards the name into the inner query, which is the failure this PR fixed. A plain read through a view is a table read rather than a subquery, so it is never a pushdown target.

I have not established what the right derivation is. Resolving the subcolumn name against the types the inner query really produces, rather than against the view's declared types, is where I would look, but I have not measured it.

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
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 pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants