Skip to content

Fix a _table or _database filter silently returning no rows over a Merge table - #113735

Closed
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-virtual-column-prefilter-delegating-child
Closed

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-virtual-column-prefilter-delegating-child

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a WHERE _table = ... or WHERE _database = ... filter on a Merge table silently returning no rows when a child table reads through another table, for example a Distributed, Merge, Buffer or Alias child. The filter now prunes only the children whose rows carry that child's own name, and is applied per row for the rest.

Description

SELECT ... FROM merge(db, <regexp>) WHERE _table = '<name>' silently returns zero rows whenever a child does not stamp its own name into _table. There is no exception, so the user gets a short answer with no signal. _database behaves the same; both reproduce on master.

The prefilter in ReadFromMerge::getSelectedTables matches the predicate against the child's own name, but the value the rows carry is stamped lower down, by whichever storage produces the block. For a MergeTree or View child these agree. For a child that delegates its read they differ: the rows carry the delegate's name, the prefilter the delegator's. This dates from #102471, which made Merge proxy virtual columns to its children without updating the prefilter.

The fix prunes a child only where its rows are guaranteed to carry that child's own StorageID, and admits every other child so the per-row filter decides. Admitting is safe: the predicate is still pushed down and still prunes below an admitted child, so an unrecognised engine loses only an optimisation. Streaming engines stay pruned, because reading one consumes its queue, durably for FileLog. That is resolved through Alias, Buffer, MaterializedView, MaterializedPostgreSQL and lazy-table-proxy hops of any depth, each using a non-throwing accessor. An unresolvable hop, a chain over sixteen deep, or a proxy whose table is not yet loaded stays pruned, as on master.

Physical-column shadowing is a separate defect, #103631, left unchanged. One case is deliberate: a Distributed child over a streaming engine is now read rather than pruned, since the initiator cannot know the remote engine.

The two tests add 77 arms, 37 of them controls. Each recognised class and each guard is pinned by a mutant reverting it, which reddens that class's arms and no others. An EXCHANGE TABLES racing the check is left open, as on master.


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

A `_database`/`_table` prefilter on `Merge` is applied against each child's own
name, but the constant that ends up in the rows is stamped by whatever storage
actually reads them. For a child that delegates its read the two names differ, so
the prefilter is compared against a name the rows never carry and every row is
silently dropped -- a wrong answer, not an error. `Merge` over a `Distributed` is
the reported shape: the prefilter matches the `Distributed` table's name while the
shard's reader stamps the remote leaf's name.

The fix prunes by name only where the child is proven to stamp its own name.
`childMaterializesOwnStorageId` recognises three such classes: `MergeTreeData`,
which stamps both names from its own id in the reader at any stage; a child whose
read reaches a streaming engine; and, at `FetchColumns` only, a
`StorageWithCommonVirtualColumns` that declares `_database` and `_table` at `Plan`
place. Anything else is admitted, which is always safe -- the per-row filter above
the union still decides, so admitting costs a pruning opportunity and never an
answer. The `dynamic_cast` for MergeTree is deliberate rather than `isMergeTree()`,
which `StorageAlias` forwards to its target.

Pruning a streaming child is required rather than optional: reading one is not
merely wasted work. At the default it fails the whole query with
`QUERY_NOT_ALLOWED`, and with `stream_like_engine_allow_direct_select` it consumes
the queue, durably for `FileLog`. So `readReachesStreamingStorage` follows the
wrappers that forward a whole read and prune nothing themselves -- `StorageAlias`,
`StorageBuffer`, `StorageMaterializedView` and `StorageProxy` -- while a nested
`StorageMerge`, which prunes by name itself, is not followed. The recursion is
bounded at sixteen hops, mirroring `max_insert_forwarding_depth`, and fails closed
on an over-long chain or an unresolvable hop: staying prunable is what master does
for every child, so it cannot regress, whereas admitting a streaming child
consumes its queue.

Each hop uses a non-throwing accessor, because a pruning decision must not throw.
`StorageBuffer` gains a public `tryGetDestinationTable` alongside the private
`getDestinationTable`, which throws `INFINITE_LOOP` when the destination is the
`Buffer` itself. `StorageProxy` gains `tryGetNested`, which returns the nested
storage only when it is already materialized: `getNested` force-loads it, calls
`startup` and renames it, so the two lazy subclasses return the raw member under
`nested_mutex` -- the shape those files already use in six methods -- and the two
eager subclasses, whose delegate is a constructor argument, return it unlocked.

A proxy is classified by that recursion and never by its own name. The tempting
inference -- that `StorageTableProxy::getNested` calls
`nested_storage->renameInMemory(getStorageID())`, so the nested storage's
`StorageID` is the proxy's, so the rows carry the proxy's name -- is false, and the
premise does not imply it: `IStorage::renameInMemory` assigns `storage_id` alone,
so a nested `StorageDistributed` keeps the `remote_database` and `remote_table` its
constructor fixed and ships the query there, and a nested `StorageMerge` stamps its
own children's names. Pruning by the proxy's name would reintroduce this defect one
layer up, which arm C of 04741 pins.

The two new tests are one per direction. 04741 covers the wrong-answer direction,
including `Distributed`, nested `Merge`, `Alias`, `Buffer`, `MaterializedView`,
`View`, a physical `_table` column shadowing the virtual one, and lazy proxies over
a `MergeTree` and over a `Merge`. 04742 covers the streaming direction with
`FileLog` behind nothing, behind an `Alias`, behind one and two `Buffer` hops,
behind a `MaterializedView` target, and behind a lazy proxy, asserting for each
that the filtered query succeeds at the default, returns only the other child's
rows with direct select allowed, and leaves the queue unconsumed. Both carry
positive controls -- that the child really is a proxy, that the unfiltered query
really is refused -- since without them a green arm cannot be told from a fixture
that built the wrong object.
The previous revision widened the prunable set with a Plan-place virtual-column
test, which admitted three classes of child whose rows never carry that child's
own name. For a child the `_database`/`_table` predicate EXCLUDES, master decided
on the name alone and never opened it, so admitting one is a regression:

  - a file-like child (`File`, `URL`, the object storages) declares `_table` at
    `Reader` place, so the Plan-place test missed it. `StorageFile::read` raises
    `FILE_DOESNT_EXIST` when its path is absent at the default
    `engine_file_empty_if_not_exists`, so an excluded child could fail the query.
  - a `loop()` child re-reads its inner storage forever, so an excluded one never
    terminates.
  - a `WindowView` child forwards the read to an arbitrary `TO` target.

