Skip to content

Extra test coverage for single-argument or() in JOIN ON - #107113

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-single-arg-or-join-on-extract-common-expressions
Aug 28, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-single-arg-or-join-on-extract-common-expressions

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113412
Related: #112654

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Description

Scope changed on 2026-08-26: this pull request is now test-only.

tryExtractCommonExpressions in the LogicalExpressionOptimizer pass assumed every or function node has at least two arguments and enforced it with chassert(or_argument_nodes.size() > 1), throwing an exception with a logical error in debug/sanitizer builds. Release builds were not affected (the chassert is a no-op there and the query returns the correct empty result), hence no changelog entry.

A single-argument or can be resolved when its only argument has the Nothing type: IFunctionOverloadResolver::getReturnTypeWithoutLowCardinality short-circuits to Nothing for any Nothing-typed argument before the function's own getReturnTypeImpl runs, so the "at least 2 arguments" check in FunctionAnyArityLogical is skipped. An empty ARRAY JOIN makes a column Nothing-typed, so

CREATE TABLE t1 (c0 Int) ENGINE = Memory;
SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0 LEFT JOIN t1 ON or(a0 = t1.c0);

produced a single-argument or in the JOIN ON expression and tripped the assert.

The semantically identical guard (return without optimizing when the or has fewer than two arguments) landed on master in #113412 on 2026-08-10, which also closed #112654. Merging master into this branch therefore drops the source change from this pull request as redundant, and what remains is the additional regression test 04327_single_argument_or_in_join_on, which covers shapes that the merged test 04759_single_argument_or_in_join_on does not:

  • a nested single-argument or: ON or(or(a0 = t1.c0));
  • a single-argument or wrapping a Nothing-typed and: ON or(and(a0 = t1.c0, a0 = tx.c0));
  • single-argument or outside JOIN ON — in WHERE, PREWHERE and HAVING, including with convert_query_to_cnf = 1, whose CNF builder also assumes a binary or — asserting that these are rejected cleanly with ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER rather than reaching the pass.

Found by the AST fuzzer (STID 2508-3fad). Reproduced on two unrelated pull requests:


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

Version info

  • Merged into: 26.9.1.247 (included in 26.9 and later)

tryExtractCommonExpressions in the LogicalExpressionOptimizer pass
assumed every or() function node has at least two arguments and asserted
it with chassert(or_argument_nodes.size() > 1), aborting the server in
debug/sanitizer builds.

A single-argument or() can be resolved when its only argument has the
Nothing type: IFunctionOverloadResolver::getReturnTypeWithoutLowCardinality
short-circuits to Nothing for any Nothing-typed argument before the
function's own getReturnTypeImpl runs, so the "at least 2 arguments"
check in FunctionAnyArityLogical is skipped. An empty ARRAY JOIN makes a
column Nothing-typed, e.g.

  SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0
  LEFT JOIN t1 ON or(a0 = t1.c0);

produces a single-argument or() in the JOIN ON expression, which tripped
the assert. Common-expression extraction across disjuncts is meaningless
with fewer than two disjuncts, so return without optimizing instead of
asserting. The single-argument or() then falls through to normal JOIN ON
validation, which rejects it with a clear error where appropriate.

