Skip to content

Fix a _table/_database filter over a Merge table returning no rows for children that read from other tables - #116371

Merged
fm4v merged 4 commits into
masterfrom
merge-prefilter-delegating-children
Aug 29, 2026
Merged

fm4v merged 4 commits into
masterfrom
merge-prefilter-delegating-children

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Related: #113735
Related: #113242
Related: #115356

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 WHERE _table = ... or WHERE _database = ... condition over a Merge table silently returning no rows when the matching child table reads its data from other tables, for example a Distributed, Merge, Buffer, or Alias child. Such children are now always read, and the condition filters their rows.

Description

A rework of #113735, reduced to the root cause.

CREATE TABLE t_leaf (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t_leaf VALUES (1), (2), (3);
CREATE TABLE t_dist (x UInt64) ENGINE = Distributed(test_shard_localhost, currentDatabase(), t_leaf);

SELECT DISTINCT _table FROM merge(currentDatabase(), '^t_dist$');  -- 't_leaf': the rows carry the leaf's name
SELECT count() FROM merge(currentDatabase(), '^t_dist$') ARRAY JOIN [1] AS one
WHERE _table = 't_leaf';                                           -- 0 rows, expected 3

Root cause. The values of the _table and _database virtual columns are stamped by the table that actually produces the rows: for a Distributed child that is the remote table, for a Buffer child mostly the destination table, for an Alias child the target, for a nested Merge its children. But the pruning in ReadFromMerge::getSelectedTables evaluates the predicate against the child's own name. Whenever the child reads its data from another table the two disagree, so a child holding matching rows is pruned and the query silently returns nothing. The disagreement dates back to #63665/#102471, which moved the stamping from Merge itself (which stamped the child's name, in agreement with the pruning) down to the producing table, without updating the pruning.

Fix. Pruning by name is an optimization — the predicate is applied to the rows anyway — and it is only sound when the child's rows are guaranteed to carry the child's own name. A new IStorage::readsFromOtherTables predicate, overridden by Distributed, Merge, Buffer (when it has a destination table) and Alias, marks the children whose reads are delegated: they are always read, and the per-row filter decides. Every other child is pruned exactly as before, so a Merge over many MergeTree tables keeps the optimization, and engines that must not be read spuriously (message queues, whose reads consume data) stay prunable.

Compared to #113735, which classified every engine that does stamp its own name (forwarding-chain resolution with a depth limit, file-like family detection, processing-stage analysis), this inverts the classification into the small closed set of delegating engines and keeps master behavior everywhere else, in a few lines. The stamped values themselves are unchanged, i.e. the leaf-name semantics introduced by #63665 are kept; the alternative approach in #115356 changes the stamped values to the child's name instead. This fix also unblocks #113242: its FetchColumns gate newly routed 00717_merge_and_distributed onto this defect.


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

Version info

  • Backported to: 26.8.1.2033, 26.7.6.43, 26.6.4.42

… that read from other tables

The values of the `_table`/`_database` virtual columns are stamped by the
table that actually produces the rows: the remote table for `Distributed`,
the destination for `Buffer`, the target for `Alias`, the children for a
nested `Merge`. But `ReadFromMerge::getSelectedTables` pruned children by
their own names, so whenever a child reads its data from other tables, the
two disagree and the query silently returned no rows.

Prune only the children that do not read from other tables; the rest are
always read, and the predicate filters their rows.

A rework of #113735.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aca0eb1]

Summary: ✅


AI Review

Summary

This PR fixes Merge-table _table / _database pruning for several delegating children by always reading those children and leaving the filter to row evaluation. The lazy StorageTableProxy gap was fixed correctly, but the new readsFromOtherTables() contract is too coarse: it also forces reads through wrappers that can land on stream-like / message-queue engines, so filtered-out children can now throw or consume data. The PR is not ready as-is.

Findings