Recognise the file-like family by the whole shared declaration that
`getVirtualsForFileLikeStorage` installs, not by `_table` alone: `Merge`,
`Buffer`, the message queues and `Hive` also declare `_table` at `Reader` place
without stamping their own name, `Hive` stamping the remote metastore table's
name. Decide per column rather than per child, because that family declares
`_table` but not `_database`, so its rows carry an empty `_database` and only a
`_table` predicate may prune it; the names the predicate actually reads come from
the extracted filter's own required columns.

`Loop` and `WindowView` are pruned unconditionally rather than followed. Neither
declares `_database`/`_table`, so a query that names one is rejected whether or
not it is admitted, and admitting an excluded one only reads a table the
predicate rules out.

Also make the forwarding probe fail closed on a hop it cannot resolve safely.
`DatabaseCatalog::tryGetTable` dispatches to the database implementation, and
`DatabasePostgreSQL::tryGetTable` fetches the table structure over the network,
which can throw; such a hop is now unresolvable, which the existing contract
already treats as prunable, that being master's behaviour. `LOGICAL_ERROR` is
still propagated. Each resolved target is held for the duration of the decision.
`MaterializedPostgreSQL` is added as a hop through its non-throwing accessor.

A post-probe `EXCHANGE TABLES` can still change which storage the read reaches.
Closing that needs target locks held through child planning, a larger change to
this function's locking contract; at the default the outcome is a loud
`QUERY_NOT_ALLOWED` rather than wrong results, and the pre-existing code has the
same re-resolution gap between `getQueryProcessingStage` and `read`.

Note that `getSelectedTables` really can see an unresolved child: on master
`StorageMerge::getQueryProcessingStage` returns at `StorageMerge.cpp:433-434`
for a `JOIN` or `ARRAY JOIN`, before the child loop at `:442-461` whose `:456`
is the only place a child's stage, and hence its resolution, is reached.

`04741` gains four witnesses and three controls for the new classes. The empty
`_database` value is what makes the per-column arm discriminate: a
`currentDatabase()` predicate matches the child's own database name, so it keeps
the child either way.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review, final round (11 findings: 5 corrected, 4 published as residuals, 2 dropped as repeats)

An independent reviewer read the resulting code cold, then a second model re-reviewed the diff against the frozen PR body. This change reached my internal fix-round cap, so I am publishing it with the residual findings listed rather than iterating further; each names its own carrier and its direction, so they can be weighed directly. Every verdict below is a measurement or a source citation, not an argument.

⚠️ Corrected before publication

1. The PR body understated the test size. It said the two tests add "61 arms, 29 of them controls". Measured on the shipped tree: 68 arms, 32 controls (04741 37/19, 04742 31/13). A later round added seven arms and the frozen body was deliberately not edited then.

2. The body understated the mutant coverage. It said "two guards cover states no in-tree fixture can construct". Both now have fixtures: one mutant reddens only the arm filtering for the empty _database that file-like rows carry, another only the loop() arm. The one genuinely unpinned gap is the EXCHANGE TABLES race below.

3. The body's hop list was short by one. It named four forwarding hops; the code follows five: Alias, Buffer, MaterializedView, MaterializedPostgreSQL and the lazy table proxy.

4. The validation comment quoted an earlier round's arm count as if it were current.

