Skip to content

Fix Bad cast FunctionNode to ConstantNode with WITH FILL on Distributed - #109938

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-distributed-with-fill-const-scalar-bad-cast
Jul 10, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-distributed-with-fill-const-scalar-bad-cast

Conversation

@groeneai

@groeneai groeneai commented Jul 9, 2026 •

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 Bad cast from type DB::FunctionNode to DB::ConstantNode logical error (server abort in debug/sanitizer builds) when running SELECT ... ORDER BY ... WITH FILL against a Distributed table with a low optimize_const_name_size.

Description

When a query is sent to remote shards, ReplaceLongConstWithScalarVisitor (src/Storages/buildQueryTreeForShard.cpp) replaces large constants with __getScalar('hash') function nodes. It already skips LIMIT/OFFSET/LIMIT BY constants, which the planner reads directly as ConstantNode, but it did not skip the WITH FILL FROM/TO/STEP/STALENESS constants under a SortNode.

extractWithFillValue in src/Planner/PlannerSorting.cpp reads those values via node->as<ConstantNode &>(), so a __getScalar FunctionNode there caused Bad cast from type DB::FunctionNode to DB::ConstantNode — an abort in debug/sanitizer builds, a caught exception in release.

Fix: extend needChildVisit to also skip the WITH FILL constant children, mirroring the existing LIMIT guard.

optimize_const_name_size = 0 replaces all constants with __getScalar and reliably triggers the issue; it is CI-randomized, which is why the AST fuzzer and several stress runs surfaced this.

Found by the AST fuzzer / stress tests.
Example CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101791&sha=1859ccbc35ec&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Closes #109992

Version info

  • Merged into: 26.7.1.758 (included in 26.7 and later)

ReplaceLongConstWithScalarVisitor replaced WITH FILL FROM/TO/STEP/STALENESS
constants with __getScalar function nodes when sending a query to remote
shards. The planner reads those values directly via as<ConstantNode &>() in
extractWithFillValue (PlannerSorting.cpp), so a FunctionNode there caused a
"Bad cast from type DB::FunctionNode to DB::ConstantNode" abort in
debug/sanitizer builds (caught exception in release).

Skip the WITH FILL constant children in needChildVisit, mirroring the
existing LIMIT/OFFSET/LIMIT BY guard. optimize_const_name_size = 0 replaces
all constants and reliably triggers the issue.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. SELECT c0 FROM <distributed> ORDER BY c0 WITH FILL TO 6 SETTINGS optimize_const_name_size = 0 aborts every time on the unfixed binary.
b Root cause explained? ReplaceLongConstWithScalarVisitor replaces WITH FILL constants with __getScalar FunctionNodes when building the per-shard query tree; extractWithFillValue (PlannerSorting.cpp) then does as<ConstantNode &>() on that FunctionNode → bad cast. optimize_const_name_size = 0 makes it replace all constants, so WITH FILL constants get replaced too.
c Fix matches root cause? Yes. needChildVisit now skips the WITH FILL FROM/TO/STEP/STALENESS children, exactly mirroring the existing LIMIT/OFFSET/LIMIT BY guard that exists for the same "planner reads it as ConstantNode" reason.
d Test intent preserved / new test added? New test 04401_distributed_with_fill_const_to_scalar.sql covering WITH FILL TO / FROM..TO / FROM..TO STEP with optimize_const_name_size = 0 on a Distributed table.
e Demonstrated in both directions? Yes. Unfixed binary (Build ID 26b6c6…) aborts with the exact CI stack at extractWithFillValue; fixed binary (Build ID 0c4654…, and master-base rebuild 61ee7e…) returns correct results.
f Fix is general, not a narrow patch? Covers all four WITH FILL constant slots (FROM, TO, STEP, STALENESS), all read via as<ConstantNode &>(). The sibling ConstantNode-read sites (LIMIT/OFFSET/LIMIT BY) were already guarded; WITH FILL was the only remaining SortNode gap.
g Generalizes across inputs? The guard is keyed on node identity (the SortNode's fill children), independent of value/type, so it holds for any constant type/value in those positions.
h Backward compatible? Yes. No setting default, format, or behavior change; only prevents an incorrect scalar-substitution that produced an abort.
i Invariants and contracts preserved? Yes. Upholds the invariant that constants the planner reads directly via as<ConstantNode &>() are never rewritten to __getScalar FunctionNodes on the shard query tree.

Session id: cron:clickhouse-worker-slot-3:20260709-200500

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @vdimir — could you review? This mirrors the LIMIT/OFFSET/LIMIT BY guard in ReplaceLongConstWithScalarVisitor (PedroTadim's #109-era fix) for the WITH FILL FROM/TO/STEP/STALENESS constants, which extractWithFillValue also reads directly as ConstantNode. Fixes the AST-fuzzer/stress Bad cast FunctionNode → ConstantNode with optimize_const_name_size = 0 on Distributed.

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

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6d638af]

Summary: ✅


AI Review

Summary

This PR fixes the reported WITH FILL failure by keeping those SortNode constants as ConstantNodes when building shard queries, and the new stateless regression covers the reproduced Distributed cases. I don’t think it is complete yet, because the same scalar-rewrite mechanism still reaches window frame offset children, which leaves another deterministic distributed-query failure in the same area.

Findings

⚠️ Majors

  • [src/Storages/buildQueryTreeForShard.cpp:329] The new guard handles SortNode fill children, but WindowNode frame offsets are still traversed by ReplaceLongConstWithScalarVisitor. WindowNode::toASTImpl serializes those rewritten children back into the shard SQL, while the shard analyzer still requires getFrameBeginOffsetNode / getFrameEndOffsetNode to be ConstantNodes in QueryAnalyzer.cpp:2903 and QueryAnalyzer.cpp:2924. On supported distributed window queries, SETTINGS optimize_const_name_size = 0 can therefore still turn ROWS BETWEEN 1 PRECEDING ... into ROWS BETWEEN __getScalar(...) PRECEDING ..., which the shard rejects. Suggested fix: also skip WindowNode frame offset children in this visitor and add a distributed window regression with a bounded frame.
Final Verdict

Changes needed before merge: the fix closes the reported WITH FILL path, but the same post-analysis scalar rewrite still breaks bounded window frames on distributed queries.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 9, 2026
return false;
}

