Skip to content

Fix THERE_IS_NO_COLUMN for optimize_rewrite_aggregate_function_with_if with distributed queries - #106908

Merged
yakov-olkhovskiy merged 6 commits into
masterfrom
cursor/fix-rewrite-aggregate-if-distributed-5863
Jun 13, 2026
Merged

yakov-olkhovskiy merged 6 commits into
masterfrom
cursor/fix-rewrite-aggregate-if-distributed-5863

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

Closes: #82941
Related: #83363

When RewriteAggregateFunctionWithIfPass rewrites sum(if(cond, val, null)) to sumIf(_CAST(val, 'Nullable(T)'), cond), the _CAST stays as a FunctionNode on the initiator (no resolve pass runs after optimization). On the remote (secondary) server, the same _CAST gets constant-folded during re-resolution, producing a ConstantNode with result type Nullable(T).

The column naming function calculateActionNodeNameWithCastIfNeeded used getResultType for the inner type annotation, which gives T on the initiator (from the pre-cast constant) but Nullable(T) on the remote (from the folded result). This caused a column name mismatch:

  • Initiator: _CAST(0_UInt8, 'Nullable(UInt8)'_String)
  • Remote: _CAST(0_Nullable(UInt8), 'Nullable(UInt8)'_String)

Fix: when the constant was folded from _CAST (receivedFromInitiatorServer is true), use the source _CAST function's first argument type as the inner type annotation. This mirrors how the initiator names it by recursively walking the FunctionNode's arguments.

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 THERE_IS_NO_COLUMN exception for distributed queries involving optimize_rewrite_aggregate_function_with_if optimization when the aggregate function argument requires a cast to Nullable type.

Open in Web Open in Cursor 

Version info

  • Merged into: 26.6.1.733