Found by the AST fuzzer (STID 2508-3fad), reproduced on two unrelated PRs
(ClickHouse#106981 AST fuzzer amd_debug, ClickHouse#106682 AST fuzzer arm_asan_ubsan).

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. CREATE TABLE t1 (c0 Int) ENGINE=Memory; SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0 LEFT JOIN t1 ON or(a0 = t1.c0); aborts every time on a debug build (SIGABRT, exit 134). gdb backtrace: abortOnFailedAssertion <- tryExtractCommonExpressions (LogicalExpressionOptimizerPass.cpp:339) <- tryOptimizeCommonExpressionsInOr <- JoinOnLogicalExpressionOptimizerVisitor.
b Root cause explained? LEFT ARRAY JOIN [] makes a0 Nothing-typed, so a0 = t1.c0 resolves to Nothing (the framework's useDefaultImplementationForNothing short-circuit in IFunctionOverloadResolver::getReturnTypeWithoutLowCardinality returns Nothing for any Nothing-typed argument BEFORE getReturnTypeImpl runs). That short-circuit skips FunctionAnyArityLogical::getReturnTypeImpl's arguments.size() < 2 check, so or(<single Nothing arg>) resolves as a single-argument or. It reaches tryExtractCommonExpressions, whose chassert(or_argument_nodes.size() > 1) then fires.
c Fix matches root cause? Yes. The assert encodes a false invariant (a resolved or is not guaranteed to have >= 2 args). The Nothing short-circuit is intentional, broad framework behaviour and must not change. Common-expression extraction across disjuncts is meaningless for < 2 disjuncts, so tryExtractCommonExpressions now returns {} (no optimization) for size <= 1 instead of asserting. The node then falls through to normal JOIN ON validation.
d Test intent preserved / new tests added? New regression test 04327_single_argument_or_in_join_on added, covering single-arg or in JOIN ON, nested or(or(...)), the or(and(...)) variant (now a clean INVALID_JOIN_ON_EXPRESSION), and the WHERE form (clean ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER). No existing test weakened.
e Both directions demonstrated? Yes. Without the fix (master HEAD fc73f46): query aborts (SIGABRT). With the fix: 04327_single_argument_or_in_join_on passes via clickhouse-test; normal common-expression extraction and or-to-IN optimizations still produce correct results.
f Fix is general, not a narrow patch? The single entry point tryExtractCommonExpressions routes all reproduced shapes (direct or, or(and(...)), nested or(or(...))). The sibling and path (tryOptimizeCommonExpressionsInAnd) does not hit this assert (it dispatches per-argument and returns {} for non-or nodes), and the WHERE path is already rejected by filter-type validation. The early return also short-circuits before the downstream chassert(!common_exprs.empty()) and chassert(new_or_arguments.size() >= 2) in the same function. This is not a defensive symptom guard: the assertion's premise was simply wrong for a legitimately resolved single-arg or.

Session id: cron:clickhouse-worker-slot-27:20260610-230500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? It fixes a debug/sanitizer abort (chassert(or_argument_nodes.size() > 1)) in the LogicalExpressionOptimizer pass: a single-argument or() can be resolved when its only argument is Nothing-typed (the framework's Nothing short-circuit skips the arity check), e.g. via an empty ARRAY JOIN in a JOIN ON. tryExtractCommonExpressions now returns without optimizing for fewer than two disjuncts instead of asserting.

@pufit pufit added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ab1d807]

Summary: ✅


AI Review

Summary

This PR has been reduced to an extra stateless regression test, 04327_single_argument_or_in_join_on, that adds unary-or shapes not covered by 04759_single_argument_or_in_join_on after the source fix itself merged separately into master. The added coverage is useful, but the JOIN ON assertions are still tied to the query's current execution behavior on an empty table instead of the stable analysis-phase contract, so I would keep this at ⚠️ Request changes until the test is made less brittle.

Findings

⚠️ Majors

  • tests/queries/0_stateless/04327_single_argument_or_in_join_on.sql:14 The three new JOIN ON rows are asserting today's runtime result (returns empty) even though the regression here is the analysis-time unary-or assert in LogicalExpressionOptimizerPass. That already bit this file once: the or(and(...)) row had to change from INVALID_JOIN_ON_EXPRESSION to success after an unrelated analyzer refactor. Another benign join-analysis change can fail this test while the original bug stays fixed. Suggested fix: follow 04759_single_argument_or_in_join_on and exercise these shapes via EXPLAIN QUERY TREE run_passes = 1, or otherwise assert only the analysis boundary instead of a specific execution result.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: make the new JOIN ON coverage assert the stable analysis-phase invariant rather than the current execution result on an empty table.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
The new regression test only holds under the new analyzer. The old analyzer
rejects these JOIN ON shapes through a different path
(INVALID_JOIN_ON_EXPRESSION), so tag the test no-old-analyzer.

Under the new analyzer, randomized optimize_or_like_chain=1 routes the nested
or(or(...)) through ConvertOrLikeChainPass, which folds the Nothing-typed
disjunct to a constant and rejects the JOIN ON before reaching the
LogicalExpressionOptimizer pass under test. Pin optimize_or_like_chain=0 on
that one statement so it deterministically exercises the fixed pass.

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

Copy link
Copy Markdown
Collaborator Author

The first CI run surfaced two PR-caused test failures (both now fixed in 9896758) plus two unrelated infrastructure failures.

1. Stateless tests (old analyzer): 04327_single_argument_or_in_join_on FAIL
Under the old analyzer, ... LEFT JOIN t1 ON or(or(a0 = t1.c0)) is rejected via a different join-key-extraction path (Code 403 INVALID_JOIN_ON_EXPRESSION) rather than returning the empty result the new analyzer produces. The fix here lives in the new analyzer's LogicalExpressionOptimizerPass, so the test is now tagged no-old-analyzer (the old analyzer already rejects the bad ON cleanly, with no crash to guard).

2. Flakiness under optimize_or_like_chain (new analyzer)
While verifying, I found the test was also ~50% flaky under the new analyzer when the randomized setting optimize_or_like_chain=1 is active: it routes or(or(...)) through ConvertOrLikeChainPass, which folds the Nothing-typed disjunct to a constant and rejects the JOIN ON (Code 403) before reaching the pass under test (clean error, no abort). Pinned optimize_or_like_chain = 0 on that single statement so it deterministically exercises the fixed path. Verified 50/50 runs with full randomization on the new analyzer, and [ SKIPPED ] under the old analyzer.

3. Bugfix validation (functional tests): FAIL — expected, not actionable
This is a debug/sanitizer-only chassert crash. Bugfix validation downloads the master HEAD release binary, where chassert is compiled out, so the test passes there and the inverter reports "Failed to reproduce the bug". A debug-only crash regression test cannot satisfy bugfix validation; this check is informational and non-blocking.

4. arm_asan_ubsan (azure) Segfault STID 0883-49e8 / Stress hung check: infra
Both are part of the known 2026-06-10/11 azure ASan-allocator-OOM outage (__sanitizer::LargeMmapAllocator::Deallocate, no ClickHouse frames), unrelated to this PR.

Both directions re-verified after the change:

  • Without the fix (chassert restored, rebuilt): SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0 LEFT JOIN t1 ON or(a0 = t1.c0) aborts with Logical error: 'or_argument_nodes.size() > 1'.
  • With the fix: 50/50 passes under randomization (new analyzer), skipped under the old analyzer.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI update (HEAD 9896758): one additional failure surfaced after the prior CI summary — Fast test / 03916_system_table (DESCRIBE-derived value returned 2 instead of 0). This is a pre-existing chronic flaky unrelated to this PR (analyzer-only change): the same non-deterministic scheduler/workload value flip has hit 8 distinct unrelated PRs since 2026-05-20 (incl. #77210, #105338, #104493, #105255, #76867, #106987). 0 master hits. Tracked separately for a dedicated fix; not caused by this change. All other checks are accounted for (azure asan-allocator-OOM infra outage + debug-only bugfix-validation, both explained above).

@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Dear @vdimir, 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.

@vdimir vdimir self-assigned this Jul 13, 2026
@vdimir

vdimir commented Jul 13, 2026

Copy link
Copy Markdown
Member

@groeneai check CI failures and proceed with the PR

@groeneai

Copy link
Copy Markdown
Collaborator Author

@vdimir Thanks. Merged fresh master into the branch (head ce52a2f) to get a clean CI run; the stale run was ~13k commits behind. The fix is unchanged: 3 files, +24/-1 (the graceful early-return in LogicalExpressionOptimizerPass::tryExtractCommonExpressions for a single-arg or + regression test 04327).

Prior CI ledger (SHA 9896758) had no blocking failures:

  • Fast test / 03916_system_table: chronic flaky, unrelated (scheduler value non-determinism, 8+ unrelated PRs, 0 master). Not this PR.
  • Bugfix validation (functional tests): expected non-blocking. The bug is a debug-only chassert abort; the bugfix-validation inverter runs the release binary where chassert is a no-op, so it cannot reproduce. No test change can make it pass.
  • CH Inc sync: private, not actionable.

The bug reached master on 2026-07-03 (AST fuzzer amd_tsan, single-arg or() in JOIN ON tripping the assert), so merging closes an active trunk crash. Will watch the fresh CI and report the ledger once it finishes.

@vdimir

vdimir commented Jul 13, 2026

Copy link
Copy Markdown
Member

@groeneai added a test that now passes with a different error code. Something has changed on master, and we need to understand whether the original bug is still present or was fixed by something else.

An intervening analyzer JOIN-analysis change makes a single-argument or()
wrapping a Nothing-typed and() fall through gracefully and return an empty
result instead of raising INVALID_JOIN_ON_EXPRESSION. The original chassert
abort is still present on master (verified: pristine master aborts on all
repros, the fix returns cleanly), so the fix is unchanged; only the S3
expectation is updated to match the new benign behavior.

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

Copy link
Copy Markdown
Collaborator Author

@vdimir The original bug is still present on current master; the fix is still needed.

I built pristine current master (without this PR's change, only the LogicalExpressionOptimizerPass.cpp reverted) and ran the repros against it and against the fixed binary (build IDs verified distinct):

  • Pristine master aborts (SIGABRT, or_argument_nodes.size() > 1) on all three shapes: or(a0 = t1.c0), or(or(a0 = t1.c0)), and or(and(a0 = t1.c0, a0 = tx.c0)) in a JOIN ON where a0 is Nothing-typed (empty ARRAY JOIN).
  • With the fix, all three return cleanly.

The different error code you saw is a benign downstream change, not a fix for the root cause. Previously or(and(a0 = t1.c0, a0 = tx.c0)) fell through to INVALID_JOIN_ON_EXPRESSION (403); on current master the analyzer now accepts the Nothing-typed ON and returns an empty result (t1 is empty) instead of raising. The single-arg or still reaches the same tryExtractCommonExpressions chassert without the fix, so the crash guard is unchanged. I updated statement 3 in 04327 to expect the empty result rather than 403 (8e589a2). The test still fails-without / passes-with the fix.

Ready to merge once CI is green.

A single-argument or is always Nothing-typed (the Nothing short-circuit is the
only path that skips arity validation), so a Nothing-typed WHERE/PREWHERE/HAVING
filter is rejected during query analysis, before ConvertLogicalExpressionToCNFPass
runs. The CNF builder's binary-or assumption is therefore never reached from a
filter. Verified on a debug build: the JOIN ON path still aborts without the fix
while these convert_query_to_cnf=1 forms return ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER
with the server alive.

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

Copy link
Copy Markdown
Collaborator Author

Checked the convert_query_to_cnf = 1 path on a debug build (chassert live: the JOIN ON repro still aborts on the same binary). The unary-or filter does not reach PushOrVisitor there.

A unary or only exists via the Nothing short-circuit in IFunctionOverloadResolver::getReturnTypeWithoutLowCardinality (a real 1-arg or otherwise throws TOO_FEW_ARGUMENTS_FOR_FUNCTION). That makes the or node Nothing-typed, and Nothing is contagious through the logical connectives PushOrVisitor descends. So a WHERE/PREWHERE/HAVING/QUALIFY holding such an or is itself Nothing-typed, and validateFilters (in QueryAnalysisPass, which runs before ConvertLogicalExpressionToCNFPass) rejects it with ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER first.

Confirmed on the debug binary with convert_query_to_cnf = 1: WHERE, PREWHERE, HAVING unary-or (and or(or(...)), and(..., or(...)), not(or(...)), coercion wrappers) all return code 59, server alive; no PushOrVisitor abort. Added those three modes to 04327 as { serverError ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER } (ce4bced), 20/20 under randomization.

Hardening the CNF builder to accept unary or is still reasonable defense-in-depth, but it is not reachable from a filter today, so I kept the fix scoped to the JOIN ON pass plus this coverage. Happy to add the PushOrVisitor guard too if you prefer belt-and-suspenders.

@groeneai

groeneai commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ce4bced

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk, 206 PRs / 40 master in 30d) #110030 (ours, open)
Stateless tests (amd_debug, parallel) / 01730_distributed_group_by_no_merge_order_by_long flaky (Code 241 MEMORY_LIMIT, 66 PRs / 7 master in 30d) #109456 (ours, open)
Mergeable Check rollup of the above owned via the rows above
Sync - CH Inc sync (private, not actionable)

This PR is an analyzer-only fix (single-arg or() in JOIN ON). Neither failure is in a code path this PR touches; both are pre-existing chronic trunk flakies. No PR-caused failure.

Session id: cron:our-pr-ci-monitor:20260714-030000

@vdimir

vdimir commented Jul 14, 2026

Copy link
Copy Markdown
Member

@groeneai check CI

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on ce4bced. 152 pass, 2 reds, both pre-existing flaky trunk failures unrelated to this analyzer-only change, each owned by an open fixing PR:

No PR-caused failure. Ready to merge.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 996f2d4

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / 01548_parallel_parsing_max_memory test exceeds the 60 s per-test runner cap on the macOS runners; the victim is the clickhouse-local --max_memory_usage=50Mi ... file(1g.csv) child, killed by Reason: Timeout! Killing process group a fix task is created (investigating at full effort, fixing-PR link to follow here)

174 of 174 check-runs completed, Finish Workflow green, and this was the only failure.

Not caused by this diff, which changes single-argument or() handling in LogicalExpressionOptimizerPass plus its regression test. Breadth over 30 days is 8 rows across 8 distinct PRs with 0 master rows, 7 of them on arm_darwin within a single 3-hour window on 2026-08-01, which reads as an environmental onset on those runners rather than anything in this branch.

One attribution note: the merged arm_darwin hang fix (#112267, base/darwin-compatibility) is present at this commit, so it does not cover this occurrence. This failure is a plain per-test timeout, not the psynch pthread_rwlock hang that PR addressed, so it needs the separate owner above.

Session id: cron:our-pr-ci-monitor:20260802-010000

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Maintenance pass: the branch was 8 days (~2,715 commits) behind master, so I merged current master (clean, no conflicts; head is now 0000ab347192). Verified locally: incremental build clean, and the 04327_single_argument_or_in_join_on queries run correctly with the fresh binary (the negative case still yields ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER).

The only red on 996f2d4e was Fast test (arm_darwin) / 01548_parallel_parsing_max_memory timing out — a fleet-wide darwin runner flake (it hit 6 unrelated PRs on 2026-08-01), which the fresh CI run should clear.

Also applied the AI review's remaining nit: changed the changelog category to "Not for changelog", since the abort only occurs in debug/sanitizer builds (chassert is a no-op in official releases, which already returned the correct empty result).

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0000ab347 with master 9b6a2d734 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e2194b4a8; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.65 MiB 687.62 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0000ab3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Fresh ledger for the head produced by the master merge (2026-08-09T10:19:31Z). The most recent
previously posted ledger covered 996f2d4ead714e766ffc534bac891e637659f11d and is superseded.

CI is fully finished here: 175 check-runs, 0 queued/in_progress, Config Workflow and
Finish Workflow both success, 154 success / 20 skipped / 1 failure, last completion
2026-08-09T14:25Z. The praktika report has 0 job-level errors and 144 executed jobs, so this is a
full-coverage run.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Logical error: Coordination mode mismatch for stream A: got B, expected C (STID 6117-726a) chronic parallel-replicas coordination defect: replicas roll independent join-order randomization seeds, so they disagree on which relation announces WithOrder fixing PR #112660 (mine, open)

Causal link and fix-presence probe for that owner: #112660 derives the join-order randomization seed
from the initial query id so every replica of one query picks the same join order. Its
QueryPlanOptimizationSettings.cpp hunk is not on this head, which still resolves the sentinel via
randomSeed() per settings-object construction, so this build necessarily predates the fix. Not
PR-caused: the signature spans 5 distinct PRs across 4 Stress test flavours in the last three days
alone (49 rows / 37 PRs / 3 master over 90 days), stress.py forces parallel replicas on every test so
carriers are diffuse, and this diff touches only tryExtractCommonExpressions plus one stateless test.

Session id: cron:our-pr-ci-monitor:20260810-050000

@qoega

qoega commented Aug 10, 2026

Copy link
Copy Markdown
Member

@groeneai — our fuzz agent hit the same or_argument_nodes.size() > 1 assertion post-fix. Commit 52ff84f2570 is in the fleet binary and the assertion at LogicalExpressionOptimizerPass.cpp:1247 still fires — but through JoinOnLogicalExpressionOptimizerVisitor rather than the top-level entry:

tryExtractCommonExpressions (:1247)
  <- tryOptimizeCommonExpressionsInOr (:1376)
  <- JoinOnLogicalExpressionOptimizerVisitor

Trigger (fuzzer mutation of the very test 04759 you added with the fix):

SELECT count() > 0 FROM (
  EXPLAIN QUERY TREE run_passes = 1
  SELECT 9223372036854775807 AS x FROM t_04759 AS tx
  LEFT ARRAY JOIN [] AS a0
  GLOBAL ANTI RIGHT JOIN t_04759 ON or(t_04759.c0 = a0));

Schema-dependent — exact query on a minimal t_04759 (c0 Int) does NOT trip it (needs the fuzzer table's structure); snapshot data dir preserved on the fuzz host. Debug/sanitizer abort; release Code 49.

Suggested scope-extension: the or_argument_nodes.size() > 1 guard needs to hold in the JOIN-ON entry path too, not only at the top-level entry. Same skip-when-single-argument pattern should work; the visitor's dispatch to tryOptimizeCommonExpressionsInOr needs the equivalent early-return.

Happy to file as a fresh sibling if you'd rather keep this PR's scope narrow — just say.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the report, but I do not think there is a second entry path here: the guard lives inside tryExtractCommonExpressions itself, not at its callers, so no caller can bypass it. On master (930f8634c8bf) that function has exactly one definition and the check is at LogicalExpressionOptimizerPass.cpp:1251:

auto & or_argument_nodes = or_node->getArguments().getNodes();
/// ... `Nothing` short-circuit skips the arity check ...
if (or_argument_nodes.size() < 2)
    return {};

Both call sites reach it normally: :1381 from tryOptimizeCommonExpressionsInOr (the JOIN-ON path in your stack) and :1432 from the and variant. The JOIN-ON entry is already covered by construction.

The line numbers in your stack are the pre-fix ones, which I think is the real story:

  • pre-fix :1247 was chassert(or_argument_nodes.size() > 1). Post-fix :1247 is a comment line and the guard moved to :1251.
  • pre-fix :1376 was the tryExtractCommonExpressions call. Post-fix that call is at :1381, and :1376 is now [[maybe_unused]] auto * root_node.

52ff84f2570 added exactly 5 lines, which is precisely the 1247 -> 1251 and 1376 -> 1381 shift. The literal chassert(or_argument_nodes.size() > 1) no longer exists anywhere in the file, so a frame reporting it cannot come from a build that contains that commit.

Measured, two matched Debug binaries (pre-fix 604017b7, guard absent; post-fix c6fcd299bac1, 52ff84f2570 an ancestor), 5 shapes including your exact query, its or(or(...)) / or(and(...)) / FULL JOIN variants, and the 04759 schema: all 5 abort with 134 on pre-fix, all 5 return 1 with rc 0 on post-fix.

That also covers the schema dependence: your exact query on a minimal t_04759 (c0 Int) does abort on a pre-fix binary, so the schema was never the discriminator.

Cheapest check on the fuzz host: run 04759_single_argument_or_in_join_on itself. If it aborts, the binary predates the fix (VERSION_GITHASH is not reliable for this, both of my binaries report the same stale hash).

So no scope extension is needed and no sibling PR either, and thanks for offering. Separately, #107113 is now redundant: #113412 merged the semantically identical change, so I am waiting on vdimir for the disposition of this PR rather than adding to it.

If 04759 passes on your host and the fuzzer still aborts there, that would be a genuinely different defect. Post the stack and the SHOW CREATE TABLE here and I will take it.

@qoega

qoega commented Aug 11, 2026

Copy link
Copy Markdown
Member

Thanks for the correction — you're right, the guard is inside tryExtractCommonExpressions and can't be bypassed by callers, and the :1247/:1376 line numbers in our stack are pre-fix (they shift to :1251/:1381 post-52ff84f2570). So our fleet binary predates the fix despite what VERSION_GITHASH reports. Will run the 04759_single_argument_or_in_join_on stateless test on the fuzz host as your suggested check — if it aborts, the binary is pre-fix and this find is spurious. If it passes and the fuzzer still trips something, I'll come back with the fresh stack + SHOW CREATE on a genuinely post-fix binary. Thanks again — good to know VERSION_GITHASH isn't reliable for these disposition checks. Fine with #107113 waiting on vdimir vs #113412; no scope extension needed.

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Dear @vdimir, 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.

@qoega

qoega commented Aug 17, 2026

Copy link
Copy Markdown
Member

Following up: dev fleet is in a resource-exhaustion state (fork: Cannot allocate memory on trivial ssh commands, likely the recurring clickhouse client leak), so I can't run 04759_single_argument_or_in_join_on on the fuzz binary today to confirm the pre-fix hypothesis directly. Given #113412 merged the semantically identical change on 2026-08-10, master is fixed regardless — our fleet's fresh binaries (once the leak is resolved and next rebuild lands) will pick up the fix and any residual reports on this signature will be checked with the regression-test-as-positive-control approach going forward. Fine with this PR waiting on vdimir's disposition; no further action from our side.

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
…oin-on-extract-common-expressions

Criss-cross merge (two merge bases) produced 592 spurious conflicts; resolved
mechanically by taking master verbatim for every file outside this PR's file set.

The source fix in `LogicalExpressionOptimizerPass.cpp` is dropped: the
semantically identical guard already landed on master, so only the additional
test coverage remains.
@alexey-milovidov alexey-milovidov changed the title Fix LOGICAL_ERROR on single-argument or() in JOIN ON Extra test coverage for single-argument or() in JOIN ON Aug 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and rescoped this pull request to test-only.

Merge. The branch was 17 days / 255197 commits behind master, and it had merged master before, so git merge origin/master hit a criss-cross (two merge bases: 9b6a2d7346fd and fc73f46fae65) and reported 592 conflicts for a 3-file change. Resolved mechanically: master verbatim for every conflicted path outside this branch's own file set, plus the usual silent-drop repair (.gitmodules, four tests/integration/*/__init__.py, and eight contrib submodule gitlinks that the merge deleted without a conflict). Verified invariant: git diff HEAD origin/master --ignore-submodules=none is exactly the one test file. Head 0000ab347192 → ab1d807cdd45.

Source change dropped as redundant. #113412 merged the semantically identical guard on 2026-08-10, so master already returns early from tryExtractCommonExpressions when the or has fewer than two arguments, and already carries 04759_single_argument_or_in_join_on. The conflict in LogicalExpressionOptimizerPass.cpp was therefore resolved in favour of master, and what is left here is only 04327_single_argument_or_in_join_on, which adds shapes 04759 does not cover: nested or(or(...)), or(and(...)), and single-argument or in WHERE/PREWHERE/HAVING including convert_query_to_cnf = 1 (its CNF builder also assumes a binary or). Title and description updated accordingly; still Not for changelog.

Verified locally. ninja clickhouse exit 0, no warnings. Against a scratch server built from ab1d807cdd45 (v26.9.1.1), 04327_single_argument_or_in_join_on passes with the reference output, and the negative cases genuinely raise ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER (checked one of them without the test hint: Code: 59 ... Invalid type for filter in WHERE: Nothing).

Previous CI red is unrelated and now fixed by the merge. The only failure on 0000ab347192 was Stress test (amd_msan) with Logical error: 'Coordination mode mismatch for stream test_1.testing_105153: got Default, expected WithOrder' (STID 6117-726a) in ParallelReplicasReadingCoordinator::getOrCreateCoordinator — nothing to do with the analyzer. #114916 (fix-106039-parameterized-view-coordination-mode) merged into master and is now in this branch.

0 unresolved review threads. Awaiting fresh CI on ab1d807cdd45 and @vdimir's disposition: merge for the extra coverage, or close since the fix itself already landed via #113412.

Comment on lines +14 to +19
SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0 LEFT JOIN t1 ON or(a0 = t1.c0);
-- A nested single-argument `or` reaches the pass the same way.
SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0 LEFT JOIN t1 ON or(or(a0 = t1.c0));
-- A single-argument `or` wrapping a `Nothing`-typed `and` also falls through the pass gracefully;
-- the analyzer accepts the `Nothing`-typed `ON` and the query returns an empty result (t1 is empty).
SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0 LEFT JOIN t1 ON or(and(a0 = t1.c0, a0 = tx.c0));

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.

These JOIN ON repros are still asserting the query's current runtime outcome on an empty table, but the regression this PR wants to guard is the analysis-time unary-or assert inside LogicalExpressionOptimizerPass.

04759_single_argument_or_in_join_on avoids exactly that coupling by using EXPLAIN QUERY TREE run_passes = 1, and this file has already had to rewrite the or(and(...)) expectation once when unrelated join-analysis behavior changed from INVALID_JOIN_ON_EXPRESSION to "returns empty". Another benign analyzer refactor can flip these rows again while the original assert stays fixed.

I think these JOIN ON shapes should also be expressed through EXPLAIN QUERY TREE run_passes = 1 (or otherwise assert only the analysis boundary), so the extra coverage stays pinned to the real contract instead of today's execution semantics.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and the history you cite is exact: 8e589a2a4253 ("Update 04327 for current master: or(and(...)) JOIN ON now returns empty") flipped this very row from -- { serverError INVALID_JOIN_ON_EXPRESSION } to a bare select, for a join-analysis change unrelated to the arity guard. With t1 empty, the three JOIN ON rows also assert only silence, so they carry no positive signal.

I checked that the form you propose actually reaches the pass rather than merely skipping execution. On a master debug build (04759_single_argument_or_in_join_on passes on it, so the guard is present), EXPLAIN QUERY TREE run_passes = 1 over LEFT JOIN ... ON (a AND b) OR (a AND c) shows the join expression root as or(and(...), and(...)) with optimize_extract_common_expressions = 0 and as and(equals(...), or(...)) with it at 1. So the extraction pass does run inside that form for a JOIN ON. All three current shapes return 1 under it.

I will re-express those three rows that way. The four WHERE/PREWHERE/HAVING rows already pin an analysis-time error (ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER is thrown in src/Analyzer/ValidationUtils.cpp), so I plan to leave them as they are unless you want them converted too.

Sequencing: this PR is test-only now and the merge-or-close call on it is still open, with CI running on ab1d807cdd45. Rather than restart that CI, I am holding the rewrite until that call is made, and I will confirm the new form reddens with the guard removed before pushing it.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit d2237d7 Aug 28, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 28, 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 groeneai-origin-unknown PR origin: unclassified (legacy task) pr-not-for-changelog This PR should not be mentioned in the changelog 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 'or_argument_nodes.size() > 1' in LogicalExpressionOptimizerPass on single-argument or() in JOIN ON

6 participants