5. An internal probe script carried a wrong expected value in its label (filtering a Distributed child by its own name must return no rows, since the rows carry the leaf's name). No published text repeated it; the shipped test filters the leaf name.

❌ Residual findings, published rather than fixed

6. A File table with a physical _path column is admitted where master pruned it. getVirtualsForFileLikeStorage omits any family virtual whose name is already a physical column, while the new classifier requires all six, so such a child fails the fingerprint and is read; an absent file then raises FILE_DOESNT_EXIST for a query master answered. This is the one residual whose direction is a regression rather than an unreached fix. The narrow remedy is to require the family minus any name the child declares physically.

7. An Alias over a file-like target is still pruned by the alias's own name. StorageAlias::getInMemoryMetadataPtr returns its target's metadata verbatim, so the alias satisfies the file-like fingerprint, while StorageAlias::read delegates and the rows carry the target's name. The Plan-place branch immediately below is explicitly guarded against StorageAlias for exactly this reason; the file-like branch is not. Master prunes this child too, so the fix does not reach one shape rather than regressing it.

8. A loop() child is pruned unconditionally, and the comment justifying that is half wrong. StorageLoop's constructor copies its inner storage's metadata wholesale, virtuals included, so its rows can carry the inner table's name and WHERE _table = '<inner>' is a legitimate query. The in-code comment asserting that neither Loop nor WindowView declares _database/_table is false for Loop and true for WindowView, which copies only columns. Any remedy must keep the query terminating, which is what the unconditional prune currently buys.

9. Arm H of 04741 is vacuous. It is labelled as reading the file-like child by its own name, but its regexp selects only the MergeTree sibling, so it exercises no file-like storage and passes for a true but uninteresting reason. Arms F and G remain the genuine witnesses for that class, so the class is still covered.

💡 Raised and not carried

An EXCHANGE TABLES between the classification and the read can still swap the storage. Already disclosed: both the commit message and the PR body name it. Master re-resolves the same way between getQueryProcessingStage and read, so it is not introduced here, and closing it needs target locks held through child planning, a wider change to this function's locking contract.

A request for separate per-class mutants for WindowView and MaterializedPostgreSQL. The combined cast is pinned by a mutant that reddens the loop() arm. WindowView alone has no arm, and MaterializedPostgreSQL cannot have one in a stateless test, the same structural limit already stated for Hive; neither is claimed as tested.

Session id: cron:clickhouse-review-self-slot-58:20260806-220200

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test --binary <bin> 04741_merge_virtual_column_filter_delegating_child fails on unpatched master and passes with the fix, reproduced repeatedly with the server's buildId() asserted equal to the binary's readelf Build ID before every verdict. On the unpatched binary 11 of that test's arms are red and all of its controls are green, so it fails for the reason it exists for. Two of the green arms are the row-level half of the lazy-proxy group, which pins a pruning loss this PR introduces rather than one master has, and is measured against the intermediate head instead. 04742 is the companion for the streaming direction: on a binary lacking that half, the same query dies Code: 620 QUERY_NOT_ALLOWED.
b Root cause explained? The prefilter in ReadFromMerge::getSelectedTables matches the extracted _database/_table predicate against the child's own name, while the value the rows carry is stamped much lower down by whichever storage produces the block. A child that delegates its read carries the delegate's identity, so no filter value matches at either end and the child is dropped. The premise stopped holding when #102471 made Merge proxy virtual columns to its children.
c Fix matches root cause? Yes. It narrows the unsound pruning to the children whose identity provably matches, at the pruning decision itself. It is not a widened bound, a no-random-* tag, or a guard at a symptom site, and nothing about how any value is materialized changes.
d Test intent preserved / new tests added? No existing test was weakened or removed. Two new stateless tests add 68 arms, 32 controls (04741 37/19, 04742 31/13). 04367's EXPLAIN reference did not need updating and was not touched. Arm 10 of 04741 characterizes physical-column shadowing (#103631) as deliberately unchanged. Every streaming arm of 04742 pins stream_like_engine_allow_direct_select explicitly, in both directions, so the stateless CI profile that sets it to 1 for the whole default profile cannot silence the arms that assert a streaming child was pruned.
e Both directions demonstrated? Yes, plus a fourteen-mutant matrix. The first six were scored on the 23-arm revision of 04741 that existed when they ran, so their counts are quoted against that revision rather than against the 37 arms it has now: reverting to isRemote() reddens 6 of those arms while arm 1 stays green (pinning why remoteness is the wrong discriminator); making the predicate unconditionally true reddens 9; dropping the MergeTreeData cast reddens only the two pruning assertions (so pruning is asserted, not assumed); dropping the ancestry conjunct reddens exactly the Alias-over-Memory arm; reverting the bare streaming recognition reddens 04742 from arm 1, reverting only the alias hop reddens it from arm 6 with arms 1-5 still green, and reverting only the Buffer hop reddens it from arm 10 with arms 1-9 still green, and that three-way difference is what shows each hop is independently load-bearing. All three leave every arm of 04741 green. A tenth mutant makes an admitted Buffer child stamp its destination's name for its own buffered rows, which touches no pruning code and reddens exactly the arm group asserting the per-row name distinction. Two further mutants pin this round's recursive resolution and are perfect mirror images: reverting only the MaterializedView hop breaks only the view shape and leaves all six wrapper chains working, while reverting only the recursion breaks every composed chain and leaves the single-level Buffer/Alias cases and the view shape working, so neither carries the other's weight. That disjointness is measured per shape in its own server instance, because 04742 runs under set -eu and aborts at its first failing arm, which leaves later arms unrun rather than red. A fourteenth mutant re-adds a read-forwarding-proxy branch that an earlier round of this PR carried and that was removed for reinstating the PR's own defect: it reddens two arms, the plan-level arm of the lazy-proxy group and the proxy-over-Merge witness, leaving all 25 arms 04742 had at that round, and every other arm of 04741, green. Its source was asserted byte-identical to the reverted commit's before building, so its Build ID came back exactly that commit's value, which is why the pre-change measurement doubles as that mutant's arm. One mutant leaves every arm green and is documented rather than papered over: the stage guard is reached but never with a filter present, so no arm can redden it. Three further mutants pin this round's changes and each reddens exactly one arm with every other arm of both tests green: dropping the file-like recognition reddens the arm whose excluded File child has no backing file (return code: 107); keeping it but dropping the per-column rule reddens only the arm that filters for the empty _database those rows carry; and dropping the Loop/WindowView guard reddens only the loop arm, by hanging until the runner's timeout. The second of those initially SURVIVED, which showed the arm was vacuous: it filtered _database = currentDatabase(), a value the child's own database name matches, so the child was kept either way; filtering for the empty value the rows actually carry discriminates all three of master, that mutant and the fix. The loop arm's plan control likewise had to stop matching %Loop%, which the sibling table's own name contains, and key on the ReadFromLoop step name instead. The direction is also shown on real binaries rather than only on mutants: 04741 fails on unpatched master, 04742 fails on the intermediate head that admits an aliased streaming child, and both pass on the shipping binary. After the last mutant the Build ID returned exactly to the shipping value, which proves the mutants ran different binaries and that the shipping tree is what was measured.
f Fix is general across code paths? Both directions of the boundary were enumerated from source, not from a list. Delegating children that must now be admitted: Distributed, Merge, Buffer, Alias, Hive, each handled by the fail-safe default, so an engine nobody enumerated is admitted too. Self-stamping children that must stay pruned: MergeTree, plus the streaming engines, whose own sources insert getStorageID().getTableName() (Kafka, Kafka2, FileLog, NATS, RabbitMQ, ObjectStorageQueue). StorageFileLog does not report isStreamingStorage, so it carries its own test, and because no wrapper in the tree forwards that predicate either (git grep isStreamingStorage -- src/ finds five occurrences, none of them a forwarding override, against a positive control of two forwarded isMergeTree lines in StorageAlias.h) the test also resolves through the wrappers that forward a whole read and prune nothing of their own -- Alias, Buffer and MaterializedView -- recursively, to any depth, because these compose freely: only alias-over-alias is refused, and Buffer does not validate its destination engine at all. Resolution fails closed to "prunable" on an over-long chain or an unresolvable hop, which is what master does for every child and so cannot regress; a hop whose lookup throws is an unresolvable hop too, because DatabaseCatalog::tryGetTable dispatches to the database implementation and DatabasePostgreSQL::tryGetTable does remote schema I/O that can throw. MaterializedPostgreSQL is a fifth hop, through its existing non-throwing tryGetNested. Loop and WindowView forward a read without being proxies and are pruned unconditionally: neither declares _database/_table at all, so a query naming one is rejected whether or not it is admitted, while admitting an excluded Loop never terminates (measured: it hangs where master returns 0) and an admitted WindowView is rejected on master too. A nested Merge is deliberately not followed, because unlike those wrappers it prunes by name itself and so keeps a second line of defence; Buffer -> Merge -> FileLog is measured unchanged. The file-like engines (File, object storage, URL) also stamp their own _table, and an earlier round of this PR admitted them on the belief that this costs only extra I/O. That was measured false: StorageFile::read raises FILE_DOESNT_EXIST when its single path is absent at the default engine_file_empty_if_not_exists, so an excluded child that master pruned could fail the whole query (reproduced 3/3, and 3/3 pruned on master). They are now recognised by the whole shared declaration that getVirtualsForFileLikeStorage installs at Reader place, across all seven of its callers -- not by _table alone, because Merge, Buffer, the message queues and Hive declare _table there too without stamping their own name, Hive stamping the remote metastore table's name instead. The recognition is per column, not per child: the family declares _table but not _database, so its rows carry an empty _database and only a _table predicate may prune it, which the decision derives from the extracted predicate's own required columns. The read-forwarding proxies are admitted, and they are the one family that cannot be classified at all: they do rename the nested storage to the proxy's own id, but a rename assigns storage_id alone and does not change which storage stamps the name into the rows, so a proxy over a Distributed or a Merge carries the delegate's or the grandchildren's names. Resolving the nested storage would answer it and is prohibited, because the only accessor force-loads and starts up the table inside a planning decision, so the classification falls back to the safe answer and the child is read. A fourth subclass does not even rename, and is unreachable as a Merge child because the only database that creates it reports itself permanently empty and hands out an empty table iterator. Hive gets no test arm because a stateless test cannot reach a metastore; its behaviour was read from the source and the description says so rather than implying it is tested.
g Fix generalizes across inputs (params/datatypes/wrappers)? Equality, negation and IN; _table and _database, the latter across two databases; JOIN and ARRAY JOIN as stage levers, and children that need no lever at all; the Alias-over-Memory case that discriminates the conjunction from either half alone; and for the streaming direction both settings values, since stream_like_engine_allow_direct_select changes the consequence from a hard error to a consumed queue. Row counts differ per table so a wrong answer differs by value, not only by emptiness.
h Backward compatible? (maintainer-approved exception only) No setting, no format and no serialization change, so no SettingsChangesHistory.cpp entry is needed. The observable change is that a query which silently returned nothing now returns the right rows; the description notes this is still a behaviour change for anyone relying on the empty result.
i Invariants and contracts preserved? The table_filter call sits in the same if chain as the SHOW_TABLES and SELECT grant checks; those conditions are untouched and still evaluated independently, so admitting more children cannot relax a grant. The metadata fetch is lazy and guarded on the filter being present, so a query without a _table/_database predicate pays nothing and a MergeTree child pays nothing either. No lock-ordering or lifetime change: the metadata handle is a named local, which is required because StorageMetadataHandle deletes its rvalue operator-> precisely to stop the virtuals reference outliving it.

Session id: cron:clickhouse-impl-self-slot-57:20260806-145604

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd, could you review this? A WHERE _table = ... filter on a Merge table is matched against each child's own name, but the value the rows carry is stamped by whichever storage actually reads them, so a child that delegates its read (Distributed, nested Merge, Buffer, Alias) was pruned against a name its rows never carry and every row was silently dropped; the filter now prunes only children proven to stamp their own name and is applied per row for the rest.

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75720e8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04741_merge_virtual_column_filter_delegating_child FAIL cidb
04741_merge_virtual_column_filter_delegating_child FAIL cidb
04741_merge_virtual_column_filter_delegating_child FAIL cidb
04742_merge_prefilter_prunes_streaming_child FAIL cidb
04742_merge_prefilter_prunes_streaming_child FAIL cidb
04742_merge_prefilter_prunes_streaming_child FAIL cidb
04742_merge_prefilter_prunes_streaming_child FAIL cidb
Too many test failures FAIL cidb
Stress test (amd_asan_ubsan) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb
Stress test (arm_msan) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-39b4) FAIL cidb