…if` with distributed queries

When `RewriteAggregateFunctionWithIfPass` rewrites `sum(if(cond, val, null))`
to `sumIf(_CAST(val, 'Nullable(T)'), cond)`, the `_CAST` stays as a
FunctionNode on the initiator (no resolve pass runs after optimization).
On the remote (secondary) server, the same `_CAST` gets constant-folded
during re-resolution, producing a ConstantNode with result type
`Nullable(T)`.

The column naming function `calculateActionNodeNameWithCastIfNeeded` used
`getResultType()` for the inner type annotation, which gives `T` on the
initiator (from the pre-cast constant) but `Nullable(T)` on the remote
(from the folded result). This caused a column name mismatch:
- Initiator: `_CAST(0_UInt8, 'Nullable(UInt8)'_String)`
- Remote:    `_CAST(0_Nullable(UInt8), 'Nullable(UInt8)'_String)`

Fix: when the constant was folded from `_CAST` (`receivedFromInitiatorServer`
is true), use the source `_CAST` function's first argument type as the
inner type annotation. This mirrors how the initiator names it.

Closes: #82941

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [654bc64]

Summary: ✅


AI Review

Summary

This PR fixes the distributed analyzer column-name mismatch for optimize_rewrite_aggregate_function_with_if by converting rewritten constant branches to nullable constants instead of leaving an initiator-side _CAST that remote shards can fold differently. The added stateless test pins the rewrite setting and uses the established multi-shard remote('127.0.0.{1,2}', ...) pattern. I did not find any remaining code issues that need inline comments; the previous bot-authored threads are resolved against the current code.

Missing context / blind spots
  • ⚠️ I could not execute the new stateless test locally because this workspace has no clickhouse binary or build directory, and .git cannot fetch the current PR head. Review used the GitHub-fetched PR head 14dabbc210ffe2a772754be06205a1ab8de22507, the combined PR diff, prior discussion, and the current PR checks; Fast test, Build (arm_tidy), and the aggregate PR check were still pending when reviewed.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
The bugfix validation requires the test to fail on master. Using
`remote('127.0.0.1', ...)` (single host) doesn't trigger the distributed
execution path — the query runs locally without header comparison between
initiator and remote. Change to `remote('127.0.0.{1,2}', ...)` which
forces actual distributed execution and reproduces the column name mismatch.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
cursoragent and others added 3 commits June 10, 2026 03:32
The previous fix was too aggressive — it used the source _CAST's first
argument type for ALL `receivedFromInitiatorServer` constants, which broke
cases where the `_CAST` was added during AST serialization of a folded
constant (e.g., NULL with type Nullable(String)).

Now we only use the first argument's type when it's a "simple" constant
whose natural field type matches its stored type (i.e., it wouldn't need
its own _CAST wrapping). This correctly distinguishes:
- Case A: `_CAST` was a live FunctionNode on the initiator (optimization
  pass) — first arg `0` has type UInt8, field type matches → use UInt8
- Case B: `_CAST` was added during serialization — first arg NULL has
  type Nullable(Nothing), field type is Nullable → needs cast → fall back
  to `getResultType`

Co-authored-by: Yakov Olkhovskiy <[email protected]>
- Add comment to empty catch block to satisfy style checker
- Force `optimize_rewrite_aggregate_function_with_if = 1` in test to
  prevent the stateless runner from randomizing it to 0

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Replace `FieldToDataType` + try/catch with a simpler check: call
`requiresCastCall(type, type)` on the first arg's result type directly.
For literals parsed from AST, the natural field type always equals the
result type, so this is equivalent. The check reduces to testing if the
type is Nullable/Array/Tuple (which triggers cast wrapping).

Co-authored-by: Yakov Olkhovskiy <[email protected]>
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
…apping in _CAST

The previous approach of modifying `calculateActionNodeNameWithCastIfNeeded`
was fundamentally flawed — it couldn't distinguish between _CAST nodes
created by the optimization pass vs those added during AST serialization,
causing regressions in multiple tests.

New approach: in `RewriteAggregateFunctionWithIfPass`, when the kept branch
is a ConstantNode and needs type promotion to Nullable, use
`convertToNullable` directly instead of `createCastFunction`. This avoids
the naming mismatch entirely because:
- On initiator: the constant is already Nullable, named via getResultType
- On remote: after AST round-trip and folding, same getResultType applies
- No FunctionNode vs folded-ConstantNode asymmetry exists

For non-constant arguments (column references, expressions), the original
`createCastFunction` path is preserved since those don't have the naming
divergence issue.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.60% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.20% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 11/14 (78.57%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review June 10, 2026 14:15
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR narrowly changes how the aggregate-function-with-if rewrite handles constant arguments (converting constants directly to Nullable instead of wrapping in CAST) to fix column-name mismatches in distributed queries. The only flagged query, TPC-H Q4, is a count(*) with an EXISTS semi-join and never triggers that rewrite path, so the +19.86% delta (borderline and not a large shift) is run-to-run variance rather than a real PR effect. Downgrading it to not-sure. No other queries regressed and no cross-query patterns were observed.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 2759 3307 +19.9% 0.0321 aggregation: PR only touches the aggregate(if/CASE-with-constant) rewrite pass; Q4 (count(*)+EXISTS) never hits it

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
  • StressHouse run: d483ddca-0855-462f-87d1-6a22d2ab929e
  • MIRAI run: 417a7cb5-362e-493b-b6ef-860397cfb114
  • PR check IDs:
    • clickbench_285727_1781198317
    • clickbench_285888_1781198349
    • clickbench_285908_1781198349
    • tpch_adapted_1_official_286091_1781198548
    • tpch_adapted_1_official_286187_1781198586
    • tpch_adapted_1_official_286207_1781198587

@KochetovNicolai KochetovNicolai self-assigned this Jun 12, 2026
@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Jun 13, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Jun 13, 2026
@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Jun 13, 2026
Merged via the queue into master with commit 4369d8d Jun 13, 2026
166 checks passed
@yakov-olkhovskiy
yakov-olkhovskiy deleted the cursor/fix-rewrite-aggregate-if-distributed-5863 branch June 13, 2026 03:23
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @yakov-olkhovskiy @KochetovNicolai — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently misleading):

  • Why: The PR body describes a fix that modifies calculateActionNodeNameWithCastIfNeeded to use the source _CAST function's first argument type when receivedFromInitiatorServer is true. The actual shipped diff does NOT touch PlannerActionsVisitor.cpp; instead it modifies RewriteAggregateFunctionWithIfPass.cpp so constant arguments are converted via ConstantNode::convertToNullable instead of being wrapped in _CAST. The description reflects an earlier/alternative approach and no longer matches the code.

  • Suggested addition:

    Update the description to reflect the implemented approach: in RewriteAggregateFunctionWithIfVisitor::enterImpl, when the preserved if argument is already a ConstantNode, clone it and call ConstantNode::convertToNullable instead of wrapping it in a _CAST FunctionNode. This makes the initiator produce a ConstantNode (matching the constant-folded node on the remote), so calculateActionNodeNameWithCastIfNeeded derives identical column names on both sides.

Ignore this if the current title/body is intentional.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 13, 2026
Same macOS loopback issue as 04336 in this PR. The test runs
remote('127.0.0.{1,2}', system.one), connecting to 127.0.0.2. Linux
auto-routes all of 127.0.0.0/8 to loopback, but macOS only binds 127.0.0.1, so
the connection to 127.0.0.2:9000 times out on the Fast test (arm_darwin) runner.

CIDB shows the failure is macOS-only (0 OK / 3 FAIL on arm_darwin across 3
unrelated PRs, 100% pass on every Linux job including the flaky check 50/50 on
4 sanitizers). The shard tag does not skip it because Fast test forces
clickhouse-test --shard. Add it to ci/defs/darwin.skip, next to its sibling
distributed tests. Added by ClickHouse#106908.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

THERE_IS_NO_COLUMN / optimize_rewrite_aggregate_function_with_if + distributed + analyzer

6 participants