Skip to content

Fix logical error joining a Merge over Distributed table with USING - #111327

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-111253-join-using-merge-over-distributed
Sep 6, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-111253-join-using-merge-over-distributed

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111253

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 a LOGICAL_ERROR ("query tree node does not have valid source node") when a Merge table wrapping a Distributed table is joined and a bare column of the joined-away side is used as a predicate.

Description

ReadFromMerge builds a separate query for each underlying table. It removes the JOIN and then strips the WHERE/PREWHERE sub-expressions that reference the joined-away table, via removeExpressionsThatDoNotDependOnTableIdentifiers. That helper only inspected FunctionNode top-level expressions; a bare-column predicate such as WHERE r.k (a ColumnNode) hit an early return and was left in the child query. When the Distributed child was re-planned to be sent to the shards, that column had a dangling source and the analyzer threw Code: 49 ... Column k UInt32 query tree node does not have valid source node.

The fix treats any non-and top-level expression (bare column, constant, or single non-and function) uniformly: it is dropped if it references only removed tables. This is the same rule the helper already applied to single-function predicates and to each conjunct of an and.

The single-line change covers more shapes than the reported one, so the test pins each entry path (all verified to raise the logical error without the fix and to pass with it):

  • USING and ON, and a self-join of the Merge table, which needs one table and no second fixture. Reported by zlareb1 on the issue after this PR was opened.
  • QUALIFY and HAVING, not only a hand-written WHERE. The planner folds QUALIFY into HAVING when there are no window functions and HAVING into WHERE when there is no aggregation, so such a predicate reaches the same helper. This is also the shape the AST fuzzer hit on Fix wrong ORDER BY results for Merge over Distributed #112931.
  • Left-side counterparts (qualify_l, self_join_on_l, bare_where_l_k), so no case can pass by dropping the predicate outright.
  • PREWHERE, which StorageMerge::replaceTableExpressionAndRemoveJoin strips through a separate call of the helper. Only the inner-join form is pinned (with USING and with ON): its result does not depend on whether the predicate is applied before or after the join, so it must equal the WHERE form. With an outer join, PREWHERE is applied before the join by design (Wrong PREWHERE with LEFT JOIN query result #89097).

The same helper is used to decide push-down for query-backed MySQL/PostgreSQL/SQLite sources, so 04341_sqlite_query_passing pins that partition too. Measured on both arms, the only verdict this patch changes there is a bare predicate on the joined local side, which master rejected while accepting every other spelling of it. A disjunction mixing the two sides is still not rejected; that verdict is identical on both arms, so it is a pre-existing gap of testing a reconstructed AST for a surviving WHERE, pinned here rather than fixed.

A second pre-existing false positive of that guard is fixed here: with the query-backed external table on the non-preserving side of an outer join (or in a FULL JOIN), getASTForExternalDatabaseFromQueryTree pushes nothing down but cleared only the WHERE of the reconstructed query, so a PREWHERE on the joined MergeTree table survived and was rejected as a filter on the source (... FROM mt AS l LEFT JOIN sqlite(db, query('...')) AS r USING (id) PREWHERE l.flag), although the same query with WHERE l.flag is accepted. A PREWHERE on the external table's own columns cannot reach the guard at all: these engines do not support PREWHERE and the query fails earlier with ILLEGAL_PREWHERE. PREWHERE is now cleared together with WHERE, and 04341_sqlite_query_passing pins both the joined-side PREWHERE cases and the ILLEGAL_PREWHERE ones.

The external_table_strict_query setting text and the sqlite, mysql and postgresql table function docs are updated to state this scope: a filter on the columns of the external table that cannot be pushed down is rejected, while a predicate that references only other tables joined in the surrounding query is evaluated after the join and is not affected.


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

Version info

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

When Merge builds the per-child query it removes the JOIN and strips the
parts of WHERE/PREWHERE that reference the joined-away table, via
removeExpressionsThatDoNotDependOnTableIdentifiers. That helper only handled
FunctionNode-typed top-level expressions: a bare-column predicate over the
joined-away table (e.g. `WHERE r.k`) hit an early return and was left in the
child query. When the Distributed child was re-planned to be sent to the
shards, that column had a dangling source and threw

  Code: 49. Column k UInt32 query tree node does not have valid source node

Treat any non-`and` top-level expression (bare column, constant, or single
non-`and` function) uniformly: drop it if it references only removed tables.

Closes ClickHouse#111253

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. The exact query from the issue aborts on demand on pristine HEAD (test_cluster_two_shards form used in the test).
b Root cause explained? Yes. When Merge builds the per-child query it removes the JOIN and strips WHERE/PREWHERE parts referencing the joined-away table via removeExpressionsThatDoNotDependOnTableIdentifiers. That helper early-returned for a non-FunctionNode top-level expression, so a bare-column predicate (WHERE r.k) was left in the child query. The Distributed child is then re-planned through the analyzer, where r.k has a dangling source, throwing at ColumnNode::getColumnSource().
c Fix matches root cause? Yes. The owning stripping helper now handles bare columns/constants (drop if they reference only removed tables), not a guard at the throw site.
d Test intent preserved / new tests added? New test 04545_join_using_merge_over_distributed covering the crash + differential (bare r.k, bare r.n, function r.k>0, and mix, surviving l.k). No existing test weakened.
e Demonstrated in both directions? Yes. Clean A/B rebuild in one worktree: pristine HEAD (Build ID e092f57...) aborts; fixed (1ce6fb39...) passes. Result equals the Distributed-direct control (EXCEPT check EQUIVALENT).
f Fix general, not a narrow patch? Yes. Fixes the single owning helper. Its other caller (transformQueryForExternalDatabaseAnalyzer.cpp, external-DB push-down) benefits identically; the symmetric and/PREWHERE paths already worked and still do.
g Generalizes across inputs? Verified bare join-key (r.k) and non-key (r.n); function r.k>0; conjunction r.k AND l.k>0; surviving-side bare l.k (kept, source valid); no-WHERE; Distributed-direct control. All correct.
h Backward compatible? Yes. No setting/format/wire change; only removes an invalid, crash-inducing predicate from an internally-generated child query. WHERE semantics of the user query are unchanged (result equivalence with Distributed-direct confirmed).
i Invariants/contracts preserved? Yes. Completes the helper's contract ("remove expressions that don't depend on this child table") for the bare-column case. hasUnknownColumn correctly keeps child-table columns and drops others (proven by the differential). The and-only code below still runs only for a non-null and, so no null deref.

Session id: cron:clickhouse-author-slot-1:20260722-071100

@groeneai

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

An independent second model reviewed the resulting code before this PR was opened. Findings and dispositions:

❌ Blockers

  • External-DB strict-query bypass for bare predicates — DISAGREE (disproved locally).
    The claim was that this change makes the external-database analyzer path strip a foreign bare-column WHERE before external_table_strict_query=1 validation runs. Verified with an A/B rebuild in one worktree using a SQLite-backed external table and the same LEFT JOIN under external_table_strict_query=1:

    • bare WHERE l.id, enable_analyzer=1: returns rows on both pristine HEAD and the fixed build;
    • same, enable_analyzer=0: throws INCORRECT_QUERY on both;
    • function WHERE l.id>0, enable_analyzer=1: returns rows on both.

    A byte-diff of the two runs is identical. The analyzer-vs-legacy strict-query divergence is pre-existing (it already applies to function predicates, which never touched the changed line) and is unchanged by this fix. No action.

💡 Nits

  • Comment precision in removeExpressionsThatDoNotDependOnTableIdentifiers — AGREE, fixed. hasUnknownColumn drops an expression when any referenced column has a source other than the child table; the comment was reworded to say exactly that.
  • "crash"/"aborted" wording in the test — AGREE, fixed. A LOGICAL_ERROR is a catchable exception (aborts only in debug/sanitizer builds); the test comment now says "raised the logical error".

Both nit fixes are comment-only; the binary was rebuilt and the regression test re-run (10/10 and 50/50 OK). A delta re-review of the fix commits returned 0 findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @azat — could you review this? It fixes a LOGICAL_ERROR ("query tree node does not have valid source node", #111253) when a Merge-over-Distributed table is joined with USING: removeExpressionsThatDoNotDependOnTableIdentifiers skipped a bare-column WHERE (a ColumnNode, not a FunctionNode), leaving a predicate on the joined-away table in the child query with a dangling source. The fix folds the bare-column/constant case into the existing hasUnknownColumn check.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8881d0f]

Summary: ✅


AI Review

Summary

This PR fixes two related analyzer-side filter-reconstruction problems: StorageMerge now drops top-level non-and predicates whose columns no longer belong to the child table, avoiding the LOGICAL_ERROR from Merge over Distributed joins, and the external-table reconstruction path now clears both WHERE and PREWHERE on join sides where no pushdown is possible. The current PR head also brings the external_table_strict_query documentation and tests into line with the implemented analyzer behavior. I did not find any remaining blocker- or major-level issues in the current diff.

Final Verdict

✅ No new findings on the current PR head.

LLVM Coverage Report

Measured on commit 8881d0f.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 47/47 (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 Jul 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 357a95c

CI fully finished (Finish Workflow + Config Workflow pass; Mergeable Check red only because of the two non-PR-caused flaky checks below; no checks queued/in_progress/pending). This PR touches only src/Analyzer/Utils.cpp (bare-column WHERE stripping in removeExpressionsThatDoNotDependOnTableIdentifiers) + the new test 04545_join_using_merge_over_distributed — neither failure below is in a code path this diff can affect. Every failure has an owner.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table/test.py::test_check_all_tables flaky (chronic; 21 master + 60 unrelated PRs / 30d) a fix task is created (investigating at full effort — fixing PR link to follow here)
Stress test (amd_tsan) / Cannot start clickhouse-server + Check failed flaky (chronic server-boot-under-stress; 40 master + 15+ unrelated PRs / 30d) a fix task is moved to pending (investigating at full effort — fixing PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260722-153000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PRs for the Stress test / Cannot start clickhouse-server + Check failed ledger line on this PR.

That row is emitted by the stress harness itself (tests/docker_scripts/stress_tests.lib:298) after the readiness probes fail, so it only says the server was not answering; the cause is on a sibling row of the same job. On this PR the cause was the part_loading_tree_rollback test family, which fabricates part directories out of band and left an unparsable part behind across a fault-injected restart:

Check Boot error
Stress test (amd_tsan) Code 722 -> 695 -> Code 246, part all_2_3_1_0 intersects all_1_2_2_1 in test_7.t_plt_reparent

Fixed by, all merged:

The object-storage variant of the same family is pinned by #111922 (open).

Verification: all three merge commits are ancestors of master, and the signature stops dead in CIDB. Boot failures caused by t_plt_* ran 35 / 63 / 64 / 64 / 66 / 36 per day over 07-19..07-24 and then 0 from 2026-07-24 04:48 onward. Occurrences after that date are confined to Upgrade check, which runs the frozen previous-release copies of the tests, so no master-side change can reach them.

Nothing about this failure was related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_check_all_tables flaky (Integration amd_asan_ubsan, db disk, old analyzer): #111353 (merged 2026-07-22, backported to 26.7 by #111574).

The failure is the plain-rewritable metadata_dropped concurrent-create race, not anything in this PR. Every occurrence after that merge is on a build whose base predates it: I checked all 49 distinct commits that produced this failure since 2026-07-22 17:31Z, and 49 of 49 lack the fix. Merging master into this PR picks it up. Details: #111477 (comment)

Two further ways to reach the same dangling column source, both reported after
the fix was written and both verified to raise the logical error on the parent
commit while passing with the fix:

* The planner folds QUALIFY into HAVING when there are no window functions, and
  HAVING into WHERE when there is no aggregation, so a bare-column predicate
  written in either clause arrives at
  removeExpressionsThatDoNotDependOnTableIdentifiers as a WHERE and takes the
  same path as a hand-written WHERE. The blanket QUALIFY clear in StorageMerge
  is not what handles it.
* A self-join of the Merge table reaches it with a single table and no second
  fixture, with ON as well as USING (reported by zlareb1 on issue ClickHouse#111253).

Each new case has a left-side counterpart (qualify_l, self_join_on_l) so a case
cannot pass by dropping the predicate outright.

Also trim the comment on the changed branch to the local invariant, and say
"exception" rather than "crash" for the LOGICAL_ERROR: it is thrown and handled
in release builds, and only debug and sanitizer builds abort on it.
Comment thread src/Analyzer/Utils.cpp Resolved
A bot review on this PR reported that folding the non-FunctionNode
early-return in removeExpressionsThatDoNotDependOnTableIdentifiers widens
the external_table_strict_query bypass, turning a previously rejected
query into an accepted one.

The behaviour change is real but it is a fix, not a regression. The
setting's contract, stated in transformQueryForExternalDatabase.h, is
that an outer filter on the query-backed source must fail rather than be
applied locally. A predicate over the joined local side is not a filter
on that source: it constrains a table ClickHouse reads itself, so
applying it locally is where it belongs.

Master already accepted that same local-side predicate in every other
spelling (r.id = 1, r.id > 0, r.id IS NOT NULL) and rejected only the
bare-column one, because the early-return kept the bare column in the
reconstructed AST while hasUnknownColumn nulled out the function forms.
The bare-column case was the outlier; folding the early-return makes the
partition uniform.

Measured on both arms of the one-line change, with distinct build IDs and
a per-arm server restart. Predicates on the source (bare, function, and
inside a conjunction with a local-side predicate) are rejected on both
arms. Predicates on the local side are accepted on both arms, except the
bare-column one, which only master rejects. Query results are identical
across arms in every shape, so no filter is dropped from the real plan:
the helper only rewrites a clone used for the pushdown decision.

The cases are added to the SQLite test because sqlite() gives a
query-backed source with no external service, so the partition is pinned
in a stateless test. Each accepted case fails on master at the
bare-column line, and each rejected case pins the guard that must keep
firing.
A review round noted that the joined-local-side cases only used the
USING key, so r.id and the source's own id column are interchangeable
for the tested rows, leaving it arguable whether the assertion pins the
bare-column path or just the join result.

Lead with r.flag instead. It does not exist in the passed query at all,
so no pushdown of it is possible and the accepted result can only come
from the predicate being applied locally. The r.id spellings are kept
after it, since they are the exact shape the review reported.

The reference count stays 1 for both flag cases: only id = 1 has
flag = 1.

Also drop the backticks from the added comment. The whole SQL block is a
double-quoted shell string, so a backticked word there is command
substitution, and the test failed with "flag: command not found" while
still printing correct results.
The previous section header claimed a predicate on the source is rejected in
every shape. That is too strong: a disjunction mixing the source and the local
side, such as WHERE l.id = 1 OR r.flag, is not rejected.

removeExpressionsThatDoNotDependOnTableIdentifiers drops a non-and top-level
expression as a whole when it references a removed table, so the whole or
disappears from the reconstructed AST and the presence test in
rejectOuterFilterForQueryBackedExternalSourceIfStrict sees no filter left.

Measured on both arms of this PR's one-line change, with the source reverted and
restored and distinct build IDs asserted: the accept/reject verdict of every or
shape is identical, so the gap predates this PR. It is the analyzer-path
fragility of testing a rewritten AST for the presence of WHERE, not a
consequence of folding the bare-column early return. The old analyzer rejects
the same query.

Results stay correct, so this is a missed rejection rather than a wrong answer;
the two counts asserted here must agree. Narrow the header to what is measured
and pin the gap so a later change to that guard has a witness.
The external_table_strict_query verdicts asserted there hold on the
query-tree path only. On the legacy path
rejectOuterFilterForQueryBackedExternalSourceIfStrict clones the original
AST when query_info.syntax_analyzer_result is set, so the guard never
reaches removeExpressionsThatDoNotDependOnTableIdentifiers and rejects
every one of those queries instead.

Measured on this build: with enable_analyzer = 0, five of the nine new
assertions flip (all four local-side cases plus the mixed-disjunction pin
at strict = 1), while the two pre-existing assertions and the strict = 0
control are unaffected. The section now pins the path the one-line fix in
src/Analyzer/Utils.cpp actually changes.

This does not alter what CI runs today: enable_analyzer defaults to 1 and
clickhouse-local does not read the server users.d profile that the
old-analyzer job variant installs, so the reference is unchanged. The pin
is a guard against the assertion silently changing meaning if that ever
stops holding.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0353645

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
BuzzHouse (amd_debug) / Logical error: 'Pipeline stuck. Current state: (STID 3833-2f1a) trunk logical error, 4 rows / 4 unrelated PRs / 0 master in 14d a fix task is created (investigating at full effort - fixing PR link to follow here)
Upgrade check (amd_release) / Error message in clickhouse-server.log DiskLocalCheckThread probe-file leak: all local disk check threads share one clickhouse_disk_checker_<uuid> name, so one thread's cleanup makes the others log FILE_DOESNT_EXIST (Code 107) #110773 (mine, open)
Build (arm_release) / Post Hooks build-profile telemetry INSERT INTO build_time_trace gets HTTP 500 from LogCluster; check_status is success and the check is non-gating a fix task is moved to pending (investigating at full effort - fixing PR link to follow here)

Not PR-caused. This diff is confined to src/Analyzer/Utils.cpp (JOIN USING column resolution for a
Merge over Distributed) plus two stateless tests; no frame of it appears in the Pipeline stuck
stack, the disk-checker leak is a background thread unrelated to query analysis, and the Post Hooks
row is CI telemetry infrastructure.

Correction to my earlier ledger on this branch's sibling PR: I attributed the Post Hooks line to
#113009. That was wrong - #113009 touches DatabaseReplicated digest diagnostics and has nothing to
do with build-profile telemetry. The line's owner is the fix task noted above.

Session id: cron:our-pr-ci-monitor:20260804-173000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to my ledger above, on the BuzzHouse (amd_debug) line.

I wrote that no frame of this diff appears in the Pipeline stuck stack and classified the row as
not PR-caused. That conclusion was not supported by the evidence I had, and the correlation points
the other way:

  • The failed query is SELECT count() FROM merge(REGEXP('t.*'), 't.*') WHERE (database = 'd1') AND (\table` = 't17') INTO OUTFILE ...`.
  • My only source change is in removeExpressionsThatDoNotDependOnTableIdentifiers
    (src/Analyzer/Utils.cpp), which is the merge() filter-pushdown path, and the WHERE here is
    exactly a conjunction over the database / table virtual columns that function rewrites.
  • The change makes that function drop non-and expressions (bare columns and constants included)
    when hasUnknownColumn holds, where before it returned early and kept them. That is a real
    behavioural change to which filter survives pushdown.
  • Of every Pipeline stuck row in CIDB over the last 20 days, this is the only one whose query
    goes through merge(). STID 3833-2f1a is the generic PipelineExecutor::finalizeExecution abort
    site shared by unrelated defects, so its cross-PR breadth (3 rows / 3 PRs in 7 d, each a
    different query shape) does not transfer to this row.

The printed stack is only the abort site and the digraph in the report is truncated to five
already-finished nodes, so neither confirms nor refutes a link. Absent that, I am treating this as
potentially caused by this PR and investigating it as such rather than assigning it to a trunk
owner. I will report back here with the outcome, and the Pipeline stuck line has no valid external
owner until then.

The other two lines are unaffected: Upgrade check (amd_release) remains #110773 (mine, open), and
Build (arm_release) / Post Hooks remains the LogCluster telemetry fix task.

Session id: cron:our-pr-ci-monitor:20260804-173000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Second correction on the BuzzHouse (amd_debug) / Pipeline stuck line (STID 3833-2f1a). My
previous comment suspected my own diff. I measured it, and that suspicion was wrong. The owner is
#106251 (mine, open), "Fix pipeline-stuck deadlock in BufferedShardByHashTransform".

The full digraph identifies the deadlock. The digraph in the job report is truncated to five
already-Finished nodes, which is why I could not place it before. server.log carries all 583:

ExpressionTransform_140 -> BufferedShardByHashTransform_146            (PortFull)
BufferedShardByHashTransform_146 -> Resize_152 .. Resize_157           (NeedData, _157 PortFull)
                                 -> AggregatingTransform_158 .. _163   (NeedData, _163 NotStarted)

One shard-by-hash producer holds a full output port while its six consumers all sit blocked on
input; the sibling BufferedShardByHashTransform_147..151 are all Finished. That is #106237, and #106251 changes exactly
src/Processors/Transforms/BufferedShardByHashTransform.{cpp,h}. git merge-base --is-ancestor 0fbaec8f8af8 HEAD is false, so this build predates that fix.

My diff is not reachable from the failing query. Its only source hunk is
removeExpressionsThatDoNotDependOnTableIdentifiers. StorageMerge.cpp:1015 returns early when the
join tree is a table function, before that helper is called, and the failing query has no JOIN. I
put a breakpoint on the helper and ran both shapes on the branch binary:

query shape helper calls
failing shape: merge() + AND over two columns + INTO OUTFILE ... TRUNCATE 0
JOIN ... USING over merge() (this PR's own repro) 1

Both runs exited normally with correct results, so the zero is a real zero and not an aborted probe.

Independently: all four heads of this PR carry byte-identical hunk text, and three of them ran
BuzzHouse (amd_debug) green. BuzzHouse reseeds per run (this one: 2449587337631163966).

What misled me was breadth: mine is still the only Pipeline stuck row in 60 days whose query goes
through merge(). That is real, but merge() here fans out over 112 child tables, which is what
makes the pipeline large enough to expose the deadlock. It explains the exposure, not the cause.

…alyzer

The AI review flagged that `A predicate that references only other tables
joined in the surrounding query ... is not affected` reads as an
unconditional promise, while it only holds on the analyzer path, where
`getASTForExternalDatabaseFromQueryTree` drops the joined-side
sub-expressions before the strict check sees the `WHERE`. With
`enable_analyzer = 0` the raw AST is used and such a predicate is
rejected.

The old-analyzer carve-out was already in the following sentence; make
the scoping explicit inside the sentence itself in the
`external_table_strict_query` description and in the six `MySQL`,
`PostgreSQL` and `SQLite` storage and table function docstrings.
Comment thread src/Core/Settings.cpp Resolved
…r the join

Under `external_table_strict_query`, a predicate that references only the joined side is excluded from the strict check (both `WHERE` and `PREWHERE` are stripped in `getASTForExternalDatabaseFromQueryTree`), but a surviving `PREWHERE` keeps its normal evaluation point before the `JOIN`. Reword the setting and the `MySQL`/`PostgreSQL`/`SQLite` storage and table-function docstrings so they describe the exclusion from the check and the usual evaluation point instead of promising evaluation after the join.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 CI status on ff11b640e3ff: all three reds are unrelated to this change (they also failed on master on 2026-09-05 with no PR involved).

Master merged in 334a5e98bda6 (clean, the diff against master is still the same 12 files). No review threads are open.

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Investigated. Both jobs are a graceful pytest overrun, and what separates them from the four green shards on the same tree is runner speed, not the suite.

3/6: 1615 passed, 38 skipped, 15 warnings in 7333.91s, i.e. 134 s past its own --session-timeout=7200, xdist workers at 98/97/98% when the cut landed. 6/6: 1339 passed, 21 skipped, 1 warning in 7210.77s, 10.8 s past the same bound, workers at 99/99/99%. No test failed in either. No oom_memcg record, no exit 137, no exit code: -9, no container-budget error, no crashed worker; /docker peaked 28.41 and 30.88 GiB of a 48.78 GiB cap. The packer priced all six shards within 1 s (Batches parallel weights: [[5402, 5403, 5403, 5402, 5403, 5402]]), so it is not a balance problem either.

For every test with a stable history I compared its duration in this run against its own 7-day median on the same shard:

shard median per-test ratio result
1/6 1.003 success
2/6 0.958 success
3/6 1.242 Timeout
4/6 0.952 success
5/6 0.957 success
6/6 1.186 Timeout

Same tree, same binary, and ncpu: 16 / mem_gb: 48 / created: 3/3 workers in all six. The two that failed ran essentially every test about 20% slower; the four that passed ran at normal speed. The slowdown is flat in time (3/6 is already at 1.27 in its first 20 minutes), so it is not a leak or a progressive degradation.

It generalises to the class. Over the last 3 days of this 6-shard family, the 10 Timeout job runs have a median per-run slowdown of 1.199, 9 of them above 1.10; the 6745 job runs that passed sit at 1.006, with 1.3% above 1.10.

A 20% slowdown is enough because the margin is thin: median realised cost per shard is 82.7% to 87.3% of the 3-worker x 7200 s bound, so a shard tolerates only 1.15x to 1.21x before it crosses. The firing order follows exactly: 5/6 (tolerance 1.145) and 3/6 (1.163) account for 7 of the 10 runs, 1/6 and 4/6 (1.21) for none.

No fix is in progress for this. Nothing in the repository makes a slow runner fast, so the repo-side lever is the margin: session_timeout_parallel = 3600 * 2 in ci/jobs/integration_test_job.py, against a praktika job timeout of 5 h, while the whole job here used 2 h 06 m. Raising the parallel bound to 9000 s lifts the per-shard tolerance to 1.43x to 1.51x, which covers the whole observed slowdown distribution (worst run 1.30x), costs nothing on a green run since the bound is only a ceiling, and still cancels a genuinely hung suite inside the job ceiling, 30 min later than today. I will send that as a separate PR and link it here. If you would rather buy the margin with batches instead (this file already runs amd_msan at 8), or make the bound track the packer's own projected shard cost, tell me which and I will send that one.

…rd checks

The check covers the top-level `WHERE`/`PREWHERE` predicate and each conjunct
of a top-level `AND`. A predicate that references other joined tables is not
pushed down and is excluded from the check under the analyzer, whether it
references only the joined side or mixes it with the external table inside one
non-`AND` expression (an `OR`). Say so in the setting text and in the six
`MySQL`/`PostgreSQL`/`SQLite` storage and table-function docstrings instead of
carving out only the joined-side-only case.
Comment thread src/Core/Settings.cpp Resolved
… guard actually inspects

`getASTForExternalDatabaseFromQueryTree` drops the whole `WHERE` when the external
table is on the non-preserving side of an outer join (`LEFT JOIN ... AS r`,
`RIGHT JOIN ... AS l`, either side of `FULL JOIN`), so neither the table-name path
nor `rejectOuterFilterForQueryBackedExternalSourceIfStrict` sees a filter there and
a source-side predicate is accepted under `external_table_strict_query = 1`. The
setting text and the `MySQL`/`PostgreSQL`/`SQLite` storage and table-function
docstrings now state where the check runs (sole table, `INNER JOIN`, preserving side
of an outer join) and that a right-hand joined external table is not checked with
the old analyzer.

Pin the symmetric case in `04341_sqlite_query_passing`: a source predicate on the
non-preserving side is accepted with strict and non-strict counts agreeing, while
the same predicate on the preserving side or in an `INNER JOIN` is rejected.
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Sent: #118384

It raises the shared parallel session bound in ci/jobs/integration_test_job.py from 7200 to 9000 s,
one literal. Per-shard tolerance goes from 1.146x-1.211x to 1.433x-1.514x, against a worst observed
slowdown of 1.327x. Green runs pay nothing, since the bound is a ceiling on a suite that is not
finishing rather than a budget they spend, and they exit well below either value. The hard subprocess
backstop follows the bound to 9600 s, so the graceful path stays reachable, and the worst case stays
about 4200 s under praktika's 5 h job default.

I picked the bound over batches because it is one literal against a scheduling change, and over a
packer-projected bound because the packer already prices these six shards within 1 s of each other
while two of them still get cut, so the projection is not what is missing. Tell me if you would
rather have either of those instead.

The bound is per-tree, so release branches keep their own 7200 copy and are not covered by this;
that side is open separately as #112261.

Comment thread src/Core/Settings.cpp Resolved
…ushed down to the external table

When the external table sits on the non-preserving side of an outer join (or on either side of a `FULL JOIN`), `getASTForExternalDatabaseFromQueryTree` pushes nothing down and cleared only the `WHERE` of the reconstructed query. A `PREWHERE` survived, and since `MySQL`, `PostgreSQL` and `SQLite` do not support `PREWHERE` (such a query fails earlier with `ILLEGAL_PREWHERE`), the survivor could only belong to the other, joined table. `rejectOuterFilterForQueryBackedExternalSourceIfStrict` then rejected e.g. `SELECT count() FROM mt AS l LEFT JOIN sqlite(db, query('...')) AS r USING (id) PREWHERE l.flag` under `external_table_strict_query = 1`, although the same query with `WHERE l.flag` is accepted and no filter on the source is involved. Clear `PREWHERE` alongside `WHERE`.

Scope the `external_table_strict_query` wording to `WHERE` (a `PREWHERE` on the external table's columns is rejected by the engine regardless of the setting) in `Settings.cpp` and the six storage / table-function docstrings, and pin the joined-side `PREWHERE` cases in `04341_sqlite_query_passing`.
@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

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

This fix is on master only, and all four supported releases still return Code: 49 for the query it fixes. I measured it on the official release binaries, with the fixture from #118627 (where this surfaced):

Build SELECT r.a FROM merge(currentDatabase(), '^dst$') AS m JOIN r ON m.x = r.a WHERE b
26.3.33.10, 26.6.5.73, 26.7.6.57, 26.8.2.3 Code: 49 ... Column b Nullable(Int64) query tree node does not have valid source node: Child table: default.dst
master 26.9.1.1 12 rows

Controls (WHERE b != 0, and a merge set with no Distributed child) pass on every arm, so what separates them is the bare-column predicate. 4a7f2f7b47f is not an ancestor of any of the four branches, and the fixed condition in src/Analyzer/Utils.cpp is absent from all four. Nothing picked it up automatically: pr-bugfix is not a backport trigger, and no cherry-pick was opened.

@alexey-milovidov could you apply v26.3-must-backport (it expands to 26.3, 26.6, 26.7, 26.8), or a newer floor if you want fewer?

One input for that decision: the load-bearing change is 4+/3- in src/Analyzer/Utils.cpp and applies cleanly with a three-way merge on all four branches, but this PR also carries the external_table_strict_query scoping work, so a whole-PR cherry-pick moves that behaviour onto the release branches as well.

pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 12, 2026
…cans

Joining two external-database tables and filtering on a bare column of one side, as in

    SELECT count() FROM sqlite(db, 't') AS a JOIN sqlite(db, 't') AS b ON a.id = b.id2 WHERE b.flag

silently lost rows: the predicate also reached `a`'s remote scan, where it was written without its
qualifier and therefore filtered `a` by `a.flag`. Written as a function, `b.flag = 1`, the same
condition was scoped correctly.

The cause was in `removeExpressionsThatDoNotDependOnTableIdentifiers`, which returned early for a
top-level expression that is not a `FunctionNode`, so a bare-column predicate over the other side of
the join stayed in the query built for this side. That was fixed in
ClickHouse#111327 (`357a95cba2b`, merged into `master` on
2026-09-06) while fixing a related logical error for `Merge` over `Distributed`; this test pins the
external-database spelling of the same defect, which is not covered by that pull request's test.

Verified in both directions with `clickhouse-local`: the test fails on a build from 2026-09-03
(`bare column 1` instead of `2`) and passes on current `master`.

Closes: ClickHouse#118430
Related: ClickHouse#111327
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Oct 3, 2026
When a PostgreSQL protocol client goes away while the server is still streaming the result, the next write to the socket fails with `NETWORK_ERROR` (`Broken pipe`), and `WriteBuffer::next` cancels the socket buffer. The error handlers of `processQuery` and `processExecuteQuery` in `PostgreSQLHandler` then tried to send `ErrorResponse` through the same buffer, which is a logical error: `Cannot write to canceled buffer`.

Tear the connection down instead when the output buffer is already canceled: there is nobody left to deliver the error to.

Seen in the stress test of a PR that does not touch this code: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111327&sha=ff11b640e3ff97e92863685fdba4882a09597508&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 (ClickHouse#111327), and on master on 2026-09-05.

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

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-unknown PR origin: unclassified (legacy task) 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 "query tree node does not have valid source node" joining a Merge table over a Distributed table with USING

5 participants