AI Review

Summary

This PR teaches Merge to stop pre-pruning delegating children when their rows stamp another storage's _database / _table, and it adds broad coverage for Distributed, nested Merge, Buffer, proxies, file-like engines, and streaming children. The current head fixes several earlier gaps, but it is still not ready: one blocker in getSelectedTables falls back to the child iterator identity after the code has already computed the emitted identity, and the previously discussed StorageLoop wrong-answer case is still present.

Findings

❌ Blockers

  • [src/Storages/StorageMerge.cpp:2067] The new prunable() path is not final: after childMaterializesOwnStorageId has already checked the extracted predicate against the identity the child actually emits, this branch still admits the child when the predicate matches iterator->databaseName() / iterator->name(). That reintroduces the same mismatch for file-like shapes whose rows do not carry the iterator identity. A direct File child still opens and raises on WHERE _table = '<child>' AND _database = currentDatabase(), even though its rows always carry (_database = '', _table = '<child>'); the same fallback also keeps wrappers like Buffer or MaterializedView over file-like targets alive for predicates that match the wrapper name but not the emitted identity. Once the emitted identity is known to be rejected, the child should be pruned unconditionally.
  • [src/Storages/StorageMerge.cpp:1912-1915] [dismissed by author -- https://github.com/Fix a _table or _database filter silently returning no rows over a Merge table #113735#discussion_r3734575497] StorageLoop is still hard-coded as "not self-named", but StorageLoop::StorageLoop copies the inner metadata and LoopSource rebuilds the read against the inner table, so _table / _database can legitimately expose the inner storage identity. The current code therefore still returns no rows for WHERE _table = '<inner>' on a loop(...) child, which is the same silent wrong-result pattern this PR fixes for other delegating children.
Tests
  • ⚠️ Extend 04741_merge_virtual_column_filter_delegating_child with the cases where the predicate matches the child identity but rejects the emitted one, for example a direct file-like child under WHERE _table = '<child>' AND _database = currentDatabase() and a Buffer / MaterializedView over a missing file-like target filtered by the wrapper name. The current suite exercises sibling-name and emitted-name cases, but it does not pin this fallback.
Final Verdict

Changes requested. The main classifier is much closer, but StorageMerge::getSelectedTables still falls back to the wrong identity in a way that can reopen the same exception / wrong-answer class for file-like children, and the StorageLoop gap remains unresolved.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 95/109 (87.16%) · 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 7, 2026
Comment thread src/Storages/StorageMerge.cpp Outdated
{ return virtuals.tryGetDescription(name, VirtualsKind::Ephemeral, VirtualsMaterializationPlace::Reader); });
}

/// The prefilter matches the child's own name, so it may prune only a child whose rows carry that child's

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.