❌ Blockers

  • [src/Storages/StorageMerge.cpp:1872] readsFromOtherTables() is being used as "always safe to read", but wrappers such as Alias, Buffer, and Distributed can still route the read into Kafka / NATS / RabbitMQ. A Merge over Alias('kafka_t') or Distributed(..., kafka_t) now reads that child even for WHERE _table = 'other_table', which turns a previously pruned child into either Direct select is not allowed... or actual message consumption / acknowledgements when direct select is enabled. Suggested fix: keep the optimization fail-closed for side-effecting targets, or resolve the effective producer names without forcing the read.
Final Verdict

Needs changes: the new pruning rule still violates the existing "do not touch filtered-out queue children" invariant on supported wrapper configurations.

LLVM Coverage Report

Measured on commit aca0eb1.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 26/27 (96.30%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aca0eb1d0 with master 48dffd6fb (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 710.08 MiB 707.02 MiB -3.06 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +387.8 s (+7%) in total before that adjustment.

Job report

alexey-milovidov and others added 2 commits August 28, 2026 01:01
In a database with the lazy_load_tables setting, an unloaded table is a
StorageTableProxy, and StorageProxy did not forward the new
readsFromOtherTables flag to the nested storage. A lazily loaded
Distributed, Merge, Buffer, or Alias child of a Merge table would
therefore still be pruned by a `_table`/`_database` filter by the
proxy's own name, silently returning no rows after a restart or
`ATTACH DATABASE`. Forward the flag like the other capability bits and
add a `lazy_load_tables = 1` regression test.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (arm_release) failure ("Hung check failed, possible deadlock found") is unrelated to this PR: the hung query is an AST-fuzzer-generated SELECT sum(length(h3PolygonToCellsWithContainment([...], 9, 0))) with a degenerate out-of-domain coordinate (9007199254740994.), stuck unkillably inside H3 for 457 s. This is #116195, with fixes in progress: #116225 and #116335. This PR only changes ReadFromMerge::getSelectedTables pruning and touches no H3 code. I merged the current master and addressed the review, so CI will re-run.

The `various` style check (`ci/jobs/scripts/check_style/various_checks.sh`) requires every test querying `system.tables` to scope it to a single database, and recognizes only three spellings: `database ... currentDatabase`, `database ... $CLICKHOUSE_DATABASE`, and a quoted literal. The SQL query-parameter form `database = {CLICKHOUSE_DATABASE_1:String}` is equally scoped but matches none of them, so the check failed:

    Queries to system.tables ... does not have database = currentDatabase()/$CLICKHOUSE_DATABASE condition in ./tests/queries/0_stateless/05045_merge_prefilter_lazy_load_tables.sql

Since the style check is a `run_after` dependency of the whole workflow, this dropped 151 jobs, including both `Bugfix validation (functional tests, *)` jobs, which in turn failed the `new_tests_check.py` post-hook in `Finish Workflow`, and the same failure blocked the `CH Inc sync` workflow.

Spell the probe with `currentDatabase()` under a `USE`, as `04870_column_declaration_statistics_lazy_load` already does for the same situation. `USE` does not load the lazily loaded tables, so the reported engine is still `TableProxy` and the reference file is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116371&sha=1193fcaafc2d139446ca246788530956cd79b7d8&name_0=PR
Related: #116371
/// always read, and the predicate is applied to the rows.
if (storage.get() != storage_merge.get())
if (!table_filter || table_filter(iterator->databaseName(), iterator->name()))
if (!table_filter || storage->readsFromOtherTables() || table_filter(iterator->databaseName(), iterator->name()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This branch treats readsFromOtherTables() as "safe to read even when the _table / _database predicate excludes the child", but the new overrides do not preserve that invariant.

Alias, Buffer, and Distributed can still route the read into a stream-like / message-queue engine. For example, Alias('kafka_t') or Distributed(cluster, db, kafka_t) under a Merge table will now be read here for WHERE _table = 'some_other_table', whereas before it was pruned by the wrapper name. That changes the query from "skip that child" into either Direct select is not allowed... (default path) or actual message consumption / acknowledgements when direct-select settings are enabled. The PR description explicitly says message queues stay prunable, so this boolean is too coarse for the optimization.

At minimum this forced-read path needs to fail closed for side-effecting targets; the full fix likely needs a stronger distinction than a single readsFromOtherTables() bit.

@fm4v
fm4v added this pull request to the merge queue Aug 29, 2026
@fm4v fm4v self-assigned this Aug 29, 2026
Merged via the queue into master with commit 0bb1fc7 Aug 29, 2026
174 checks passed
@fm4v
fm4v deleted the merge-prefilter-delegating-children branch August 29, 2026 06:31
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 29, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
alexey-milovidov added a commit that referenced this pull request Aug 29, 2026
`StorageAlias.h` and `StorageProxy.h` carry master-only members that 26.6 does
not have, so the two `readsFromOtherTables` additions landed inside conflicting
hunks. Kept the 26.6 side of both files and re-applied only this pull request's
own lines, so the cherry-pick's diff against `backport/26.6/116371` is identical
to the original diff of #116371.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 29, 2026
`StorageProxy.h` carries master-only members that 26.7 does not have, so the
`readsFromOtherTables` forward landed inside a conflicting hunk. Kept the 26.7
side of the file and re-applied only this pull request's own lines, so the
cherry-pick's diff against `backport/26.7/116371` is identical to the original
diff of #116371.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 29, 2026
`StorageProxy.h` carries master-only members that 26.8 does not have, so the
`readsFromOtherTables` forward landed inside a conflicting hunk. Kept the 26.8
side of the file and re-applied only this pull request's own lines, so the
cherry-pick's diff against `backport/26.8/116371` is identical to the original
diff of #116371.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Aug 29, 2026
Cherry pick #116371 to 26.6: Fix a `_table`/`_database` filter over a `Merge` table returning no rows for children that read from other tables
robot-clickhouse added a commit that referenced this pull request Aug 29, 2026
…erge` table returning no rows for children that read from other tables
robot-clickhouse-ci-1 added a commit that referenced this pull request Aug 29, 2026
Cherry pick #116371 to 26.7: Fix a `_table`/`_database` filter over a `Merge` table returning no rows for children that read from other tables
robot-clickhouse added a commit that referenced this pull request Aug 29, 2026
…erge` table returning no rows for children that read from other tables
robot-clickhouse-ci-1 added a commit that referenced this pull request Aug 29, 2026
Cherry pick #116371 to 26.8: Fix a `_table`/`_database` filter over a `Merge` table returning no rows for children that read from other tables
robot-clickhouse added a commit that referenced this pull request Aug 29, 2026
…erge` table returning no rows for children that read from other tables
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #116371 to 26.6: Fix a `_table`/`_database` filter over a `Merge` table returning no rows for children that read from other tables
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #116371 to 26.8: Fix a `_table`/`_database` filter over a `Merge` table returning no rows for children that read from other tables
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #116371 to 26.7: Fix a `_table`/`_database` filter over a `Merge` table returning no rows for children that read from other tables
alexey-milovidov added a commit that referenced this pull request Oct 4, 2026
#116371 landed on master with the
alternative semantics: the rows of a child that reads from other tables carry
the names of those tables, and such children are never pruned. Its tests
`05043_merge_prefilter_delegating_children` and
`05045_merge_prefilter_lazy_load_tables` pin those values and failed in the
Fast test of this PR, which intentionally makes the `Merge` engine stamp the
child's own name instead.

With child-name semantics the rows always agree with the pruning, so the
`readsFromOtherTables` exemption in `ReadFromMerge::getSelectedTables` is no
longer needed: every child is pruned by its own name again. Update both tests
to the new values and add a check that a `Distributed` child is pruned too.
`readsFromOtherTables` itself stays, as it is used by the analyzer and parallel
replicas.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115356&sha=f20e359604b20fef72cfa12a6243e03c8efeb7eb&name_0=PR&name_1=Fast%20test
PR: #115356

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

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants