Repository navigation
Conversation
…ubqueries optimizeUseNormalProjections sets required_columns = getAllColumnNames(). Columns in that set not consumed by the rebuilt query.dag survive as pass-throughs (ActionsDAG::updateHeader appends every un-consumed input) and widen the projection-rewritten read output header. The all-parts-from-projection branch (parts_with_ranges.empty()) spliced that widened node into the plan without the makeMaterializingDAG + blocksHaveEqualStructure guard the Union branch already had. When such a read feeds the input of a correlated subquery decorrelated into a join, the JoiningTransform pushed a chunk with more columns than its declared output header, aborting the server with 'Invalid number of columns in chunk pushed to OutputPort' (STID 2270-3452, found by the AST fuzzer). Hoist the materialize-constants + equal-structure guard so it protects both replacement branches; on a structure mismatch skip the projection and keep the regular read. filterPartsByProjection mutates the parent analysis result in place, so restore the pre-filter result on the skip path to avoid dropping rows. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-3:20260722-123300 |
Internal second-model review (click to expand)Independent second-model review of the resulting code before opening this PR. Each finding was adjudicated and verified against the code.
💡 Nits
Adjudicated but not applied (DISAGREE, with evidence)
Session id: cron:clickhouse-author-slot-3:20260722-123300 |
|
cc @novikd @CurtizJ — could you review this? It fixes a |
|
Workflow [PR], commit [e95f98d] Summary: ❌
AI ReviewSummaryThis PR fixes the normal-projection rewrite when the projection stream is wider than the subplan it replaces: it narrows surplus pass-through columns before the shared Missing context / blind spots
Final Verdict✅ No new findings. |
…rase The analyzer has been the default since 24.3, so the check_style "analyzer wording" pass bans "new analyzer" in comments. Reword line 2 of 04410_normal_projection_correlated_subquery_part_offset (both .sql and .reference, kept identical for echo mode) to "the analyzer". Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
CI Triage (bot) — head Verdict: REAL FAILURE — AST fuzzer LOGICAL_ERROR crash; integration test flake AST fuzzer (amd_debug, targeted): Server crash (exit code 134) with: This is a LOGICAL_ERROR in the query pipeline execution. PR #111401 fixes a LOGICAL_ERROR in normal projection optimization with correlated subqueries — the fuzzer may be triggering a related or adjacent code path. Integration tests — test_replicated_database/test_replicated_table_structure_alter: This test PASSED on retry (first run failed, second passed), indicating a flake unrelated to this PR. Action needed: Investigate the Run ID: 29939580700 |
CI finish ledger — 2284399Every failure below has an owner. None are PR-caused on this head: the Style-check
Session id: cron:our-pr-ci-monitor:20260723-023000 |
|
Fixing PR for the The failure is the plain-rewritable |
The hoisted structure guard in optimizeUseNormalProjections was verified against one more carrier of the same defect, found by the AST fuzzer on an unrelated pull request (STID 0993-3a3c, AST fuzzer (amd_tsan) on ClickHouse#92472; also seen in Stress test (arm_debug) on ClickHouse#108289). Same root cause as the case already covered: ActionsDAG::updateHeader appends every input the rebuilt query.dag does not consume, so unconsumed columns of required_columns survive as pass-throughs and widen the projection-rewritten stream past the header of the subplan it replaces. What differs is the consumer. Here the leaked columns are real (not virtual), and the parent is the right side of the inner correlated-decorrelation join, whose contract is a single column (payload and id belong to the outer stream). So instead of the output port check in JoiningTransform::prepare, the widened block trips the right-side structure assert in ConstantJoin::addBlockToJoin. Which of the two fires depends only on the settings: correlated_subqueries_use_in_memory_buffer = 0 gives the ConstantJoin one, additionally setting correlated_subqueries_default_join_kind to 'left' gives the output port one. Reproduced on unmodified master for both asserts, byte-identical to the CI report (message, column dump including the sparse id column, and the whole frame chain). It only surfaces when query_plan_remove_unused_columns is off, because that optimization re-narrows the stream; CI reached it through compatibility = '25.3'. No source change was needed: removing only the hoisted blocksHaveEqualStructure block from the fixed build makes both asserts fire again with the original messages, and restoring it rebuilds bit-identically, which is what proves the existing guard is what covers this carrier. The check was deliberately made on the branch merged with current master rather than by comparing prebuilt binaries of different vintages, since ConstantJoin.cpp does not exist at this branch's original merge base. The test pins query_plan_remove_unused_columns = 0 (otherwise the check is vacuous), keeps id sparse-serialized and asserts that it is, and compares projection-on against projection-off results so the skip path is shown to lose no rows. No randomization tags are needed: 100 randomized runs pass. While verifying this I confirmed that issue ClickHouse#112128 (correlated EXISTS under OR with full_sorting_merge) is a different producer of the same symptom, since it is unaffected by optimize_use_projections = 0. It is tracked separately.
The regression statements for the second carrier are result-based: they pass
whenever the normal projection is not used, including in a hypothetical world
where the candidate is declined earlier than the hoisted structure check (for
example if has_all_required_columns started failing, or if the read-in-order
precondition stopped holding). They prove the queries do not abort, but not
that the guard this change adds is what makes them pass, so the test could
silently stop exercising it.
Add, for each of the two detector statements, a companion assertion on the
stat description the skip path writes, using the same settings clause so the
plan path is identical:
SELECT count() > 0
FROM (EXPLAIN projections = 1 <same SELECT, same SETTINGS>)
WHERE explain ILIKE '%does not match the structure it replaces%';
It asserts a boolean over one stable substring rather than plan text, so it
does not churn with the plan format. Deleting only the two lines that set the
description flips exactly these two assertions and leaves every pre-existing
assertion green, so they are the sole carriers of the reachability claim.
Also pin max_bytes_to_merge_at_max_space_in_pool = 1 on the second fixture,
matching the mechanism the first fixture in the same file already uses. The
two small parts cannot be selected for merging within the test's lifetime
today, so this is not a redness fix; it removes the shipped test's dependence
on merge-selector arithmetic that a future change could invalidate silently.
Co-Authored-By: Claude Fable 5 <[email protected]>
…check The reachability assertions added for the real-column carrier used count() > 0 over the whole EXPLAIN output. That is an existence test, and a single plan legitimately holds reads with opposite verdicts: in these queries the outer read uses the projection while only the nested read is rejected at the structure check. The assertion therefore proved "some candidate was rejected somewhere" rather than "the read under test hit the check", and would have stayed green if the rejection moved to an unrelated read. Count the occurrences instead. Exactly one read reaches the check in each of the three statements, measured on the build under test, so an equality pins the rejection to that read without forbidding the outer read's legitimate use of the projection. The virtual-column carrier had only result-based assertions, which pass whenever the projection is not used at all, including when the candidate is declined earlier than the structure check. It now carries the same assertion, mirroring the settings of the statement it follows. Verified by deleting only the two lines that rewrite the skipped candidate's stat description: the reference then differs in exactly three places, all three of the new counts flipping to 0, while every result-based assertion stays green. That is what shows the three assertions are the sole carriers of the reachability claim.
Internal second-model review (4 rounds, 22 findings adjudicated: 13 agreed, 6 refuted with evidence, 2 dropped, 1 split)Every change in this pull request was reviewed by an independent model before ❌ Blockers / majors that were fixed
|
|
Updated for the second carrier added since the first version of this pull request; supersedes the gate comment posted on 2026-07-22. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260729-015900 |
The projection-on/off equality for the aggregate statement held whenever the projection was not used, including when it was declined before the hoisted structure check. Both result lines then stayed equal and the assertion stopped proving that running filterPartsByProjection after the check preserves rows. The existing reachability assertion covers the "= 8" statement only; the aggregate has a different plan shape (unrestrictive predicate, four parts instead of one), so it needs its own. Measured with a mutation that declines the candidate before the check: the four reachability assertions all flip to 0 while every projection-on/off equality stays equal, which is the gap being closed. A mutation restoring the pre-fix ordering turns the aggregate result into 0 0 0, so the row-preservation half stays live as well.
Applies the repository convention from `.claude/CLAUDE.md` to the comments this change added: literal names from the ClickHouse SQL language, classes and functions, and literal excerpts from log messages go in inline code blocks. Comment-only across both files. The optimization's compiled `.text` is unchanged, and the echoed reference file is regenerated so it stays in sync without any result row moving.
CI finish ledger - 6833b78174 check-runs, all completed, 1 failed. It has an owner.
Every other Bugfix validation job on this head is green or correctly skipped, and the earlier Session id: cron:our-pr-ci-monitor:20260729-190000 |
CI finish ledger - ab209b8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 174 check-runs on this head are completed; the only failure is the row above. Not caused by this PR: the diff is Session id: cron:our-pr-ci-monitor:20260730-003000 |
The four EXPLAIN oracles counted the projection reads and checked that no read was declined, which both hold on a mixed UnionStep plan as well: such a plan keeps the same two ReadFromMergeTree (p) / (p_by_session) lines and adds a base-table arm beside each. Measured on both carriers, with a mixed-parts table built by materializing the projection and then attaching a part that has none: shipped oracle 1 on all-parts and 1 on mixed, so a regression away from the all-parts replacement kept the file green. With the third conjunct the oracles read 1 on all-parts and 0 on mixed. This is the assertion already used by 04907 for the same distinction. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - 6d1036aEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All three rows are one causal chain, not three defects. The fix is not yet merged, so this build could not carry it. This PR's diff touches one optimizer Session id: cron:our-pr-ci-monitor:20260819-160000 |
CI finish ledger - 5a7f4baEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The owner above is a linkable open fix rather than a task because #114523 modifies exactly the Report: Session id: cron:our-pr-ci-monitor:20260820-040000 |
…on-correlated-subquery-outputport
|
🕵 Merged |
… the Union plan shape The AI review verdict asked to make `03324_union_block_structure_mismatch` stay on the mixed `UnionStep` path deterministically and to assert the base-table `ReadFromMergeTree` arm: - Disable merges on the fixture table (`max_bytes_to_merge_at_max_space_in_pool = 1`), so the projection-less part written before `ADD PROJECTION` can never be merged with the projection-carrying one, which would silently collapse the mixed `Union` plan into the all-parts rewrite. - Pin the mixed-parts state itself: two active parts in `system.parts`, exactly one row for projection `x` in `system.projection_parts`. - Extend the `EXPLAIN projections = 1` oracle to require exactly one `Union`, one projection read arm `ReadFromMergeTree (x)`, and one surviving non-projection `ReadFromMergeTree` arm, in addition to the absence of the structure-mismatch decline message. Verified locally: the test is diff-clean against its reference, and the extended oracle returns 0 when `optimize_use_projections = 0` (negative control), so it still discriminates. ClickHouse#111401 Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - f488916Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Notes on the arithmetic, so the omissions are auditable:
Session id: cron:our-pr-ci-monitor:20260825-180000 |
The `amd_llvm_coverage, ParallelReplicas, s3 storage, parallel` job installs tests/config/users.d/enable_parallel_replicas.xml, which turns `enable_parallel_replicas` on in the default profile. That breaks the two tests in two independent ways. Normal projections are unsupported when reading over parallel replicas unless `parallel_replicas_local_plan` is on and aggregation in order is off (projectionsCommon.cpp), and tests/clickhouse-test randomizes both settings. So the `force_optimize_projection = 1` query in 03324 raises PROJECTION_NOT_USED, and the projection-read assertions in 04907 return 0, on the configurations the runner happens to roll. Independently, reading over parallel replicas wraps the plan in an outer `Union` of the local plan and `ReadFromRemoteParallelReplicas`. The plan-shape assertion added to 03324 in "Address review: make 03324 mixed-parts state deterministic and assert the Union plan shape" requires exactly one `Union`, so it counted 2 and returned 0. That is the `-1 / +0` reference diff on the fourth line seen in CI. The mixed projection `Union` the test pins was intact and nested inside: the projection arm, the surviving base-table arm and the absence of a structure decline all held on that job. Pinning `enable_parallel_replicas = 0` at session scope in both tests keeps them about the plans they were written for. This is what 238 other stateless tests already do. Verified against a server started with that job's parallel-replicas profile: before, 03324 failed with the same fourth-line diff and 04907 failed two assertions; after, both pass with the profile off and on, across all four combinations of the two randomized settings. Both remain live - with `makeNarrowingDAG` made to decline, 03324 fails with PROJECTION_NOT_USED, and with the hoisted structure check made to decline, 04907 fails both assertions. 04410 was checked over the same four combinations and needs no pin.
|
Pushed That job installs
Fix is Verified against a server running that job's parallel-replicas profile: before,
Tests only, |
…on-correlated-subquery-outputport
CI finish ledger - 4d82c4dEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
No other check failed at this head, and none of the failures is PR-caused: the diff here touches Session id: cron:our-pr-ci-monitor:20260830-190000 |
…write The hoisted `blocksHaveEqualStructure` check is the last safety net for an all-parts rewrite whose rewritten output cannot be repaired by `makeNarrowingDAG` / `makeMaterializingDAG`, and no stateless test pinned it: all three regressions in this pull request assert accept paths. A query cannot reach the branch. Both conversions refuse only on headers the analyzer never builds for a `MergeTree` read (duplicate column names), and a type difference raises inside `ActionsDAG::updateHeader` before the check, so the branch has no natural carrier. Add the failpoint `normal_projection_skip_output_header_conversions`, which disables both conversions, so the very rewrite the new test's baseline accepts reaches the check with a surplus pass-through column and must be declined there. The new test `05054_normal_projection_output_header_mismatch` pins the flip: the same statement uses the projection with the conversions in place, returns `PROJECTION_NOT_USED` under `force_optimize_projection = 1` once they are disabled, and still reads every row of the table afterwards - with and without `optimize_use_projections` - so a declined rewrite provably keeps all parts.
|
Dear @novikd, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
novikd
left a comment
There was a problem hiding this comment.
None of the tests reproduces any issue (Bugfix validation did not work). Tests are working on the latest release: https://fiddle.clickhouse.com/4588be18-8cf6-436e-9e8f-d787c36b89d4
I'd recommend closing this PR
|
You are right about the two new tests, and I agree the PR as titled is not supported. One correction on the CI. Bugfix validation did run, on the three commits before the current head, and returned Which is to say: the only thing that reddens without this change is a projection being refused, not the logical error in the title. That agrees with what I measured on this branch earlier (#111401 (comment)): 112 instrumented arrivals at the So what is left is an improvement (a projection master declines becomes usable) plus a defensive guard, not |
CI finish ledger - e95f98dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Both owners merged AFTER these jobs started (the two stateless legs began 10:32:10Z and 10:34:34Z, Session id: cron:our-pr-ci-monitor:20260903-163000 |
|
The reproducer behind this PR no longer fails on master: @ alexey-milovidov measured it on I measured what the remaining src change still does on today's master and concluded it is not worth keeping: #112128 (comment). Your recommendation stands as far as I am concerned, no objection to closing. |
Related: #103695 (same
Invalid number of columns in chunk pushed to OutputPorterror family)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
LOGICAL_ERRORraised when a normal projection was used to read the input of a correlated subquery (decorrelated into a join) and all parts were served from the projection. Depending on the settings it was reported asInvalid number of columns in chunk pushed to OutputPortor asBlock structure mismatch in joined block stream. It is an exception in release builds and aborts the server in debug and sanitizer builds.Description
Found by the AST fuzzer, reproduces on current master and is unrelated to the pull requests it was seen on: amd_msan (STID 2270-3452), amd_tsan (STID 0993-3a3c), and
Stress test (arm_debug).Root cause:
optimizeUseNormalProjectionsreads the projection overrequired_columns = reading->getAllColumnNames(). Columns of that set which the rebuiltquery.dagdoes not consume survive as pass-throughs, becauseActionsDAG::updateHeaderappends every un-consumed input, and widen the rewritten read's output header. The all-parts-from-projection branch spliced that widened node in without theblocksHaveEqualStructurecheck the Union branch already had, so a downstream step got more columns than its declared header.Change: emit the replaced header's columns by name, dropping the surplus pass-throughs so the projection stays usable, and hoist the equal-structure check to cover both replacement branches. It stays below the narrowing as a fail-closed net for what narrowing cannot repair (a missing column, or a type difference), skipping the projection and keeping the regular read. Since
filterPartsByProjectionmutates the parent analysis result in place, it now runs only after that check passes, so a skipped projection no longer drops parts;has_parent_partsmoves ahead of it and is computed non-destructively.Validation: the load-bearing regression test is
03324_union_block_structure_mismatch. Reverting only this change makes its first statement fail withPROJECTION_NOT_USED; that statement previously carried-- { serverError PROJECTION_NOT_USED }, so the projection is now used where it was refused before.04410and04907pin the plan shape viaEXPLAIN: every read served by the projection, none declined, no base-table arm. The04410carriers abort on the commit the fuzzer reports came from, but not at the current merge-base, where an earlier pass prevents the widening; they are kept as plan-shape pins, not as the proof. The failing-test set across the projection, prewhere, part_offset and correlated suites is unchanged.05054_normal_projection_output_header_mismatchpins the fail-close side of the hoisted check: the failpointnormal_projection_skip_output_header_conversionsdisables both header conversions, so the same rewrite the test's baseline accepts reaches the check with a mismatch, and the statement flips toPROJECTION_NOT_USEDunderforce_optimize_projection = 1while the surviving read still returns every row.Both carriers: error signatures
Carrier 1, virtual columns (
_part_offsetin the projection), output port assert:Carrier 2, real columns. The inner decorrelation join's right side carries exactly one column by design, so the leaked columns trip its structure check instead of the output port one:
correlated_subqueries_use_in_memory_buffer = 0selects theConstantJoinassert; addingcorrelated_subqueries_default_join_kind = 'left'selects the output port one. Runnable reproducers for both are the statements in the new test file.Workflow [PR]
Sync PR [sync-upstream/pr/111401]