StorageLoop does not have the same contract as StorageWindowView here. Its constructor copies the inner storage metadata, including virtuals, and LoopSource rebuilds the read against the inner table, so _table / _database can legitimately expose the inner table's identity. Returning true here means Merge still prunes a loop(...) child against the loop table's own name and returns nothing for WHERE _table = '<inner>', which is the same silent wrong-result pattern this PR is fixing elsewhere. The current test only covers the "filtered-out loop should stay pruned" direction, not selecting the inner table by name.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thank you, this is a fair reading of the comment and it is half wrong: the comment claims neither Loop nor WindowView declares _database/_table, and that is true of WindowView (which copies only columns) and false of Loop, whose constructor does setInMemoryMetadata(*inner->getInMemoryMetadataPtr(...)) and copies the inner virtuals wholesale. I had already published that correction as a residual on this PR before your review, so I am not treating it as new, but you are right to point at it.

Measured on a debug build, loop() child plus a MergeTree sibling, filtering for the inner table name with a LIMIT:

pristine master this branch
WHERE _table = '<inner>' 0 0
_table value the loop rows carry <inner> <inner>
WHERE _table = '<sibling>' (termination) 6 6

So the rows do carry the inner name, as you say, and the query returns nothing on unpatched master too. This is a pre-existing shape that the PR does not reach rather than something it introduces, which is why I am not widening the classifier for it here: the unconditional prune is what currently buys termination, and any remedy has to keep that. Fixing it means modelling the inner emitted identity, which is a different change from this one.

One correction to the premise for the record: DESCRIBE TABLE <loop child> SETTINGS describe_include_virtual_columns = 1 lists only the physical column on both binaries, with a MergeTree sibling as the positive control listing both _table and _database. So the copied virtuals are not visible through that path, even though the emitted rows carry the inner name.

On the test-coverage half you are right, and I have acted on it. Arm H did not test what its label claimed: I measured it on master, on this branch, and on this branch with the classifier reverted, and it reads the same on all three, so it is a control and not a witness. It is relabelled as one, and the class now has two real witnesses in the same file (arms J and K below), each with a mutant that reddens it alone.

Comment thread src/Storages/StorageMerge.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
`getVirtualsForFileLikeStorage` omits a family virtual whose name the table already declares as a
physical column, so `File(TSV, ...) (x UInt32, _path String)` declares `_table` but not `_path`.
The all-six fingerprint therefore rejected it, the child was admitted where master pruned it, and
an absent backing file raised FILE_DOESNT_EXIST for a query master answered.

Measured on a debug build, `_table` filter excluding such a child alongside a MergeTree sibling:
pristine master 5 rows, this branch before the change FILE_DOESNT_EXIST, after the change 5 rows.
An unshadowed `File` child returns 5 on all three, so only the shadowed shape moved.

A physical column counts as declared for the five shadowable names. `_table` stays strict because
it is the name the pruning decision reads, and a physical `_table` is a different column: it keeps
its own type, so a string predicate over it fails with TYPE_MISMATCH rather than being pruned.
Neither MergeTree nor Merge declares any of the five, so the relaxation cannot admit them.

Arm H of 04741 is also repointed. Its regexp selected only the MergeTree sibling, so it exercised
no file-like storage and passed for a true but uninteresting reason; it now reads a present
file-like child by its own name. New arm J pins the shadowed shape, with a control asserting the
unfiltered query still opens the absent file. Reverting the predicate reddens arm J alone.
Measured on three binaries: pristine master, this branch, and this branch with the classifier
reverted. All three read 0, because the child in that arm declares the whole family and is pruned
under every classification. It is therefore a control asserting that ordinary file-like pruning is
preserved, not a witness. Arms F, G and J are the witnesses for the class.

A row count cannot discriminate in this shape either: an admitted child's rows are dropped by the
per-row filter above it, so the total is the same whether the child was pruned or read. The arm
asserts the plan shape instead, and its own control asserts the child is genuinely readable.
A `Buffer`, `Alias`, `MaterializedView` or lazy proxy over a `File`/`URL`/object-storage target
emits the target's `StorageID`, because the file-like family stamps `_table` from the storage that
actually reads. That name is not the wrapper's, so reading through the wrapper is not self-named
and the child must stay prunable. The recursion returned false for the file-like leaf and the
wrapper then fell through to tests over its own metadata, which does not declare the family, so
the child was admitted and an absent destination raised FILE_DOESNT_EXIST.

Measured on a debug build with a `_table` filter excluding a `Buffer` over an absent `File`,
alongside a MergeTree sibling: pristine master 5 rows, this branch before the change
FILE_DOESNT_EXIST, after the change 5 rows. The unfiltered query still raises on all three.

Arm K pins it, with a control asserting the unfiltered query opens the absent destination.
Reverting the propagation reddens arm K alone.
Comment thread src/Storages/StorageMerge.cpp Resolved
…ty its rows carry

The file-like engines stamp `_table` from their own id and declare no `_database`, so their rows
carry the storage name and an empty database. The decision derived pruning from which of the two
names the extracted predicate reads, which is a proxy for the question and gets two shapes wrong.

`WHERE _table = '<sibling>' AND _database = <db>` reads `_database`, so the child was admitted
although no identity it can emit satisfies the predicate. An absent backing file then raised
`FILE_DOESNT_EXIST` where master answered. `WHERE _database = ''` reads `_database` too, but the
value matches what the rows carry, so pruning dropped the child and the query returned no rows.
The wrapper branch had neither test and pruned a `Buffer`, `Alias`, `MaterializedView` or lazy
proxy over a file-like target under any predicate, including one naming the target.

Both branches now evaluate the extracted filter against the identity the child actually emits:
its own name with an empty database for a direct child, the forwarding target's name for a
wrapper. That is the question the prefilter exists to answer, so `filtered_names` is no longer
needed and is removed.

Measured on a debug build with a MergeTree sibling and a file-like child whose file is absent,
against pristine master, the previous head and two mutants that revert one identity test each:

  arm                                      master  head  both  wrapper  fix
  G  direct, _database = ''                     0   err     0      err   err
  L  wrapper, _database = ''                    0     0     0        0   err
  M  wrapper, sibling AND _database = db       23    23    23       23    23
  N  direct, sibling AND _database = db        23   err    23       23    23
  O  wrapper, _table = '<target>'               0     0     0        0   err

