Skip to content

Fix THERE_IS_NO_COLUMN through remote() and parallel replicas for tuple comparisons with a false or NULL constant element - #125195

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/comparison-tuple-elimination-no-foldable-comparison
Oct 15, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/comparison-tuple-elimination-no-foldable-comparison

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #124546

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

Fixed THERE_IS_NO_COLUMN and NOT_FOUND_COLUMN_IN_BLOCK errors in queries over remote() or with parallel replicas that compare tuples where one pair of elements is constant and false, such as (n, 1) = (n, 2), or where NULL is compared with a column, such as (n, s) = (NULL, s).

Description

On 26.8.21.12, SELECT NOT ((n, 1) = (n, 2)) AS r, min(s) FROM remote('127.0.0.{1,2}', currentDatabase(), t) GROUP BY r fails with THERE_IS_NO_COLUMN. With parallel replicas the same defect makes 05350_comparison_tuple_elimination_shared_alias fail in about 1 of 130 runs (PR #105667).

ComparisonTupleEliminationPass runs after constant folding and builds and(equals(n, n), equals(1, 2)) without folding it. A remote server analyzes the query again, folds 1 = 2 and then the and to a constant, and names that constant after its source expression, where n is unqualified because the remote does not read it. The initiator then looks for __table1.n and does not find it. n = NULL folds to NULL and breaks the same way.

The pass now applies resolveFunction's own folding decision and guards to the nodes it creates: the element comparisons, then and with their results. It keeps the original tuple comparison when a folded result would depend on a column. Constant pairs that do not make and fold (true, NULL, LowCardinality) are still rewritten as before, so the primary key is still used. The __getScalar lookup is shared with resolveFunction through a new helper. One cost: an always-false comparison such as WHERE (n, 1) = (5, 2) is no longer folded to 0, so the table is read and filtered.

The test gains a remote() query for each declined shape (all fail on master) and a force_primary_key query for each kept shape. 100/100 runs passed (50 with random settings), and an A/B run of 1599 related tests on master and on the fix gave the same results apart from this test.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/125195]

Version info

  • Merged into: 26.10.1.2435-master (included in 26.10 and later)

groeneai and others added 6 commits October 11, 2026 09:12
… ComparisonTupleEliminationPass

The pass runs after constant folding and builds element comparisons with
resolveOrdinaryFunctionNodeByName, which does not fold. A comparison such as
equals(1, 2), equals(n, NULL) or one with a __getScalar argument stays a
function on the initiator, but a remote shard or parallel replica re-analyzes
the shipped query text and folds it. The secondary server then names the folded
constant after its source expression, with unread columns unqualified, so the
initiator fails with NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN.

When resolveFunction could fold the comparison (all arguments constant,
getConstantResultForNonConstArguments returns a constant, or a direct
__getScalar argument), the pass now keeps the original tuple comparison.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… pass-created comparison folds

The previous commit declined every comparison with a direct __getScalar
argument, which dropped the rewrite for a non-NULL Array / Tuple /
LowCardinality scalar facing a column, although a remote server does not fold
that comparison either. Extract the scalar lookup resolveFunction uses for
constant folding into tryGetScalarConstantColumn and use it in
canBeConstantFolded, so the pass sees the scalar's value exactly as a fresh
analysis does. resolveFunction's behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… 05350

Lines 1-2 read min(s) so the remote server never reads n: otherwise it
reads its cheapest column for the row count, which can be n, and the names
then match by accident. Lines 3-4 cover a NULL literal and a NULL
LowCardinality scalar facing a column. Line 5 checks that a non-NULL scalar
facing the key column is still rewritten and uses the primary key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ss it makes and fold

Declining every element comparison that a fresh analysis would fold also
dropped the rewrite for a true constant pair, e.g. `02030_tuple_filter`'s
`(1, (1, (id, value))) = (1, (1, (1, 'A')))`, which then lost the primary
key (`force_primary_key` gave INDEX_NOT_USED). Such a pair is harmless on a
remote server: it folds to a constant whose source expression contains no
column, so both sides name it the same way, and `and(x, 1)` is not folded.