if (auto * sort_node = parent->as<SortNode>())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes the SortNode branch, but the same ConstantNode invariant is still broken for window frame offsets. ReplaceLongConstWithScalarVisitor will still traverse WindowNode::getFrameBeginOffsetNode / getFrameEndOffsetNode, and src/Analyzer/WindowNode.cpp serializes those children back into the SQL we send to shards. Distributed window queries are already supported here (tests/queries/0_stateless/01568_window_functions_distributed.sql), so with SETTINGS optimize_const_name_size = 0 a query like ... OVER (ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) on a Distributed / remote table will still turn that 1 into __getScalar(...) on the shard query. The shard analyzer then rejects it at src/Analyzer/Resolve/QueryAnalyzer.cpp and src/Analyzer/Resolve/QueryAnalyzer.cpp because frame offsets must also stay ConstantNodes.

I think this visitor needs the same skip for WindowNode frame offset children, plus a regression test that covers a distributed window query with a bounded ROWS/RANGE frame.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for flagging this. I checked whether window frame offsets hit the same Bad cast and could not reproduce it. Details below.

The __getScalar substitution does happen for frame offsets. Over a genuinely-remote shard with optimize_const_name_size = 0, the shard query is exactly what you predicted:

SELECT sum(n) OVER (ORDER BY n ASC ROWS BETWEEN __getScalar('...') PRECEDING AND __getScalar('...') FOLLOWING) ...
SELECT sum(n) OVER (ORDER BY n ASC RANGE BETWEEN __getScalar('...') PRECEDING AND CURRENT ROW) ...

But the shard does not reject it and results are correct. __getScalar is a constant-foldable function (FunctionGetScalar uses the default isSuitableForConstantFolding() == true), so on the shard the analyzer folds it back into a ConstantNode before the frame-offset validation at QueryAnalyzer.cpp:2903/:2924. The as<ConstantNode>() check there sees a real ConstantNode and passes.

Why WITH FILL is different. The SortNode Bad cast is not an analyzer-time check. It fires at planning time in extractWithFillValue (PlannerSorting.cpp), which reads the fill value straight off the node with node->as<ConstantNode &>() on the tree that still holds the __getScalar FunctionNode. Window frame offsets have no analogous planner-time node read: the offset value is materialized into a Field (window_frame.begin_offset / end_offset) during analysis (QueryAnalyzer.cpp:2910/:2931), and getFrameBeginOffsetNode()/getFrameEndOffsetNode() are never read anywhere under src/Planner/ or src/Interpreters/.

I reproduced the WITH FILL crash locally to confirm the harness, then ran window frame offset queries (ROWS + RANGE, begin + end offsets) over test_shard_localhost, remote(...), a genuinely-remote single-shard Distributed, and distributed-over-distributed, all with optimize_const_name_size = 0: correct results, no crash, in every case.

