Repository navigation
Fix merge, Merge and Buffer reads of a data lake table missing rows of newer commits - #125401
PedroTadim merged 12 commits into
Conversation
…g their snapshot `StorageObjectStorage::updateExternalDynamicMetadataIfExists` refreshes a data lake table and pins the resulting snapshot into its shared in-memory metadata, and `StorageObjectStorage::read` refreshes only when no snapshot is pinned. The analyzer calls the hook only for the storage it resolves by identifier, so for a `Merge` or `Buffer` table (and for the `merge` table function, which gets no call at all) the child or destination kept whatever snapshot its last direct query had pinned. Every commit made after that query (by another writer, or by an INSERT through the table itself) was silently missing from reads through `merge`, `Merge` and `Buffer` until the table was queried directly again. Call the hook right before the nested metadata snapshot is taken in `ReadFromMerge::createChildrenPlans`, `StorageBuffer::read` and the `Merge` structure inference (`getColumnsDescriptionFromSourceTablesImpl`, which also serves `merge` and `DESCRIBE merge(...)`), as `StorageMaterializedView::read` already does for its target. Each call runs after the access check of its path, and is a no-op for non data lake tables. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (6 nits).
Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20261012-111200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261012-094000 |
|
Workflow [PR], commit [fc3b52a] Summary: ✅
AI ReviewSummaryThe PR refreshes external metadata before reads through Findings❌ Blockers
Missing context / blind spots
Tests
Final Verdict❌ Block on the remaining silent wrong-result path, retained here as explicitly dismissed rather than escalated inline. The minimum correctness change is to preserve the inferred snapshot or fail the query when a UUID-less catalog child's schema changes before its read. |
…and `Alias` In a database with `lazy_load_tables` the catalog hands out a `StorageTableProxy`, which does not forward `updateExternalDynamicMetadataIfExists`, so the refresh calls of `Merge`, `Buffer` and the `Alias` hook were no-ops there. An `INSERT` resolves the stand-in and pins the pre-insert snapshot of the storage behind it, and `merge()`, `Merge`, `Buffer` and `Alias` reads (also a direct `SELECT` from the alias) kept returning that snapshot. Resolve the stand-in with `resolveStorageProxy` before refreshing. It does not load an untouched table: such a table has no pinned snapshot, and its first read refreshes it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
In a database with `lazy_load_tables`, a table that has not been accessed since the database was attached is a stand-in that reports the columns of its stored `CREATE` query. `resolveStorageProxy` does not load it, so the refresh before `merge` schema inference was a no-op for such a child: after an external `RENAME COLUMN k TO v` on an Iceberg table, `DESCRIBE merge(...)` reported `k`, `SELECT sum(v) FROM merge(...)` failed with `UNKNOWN_IDENTIFIER`, and `SELECT sum(k) FROM merge(...)` returned default values, because the read path then refreshed the loaded child to the new schema. `CREATE TABLE ... ENGINE = Merge` without columns persisted the old column too. Inference reads the child's schema, so loading it is the cost of the operation, as for `CREATE TABLE ... AS`. The same holds for an `Alias` over such a table: its hook now loads the target, which also fixes a direct `SELECT` from the alias. A direct read of the stand-in itself is still stale; that needs `StorageProxy` to forward the hook, which ClickHouse#113389 does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 1dabd57Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261013-013014 |
|
@groeneai 🕵️ The fix looks right to me; I reproduced the stale
|
| Aliases aliases; | ||
| RowPolicyDataOpt row_policy_data_opt; | ||
| /// The analyzer refreshes only the outer storage, so a data lake child would keep the snapshot of its last direct query. | ||
| resolveStorageProxy(storage)->updateExternalDynamicMetadataIfExists(modified_context); |
There was a problem hiding this comment.
❌ Keep the child snapshot used for schema inference through the read
For the merge table function, getColumnsDescriptionFromSourceTablesImpl has already refreshed this child and bound the query to that snapshot's columns. This second refresh can select a different schema: StorageObjectStorage::updateExternalDynamicMetadataIfExists replaces both the pinned state and the column list.
A concrete failing interleaving is a single Iceberg child containing k = 7: analyze SELECT sum(k) FROM merge(db, '^t$'), pause at storage_merge_create_children_plans_pause, and commit ALTER TABLE writer RENAME COLUMN k TO v through another table object over the same Iceberg location. On resuming, this call changes the child's schema to v; the missing-column handling in getModifiedQueryInfo and createChildrenPlans treats k as absent, and convertAndFilterSourceStream fills it with zero. The source trace therefore yields sum(k) = 0, silently replacing existing data with defaults.
Please retain the per-query child snapshot captured during inference and use it for the read, or detect this schema drift and reject/retry the query. Add a focused concurrent-rename regression test; the current test renames before starting the query and cannot exercise this interleaving.
There was a problem hiding this comment.
Fixed in ee793e4: the merge read reuses the metadata its structure inference took, and 05401 covers the concurrent rename.
There was a problem hiding this comment.
The snapshot-consistency issue remains for stateless DataLakeCatalog children at src/Storages/StorageMerge.cpp:1197. DatabaseDataLake::getTablesIteratorImpl calls tryGetTableImpl for each enumeration (src/Databases/DataLake/DatabaseDataLake.cpp:1411); with allow_experimental_iceberg_compaction = 0, that constructs a fresh StorageObjectStorage (:1254) instead of returning a cached object. The inference records object A in inferred_source_metadata, while getSelectedTables obtains object B. Since the map compares pointer ownership, the lookup always misses, and :1204-1205 uses B's current metadata rather than A's saved snapshot. Keeping A alive alone would still leave A and B as different keys.
Source trace: infer SELECT sum(k) FROM merge('catalog', '^ns[.]t$') from a catalog Iceberg table containing k = 7; an external writer commits RENAME COLUMN k TO v before the later child enumeration fetches its metadata. B then has v, the lookup misses, :1400-1404 drops k from the read list, and convertAndFilterSourceStream supplies its default, yielding 0 again. This does not need a third query to refresh a shared target.
Please preserve the inferred storage/snapshot across catalog re-enumeration, or associate the saved snapshot with a stable table identity and reject incompatible replacement. A catalog-backed schema-change regression is needed here; 05401 uses a persistent Atomic table, whose storage identity stays the same. This is a source-level trace; I could not execute it in this checkout.
There was a problem hiding this comment.
Fixed in 06e3f38: the snapshot is keyed by the table's StorageID now, and test_merge_reads_the_snapshot_it_inferred_from in test_database_iceberg covers a rename in a REST catalog between the inference and the read's lookup.
There was a problem hiding this comment.
The catalog case is still present on 59df6cad59a4d7e5975306420d5588ce1eae8da6 at src/Storages/StorageMerge.cpp:1198 for Glue and Hive catalogs. GlueCatalog::tryGetTableMetadata (src/Databases/DataLake/GlueCatalog.cpp:333) and HiveCatalog::tryGetTableMetadata (src/Databases/DataLake/HiveCatalog.cpp:215) never set TableMetadata::table_uuid, so DatabaseDataLake::tryGetTableImpl assigns UUIDHelpers::Nil (src/Databases/DataLake/DatabaseDataLake.cpp:1153). With the default allow_experimental_iceberg_compaction = 0, each enumeration still creates a new storage object. Consequently neither side of the identity condition passes, and lines 1205–1206 refresh and use the later schema.
The same rename interleaving therefore remains: infer SELECT sum(k) FROM merge('glue_db', '^ns[.]t$') from an Iceberg table containing k = 7, then externally rename k to v before the read's catalog enumeration. Its new storage has only v; the missing-column path drops k and supplies defaults, yielding 0. No table replacement or third query is needed. This is a source trace, not a local runtime reproduction.
Please preserve the inferred storage/snapshot for catalogs without UUIDs, or establish a durable physical identity before reusing metadata; retain the protection against transferring versions to replacement tables. The REST-only regression does not exercise this path; add the equivalent case using the existing Glue catalog fixture.
The schema inference of the `merge` table function refreshes each data lake source table, and the read refreshed it again: two metadata requests per table per query (two remote round trips for Iceberg on S3 or behind a catalog), and a commit landing between the two could change the schema under the query. A column renamed by another writer in between was then read as missing and filled with defaults (`sum(k)` returned 0 instead of 7). The `merge` table function's storage now keeps the metadata the inference read for each source table, and its read uses it instead of refreshing the table again. Tables the inference did not look at, and `Merge` tables, still refresh once in the read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, both addressed in ee793e4.
|
…torage object A `DataLakeCatalog` database builds a new storage object on every lookup, and `merge()` looks its tables up again for the read, so the object the structure inference saw never matched the one being read. The read then refreshed the new object, and a column renamed by another writer in between was filled with defaults (`sum(k)` returned NULL instead of 7 with a local REST catalog). Key the saved metadata by `StorageID` (database, table and UUID), so another object of the same table reuses it. Only metadata that pins a data lake snapshot is kept: that snapshot identifies the table version for whichever object reads it, while for other tables a replacement created under the same name without a UUID (an `Ordinary` database) must not get the metadata of the old one, so they read their current metadata, as on master. This also keeps catalog children at one refresh per query: Iceberg metadata file lookups of `merge()` over a catalog table go from 9 back to 6, the same as a direct read and as master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 06e3f38Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261015-220013 |
|
🕵️ @groeneai The reuse of the inferred snapshot aborts the server in the private build. On the sync PR (clickhouse-private#80916), The server goes down, so every later test in Why only the private build: for a
Public code allows the combination "pinned snapshot, uninitialized configuration", but nothing guarantees it. Two ways to remove it:
After the fix, the private flaky-check job is the one to re-run: it runs the whole module. |
…ady pinned A `DataLakeCatalog` builds a new `StorageObjectStorage` on each lookup, so the `merge` read of a catalog table gets a different object than the one its schema inference refreshed, and hands it the snapshot pinned on that other object. Nothing initializes the configuration of the new object, and `read` skips its own initialization when a snapshot is pinned. Public code only reaches the configuration's metadata later, in `prepareReadingFromFormat`, which initializes it lazily, but anything that uses it earlier throws `Metadata is not initialized` (a LOGICAL_ERROR, so the server aborts in debug and sanitizer builds). Initialize it lazily at the start of `read` when a state is pinned. This does not re-pin: the read still uses the pinned state, and for an already initialized configuration it is a no-op, so it adds no request. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`RowPolicyData` took the child's current in-memory metadata, while the read uses the snapshot `merge` inferred its columns from. For a `DataLakeCatalog` child, which is a new storage object per lookup, a schema change committed between the inference and the read's lookup made the policy refer to columns the new object no longer has (`Missing columns: 'k' while processing: 'k > 0'`). Pass it the snapshot chosen for the read instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Confirmed and fixed, thanks.
Could you re-run the private flaky-check job? I have no access to |
…ts name For a table without a UUID (e.g. in an `Ordinary` database) the `StorageID` key holds only the database and the table name. When another table is renamed to that name between the schema inference and the read, the read used the saved state of the old table, and for `DeltaLake` that state is only a version number, which the new table interprets against its own log: `SELECT sum(k) FROM merge(db, '^t$')` returned 100, the replacement's version 1, instead of its current 300 (master) or the old table's 7. The saved metadata now keeps a weak reference to the storage it was read from, and is reused for another object only when the key carries a UUID, i.e. a durable table identity (`DataLakeCatalog` tables get the catalog's table UUID, which keeps the per-lookup objects of a REST catalog covered). Otherwise the read refreshes the table, as on master, which is also what a `Glue` or `Hive` catalog table gets now, since those catalogs report no table UUID and build a new object per lookup. Test `05406` pauses the scalar subquery of the `merge` query at `delta_lake_metadata_iterate_pause`, i.e. after the inference and before the read enumerates its tables, and swaps the tables there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 15bc6e4Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261016-193006 |
|
Fixing PRs for the |
| trap '$CLICKHOUSE_CLIENT -q "SYSTEM DISABLE FAILPOINT ${FP}" ||:; $CLICKHOUSE_CLIENT -q "DROP DATABASE IF EXISTS ${DB}" ||:; rm -rf "${DIR}"' EXIT | ||
|
|
||
| # The first `Ordinary` database of the server logs a deprecation warning. | ||
| $CLICKHOUSE_CLIENT --allow_deprecated_database_ordinary 1 --send_logs_level fatal -q "CREATE DATABASE ${DB} ENGINE = Ordinary" |
There was a problem hiding this comment.
@groeneai why do you need 3 test files? Can you remove at least one of them?
There was a problem hiding this comment.
Removed 05406: its replacement-table case is now the second half of 05401 (400151e). Both pause merge() between its structure inference and its read, so they share one failpoint, and the case uses Iceberg now, so the no-msan tag is gone too. 05366 stays separate because it needs no failpoint and runs in parallel.
Checked: without the table identity check the merged case returns 7 instead of 300; on master both cases fail.
| @@ -497,7 +497,7 @@ CancellationCode StorageAlias::killPartMoveToShard(const UUID & task_uuid) | |||
|
|
|||
| void StorageAlias::updateExternalDynamicMetadataIfExists(ContextPtr local_context) | |||
There was a problem hiding this comment.
@groeneai are you sure all the table engines that take another table as input such as Distributed are doing to be fine with data lakes?
There was a problem hiding this comment.
Yes. I measured it on 400151e and on master: a direct read pins the snapshot, a second table object over the same Iceberg path commits 10 rows, then each engine reads (non-trivial countIf, since a plain count() takes the trivial-count path and reads fresh).
| Engine over the Iceberg table | master | this PR |
|---|---|---|
Merge, merge(), Buffer |
stale | fresh |
Distributed (prefer_localhost_replica 0 and 1), remote, cluster |
fresh | fresh |
View, view(), loop, dictionary with a CLICKHOUSE source |
fresh | fresh |
Alias, MaterializedView (TO the table), table over a table function |
fresh | fresh |
INSERT through Distributed, Alias, Buffer, a materialized view, a table over a table function |
all rows kept | all rows kept |
The second and third groups run a query over the table name, which the analyzer refreshes. The fourth forwards the hook (StorageAlias, StorageTableFunction) or calls it on the target (StorageMaterializedView::read). Merge and Buffer were the only ones that read the child storage directly without it.
One gap is left as on master (raised by the bot in r4304227983; I read it from the code, I have no Glue rig): Glue and Hive catalogs give no table UUID and a new storage object per lookup, so merge() over them refreshes again at read, and a column renamed between inference and read is still read as missing. As you suggested, this is documented in InferredSourceMetadata (fc3b52a) instead of a new identity rule.
|
🕵️ @groeneai
|
Both tests pause `merge()` between its structure inference and its read, so one file can hold both cases. The replacement case now uses Iceberg tables and the same `storage_merge_create_children_plans_pause` failpoint, reached by a `merge()` in a scalar subquery of the outer query, so `05401` needs no `no-msan` tag (that tag was only needed for delta-kernel-rs). Negative control: with the table identity check removed from `ReadFromMerge::createChildrenPlans`, the second case returns 7 (the replaced table) instead of 300, 3/3; on master both cases fail (0 and 100). Co-Authored-By: Claude Opus 5.5 <[email protected]>
`loop(db, t)` reads its rows through a `SELECT` over the table name, which the analyzer refreshes, but it took its columns from the table's in-memory metadata without a refresh. After an external `RENAME COLUMN k TO v` on an Iceberg table, `DESCRIBE loop(db, t)` still showed `k` and `SELECT v FROM loop(db, t)` failed with UNKNOWN_IDENTIFIER until some other query refreshed the table (master and this PR alike). `getActualTableStructure` (DESCRIBE, CREATE AS) and `executeImpl` (the `StorageLoop` columns) now refresh first, like a direct read and `merge()` structure inference do. An `Alias` whose target was dropped is skipped: its hook throws UNKNOWN_TABLE, while `loop` over it keeps reporting no columns (04945). Also documents in `InferredSourceMetadata` that a Glue or Hive catalog table, having no UUID and a new storage object per lookup, is refreshed again by the read, as asked in review. Test: 05366 gains a `loop` DESCRIBE line and a `loop` read line, each after its own external rename, so each refresh site is pinned by one line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Resolve the conflicts by porting only the hunks of #116793. The conflicting regions hold code of master PRs that are not on 26.10 (#125401 refreshExternalMetadata in TableFunctionLoop.cpp); they are left as on 26.10. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflicts by porting only the hunks of #116793. The conflicting regions hold code of master PRs that are not on 26.9 (#125401 refreshExternalMetadata in TableFunctionLoop.cpp, #123364 SecretArgumentsSpec in TableFunctionViewIfPermitted.cpp); they are left as on 26.9. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #125383
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed reads of a data lake table such as
Icebergthrough themergetable function, aMergetable or aBuffertable (and, in a database withlazy_load_tables, through anAliastable), which returned the snapshot of the last direct query of that table and silently missed the rows of newer commits.loopover such a table now reports its current columns.Description
On 26.8.2.3 and 26.3.33.10, after a direct query of an Iceberg table, reads through
merge(),MergeorBufferkeep that query's snapshot and miss every later commit:StorageObjectStorage::updateExternalDynamicMetadataIfExistsrefreshes a data lake table and pins the snapshot, andreadrefreshes only when nothing is pinned. The analyzer calls it only for the storage it resolves.The fix calls the hook before the nested snapshot in
ReadFromMerge::createChildrenPlans,StorageBuffer::readand theMergestructure inference, and beforelooptakes the table's columns. Formerge()the read and the child's row policy reuse the snapshot of the structure inference, so each child is refreshed once and keeps its columns. It is keyed by table and UUID (a catalog builds a new object per lookup, whichreadinitializes), else by the object.In a
lazy_load_tablesdatabase the catalog holds a stand-in that drops the hook, so these calls and theAliashook resolve it first. A direct read of such a table stays stale until the stand-in forwards the hook (#113389).The test covers each read and
merge()after an externalRENAME COLUMN, in a plain and alazy_load_tablesdatabase, andloop; each fails without the fix. A second test renames the column, then swaps a UUID-less table, whilemerge()pauses between inference and read; an integration test renames before the read's catalog lookup.Other engines read the current snapshot (measured):
Alias,MaterializedViewand tables over a table function forward the hook;Distributed,remote, views and dictionaries query the table by name.Found via an AST fuzzer report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125275&sha=68dabec672d4b2e357a16f21849b2eb329fe931d&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Workflow [PR]
Sync PR [sync-upstream/pr/125401]
Version info
26.11.1.323-master(included in26.11and later)