The pass now asks the folding decision of `resolveFunction` (execution for
constant arguments, otherwise `getConstantResultForNonConstArguments`, with
its aggregate / arrayJoin / dummy / 1 MiB guards) on the nodes the remote
folds: the element comparisons, then `and` with their folded results. It
declines only when an element containing a column folds (NULL facing a
column) or when the `and` folds (a native-number false pair). A single-
element tuple still declines any fold of the comparison that replaces it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds a single-element NULL comparison through remote() (declined: it folds
to a NULL whose source contains a column), and four primary-key lines that
must keep the rewrite: a true constant pair, a false LowCardinality pair
(`and` does not fold it), an arrayJoin element (resolveFunction does not
fold such a node), and a column-free NULL fold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comment lines in ComparisonTupleEliminationPass.cpp that narrate the new code; the tryFoldFunction doc comment already says when nullptr is returned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 The fold decision in ComparisonTupleEliminationPass restates resolveFunction's folding guards (the same mirroring foldConstantCast does) AGREE, not changed No decision differs for the functions it runs on (equals, and); the and check and the arrayJoin guard are each pinned by a mutation of the test. I can extract a shared predicate if preferred.
2 💡 During a rolling upgrade, a new initiator and an old shard disagree on the header for the declined shapes AGREE, not changed Only always-false or NULL-arm tuple comparisons are affected; every other shape ships the same tree as before.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-10:20261011-125600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Through remote('127.0.0.{1,2}', ...) the five new declined-shape queries fail on master every run with Code: 8 THERE_IS_NO_COLUMN. With parallel replicas and parallel_replicas_local_plan = 0 the CI error Code: 10 NOT_FOUND_COLUMN_IN_BLOCK ... While executing Remote reproduces 15/15. Also red on 26.8.21.12.
b Root cause explained? The pass runs after constant folding and creates comparisons and an and without folding them. A remote server analyzes the query again, folds them to a constant, and names it after a source expression whose column it does not read (n, not __table1.n), so the initiator's header lookup fails.
c Fix matches root cause? Yes. The pass applies resolveFunction's own folding decision and guards to the nodes it creates, and keeps the original tuple comparison when a folded result would depend on a column. No setting pin, no tag, no widened assertion.
d Test intent preserved / new tests added? The original 05350 queries are unchanged. New: a remote() query per declined shape (red on master) and a force_primary_key query per kept shape. Each line is turned red by at least one of 11 code mutations, and each mutation reddens exactly its planned lines.
e Both directions demonstrated? Master: whole test FAIL (return code 8), each declined line Code 8, parallel replicas Code 10. Fix: test OK, every remote() line equal to its local twin, parallel replicas OK.
f Fix is general across code paths? Both single-element and both multi-element paths of the pass go through the check. resolveFunction's scalar folding uses the same new helper (pure refactor). JOIN ON is never visited by the pass.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered: NULL and NULL-scalar elements, LowCardinality(Nullable) and LowCardinality scalars, LowCardinality constant pairs, arrayJoin elements, column-free folds, nesting, single and multi element, = and !=, a constant on either side, a literal over 1 MiB. 10-row truth table through remote(): master is red exactly on the declined shapes.
h Backward compatible? (maintainer-approved exception only) Yes, no setting, format or default change. Behaviour changes only for the declined shapes. One plan cost: an always-false tuple comparison is no longer folded to 0.
i Invariants and contracts preserved? The pass still returns "no candidate" on a decline, created nodes are resolved as before, and initiator and remote header names now agree. Evaluation errors propagate; the same error is raised on master at plan build. 1599 related tests gave the same results on master and the fix, apart from this test.

Session id: cron:clickhouse-impl-slot-4:20261011-114200

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a98856]

Summary: ✅


AI Review

Summary

This PR teaches ComparisonTupleEliminationPass to skip rewrites that a fresh analysis would fold, which fixes the same-version remote() / parallel-replicas header mismatch for false and NULL tuple arms. I still see one compatibility hole: the declined shapes now ship a different analyzed expression than older servers produce, so mixed-version clusters can still fail during rolling upgrades.

Findings
  • ❌ Blockers
    • [dismissed by author -- https://github.com/Fix THERE_IS_NO_COLUMN through remote() and parallel replicas for tuple comparisons with a false or NULL constant element #125195#issuecomment-6109617375] [src/Analyzer/Passes/ComparisonTupleEliminationPass.cpp:255] Returning {} here fixes same-version re-analysis, but it is not rolling-upgrade-safe: a new initiator keeps the tuple comparison while an older shard still rewrites it to and(equals(...), ...), so the two sides emit different projection names and remote() / parallel-replicas queries still fail with NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN until every shard is upgraded. tests/integration/test_analyzer_compatibility/test.py:81 already documents that analyzer-side naming skew breaks distributed execution for exactly this reason.
    • Suggested fix: preserve a wire-compatible header shape when talking to older peers (or keep emitting the pre-fix rewritten tree until every participating server is new enough), and add a mixed-version integration test for this query family.
Final Verdict

Request changes — the same-version fix looks good, but the declined shapes still lack a rolling-upgrade-safe compatibility path.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 11, 2026
Comment on lines +255 to +266
if (folding_result && hasColumnNode(equals_function))
return {};
and_arguments.emplace_back(std::move(folding_result), equals_function->getResultType(), "");
}

auto result_function = std::make_shared<FunctionNode>("and");
result_function->markAsOperator();
result_function->getArguments().getNodes() = std::move(tuple_arguments_equals_functions);
resolveOrdinaryFunctionNodeByName(*result_function, result_function->getFunctionName(), getContext());

if (tryFoldFunction(result_function, and_arguments))
return {};

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 same-version remote() / parallel-replicas re-analysis, but these decline paths are still not rolling-upgrade-safe. A new initiator now keeps the tuple comparison for the declined shapes, while an older shard still rewrites the same expression to and(equals(...), ...); distributed execution matches remote blocks by name, so the mixed-version cluster still hits NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN until every shard is upgraded.

We already carry tests/integration/test_analyzer_compatibility/test.py for this exact class of analyzer-side naming skew. Please either preserve a wire-compatible header shape when talking to older peers (the same problem also applies to the single-element decline below), or add an explicit mixed-version test that proves these declined shapes cannot cross a version boundary.

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.

This is a corner case. Tolerable.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1a98856da with master ac85267b8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 1b9d29136; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

81 translation units recompiled, 528 s compile time in total, 81 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +21.2 s (+4%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Oct 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
Merged via the queue into ClickHouse:master with commit f71da67 Oct 15, 2026
173 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

#125936 is fixed by #124854 (open, approved), which now closes it; measurements: #125936 (comment)

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 comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

4 participants