Repository navigation
Conversation
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.
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.
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260806-145604 |
|
cc @KochetovNicolai @novikd, could you review this? A |
|
Workflow [PR], commit [75720e8] Summary: ❌
AI ReviewSummaryThis PR teaches Findings❌ Blockers
Tests
Final VerdictChanges requested. The main classifier is much closer, but LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 95/109 (87.16%) · Uncovered code |
| { 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
`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.
…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.
CI finish ledger — 391fbbdCI is fully finished on this head: 175 check-runs, 0 incomplete,
Both lines resolve to one event, and the second is not an independent failure. The Session id: cron:our-pr-ci-monitor:20260807-200000 |
…virtual-column-prefilter-delegating-child Co-Authored-By: Claude Fable 5 <[email protected]>
Merged current master in; this is the prerequisite for #113242, which the PR queue is now waiting onRefreshed this branch onto master ( Bumping this to the front of the queue because #113242 is sequenced behind it, and the bug #113242 I re-confirmed that defect on current master, independently of either pull request: with a SELECT count() FROM merge_distinct WHERE _table = 'dist_distinct'; -- 0
SELECT count() FROM merge_distinct; -- 200so the filter still silently drops every row. |
novikd
left a comment
There was a problem hiding this comment.
The implementation looks too complicated and very strange
| StoragePtr tryGetNested() const override | ||
| { | ||
| std::lock_guard lock{nested_mutex}; | ||
| return nested; | ||
| } |
There was a problem hiding this comment.
Why is it needed if there is getNested()?
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes7 object files changed (+27.96 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units15 translation units recompiled, 91 s compile time in total, 15 of them have a recent master baseline. |
…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())) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
… 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]>
|
🕵 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 What this PR adds beyond that rework (the forwarding-chain resolution through I am not merging |
|
Checked against Confirmed: the reproducer answers correctly there. 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 readableControl: the same The same mechanism without a streaming engine: a 2. No 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
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 |
|
🕵 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 Thank you for the analysis and the tests. The two residual cases stay tracked in your comment above:
|
|
Acknowledged. I am preparing the small separate PR for residual case 1: a streaming child behind an Leaving case 2 (a file-like child carrying an empty |
Residual case 1: the narrow change has one behaviour change in it, and that call is yoursI have the mechanism and the change worked out. One decision sits in front of sending it, and I would Mechanism, re-read on The decision. A stream-like engine stamps its own name into
I recommend 1. The name in that predicate is not a child of the |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
WHERE _table = ...orWHERE _database = ...filter on aMergetable silently returning no rows when a child table reads through another table, for example aDistributed,Merge,BufferorAliaschild. 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._databasebehaves the same; both reproduce on master.The prefilter in
ReadFromMerge::getSelectedTablesmatches 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 aMergeTreeorViewchild 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 madeMergeproxy 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 forFileLog. That is resolved throughAlias,Buffer,MaterializedView,MaterializedPostgreSQLand 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
Distributedchild 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 TABLESracing the check is left open, as on master.Workflow [PR]
Sync PR [sync-upstream/pr/113735]