Skip to content

Fix NOT_IMPLEMENTED for a direct join with parallel replicas, a Distributed table or a View - #121256

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-direct-join-dummy-plan-filter-collection
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-direct-join-dummy-plan-filter-collection

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 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):

Fixed NOT_IMPLEMENTED (None of the algorithms enabled by the 'join_algorithm' setting [direct] can execute this ALL INNER JOIN with the given right table storage type) for a query with join_algorithm = 'direct' that also makes the planner collect filters before planning, which happens when the query reads a Distributed table or a View, or sets parallel_replicas_min_number_of_rows_per_replica.

Description

Related: #71028 (comment)
Related: #119861

collectFiltersForAnalysis replaces every table with StorageDummy, optimizes the plan, reads the pushed-down filters off its ReadFromDummy nodes and throws it away; its own comment says it "is never executed". That optimize() still ran the full second pass, so it also picked physical joins. direct is the only algorithm whose candidate depends on the right table's real storage, and that storage is captured while the plan is built (tryGetStorageInTableJoin, tryMakeDirectJoinWithMergeTree) from the tables the dummy replacement had just erased, so chooseJoinAlgorithm had nothing left to offer it. With any other list the loop falls through to hash, which is why only direct surfaces it. The fix keeps that plan's joins logical, next to the three flags already turned off there for the same reason.

This is not parallel-replicas-specific: a Distributed table or a View reaches the same route with enable_parallel_replicas = 0. Four of the right-table kinds it accepts (MergeTree, Join, dictionary, EmbeddedRocksDB) failed before and succeed now.

The reported repro fails 100% before and passes after; the new test pins the settings reaching each trigger. A plan that collects nothing would also throw nothing, so I checked collection still happens: push-down is implemented for JoinStepLogical and applyFilters runs before any join is physicalized, so the skipped conversion cannot reach ReadFromDummy's filter. Measured on a joined query, the only shape this can affect: the filtered side still estimates one granule (8192 rows) instead of 1000000 and uses no replicas, identically before and after, while a build with collection stubbed out fails that check. The test carries that as a third arm, and a 220-test sweep over the consuming families is unchanged.

Stack trace, which locates the throw inside the filter-collection plan
5.  src/Planner/PlannerJoins.cpp:1495                 chooseJoinAlgorithm
6.  src/Processors/QueryPlan/JoinStepLogical.cpp:2154  buildPhysicalJoinImpl
7.  src/Processors/QueryPlan/JoinStepLogical.cpp:2252  JoinStepLogical::buildPhysicalJoin
8.  .../Optimizations/optimizeJoin.cpp:277             convertLogicalJoinToPhysical
9.  .../Optimizations/optimizeTree.cpp:452             optimizeTreeSecondPass
10. src/Processors/QueryPlan/QueryPlan.cpp:907         QueryPlan::optimize
11. src/Planner/Planner.cpp:396                        collectFiltersForAnalysis   <<<< here
12. src/Planner/Planner.cpp:2363                       Planner::Planner
13. src/Interpreters/InterpreterSelectQueryAnalyzer.cpp:348

Frame 11 is result_query_plan.optimize(optimization_settings), three lines under the comment
/// This plan collects pushed-down filters and is never executed.


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

collectFiltersForAnalysis replaces every table expression with StorageDummy,
builds a plan, optimizes it, reads the pushed-down filters off its ReadFromDummy
nodes and discards it. Its own comment says the plan is never executed, and three
optimization flags are already turned off there for that reason.

That optimize() call still ran the full second pass, so it also converted logical
joins to physical ones: make_distributed_plan = false was the only thing that
would otherwise have kept them logical (optimizeJoin.cpp, keep_logical =
keep_logical_steps || make_distributed_plan). The right table's storage identity
is captured while the plan is built, via tryGetStorageInTableJoin for a
StorageJoin, a non-Range StorageDictionary or any IKeyValueEntity, and via
tryMakeDirectJoinWithMergeTree for a MergeTree table; choosing a physical join is
where its absence becomes fatal, because direct is the only algorithm whose
candidate depends on it. The dummy replacement had just erased exactly that, so
with join_algorithm = 'direct' the candidate loop ended empty and
chooseJoinAlgorithm threw NOT_IMPLEMENTED out of a plan nobody was going to run.
With the default join_algorithm list the loop falls through to hash in the
throwaway plan and nothing is observable, which is why only a list whose every
entry is storage-dependent surfaces this.