So the frame-offset skip isn't needed for correctness here, and per our contributing guidance I'd rather not add a guard I can't back with a failing repro. If you have a shape that does trigger it (a planner path that reads the frame-offset node directly, or a config where __getScalar stays unfolded on the shard), please share it and I'll add the skip plus a regression test.

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 6d638af

CI fully finished (Finish Workflow: pass, Mergeable Check: pass, CH Inc sync: pass). No failing checks on this head.

Check / test Reason Owner / fixing PR
(none) — All checks green on this head
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260710-020000

@PedroTadim

Copy link
Copy Markdown
Member

@yakov-olkhovskiy maybe you can review this?

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love it!

@alexey-milovidov alexey-milovidov self-assigned this Jul 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 10, 2026
Merged via the queue into ClickHouse:master with commit bcbf203 Jul 10, 2026
175 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 10, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 10, 2026
…e_const_name_size LIMIT BY bad-cast, unrelated stress failure)
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jul 11, 2026
…an shard

`04401_distributed_with_fill_const_to_scalar` (added by ClickHouse#109938) runs
distributed `ORDER BY ... WITH FILL` queries. The CI `distributed plan`
shard installs `users.d/distributed_plan.xml`, which turns on
`serialize_query_plan` globally. `serializeSortDescription` throws
`NOT_IMPLEMENTED: WITH FILL is not supported in serialized sort description`,
so every `WITH FILL` query fails there. On master the test fails ~6/8 times
in `Stateless tests (amd_asan_ubsan, distributed plan, parallel)` while being
green in every default-settings shard (`serialize_query_plan` defaults to 0).

The test targets the query-tree shard rewrite in `buildQueryTreeForShard`
(the `Bad cast from type DB::FunctionNode to DB::ConstantNode` fix), which is
only exercised with `serialize_query_plan = 0` anyway. Pin the setting to 0 on
each query, mirroring the existing opt-out used by other distributed tests
(e.g. `02535_max_parallel_replicas_custom_key_rmt`,
`03403_parallel_blocks_marshalling_for_distributed`). Results are unchanged, so
the reference file stays identical.

Surfaced on the CI report of PR ClickHouse#96823
(shard `Stateless tests (amd_asan_ubsan, distributed plan, parallel)`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5, 26.6. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Jul 14, 2026
…lar test

Issue ClickHouse#110237 reported the same Bad cast FunctionNode->ConstantNode as ClickHouse#109938
but via the STALENESS bound (extractWithFillValueWithIntervalKind), which the
04401 regression test did not exercise. Add a DESC WITH FILL STALENESS -2 query
and a negative TO/STEP query so a regression that drops only the staleness/step
guard line is caught.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…th-fill-const-scalar-bad-cast

Fix Bad cast FunctionNode to ConstantNode with WITH FILL on Distributed
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…an shard

`04401_distributed_with_fill_const_to_scalar` (added by ClickHouse#109938) runs
distributed `ORDER BY ... WITH FILL` queries. The CI `distributed plan`
shard installs `users.d/distributed_plan.xml`, which turns on
`serialize_query_plan` globally. `serializeSortDescription` throws
`NOT_IMPLEMENTED: WITH FILL is not supported in serialized sort description`,
so every `WITH FILL` query fails there. On master the test fails ~6/8 times
in `Stateless tests (amd_asan_ubsan, distributed plan, parallel)` while being
green in every default-settings shard (`serialize_query_plan` defaults to 0).

The test targets the query-tree shard rewrite in `buildQueryTreeForShard`
(the `Bad cast from type DB::FunctionNode to DB::ConstantNode` fix), which is
only exercised with `serialize_query_plan = 0` anyway. Pin the setting to 0 on
each query, mirroring the existing opt-out used by other distributed tests
(e.g. `02535_max_parallel_replicas_custom_key_rmt`,
`03403_parallel_blocks_marshalling_for_distributed`). Results are unchanged, so
the reference file stays identical.

Surfaced on the CI report of PR ClickHouse#96823
(shard `Stateless tests (amd_asan_ubsan, distributed plan, parallel)`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…lar test

Issue ClickHouse#110237 reported the same Bad cast FunctionNode->ConstantNode as ClickHouse#109938
but via the STALENESS bound (extractWithFillValueWithIntervalKind), which the
04401 regression test did not exercise. Add a DESC WITH FILL STALENESS -2 query
and a negative TO/STEP query so a regression that drops only the staleness/step
guard line is caught.

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

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.

Logical error: Bad cast from type DB::FunctionNode to DB::ConstantNode (STID: 1635-18db)

5 participants