Repository navigation
Fix max_rows_to_transfer for GLOBAL IN/JOIN under the analyzer - #104119
PedroTadim merged 7 commits into
Conversation
The `max_rows_to_transfer` and `max_bytes_to_transfer` settings limit how much data the initiator may materialize for a `GLOBAL IN` or `GLOBAL JOIN` external table before sending it to remote shards. Under the old analyzer this was enforced inside `CreatingSetsTransform`, which is built from `prepared_sets->getSubqueries()` via `DelayedCreatingSetsStep` and runs the check `network_transfer_limits.check(rows, bytes, "IN/JOIN external table", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED)` for every chunk. The new analyzer materializes the same subqueries in a different place: `executeSubqueryNode` in `src/Storages/buildQueryTreeForShard.cpp`. The helper builds a pipeline that writes the subquery's output into a temporary table (`query_plan -> SimpleSquashingChunksTransform -> external_storage->write`) but never installed `network_transfer_limits`, so both settings were silently ignored — every `GLOBAL IN`/`GLOBAL JOIN` on a distributed cluster could materialize an unbounded amount of data on the initiator regardless of the configured limits. This commit installs the same check on the new analyzer's path. A small `ISimpleTransform` (`GlobalSubqueryTransferLimitsCheckingTransform`) is inserted after the squashing transform and mirrors `CreatingSetsTransform` exactly: same error code (`SET_SIZE_LIMIT_EXCEEDED`), same `"IN/JOIN external table"` reason string, same overflow-mode semantics (`THROW` raises an exception, `BREAK` stops reading). The transform is only added when `network_transfer_limits.hasLimits()` is true, so the default-zero configuration is a no-op. Also adds a stateless regression test that asserts the limit fires for both `GLOBAL JOIN` and `GLOBAL IN` under both analyzers, that `transfer_overflow_mode = 'break'` truncates without throwing, and that the unlimited happy path still returns the expected results. Closes ClickHouse#103333
Pre-PR validation gatePer the worker workflow used to author this fix, here are the answers to the mandatory pre-PR validation gate questions, all confirmed before opening this PR. Session id: a) Deterministic repro? Yes. With a 2-shard SELECT count() FROM t1_dist t1 GLOBAL JOIN t2_dist t2 ON t1.a = t2.a
SETTINGS max_rows_to_transfer = 10returns 400 on master HEAD and throws b) Root cause explained? The new analyzer materializes c) Fix matches root cause? Yes. The fix inserts a small d) Test intent preserved? / New tests added? New regression test e) Both directions demonstrated? Yes.
f) Fix is general, not a narrow patch? |
|
cc @KochetovNicolai @vdimir @PedroTadim — could you review this? It restores enforcement of |
|
Workflow [PR], commit [2aecdb1] Summary: ❌
AI ReviewSummaryThis PR restores Missing context / blind spots
Final Verdict✅ No inline findings to post. The implementation and focused regression coverage look consistent with the PR contract; wait for the refreshed CI run to finish before merge. |
…4119 review) `GlobalSubqueryTransferLimitsCheckingTransform` was counting raw `chunk.bytes()`. For a `ColumnConst` that only accounts for the single stored value (e.g. one `Int32` for a 1000-row literal column) and silently undercounts `max_bytes_to_transfer`, letting subqueries that produce const columns through. `CreatingSetsTransform::consume` (the equivalent old-analyzer path) calls `materializeBlock` first and counts `block.bytes()`, so a `ColumnConst` is expanded to its full per-row payload before being checked against `max_bytes_to_transfer`. Mirror that exactly: materialize, count, push the materialized columns downstream so the temporary table receives the same bytes as the old analyzer would. Extends the regression test in `04204_global_in_join_max_rows_to_transfer_103333.sql` with two constant-only subquery cases (one `GLOBAL JOIN` and one `GLOBAL IN`) that rely on the materialized byte count to fire the limit. Without this commit both queries silently succeed; with it, both throw `SET_SIZE_LIMIT_EXCEEDED`. The `GLOBAL IN` case explicitly disables `enable_add_distinct_to_in_subqueries` so the optimizer does not collapse the constant-only subquery to a single row before the bytes are counted. Bot review on PR ClickHouse#104119: ClickHouse#104119 (comment)
|
Pre-PR validation gate (per cron:clickhouse-ci-task-worker:20260505-164500): a) Deterministic repro? Yes. b) Root cause explained? c) Fix matches root cause? Yes — directly mirrors d) Test intent preserved? The original 6 test cases (new-analyzer rows-limit e) Both directions demonstrated? Yes. Reverted the C++ change, kept the test changes, rebuilt: 1 case fails with "The query succeeded but the server error '191' was expected" (the const-only f) Fix is general? Yes. Materializing applies uniformly for all input column shapes (regular column, cc @KochetovNicolai @vdimir @PedroTadim — pinging since you're the original reviewers; feel free to take another look at the new commit when you have a moment. Session: cron:clickhouse-ci-task-worker:20260505-164500 |
The CI test profile (`tests/config/users.d/limits.yaml`) sets `max_rows_to_transfer = 1G` and `max_bytes_to_transfer = 1G`. After PR ClickHouse#104119 made the new analyzer enforce these limits inside `buildQueryTreeForShard::executeSubqueryNode` via the new `GlobalSubqueryTransferLimitsCheckingTransform`, the existing `02916_glogal_in_cancel.sql` query started failing on CI: the inner `SELECT number FROM numbers(10000000000.)` materializes well past 1 GiB before the test's `max_execution_time = 0.5` cancellation fires, so the bytes limit raises `SET_SIZE_LIMIT_EXCEEDED (191)` inside the limits transform. This test exists purely to exercise the `GLOBAL IN` cancellation path (`max_execution_time` + `timeout_overflow_mode = 'break'`), not the transfer limits. Pin both `max_rows_to_transfer` and `max_bytes_to_transfer` to 0 in the session so the new transform is gated out (`SizeLimits::hasLimits()` returns false → transform not installed) and the timeout cancellation path is what gets exercised, regardless of how the test profile sets the transfer limits.
|
Pushed Why the test brokeThe test profile ( Once this PR's
FixAdd Verification
Pre-PR validationa) Deterministic repro — yes, on CI (91/91, 104/104). Locally: timing-bound, but unambiguous from CIDB. CIDB hits this is keyed off: cc @KochetovNicolai @vdimir @PedroTadim — should be a small turnaround on CI now that the regression is contained. |
| * same `"IN/JOIN external table"` reason string, and the same overflow-mode | ||
| * semantics (`THROW` raises `SET_SIZE_LIMIT_EXCEEDED`; `BREAK` stops reading). | ||
| */ | ||
| class GlobalSubqueryTransferLimitsCheckingTransform : public ISimpleTransform |
…04119 review) Per @novikd's review of PR ClickHouse#104119, drop the bespoke `GlobalSubqueryTransferLimitsCheckingTransform` and instead reuse the existing `CreatingSetsTransform` to fill the temporary table for `GLOBAL IN` / `GLOBAL JOIN` subqueries under the new analyzer. `CreatingSetsTransform` already handles the `external_table` write, calls `materializeBlock` (so `ColumnConst` columns are correctly accounted for in `bytes_to_transfer`), and applies the `network_transfer_limits` check with the same `SET_SIZE_LIMIT_EXCEEDED` error code and `"IN/JOIN external table"` reason that the old analyzer uses inside `DelayedCreatingSetsStep`. Passing `SetAndKey{external_table = external_storage}` with `set` left null makes it skip the set-building branch and only fill the table. Net effect on this file: the entire `GlobalSubqueryTransferLimitsCheckingTransform` class is removed (~50 lines), the manual `external_storage->write(...)` is removed (`CreatingSetsTransform::startSubquery` does the same call internally), and the pipeline is closed with `EmptySink` to consume the empty header that `CreatingSetsTransform` produces - mirroring the existing pattern in `FutureSetFromSubquery::buildSetInplace` (`src/Interpreters/PreparedSets.cpp`). Behaviour is unchanged: the same limit check runs at the same logical position, against the same materialized blocks, with the same error code and reason. The new-analyzer path is now in lockstep with the old-analyzer path through a single shared transform. Verified locally: - `04204_global_in_join_max_rows_to_transfer_103333` (regression test for issue ClickHouse#103333, including the const-column edge case): 50/50 pass with full randomization. - `02916_glogal_in_cancel` (the test that regressed earlier in this PR's history): 50/50 pass with full randomization.
|
@novikd — reworked in Concretely, in auto set_and_key = std::make_shared<SetAndKey>();
set_and_key->external_table = external_storage;
builder->addCreatingSetsTransform(
std::make_shared<const Block>(Block{}),
std::move(set_and_key),
network_transfer_limits,
/* prepared_sets_cache = */ nullptr);
auto pipeline = QueryPipelineBuilder::getPipeline(std::move(*builder));
pipeline.complete(std::make_shared<EmptySink>(pipeline.getSharedHeader()));With Net diff for this commit: I considered
Verified locally on the rework: Session id: |
…House#104119 review) The `ColumnConst`-regression comment in `tests/queries/0_stateless/04204_global_in_join_max_rows_to_transfer_103333.sql` referenced `https://github.com/ClickHouse/ClickHouse/pull/104119#discussion_r...` with the discussion id truncated. The link pointed nowhere. The actual bot review that flagged the `chunk.bytes()` vs `materializeBlock(block).bytes()` divergence is discussion `r3189697129`. Replace the placeholder with the full URL so the test documentation stays anchored to a real review thread. Reported by clickhouse-gh[bot] at ClickHouse#104119 (comment) endorsed by @PedroTadim at ClickHouse#104119 (comment)
|
@novikd can this PR be merged? |
CI ledger — covered SHA:
|
| Check | Test | Disposition |
|---|---|---|
Stateless tests (amd_tsan, parallel, 1/2) |
00096_obfuscator_save_load |
flaky chronic trunk — task 2026-06-02-ci-00096obfuscatorsaveload-chronic-f |
Stateless tests (amd_tsan, parallel, 1/2) |
00175_obfuscator_schema_inference |
flaky chronic trunk — task 2026-06-02-ci-00175obfuscatorschemainference-ab |
Unit tests (asan_ubsan) |
(check-level) | infra/chronic UBSan UntrackedMemoryCounter — task 2026-06-03-ci-p1-chronic-ubsan-in-untrackedmemoryc |
Bugfix validation (functional tests) |
02916_glogal_in_cancel |
not this PR's own test (this PR adds 04222_max_rows_to_transfer_global_in_join). 30d cross-PR confirms chronic flake unrelated to GLOBAL IN/JOIN analyzer fix. |
No PR-caused failures. Awaiting human review.
Session: cron:our-pr-ci-monitor:20260604-213000
|
Correction to ledger comment above: Session: cron:our-pr-ci-monitor:20260604-213000 |
|
@groeneai merge with master |
|
Dear @novikd, 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. |
|
@ PedroTadim — merged Session: cron:clickhouse-ci-task-worker:20260608-205800 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 23/23 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code |
CI Ledger — covered SHA:
|
| Check / Test | Classification | Disposition |
|---|---|---|
AST fuzzer (arm_asan_ubsan) — STID 2409-5283 Logical error: Cannot find input column __table14.number on its position in inputs of expression actions DAG (failing query: WITH RECURSIVE alias2 AS (SELECT DISTINCT number FROM test_aliases LIMIT 255, -2147483649 UNION DISTINCT ...)) |
chronic trunk bug | Cross-PR query (30d): 3 unrelated PRs hit (#103112, #104662, this one), 0 master. CTE / RECURSIVE / WITH UNION DISTINCT column-binding bug in the analyzer's actions DAG construction — fully orthogonal to this PR's diff (buildQueryTreeForShard.cpp GLOBAL JOIN/IN external table size limits). Tracked in task 2026-06-08-ci-p1-stid-2409-5283-ast-fuzzer-logical. |
All 11 builds, AST fuzzer (amd_debug / amd_msan / amd_tsan / amd_debug-targeted / amd_debug-targeted-old_compatibility), BuzzHouse (4 variants), all stress tests, all integration tests, all functional tests (parallel + sequential + s3 + WasmEdge + DatabaseReplicated + ParallelReplicas + AsyncInsert + flaky-checks across all sanitizers), unit tests (asan/tsan/msan), Style check, Fast test, Bugfix validation, Code Review, LLVM Coverage, SQLLogic, Performance Comparison, Compatibility, Install packages, Docker images, Upgrade check: all SUCCESS.
Awaiting reviewer re-review.
|
@groeneai is there a fix PR for the failed AST fuzzer job? If not, add one |
eb96a8a
|
The test is flaky @PedroTadim could you please either check why it is flaky or revert it? |
I am going to try fix the test |
|
The 04204 failures are not a bug in the test. They are the master-wide connection-pool packet desync @PedroTadim the authoritative fix already merged today at 13:22 UTC: #108854 (commit 2e573a8), which disconnects out-of-sync pooled connections in CIDB confirms the fix: the signature dropped from 142 failures / 12 on master over the 4 days before the merge (across 41 distinct distributed tests and 110 PRs) to 4 failures / 0 on master after it. The 4 residual hits are all stale-base PR branches whose CI ran within 34 min of the merge (binaries built before 13:22 UTC). Every same-settings rerun of 04204 passed. 04204's own logic is correct. |
Motivation
max_rows_to_transferandmax_bytes_to_transferlimit how many rows / bytesthe initiator may materialize for a
GLOBAL INorGLOBAL JOINexternal tablebefore transmitting it to remote shards. Under the old analyzer
(
enable_analyzer = 0) the limits fire correctly withCode: 191. SET_SIZE_LIMIT_EXCEEDED. Under the new analyzer (the default), thequery runs to completion and the limit is silently ignored.
Reported in #103333:
Root cause
Both analyzers eventually need to materialize the right-hand side of a
GLOBAL IN/GLOBAL JOINinto a temporary table that gets shipped to remoteshards. They diverge on where that materialization happens:
Old analyzer:
GlobalSubqueriesVisitor::Data::addExternalStorage(
src/Interpreters/GlobalSubqueriesVisitor.cpp) registers the subquery viaprepared_sets->addFromSubquery(...). Later,InterpreterSelectQuery::executeSubqueriesInSetsAndJoinscollects thosesubqueries via
prepared_sets->getSubqueries()and wraps them in aDelayedCreatingSetsStepconstructed withnetwork_transfer_limits = SizeLimits(max_rows_to_transfer, max_bytes_to_transfer, transfer_overflow_mode).The corresponding
CreatingSetsTransform::consume()increments cumulativerows / bytes and calls
network_transfer_limits.check(rows, bytes, "IN/JOIN external table", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED)for every chunk, raising the configured error or stopping reading.
New analyzer:
buildQueryTreeForShard(src/Storages/buildQueryTreeForShard.cpp)detects
GLOBAL IN/GLOBAL JOINnodes inDistributedProductModeRewriteInJoinVisitorand calls
executeSubqueryNodeto materialize the subquery into a temporarytable.
executeSubqueryNodebuilds a pipelinequery_plan -> SimpleSquashingChunksTransform -> external_storage->writebutnever reads
max_rows_to_transfer/max_bytes_to_transfer, so the networktransfer limits are never enforced.
Fix
Install the missing limit check on the new analyzer's materialization path. A
small
ISimpleTransform(GlobalSubqueryTransferLimitsCheckingTransform) isinserted after the squashing transform and mirrors
CreatingSetsTransform1:1:SET_SIZE_LIMIT_EXCEEDED,whatargument toSizeLimits::check:"IN/JOIN external table",THROWraises the exception,BREAKstopsreading and lets the materialization complete with truncated data.
The transform is only added when
network_transfer_limits.hasLimits()istrue, so the default zero configuration is a no-op and other tests
that materialize
GLOBAL IN/GLOBAL JOINsubqueries are not affected.Verification
test_cluster_two_shardssetup. After the fix, the query throws
Code: 191. Limit for IN/JOIN external table exceeded, max rows: 10.00, current rows: 200.00. (SET_SIZE_LIMIT_EXCEEDED)exactly like the old analyzer.
04204_global_in_join_max_rows_to_transfer_103333.sqlasserts the limit fires under both analyzers, that
transfer_overflow_mode = 'break'truncates without throwing, and that theunlimited happy path still returns the expected results.
The query succeeded but the server error '191' was expected),with the fix it passes — both directions verified locally.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
max_rows_to_transferandmax_bytes_to_transferbeing silently ignored forGLOBAL INandGLOBAL JOINqueries under the new analyzer. The settings now raiseSET_SIZE_LIMIT_EXCEEDED(or break, depending ontransfer_overflow_mode) when the materialised external table exceeds the configured limit, matching the behavior of the old analyzer. Closes #103333.Documentation entry for user-facing changes
Version info
26.6.1.640