Arms L and O are new witnesses for the wrapper, N is a new witness that reddens on the previous
head, and M is a control that no revision fails. Arms F, G, J and K are unchanged. Reverting both
identity tests reddens G, N and O; reverting only the wrapper one reddens L and O, so neither half
carries the other's weight. After each mutant the shipping Build ID returned byte-exactly.
`Storages/FileLog` is added to the build only on Linux and macOS, and `USE_FILELOG` is set from that
same condition. The unconditional `dynamic_cast<const StorageFileLog *>` therefore emitted a
reference to a vtable that is never defined elsewhere, and `Build (amd_freebsd)` failed to link:

  ld.lld: error: undefined symbol: vtable for DB::StorageFileLog
  >>>   StorageMerge.cpp.o:(DB::(anonymous namespace)::readIsNotSelfNamed(DB::IStorage const&, ...))

The header declares the class everywhere, so every translation unit compiled and only the link
broke. `registerStorageFileLog` is called under the same `USE_FILELOG`, so no `FileLog` table can
exist where the sources were not built and the cast could never have matched there. Guarding it
keeps the decision identical wherever the engine is available and removes the symbol elsewhere.

Compiling this translation unit with `USE_FILELOG` forced to 0 and everything else unchanged:

  arm                          undefined `vtable for DB::StorageFileLog`
  previous head, USE_FILELOG=0  present, which is the reported break
  this commit,   USE_FILELOG=0  absent
  this commit,   USE_FILELOG=1  present and resolved, so the cast still runs

Seven other `DB::Storage` vtables stay referenced in the guarded-out object, so the check is not
reading an empty symbol table. 04742, which builds the `FileLog` children this cast classifies,
passes on the rebuilt binary, as does 04741.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 391fbbd

CI is fully finished on this head: 175 check-runs, 0 incomplete, Config Workflow success, no job left queued or running.

Check / test Reason Owner / fixing PR
Fast test / 02280_add_query_level_settings Code: 252 TOO_MANY_PARTS on INSERT INTO table_for_alter VALUES (1, '1') into an empty table, i.e. the query counted a part it wrote itself fixing PR #113045 (external, open)
Finish Workflow / new_tests_check.py cascade of the row above, not a second defect same event as the row above

Both lines resolve to one event, and the second is not an independent failure. Fast test failing set every dependent job to DROPPED, so the four Bugfix validation jobs reported DROPPED/SKIPPED and new_tests_check.py concluded that no per-arch job had validated the bug. On the previous head 8f7e09b0ad2b529b5384900aded38922122827f9 of this PR, where Fast test was green, Bugfix validation (functional tests, amd64) and (functional tests, aarch64) both ran and both reported success, and Finish Workflow was success. Nothing about the regression test changed between those two heads.

The Fast test failure is not caused by this PR. 02280_add_query_level_settings is not touched by this diff, and over 60 days that exact TOO_MANY_PARTS signature has 11 failures spread across 11 distinct unrelated pull requests, starting 2026-08-01, with 0 failures on master. #113045 names this test explicitly, with this statement and this threshold: since max_insert_threads began defaulting to the core count, a plain INSERT fans out across several sinks and each one runs the parts_to_throw_insert check in onStart, so a sink scheduled late counts a part another sink of the same query has already committed and rejects the query mid-flight. That PR makes the check run once per query, before any sink writes.

Session id: cron:our-pr-ci-monitor:20260807-200000

…virtual-column-prefilter-delegating-child

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

Copy link
Copy Markdown
Member

Merged current master in; this is the prerequisite for #113242, which the PR queue is now waiting on

Refreshed this branch onto master (15cfe1699c8, clean merge) for a current CI run. The previous run
was from 2026-08-07 and its only red functional result was an unrelated TOO_MANY_PARTS flake in
02280_add_query_level_settings.

Bumping this to the front of the queue because #113242 is sequenced behind it, and the bug #113242
fixes is currently the top Stress test failure in the whole repository: Logical error: 'Equal values are not contiguous within the range assumed to be sorted' hit 38 times across 37 pull
requests between 2026-08-15 and 2026-08-18
(details).
#113242 cannot land before this one, because its FetchColumns gate newly routes
00717_merge_and_distributed onto the prefilter defect fixed here.

I re-confirmed that defect on current master, independently of either pull request: with a Merge
over a Distributed child holding 200 rows,

SELECT count() FROM merge_distinct WHERE _table = 'dist_distinct';   -- 0
SELECT count() FROM merge_distinct;                                  -- 200

so the filter still silently drops every row.

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The implementation looks too complicated and very strange