Keeping that plan's joins logical fixes the whole family rather than one case:
all four right-table kinds direct accepts were refused, and both ways of
requesting filter collection reached it, the parallel-replicas row estimation
under a non-zero parallel_replicas_min_number_of_rows_per_replica and a plain
Distributed table with parallel replicas off entirely.

Filter collection itself is unaffected: push-down is implemented for
JoinStepLogical directly and runs in the first pass, and the passes skipped in
the dummy plan are execution-shape optimizations that cannot change
ReadFromDummy's collected filter. Checked rather than assumed, since a plan that
collects nothing would also throw nothing, and checked with a join in the query,
since without one this change has nothing to do and both builds are trivially
equal: a selective filter on the left table still estimates one granule instead
of the whole table and still leaves parallel replicas off, identically before and
after, while a build with filter collection stubbed out fails that same check.
Shard skipping is unchanged, and 220 tests across the shard-skipping,
index-analysis, parallel-replicas and prewhere families are identical before and
after.

The new test pins the setting that reaches each route instead of drawing it, and
asserts DirectKeyValueJoin is still chosen so a silent fall back to another
algorithm cannot pass it. Its third arm asserts the estimate stays selective, so
the filters cannot silently stop being collected either; that arm is green before
the fix as well, which is what a non-regression lock should be.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 9 findings adjudicated)

Independent cold review of the resulting code plus a stateful second-model gate on each round,
adjudicated against the recorded evidence. Round 1 bounced the tree back over the item at the top of
this table; round 2 re-reviewed the delta and found one wording nit.

# Finding Verdict
❌ The regression test did not prove filter collection stays live: neither arm carried a WHERE, so an empty filter map would have produced the same counts and the same DirectKeyValueJoin rows. And the control offered for it out of tree contained no JOIN, so the dummy plan held no logical join, the flag was a no-op there, and base == fix was guaranteed a priori. AGREE, fixed: arm C now asserts the estimate stays selective, and a build with filter collection stubbed out makes it fail
❌ Related: #110518 pointed at the "unknown stream" CI matcher issue; nothing here touches that abort path. AGREE, removed
⚠️ The description attributed tryGetStorageInTableJoin / tryMakeDirectJoinWithMergeTree to physical join selection; both run while the plan is built, and the identity they capture is what chooseJoinAlgorithm later has none of. AGREE, reworded in the body and the commit message
⚠️ Arm B was flaky, 19/50 and 22/50, before a prefer_localhost_replica pin: at 0 the shard executes the join, so the initiator's plan holds a remote read the control cannot look inside. AGREE, pinned; removing the pin on the fixed binary still reddens that row, so the pin is load-bearing
💡 "All four right-table kinds it accepts" claimed an exhaustive matrix: tryGetStorageInTableJoin accepts any IKeyValueEntity, and KeeperMap and Redis implement it too. The measured matrix is four; the accepted set is larger. AGREE, weakened in the description. The commit message keeps the older phrasing; noted, not blocking
💡 Related: lines should carry full GitHub URLs. AGREE, fixed
💡 The 05233 .sql was last written after the 50-run batches that licence it. DISAGREE: system.query_log on the repro server holds the same arm C query with the same per-query SETTINGS in the 101 runs before that write and in the run after it, differing only in the comment above them
💡 The new test's opening comment restates the narrative at length. DISAGREE: comment trimming is a separate phase here, and test files are outside the density budget
💡 The local build used clang-21 while CI pins clang-22. DISAGREE: every observable here is control flow (an exception thrown or not, a row estimate, a ProfileEvent), with no codegen, UB or sanitizer-margin dependence; CI builds with the pin

Three things the review verified rather than took on trust, reported because they are what a reviewer
would otherwise have to re-derive:

  • The flag closes the whole reachable surface. keep_logical_steps has exactly one consumer,
    convertLogicalJoinToPhysical (optimizeJoin.cpp:267), and both places that reach it, the main
    second-pass traversal and the deferred pass after applyParallelReplicas, go through it, so no
    physical join can be built in this plan whatever the parallel-replicas settings are.
    replaceTableExpressionsWithDummyTables has one call site, inside the patched function, and both
    collectFiltersForAnalysis entry points funnel through it. The other dummy-plan builder,
    findParallelReplicasQuery.cpp, never calls QueryPlan::optimize, so it cannot reach the throw.
  • Filter collection cannot change, by construction. ReadFromDummy's filter_actions_dag is
    written only by applyFilters(), which has exactly one invocation in src/, in
    optimizePrimaryKeyConditionAndLimit - and that runs in the first stack loop of
    optimizeTreeSecondPass, before any join is physicalized, in the old code as well as the new. Its
    prewhere_info is written only by optimizePrewhere, which needs a FilterStep directly above the
    source step, an adjacency physicalization neither creates nor breaks (it constructs no FilterStep).
  • Nothing silently flips. All 14 stateless tests that assert NOT_IMPLEMENTED together with
    join_algorithm = 'direct' contain no filter-collection trigger, and neither tests/config nor
    tests/clickhouse-test sets parallel_replicas_min_number_of_rows_per_replica on master; a genuinely
    unsupported right table still throws the same error from the real plan. The changelog category was
    checked against the release branches rather than assumed: 26.9 carries the same
    collectFiltersForAnalysis and the same physicalization, so the defect is released.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-test 05211_pr_plan_based_direct_join_merge_tree --client-option parallel_replicas_min_number_of_rows_per_replica=1 fails 100% of runs with Code: 48 on the unfixed binary and passes 100% without that setting. Not a rate.
b Root cause explained? Yes. collectFiltersForAnalysis replaces every table with StorageDummy and optimizes a plan it then discards. That optimization ran the full second pass, which picks physical joins, and physical join selection is the only step that reads the right table's storage identity (tryGetStorageInTableJoin, tryMakeDirectJoinWithMergeTree) that the dummy replacement had erased. With join_algorithm = 'direct' no candidate remains, so a plan that is never executed throws at the user. The CI stack trace resolves frame 11 to Planner.cpp:396, that plan's optimize() call.
c Fix matches root cause? Yes. It stops physicalizing joins in the plan whose own in-tree comment says it is never executed, beside the three flags already set there for that reason. No widened bound, no no-random-* tag, no guard at the throw site.
d Test intent preserved / new tests added? Yes. 05211 is untouched and is now green with the culprit setting injected. New 05233_direct_join_dummy_plan_filter_collection asserts 6 rows: 4 across both triggers (2 of them DirectKeyValueJoin controls, both shown to flip to 0 when join_algorithm becomes hash, so no count row can pass merely because the join fell back), plus a third arm that locks the invariant this change risks, filter collection staying live. That arm is green before the fix too, and its liveness is measured: a build with filter collection stubbed out makes it FAIL, and raising the estimation threshold flips it.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (7d64e834 unfixed; c02425ee then 36bd19c3 fixed, same source, rebuilt for the mutation control), per test and also per individual row: all 4 red-on-base rows throw Code: 48 before and return their expected values after.
f Fix is general across code paths? Yes. replaceTableExpressionsWithDummyTables has exactly one call site in src/, inside the patched function, and both collectFiltersForAnalysis entry points funnel through the patched overload. keep_logical_steps has no other writer besides the user-facing EXPLAIN option, and defaults to false.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Four of the right-table kinds direct accepts go from Code: 48 to a correct result: MergeTree, Join engine, HASHED dictionary and EmbeddedRocksDB, each with a default-join_algorithm control proving the fixture itself is sound. Both filter-collection triggers are covered by the two shipped test arms: the parallel-replicas row estimation, and a Distributed table with enable_parallel_replicas = 0.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default, new setting, experimental gate, serialization or format change, and no header touched, so no SettingsChangesHistory.cpp entry applies. The only behavioural delta is that a previously rejected query now runs.
i Invariants and contracts preserved? Yes. The invariant is that the filter-collection plan is optimized only as far as filter collection needs. Measured directly rather than inferred, because a plan that collects nothing would also throw nothing, and measured on a JOINED query, which is the only shape this change can affect: the filtered side estimates one granule (8192 rows) and uses no replicas, against 1000000 rows and replicas in use unfiltered, identically before and after. That measurement is not vacuous: stubbing filter collection out makes it fail, and reverting the stub restores it. Shard skipping is unchanged and 220 tests across the shard-skipping, index-analysis, parallel-replicas and prewhere families are identical before and after.

Session id: cron:clickhouse-impl-slot-5:20260921-005100

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6dfb162]

Summary: ✅


AI Review

Summary

This PR keeps the filter-collection dummy plan from converting logical joins to physical joins, which avoids the spurious NOT_IMPLEMENTED for join_algorithm = 'direct' when collectFiltersForAnalysis runs. I did not find a remaining correctness issue in the current diff: the new keep_logical_steps guard covers both physical-join conversion sites, and the updated 05233 test now exercises both the ordinary and plan-based dummy-plan paths without weakening the filter-collection assertions.

Missing context / blind spots
  • ⚠️ I did not rerun the stateless tests locally because this checkout does not include a reusable build / clickhouse-test binary.
Final Verdict

✅ No new blockers or majors in the current PR head. No new inline review comments were necessary.

LLVM Coverage Report

Measured on commit 6dfb162.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
@groeneai
groeneai requested review from davenger and vdimir September 21, 2026 02:00
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 21, 2026
Comment thread src/Planner/Planner.cpp Resolved
convertLogicalJoinToPhysical is called from two places in optimizeTreeSecondPass. The main traversal
calls it only when enable_parallel_replicas is off; with plan-based parallel replicas on, the joins are
deliberately left logical there so applyParallelReplicas can clone a fragment, and a deferred pass
converts whatever stayed in the outer plan afterwards. keep_logical_steps returns early at both, but the
three arms shipped so far only reached the first: none of them pinned parallel_replicas_plan_based, and it
is not one of the settings the test runner randomizes, so the deferred call site had no coverage at all.
The setting reaches the filter-collection plan because that plan's optimization settings are built from
the original query context, not from the copy its own tree carries.

Measured on the base binary, the two routes throw from different lines of optimizeTreeSecondPass: the
existing arm A from the main traversal, and the new arm from the deferred pass. Both new assertions fail
with Code 48 NOT_IMPLEMENTED before the fix, measured one client invocation each so neither rides on the
other's abort.

The arm also repeats the filter-collection check in that mode, because plan-based is the one mode where
applyParallelReplicas runs on the throwaway plan as well. It cannot rewrite it: it acts only through
split markers, insertParallelReplicasSplit plants those above the MergeTree reads collectReadsToDistribute
finds, and the dummy replacement leaves none, so it returns before planting any. Those two rows are green
before the fix as well, which is what a non-regression lock should be; a build with
collectFiltersForAnalysis stubbed out fails them, and it fails exactly them and arm C's pair, so they are
not vacuous.

Test only, no source change. 50 runs twice with randomization on, plus the 05211 carrier.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 18d8a5e

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.

Check / test Reason Owner / fixing PR
Build profile diff infra: the CI logs cluster read timed out (LogCluster select failed with exception then ReadTimeoutError against the staging endpoint), so the job exits 1 instead of skipping (issue #120462) #121048 (external, open)

156 checks succeeded, 18 were skipped, Finish Workflow is green, and no test row on this head is FAIL or ERROR in the CI database. PR is the aggregate rollup over the one failure above, not a separate result.

Session id: cron:our-pr-ci-monitor:20260921-103829

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

It seems the fix is specific to parallel replicas, and the PR title does not indicate that.

@groeneai groeneai changed the title Fix NOT_IMPLEMENTED for a direct join when the query needs filter collection Fix NOT_IMPLEMENTED for a direct join with parallel replicas, a Distributed table or a View Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Not specific to parallel replicas. The throwaway plan is built whenever the planner has to collect pushed-down filters before planning for real, and storage_requires_filter_collection (src/Planner/Planner.cpp) triggers that for five cases: a Distributed table, a cluster engine such as s3Cluster, a View, a Merge over one of those, and MergeTree when the parallel replicas row estimation is on. Only the last one involves parallel replicas.

Measured on this PR's base and on its head, with parallel replicas off in every setting:

CREATE TABLE l_local (k UInt64) ENGINE = MergeTree ORDER BY k;
CREATE TABLE l_dist AS l_local ENGINE = Distributed(test_shard_localhost, currentDatabase(), l_local);
CREATE TABLE r (k UInt64, v String) ENGINE = MergeTree ORDER BY k;
INSERT INTO l_local SELECT number FROM numbers(100);
INSERT INTO r SELECT number, toString(number) FROM numbers(1000);

SELECT count() FROM l_dist AS t0 INNER JOIN r AS t1 ON t1.k = t0.k
SETTINGS enable_analyzer = 1, join_algorithm = 'direct', query_plan_join_swap_table = 0,
         enable_parallel_replicas = 0, parallel_replicas_min_number_of_rows_per_replica = 0,
         prefer_localhost_replica = 1;

Base throws Code: 48 ... [direct] ... (NOT_IMPLEMENTED); the head returns 100 and still picks DirectKeyValueJoin. With a VIEW over r as the left table instead of l_dist: base throws the same, head returns 1000. The same query against the undistributed table returns 100 on both, so the right table itself is fine for direct. Arm B of the new test is that Distributed case.

The title named no trigger at all, which was worth fixing regardless: it is now "Fix NOT_IMPLEMENTED for a direct join with parallel replicas, a Distributed table or a View", and the changelog entry and description now name View too. Tell me if you want it narrower or worded differently.

@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done

This branch has not been deployed

No deployments
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants