Repository navigation
Do not read subcolumns through a view whose declared types differ from its inner query - #113057
Conversation
…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.
Internal second-model review (2 rounds, 3 gate runs) — 4 findings agreed and fixed, 1 disagreed with evidenceBefore publishing I ran an independent cold review plus a separate second-model gate on this ❌ Agreed and fixedThe new test was analyzer-blind and would have failed this PR's own CI. An assert-absent Missing visible issue linkage. The
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260803-001900 |
|
cc @pufit @SmitaRKulkarni, could you review this? |
|
Workflow [PR], commit [99cd761] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No blocking or major issues found. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
CI finish ledger — 99cd761Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All 174 other checks completed without failure ( The one red is not attributable to this PR's diff: it fires inside a build post-hook that uploads Session id: cron:our-pr-ci-monitor:20260803-123000 |
|
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
So through a view a subcolumn read already costs a full column read: the plan computes 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 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. |
Related: #112688
Related: #82058
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
UNKNOWN_IDENTIFIERwhen selecting from aVIEWwhose declared column types differ from the types its inner query produces, for exampleSELECT sum(length(arr)) FROM vwherevdeclaresarr Array(UInt8)over aStringcolumn. With the defaultoptimize_functions_to_subcolumns = 1the optimizer rewrotelength(arr)into a read of thearr.size0subcolumn 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:
StorageViewdeclaredsupportsSubcolumns() = truewith nosupportsOptimizationToSubcolumns()override, so it inherited theIStoragedefault that derives one from the other.FunctionToSubcolumnsPassreads that bit and rewrotelength(arr)into a read ofarr.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.readImplthen 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,StorageMergeandStorageBufferall carry one, andStorageViewwas 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_optimizationfails 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:optimize_functions_to_subcolumns = 1= 0Identical through the view; a real saving only on the direct table.
EXPLAIN PLAN actions = 1shows why: the view arm computesgetSubcolumn(arr, 'size0')above aReadFromMergeTreethat has noOutput: arr.size0, so the whole column is read either way, whereas the table arm'sReadFromMergeTreecarriesOutput: 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.