Comment on lines +60 to +64
StoragePtr tryGetNested() const override
{
std::lock_guard lock{nested_mutex};
return nested;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why is it needed if there is getNested()?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

getNested() is not read-only on these two classes: it force-loads the table, calls startup() and renameInMemory() (StorageTableProxy.h:55-69, StorageTableFunction.h:38-50). It is called here from getSelectedTables, to decide whether a child may be excluded, so using it would materialize and start every lazily-loaded table in the Merge range as a planning side effect, including the ones the filter is about to discard. tryGetNested() is just the raw member under nested_mutex, which is the shape those two files already use for exactly this reason in 14 places (getName, getInMemoryMetadataPtr, shutdown, drop, ...).

So the accessor is load-bearing, but I take the wider point and I would rather cut than defend. Two things I can measure about the shape:

The 7 files outside StorageMerge.cpp are 28 of the 207 added src/ lines and exist solely to give each wrapper a non-throwing accessor. They collapse to one line if IStorage gains a single tryGetForwardingTarget() returning {} by default, with Alias/Buffer/MaterializedView/proxy overriding it, and the four dynamic_cast branches in readIsNotSelfNamed become one virtual call. That is smaller and less strange, but it widens IStorage, which I understand you would rather I did not do. Tell me which you prefer.

The recursion itself I do not think can go: without it a Buffer or Alias child over a streaming engine is no longer prunable, so Merge reads it, which either fails the whole query with QUERY_NOT_ALLOWED or consumes the queue (durably for FileLog) where master prunes it by name. That is a regression rather than lost pruning, which is why it is in scope. If you read that differently I will drop it.

Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 75720e866 with master 887b93e16 (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.16 MiB 707.13 MiB -3.03 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.

Object file sizes

7 object files changed (+27.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.16 MiB 1.19 MiB +24.57 KiB (+2.06%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

…virtual-column-prefilter-delegating-child

# Conflicts:
#	src/Storages/StorageMerge.cpp
The flaky check runs this test several times at once and every copy wrote and
truncated the same `user_files` path `04741_present.tsv`, so one copy could read
the file while another was truncating it and `arm H control` returned no rows,
which is the `result differs with reference` seen on all three flaky checks.

A `File` table created without an explicit path owns a directory under its own
database, which is unique per run, so the copies no longer collide.
`StorageMaterializedView::getInMemoryMetadataPtr` re-places the target's
`_database`/`_table` at `Plan`, and `StorageWithCommonVirtualColumns::read` then
materializes them from the VIEW's own `StorageID`, whatever the target stamps.
Following `forwards_to` to a file-like target therefore pruned the view against
the target's name: `WHERE _table = '<target>'` admitted the view and opened the
target, raising `FILE_DOESNT_EXIST` where master answered with an empty result.

Measured, a view over a `File` target emits the view's own `_table` and an empty
`_database` (the view declares no `_database`, because the file-like family does
not), so the view is classified by that identity at `FetchColumns`, which is the
only stage where that materialization site runs. Above it the view delegates the
read untouched and the target's stamping is what reaches the rows, so the
existing forwarding branch still applies there.

Arms P and R are the new witnesses, and arm Q asserts that the empty
`_database` the rows carry keeps the view admitted, as for a direct file-like
child in arm G.

if (storage.get() != storage_merge.get())
if (!table_filter || table_filter(iterator->databaseName(), iterator->name()))
if (!prunable() || 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.

childMaterializesOwnStorageId has already evaluated the extracted _database / _table predicate against the identity the child actually emits, but this fallback still rechecks iterator->databaseName() / iterator->name(). That means a child can be admitted even after the code has proved that none of its rows can satisfy the filter.

A concrete case is a direct file-like child. Its rows carry (_database = '', _table = '<child>'), so WHERE _table = '<child>' AND _database = currentDatabase() should prune it here. Instead prunable() becomes true, this second check matches the iterator identity, and the missing file is still opened, raising FILE_DOESNT_EXIST instead of returning an empty result. The same fallback keeps Buffer / MaterializedView wrappers over file-like targets alive for predicates that match the wrapper name but not the emitted identity.

Once childMaterializesOwnStorageId has determined that the emitted identity is rejected, this branch needs to skip the child unconditionally instead of testing the iterator name again.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured on three binaries with one fixture: a File child whose file is absent, a MergeTree sibling holding 23 rows, and merge() over both.

The control flow is as you describe, and your premise about the emitted identity holds: a readable file-like child emits _database=[] _table=[<child>]. Deleting the table_filter(iterator->databaseName(), iterator->name()) term makes the FILE_DOESNT_EXIST disappear, so the absent file is opened only because of that second test.

Where I disagree is that this is a defect of this change. It is master's behaviour, unchanged. Official master 26.9.1.137 against this PR at 75720e8:

query over merge() of the absent-file child and the sibling master 75720e8
_table = '<child>' AND _database = currentDatabase() FILE_DOESNT_EXIST FILE_DOESNT_EXIST
_table = '<child>' FILE_DOESNT_EXIST FILE_DOESNT_EXIST
_table = '<buffer>' AND _database = currentDatabase() FILE_DOESNT_EXIST FILE_DOESNT_EXIST
_table = '<view>' AND _database = currentDatabase() FILE_DOESNT_EXIST FILE_DOESNT_EXIST
_table = '<sibling>' 23 23

The reason is structural. At this PR's base (91687a7) the line reads if (!table_filter || table_filter(iterator->databaseName(), iterator->name())), and prunable() returns false when there is no filter, so the new condition is the old one plus one extra way to be admitted. Admission is only ever widened: every child master admitted is still admitted, and some children master pruned are now admitted, which is the fix. So this change cannot have introduced a missed prune, and pruning the child you name would prune more than master rather than restore it.

The literal remedy is also not applicable at that line. childMaterializesOwnStorageId returns true for a MergeTree child unconditionally (StorageMerge.cpp:1968), which means "pruning by the iterator name is sound here", not "prune it". I built if (!prunable()) and measured it:

query 75720e8 if (!prunable())
merge('^sibling$') WHERE _table = '<sibling>' 23 empty
merge('^sibling$') WHERE _table = '<sibling>' AND _database = currentDatabase() 23 empty
merge('^sibling$') with no filter 23 23

Every MergeTree child vanishes as soon as a _table or _database predicate matches it, which is wrong results rather than a stricter prune.

A narrower form is implementable: distinguish "sound to prune by the iterator name" from "the emitted identity is already rejected", and skip only in the second case. That would turn master's FILE_DOESNT_EXIST into an empty result. I am not adding it here, because it changes behaviour beyond the bug this PR fixes and it adds a third state to the function whose complexity is already under review. It belongs in a separate change.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 29, 2026
… 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 ClickHouse#113735.

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

Copy link
Copy Markdown
Member

🕵 Status on 2026-09-04: this PR is superseded by the merged rework #116371 (merged 2026-08-29, backported to 26.6, 26.7 and 26.8). That rework fixes the same root cause with IStorage::readsFromOtherTables, overridden by Distributed, Merge, Buffer and Alias, so a delegating child is always read and the _table / _database predicate filters its rows. The reproducer from this PR's description returns the correct rows on current master.

What this PR adds beyond that rework (the forwarding-chain resolution through Alias / Buffer / MaterializedView / the lazy proxies, the file-like family fingerprint, and the FetchColumns stage analysis) is exactly the part @novikd requested changes on, and the rework deliberately keeps master behaviour for those engines. The branch now also conflicts with master in ReadFromMerge::getSelectedTables, and both new tests exceed the 180 s limit on the ASan flaky check, so bringing it up to date would mean re-implementing a design that has been decided against.

I am not merging master into this branch or pushing anything further. Unless there is a remaining case that #116371 does not cover, this PR can be closed; the streaming-child-behind-a-wrapper argument from the review threads, if still wanted, is a separate, narrower change.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

Checked against master at 2f4969d631ba, which carries #116371.

Confirmed: the reproducer answers correctly there. WHERE _table = '<remote leaf>' over a Merge of two Distributed children returns that leaf's 100 rows, and the ARRAY JOIN form that forces FetchColumns returns 200. I also ran this branch's 04741 against that build, and 44 of its 49 arms give the same result as the reference, including the Distributed, Merge, Buffer and Alias arms over ordinary children, the cross-database _database arm, the negation and IN arms, the MergeTree, View and MaterializedView pruning controls, the lazy-proxy answers in arms A and C, and the loop arm. One of the five differences is in master's favour: it still prunes a lazily-proxied MergeTree child, which this branch gave up.

The other four are two remaining cases, neither of which needs this branch.

1. A streaming engine behind a wrapper is read when the predicate names another child. This is the argument you flagged as separate. At the default setting the query fails:

SET allow_experimental_alias_table_engine = 1;
CREATE TABLE mt (k UInt8, v UInt8) ENGINE = MergeTree ORDER BY k;
INSERT INTO mt SELECT number, number FROM numbers(5);
CREATE TABLE fl (k UInt8, v UInt8) ENGINE = FileLog('/var/lib/clickhouse/user_files/fl/', 'CSV');
CREATE TABLE al ENGINE = Alias(currentDatabase(), fl);

SELECT _table, count() FROM merge(currentDatabase(), '^(al|mt)$') WHERE _table = 'mt' GROUP BY 1;
-- Code: 620. DB::Exception: Direct select is not allowed. (QUERY_NOT_ALLOWED)

SET stream_like_engine_allow_direct_select = 1;
SELECT _table, count() FROM merge(currentDatabase(), '^(al|mt)$') WHERE _table = 'mt' GROUP BY 1;
-- mt   5
SELECT count() FROM fl;
-- 0: the two records the directory held are no longer readable

Control: the same FileLog as a direct child of the Merge answers mt 5 at the default setting and its queue still reads 2 afterwards, so the wrapper hop is the difference. The cost is a durably consumed queue, from a query that asked for another child.

The same mechanism without a streaming engine: a Merge over a Distributed whose cluster has a down replica, filtered WHERE _table = '<local sibling>', fails with ALL_CONNECTION_TRIES_FAILED while that sibling alone reads 23, and EXPLAIN of the failing query contains ReadFromRemote. Arms K and M of 04741 are the Buffer version, raising FILE_DOESNT_EXIST where the reference has 23.

2. No _database predicate returns a file-like child's rows (arms G and Q):

CREATE TABLE f (x UInt32) ENGINE = File(TSV);   -- 19 rows
SELECT _database, _table, count() FROM merge(currentDatabase(), '^f$') GROUP BY 1, 2;
-- the _database column comes back empty, _table is 'f', the count is 19
SELECT count() FROM merge(currentDatabase(), '^f$') WHERE _database = '';                 -- 0
SELECT count() FROM merge(currentDatabase(), '^f$') WHERE _database = currentDatabase();  -- 0
SELECT count() FROM merge(currentDatabase(), '^f$') WHERE _table = 'f';                   -- 19

= '' is rejected by the prefilter, which tests the child's database name, and = currentDatabase() passes the prefilter but is dropped per row, because the rows carry an empty _database. A MergeTree child answers 0 and 23 for those two predicates, so it is specific to that family, and a MaterializedView over a File target behaves like the File child.

Nothing above needs this PR, so it can be closed. The last commits on the branch are yours, so I left the close to you, and I have not merged master or pushed anything. If you want the wrapper-hop case fixed, I can send it as a small separate PR.

@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Closing on 2026-09-16 as superseded by the merged rework #116371. Your check of 2026-09-04 confirmed that the reproducer answers correctly on master and that neither of the two remaining cases needs this branch, so the condition I set for closing is met. The branch is not merged with master and nothing was pushed, so the history stays as it was.

Thank you for the analysis and the tests. The two residual cases stay tracked in your comment above:

  1. A streaming engine behind an Alias / Buffer wrapper is read, and its queue consumed, when the predicate names another child. Please send that as the small separate PR you offered.
  2. A file-like child's rows carry an empty _database, so no _database predicate returns them. That one is pre-existing master behaviour and is a separate question of what _database should be for that family.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I am preparing the small separate PR for residual case 1: a streaming child behind an Alias or Buffer wrapper is read, and its queue consumed, when the _table predicate names another child of the Merge table. I will post the link here when it is up.

Leaving case 2 (a file-like child carrying an empty _database) out of that PR, as you framed it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Residual case 1: the narrow change has one behaviour change in it, and that call is yours

I have the mechanism and the change worked out. One decision sits in front of sending it, and I would
rather you pick it than guess.

Mechanism, re-read on master at 61124de86664e. ReadFromMerge::getSelectedTables exempts a
child from name pruning when readsFromOtherTables() is true (StorageMerge.cpp:2068), which is
unconditional for Alias and holds for Buffer with a destination. The exemption is there for
provenance, and it also authorises a read whose side effect is destructive: at the default
stream_like_engine_allow_direct_select the query dies with QUERY_NOT_ALLOWED even though the only
selected child is an ordinary MergeTree, and with the setting enabled the queue is consumed by a
query that selected another child. A direct FileLog child is pruned by name, so the wrapper hop is
the only difference. The term arrived with #116371, so 26.6, 26.7 and 26.8 carry it.

The decision. A stream-like engine stamps its own name into _table
(FileLogSource.cpp:138, StorageKafkaUtils.cpp:1113), so on master, with direct selection enabled,
WHERE _table = '<the queue table>' over the Merge does return that child's rows through the wrapper.

  1. Prune the wrapper when the predicate rejects its own name and its read would consume a queue. One
    IStorage predicate defaulting to isStreamingStorage(), one override for FileLog (the one gated
    engine that is not an IStreamingStorage), four wrapper forwards, one term in getSelectedTables:
    about 19 lines across 8 files. Cost: WHERE _table = '<queue table>' returns no rows instead of
    that child's rows, and the always-read rule in the engine's DOCS_MD needs one clause.
  2. Also test the predicate against the name the rows will carry, so option 1's arm keeps working.
    About 8 lines more, and it brings back emitted-identity reasoning, including the per-stage
    difference a materialized view introduces. That is the part of this branch @ novikd asked me to
    change.
  3. Wait for The _database and _table virtual columns of a Merge table carry the matched child's name again #115356. If a Merge child's rows carry the matched child's name, the exemption has no
    rationale left and the term can simply go, which settles both residuals at once.

I recommend 1. The name in that predicate is not a child of the Merge, and the only way to return
those rows is a destructive read the query did not ask for. Tell me which you want and I will send it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants