Repository navigation
Fix logical error joining a Merge over Distributed table with USING - #111327
alexey-milovidov merged 18 commits into
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260722-071100 |
Internal second-model review (click to expand)An independent second model reviewed the resulting code before this PR was opened. Findings and dispositions: ❌ Blockers
💡 Nits
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. |
|
cc @tavplubix @azat — could you review this? It fixes a |
|
Workflow [PR], commit [8881d0f] Summary: ✅
AI ReviewSummaryThis PR fixes two related analyzer-side filter-reconstruction problems: Final Verdict✅ No new findings on the current PR head. LLVM Coverage ReportMeasured on commit 8881d0f.
Changed lines: Changed C/C++ lines covered: 47/47 (100.00%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code |
CI finish ledger — 357a95cCI 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
Session id: cron:our-pr-ci-monitor:20260722-153000 |
|
Fixing PRs for the That row is emitted by the stress harness itself (
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 Nothing about this failure was related to this PR. |
|
Fixing PR for the The failure is the plain-rewritable |
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.
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.
CI finish ledger - 0353645Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not PR-caused. This diff is confined to Correction to my earlier ledger on this branch's sibling PR: I attributed the Session id: cron:our-pr-ci-monitor:20260804-173000 |
|
Correction to my ledger above, on the I wrote that no frame of this diff appears in the
The printed stack is only the abort site and the digraph in the report is truncated to five The other two lines are unaffected: Session id: cron:our-pr-ci-monitor:20260804-173000 |
|
Second correction on the The full digraph identifies the deadlock. The digraph in the job report is truncated to five One shard-by-hash producer holds a full output port while its six consumers all sit blocked on My diff is not reachable from the failing query. Its only source hunk is
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 What misled me was breadth: mine is still the only |
…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.
…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]>
…ng-merge-over-distributed
|
🕵 CI status on
Master merged in |
|
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.
For every test with a stable history I compared its duration in this run against its own 7-day median on the same shard:
Same tree, same binary, and It generalises to the class. Over the last 3 days of this 6-shard family, the 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: No fix is in progress for this. Nothing in the repository makes a slow runner fast, so the repo-side lever is the margin: |
…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.
… 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.
|
Sent: #118384 It raises the shared parallel session bound in I picked the bound over batches because it is one literal against a scheduling change, and over a The bound is per-tree, so release branches keep their own 7200 copy and are not covered by this; |
…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`.
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
This fix is on master only, and all four supported releases still return
Controls ( @alexey-milovidov could you apply One input for that decision: the load-bearing change is 4+/3- in |
…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
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]>
Closes: #111253
Changelog category (leave one):
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 aMergetable wrapping aDistributedtable is joined and a bare column of the joined-away side is used as a predicate.Description
ReadFromMergebuilds a separate query for each underlying table. It removes the JOIN and then strips theWHERE/PREWHEREsub-expressions that reference the joined-away table, viaremoveExpressionsThatDoNotDependOnTableIdentifiers. That helper only inspectedFunctionNodetop-level expressions; a bare-column predicate such asWHERE r.k(aColumnNode) hit an earlyreturnand was left in the child query. When theDistributedchild was re-planned to be sent to the shards, that column had a dangling source and the analyzer threwCode: 49 ... Column k UInt32 query tree node does not have valid source node.The fix treats any non-
andtop-level expression (bare column, constant, or single non-andfunction) 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 anand.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):
USINGandON, and a self-join of theMergetable, which needs one table and no second fixture. Reported by zlareb1 on the issue after this PR was opened.QUALIFYandHAVING, not only a hand-writtenWHERE. The planner foldsQUALIFYintoHAVINGwhen there are no window functions andHAVINGintoWHEREwhen there is no aggregation, so such a predicate reaches the same helper. This is also the shape the AST fuzzer hit on Fix wrongORDER BYresults forMergeoverDistributed#112931.qualify_l,self_join_on_l,bare_where_l_k), so no case can pass by dropping the predicate outright.PREWHERE, whichStorageMerge::replaceTableExpressionAndRemoveJoinstrips through a separate call of the helper. Only the inner-join form is pinned (withUSINGand withON): its result does not depend on whether the predicate is applied before or after the join, so it must equal theWHEREform. With an outer join,PREWHEREis 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/SQLitesources, so04341_sqlite_query_passingpins 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 survivingWHERE, 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),getASTForExternalDatabaseFromQueryTreepushes nothing down but cleared only theWHEREof the reconstructed query, so aPREWHEREon the joinedMergeTreetable 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 withWHERE l.flagis accepted. APREWHEREon the external table's own columns cannot reach the guard at all: these engines do not supportPREWHEREand the query fails earlier withILLEGAL_PREWHERE.PREWHEREis now cleared together withWHERE, and04341_sqlite_query_passingpins both the joined-sidePREWHEREcases and theILLEGAL_PREWHEREones.The
external_table_strict_querysetting text and thesqlite,mysqlandpostgresqltable 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
26.9.1.846(included in26.9and later)