Skip to content

Fix LOGICAL_ERROR in normal projection optimization with correlated subqueries - #108242

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-part-offset-prewhere-projection-output-port
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-part-offset-prewhere-projection-output-port

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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):

Fix a LOGICAL_ERROR ("Invalid number of columns in chunk pushed to OutputPort") that could crash the server when a normal projection that materializes a virtual column (e.g. PROJECTION p (SELECT *, _part_offset ORDER BY j)) was used to read the input of a correlated subquery.

Description

CI report: AST fuzzer (arm_asan_ubsan), master (STID 2270-3452, same family as the umbrella issue #103695).

Found by the AST fuzzer. Minimal deterministic reproducer:

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (i LowCardinality(Int32), j LowCardinality(Int32),
  PROJECTION p (SELECT *, _part_offset ORDER BY j) WITH SETTINGS (index_granularity = 64))
ENGINE = MergeTree ORDER BY i SETTINGS index_granularity = 1, max_bytes_to_merge_at_max_space_in_pool = 1;
-- insert several parts
SELECT i, j FROM t
PREWHERE _part_offset < (_part_offset + _part_starting_offset)
WHERE ((SELECT _part_starting_offset) + _part_offset) = 8
SETTINGS correlated_subqueries_substitute_equivalent_expressions = 0,
         correlated_subqueries_default_join_kind = 'left';

Root cause: optimizeUseNormalProjections reads the projection with required_columns = reading->getAllColumnNames(). Columns in that set that the rebuilt query.dag does not consume survive as pass-throughs (ActionsDAG::updateHeader appends every un-consumed input column). When the subplan being replaced produced fewer columns - here a "Project only used columns" step inserted while decorrelating the correlated scalar subquery (SELECT _part_starting_offset) had pruned i/j away - those extra pass-through columns silently widened the rewritten read's output header.

The all-parts-from-projection branch then spliced the widened node into the plan without the blocksHaveEqualStructure check that the Union branch already had. At execution the decorrelation CROSS JoiningTransform pushed a 4-column chunk into a port whose header declared 2 columns, aborting the server.

Fix: hoist the existing materialize-constants + equal-structure guard so it protects both replacement branches; if the projection-rewritten stream does not match the structure of the subplan it replaces, the projection is skipped and the regular read (which is correct) is kept.

Verified: the reproducer aborts the server before the change and runs cleanly after it; results match the non-projection plan. Added a regression test (04410_normal_projection_correlated_subquery_part_offset). Existing projection / _part_offset / correlated-subquery tests still pass.

…ubqueries

A normal projection that materializes a virtual column (e.g. PROJECTION p
(SELECT *, _part_offset ...)) can be selected for a read that feeds a
correlated-subquery decorrelation CROSS JOIN. The projection read exposes every
column listed in required_columns (reading->getAllColumnNames()); any of those
not consumed by the rebuilt query.dag survives as a pass-through in the
ExpressionStep that updateHeader() appends. When the replaced subplan produced
fewer columns - here a 'Project only used columns' step inserted during
correlated-subquery decorrelation had pruned them - these extra pass-through
columns silently widen the rewritten read's output header.

In the all-parts-from-projection branch the widened node was spliced into the
plan without any structure check (unlike the Union branch, which already guarded
with blocksHaveEqualStructure). At execution the JoiningTransform then pushed a
4-column chunk into a port whose header declared 2 columns, aborting the server
with 'Invalid number of columns in chunk pushed to OutputPort. Expected 2,
found 4'.

Hoist the existing materialize-constants + equal-structure guard so it protects
both replacement branches. When the projection-rewritten stream does not match
the structure of the subplan it replaces, skip the projection (the regular read
stays correct).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT i, j FROM t PREWHERE _part_offset < (_part_offset + _part_starting_offset) WHERE ((SELECT _part_starting_offset) + _part_offset) = 8 SETTINGS correlated_subqueries_substitute_equivalent_expressions = 0, correlated_subqueries_default_join_kind = 'left' aborts the server every time (table = the regression test's projection table). Confirmed identical to CI STID 2270-3452 (Expected 2, found 4, same header/chunk shapes). optimize_use_projections=0 makes it disappear, isolating the projection optimization.
b Root cause explained? optimizeUseNormalProjections reads the projection with required_columns = reading->getAllColumnNames(). Columns not consumed by the rebuilt query.dag survive as pass-throughs (ActionsDAG::updateHeader appends every un-consumed input column). The correlated-subquery decorrelation had inserted a "Project only used columns" step that pruned i/j; the projection rewrite re-exposed them, widening the read's output header from 1 to 3 columns. The all-parts branch spliced this widened node into the plan with no structure check, so the decorrelation CROSS JoiningTransform pushed a 4-column chunk into a 2-column port.
c Fix matches root cause? Yes. The fix hoists the existing materialize-constants + blocksHaveEqualStructure guard (previously only on the Union branch) so it also protects the all-parts branch. When the projection-rewritten stream does not match the structure of the subplan it replaces, the projection is skipped. It directly addresses the widened-header mechanism from (b), not a symptom.
d Test intent preserved / new tests added? New regression test 04410_normal_projection_correlated_subquery_part_offset added (crashes before the fix, passes after). No existing test weakened.
e Both directions demonstrated? Yes. The reproducer aborts the server on the unfixed build (verified by rebuilding without the change) and runs cleanly on the fixed build; results match the optimize_use_projections=0 plan.
f Fix is general, not a narrow patch? The guard now covers both projection-replacement branches (all-parts and Union) symmetrically, rather than patching the single observed query shape. It is a structural invariant ("the projection-rewritten stream must match the replaced subplan's header"), so any correlated/decorrelation/pruning shape that would widen the header is caught, not just _part_offset + LowCardinality. Falling back to the regular read is always correct.

Session id: cron:clickhouse-worker-slot-0:20260622-221500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd — could you review? This fixes a server crash where the normal-projection optimization (optimizeUseNormalProjections) re-exposes pass-through columns that a correlated-subquery decorrelation step had pruned, widening the rewritten read's header past the decorrelation CROSS JOIN's declared port header. The fix extends the existing blocksHaveEqualStructure guard to the all-parts replacement branch. Root cause + reproducer in the description; pre-PR validation gate in the comment above.

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

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [62f7ad0]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) FAIL
04299_move_assignment_memory_limit FAIL cidb
Stress test (arm_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) ERROR
Timeout FAIL cidb
Integration tests (amd_msan, 4/6) ERROR
Timeout FAIL cidb
LLVM Coverage ERROR

AI Review

Summary

This PR makes optimizeUseNormalProjections reject a projection rewrite when the rewritten projection stream no longer matches the child plan header, and restores the parent ReadFromMergeTree analysis result if that skip happens after the final projection/parent split. The regression test covers both the original OutputPort header exception and the follow-up row-loss fallback. I did not find remaining correctness issues in the changed code.

PR Metadata
  • 💡 Changelog category: Bug Fix is appropriate.
  • 💡 Changelog entry: specific and user-readable, but for a LOGICAL_ERROR it would be clearer to say exception rather than implying server termination. Suggested wording: Fix a LOGICAL_ERROR (Invalid number of columns in chunk pushed to OutputPort) that could be thrown when a normal projection materializing a virtual column, such as _part_offset, was used to read the input of a correlated subquery.
Missing context / blind spots
  • ⚠️ I could not run 04410_normal_projection_correlated_subquery_part_offset locally because this checkout has no build directory. The direct Praktika report for commit 62f7ad01 currently has no failed checks, but most build/test jobs are still pending; a completed CI run or local stateless-test run would close this.
Final Verdict

Status: ✅ Approve

No code changes are required from this review; the changelog wording note above is optional polish.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 23, 2026
…rows

The structure check that skips the normal projection ran after
filterPartsByProjection had already removed parts from the parent
ReadFromMergeTree's analyzed result. selectRangesToRead stores that result on
the step and the optimization mutates it in place, so on the skip path the
regular read that stays in the plan saw only the remaining parts and silently
returned too few rows (the all-parts case dropped them entirely).

Snapshot the analyzed result before filtering and restore it on the skip path,
so falling back to the regular read is correct.

Extend the regression test to compare the projection-on result against the
projection-off result, which catches the silent-too-few-rows case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (fixup fd6fd0a, addressing the code review)

# Question Answer
a Deterministic repro? Yes. On a debug build, SELECT i, j FROM t_proj_corr PREWHERE toLowCardinality(-2147483648) < (_part_offset + _part_starting_offset) WHERE ((SELECT _part_starting_offset) + _part_offset) >= 0 ORDER BY ALL SETTINGS correlated_subqueries_substitute_equivalent_expressions = 0, correlated_subqueries_default_join_kind = 'left' returned 0 rows with optimize_use_projections = 1 and 25 rows with = 0.
b Root cause explained? selectRangesToRead stores the analyzed result on the ReadFromMergeTree step; parent_reading_select_result aliases it. filterPartsByProjection mutates it in place to drop parts already covered by the projection. The first fix put the blocksHaveEqualStructure skip after that mutation, so on the all-parts skip path the regular read that stays in the plan saw zero parts and silently returned too few rows.
c Fix matches root cause? Yes. Snapshot the analyzed result before filterPartsByProjection (only when it is the step's own result) and restore it via setAnalyzedResult on the skip path, so the fallback regular read is correct.
d Test intent preserved / new tests added? Test strengthened: it now compares the projection-on result against the projection-off result (sum(i), sum(j), count()), so the silent-too-few-rows case is asserted, not just "no crash". The fixup also corrected one query result that the prior reference recorded as empty while running on the buggy binary.
e Both directions demonstrated? Yes. First-fix binary: 0 rows (wrong). Fixed binary: 25 rows, equal to optimize_use_projections = 0. Original crash query still does not abort.
f Fix is general, not a narrow patch? The mutation-before-skip hazard exists only in this skip path; both replacement branches now share the corrected order. The sibling aggregate-projection optimizer takes no skip-on-structure-mismatch path, so it is unaffected. Verified the normal-projection, part_offset and correlated-subquery stateless suites stay green (failures limited to tests needing a cluster or S3, unrelated to this change).

Session id: cron:clickhouse-worker-slot-2:20260623-032400

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 18/24 (75.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up push 056a29d, no-old-analyzer tag)

This push addresses the only PR-caused CI failure on the prior head fd6fd0a: the new test 04410_normal_projection_correlated_subquery_part_offset failed deterministically (3/3 reruns) in Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) with Code: 47 ... Missing columns: '_part_starting_offset' ... (UNKNOWN_IDENTIFIER).

# Question Answer
a Deterministic repro? Yes. clickhouse local --enable_analyzer=0 -q "<the test's first query>" throws Code: 47 ... Missing columns: '_part_starting_offset' ... (UNKNOWN_IDENTIFIER) every time; with --enable_analyzer=1 it returns 20 (correct).
b Root cause explained? The test exercises correlated scalar subquery decorrelation ((SELECT _part_starting_offset) referencing the outer table's virtual column). Decorrelation is a new-analyzer-only feature. Under the old analyzer the outer virtual column cannot be resolved inside the subquery scope, so name resolution fails with UNKNOWN_IDENTIFIER before execution. The old analyzer CI combo runs with enable_analyzer=0, hitting exactly this path.
c Fix matches root cause? Yes. -- Tags: no-old-analyzer excludes precisely the analyzer mode the feature does not support (handled at tests/clickhouse-test:2639, if "no-old-analyzer" in tags and is_old_analyzer_used(args): skip). This is the canonical, targeted exclusion used by 20+ new-analyzer-only stateless tests, not a broad no-random-settings.
d Test intent preserved / new tests added? Preserved. The test still runs under the new analyzer with full settings randomization and still asserts both (1) no crash and (2) projection-on result equals projection-off result (the silent-row-drop regression guard). Only the unsupported old-analyzer mode is skipped; no assertion is weakened.
e Both directions demonstrated? Yes. Old analyzer (enable_analyzer=0) reproduces the UNKNOWN_IDENTIFIER failure; the tag makes clickhouse-test skip the test in that mode (verified by running clickhouse-test's exact find_tag_line/parse_tags_from_line on the file, which returns {'no-old-analyzer'}). New analyzer: the full echo-mode output matches the .reference byte-for-byte, 20/20 deterministic runs, and across 9 randomized-settings variants (both prewhere settings off, max_threads 1/16, max_block_size=1, enable_parallel_replicas, optimize_read_in_order=0, parallelize_output_from_storages=0, and optimize_use_projections both 0 and 1).
f Fix is general, not a narrow patch? N/A for the tag change (it gates the test, not engine code). The engine fix in this PR (the projection-skip range-restore in optimizeUseNormalProjection.cpp, head fd6fd0a) is unchanged by this push.

Build ID verified: pre-edit 350838FA... (stale, pre-row-restore binary), after rebuilding the current HEAD the binary is 5C451083... containing the row-restore fix (reading->setAnalyzedResult(...) on the skip path); confirmed optimize_use_projections=1 now returns 40 160 20, not the pre-fix 0 0 0.

Session id: cron:clickhouse-worker-slot-4:20260623-092600

Correlated subqueries are new-analyzer only, so the old-analyzer CI variant
failed with UNKNOWN_IDENTIFIER on (SELECT _part_starting_offset). Use
SET enable_analyzer = 1 (the idiom in 03411/03315/03576) so the test still
runs and validates the fix on every CI combo, rather than skipping it via
no-old-analyzer.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-part-offset-prewhere-projection-output-port branch from 056a29d to 62f7ad0 Compare June 23, 2026 11:02
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 62f7ad01d09a. Our new test 04410_normal_projection_correlated_subquery_part_offset is green here (300 OK / 7 SKIPPED) after forcing the new analyzer with SET enable_analyzer = 1. The remaining red checks are not caused by this PR:

  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) and Integration tests (amd_msan, 4/6): job-level session-timeout (infra), not a specific test failure. This PR is a normal-projection optimizer change and touches no integration test.
  • Stateless tests (amd_tsan, s3 storage, parallel, 2/2): 04299_move_assignment_memory_limit passed on rerun (0 out of 3 reruns failed). Known chronic flaky, unrelated to this PR.
  • Stress test (arm_tsan): "Hung check" - chronic trunk-wide stress flake (runaway server-side fuzzer), not PR-caused.
  • LLVM Coverage: coverage-merge infra artifact.
  • Mergeable Check / PR: aggregators reflecting the above.

Separately, the AST fuzzer "ChunkBuffer extract before all inputs finished" (STID 2651-2cfd) seen on the prior head is a pre-existing trunk bug in correlated-subquery decorrelation (reproduces on clean master, independent of this PR's projection change); fix proposed in PR #108272.

Session: cron:our-pr-ci-monitor:20260623-153000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 62f7ad0 (Finish Workflow SUCCESS). Disposition of every failure:

  • Stateless 04410_normal_projection_correlated_subquery_part_offset (this PR's regression test) - now GREEN on this head across all variants (50/50 on every flaky-check job, OK on the old-analyzer combo, OK on arm/amd debug/asan/tsan/msan/coverage). The earlier old-analyzer red was PR-caused and is fixed by forcing SET enable_analyzer = 1 in the test (correlated subqueries are new-analyzer-only), commit 62f7ad0.
  • Stateless 04299_move_assignment_memory_limit (amd_tsan, s3, 2/2) - pre-existing trunk flaky (10 unrelated PRs / 17 hits / 2 master in 30d, "Failed 0 out of 3 reruns"). Not caused by this PR; tracked separately, deferred to fix PR Cap 04299_move_assignment_memory_limit loop at 60 seconds #108273.
  • Stress test (arm_tsan / arm_msan) Hung check - chronic trunk deadlock family (leaked local ThreadPool on shutdown), not related to this projection change. Tracked under the long-standing Hung-check umbrella.
  • Integration tests (amd_asan_ubsan db disk old analyzer 4/6; amd_msan 4/6) - Timeout - batch session-timeout (infra), no per-test failure rows on this head. Unrelated to the planner change.

No PR-caused failures remain on 62f7ad0. Ready for review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Superseded by #111401, which rebases this fix onto current master and applies it more cleanly (the whole feature/projection-where rework landed since this PR's base, ~3k commits ago). #111401 addresses the same STID 2270-3452 with a smaller diff: it computes has_parent_parts without a copy, runs the equal-structure guard before filterPartsByProjection mutates the analysis result, and keeps system.query_log / EXPLAIN projections = 1 consistent when the projection is skipped. Closing this one to avoid a duplicate.

@groeneai groeneai closed this Jul 22, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants