Skip to content

Fix merge, Merge and Buffer reads of a data lake table missing rows of newer commits - #125401

Merged
PedroTadim merged 12 commits into
ClickHouse:masterfrom
groeneai:merge-buffer-data-lake-snapshot-refresh
Oct 20, 2026
Merged

PedroTadim merged 12 commits into
ClickHouse:masterfrom
groeneai:merge-buffer-data-lake-snapshot-refresh

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125383

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 reads of a data lake table such as Iceberg through the merge table function, a Merge table or a Buffer table (and, in a database with lazy_load_tables, through an Alias table), which returned the snapshot of the last direct query of that table and silently missed the rows of newer commits. loop over 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(), Merge or Buffer keep that query's snapshot and miss every later commit:

SET allow_insert_into_iceberg = 1;
CREATE TABLE t (k Int64) ENGINE = IcebergLocal('/path/t/', 'Parquet');
INSERT INTO t SELECT number FROM numbers(1000);
CREATE TABLE w ENGINE = IcebergLocal('/path/t/', 'Parquet');
SELECT count() FROM t; -- 1000
INSERT INTO w SELECT number + 1000 FROM numbers(10);
SELECT count(), sum(k) FROM merge(currentDatabase(), '^t$'); -- 1000 499500, expected 1010 509545

StorageObjectStorage::updateExternalDynamicMetadataIfExists refreshes a data lake table and pins the snapshot, and read refreshes 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::read and the Merge structure inference, and before loop takes the table's columns. For merge() 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, which read initializes), else by the object.

In a lazy_load_tables database the catalog holds a stand-in that drops the hook, so these calls and the Alias hook 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 external RENAME COLUMN, in a plain and a lazy_load_tables database, and loop; each fails without the fix. A second test renames the column, then swaps a UUID-less table, while merge() pauses between inference and read; an integration test renames before the read's catalog lookup.

Other engines read the current snapshot (measured): Alias, MaterializedView and 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

  • Merged into: 26.11.1.323-master (included in 26.11 and later)

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ❌ Refreshing an Alias child refreshes its target before StorageAlias::read checks SELECT on the target DISAGREE A direct SELECT * FROM alias on master reaches the same refresh earlier and needs fewer grants: IdentifierResolver.cpp:364-366 calls the hook with no access check and StorageAlias.cpp:498-500 forwards it. The new sites run only after the SELECT check on the alias (StorageMerge.cpp:2194-2198, StorageBuffer.cpp:337).
2 ❌ A lazy_load_tables stand-in does not forward the hook, so merge() inference stays stale DISAGREE The stand-in drops the hook on every path: DESCRIBE t and a direct SELECT call it on the same catalog object (InterpreterDescribeQuery.cpp:257, IdentifierResolver.cpp:366), so merge() now behaves like a direct read. The fix belongs in StorageProxy.h, which #117972 and #113389 already change.
3 💡 The new refresh comes before the dangling-Alias diagnostic in createChildrenPlans DISAGREE StorageMerge::getQueryProcessingStage already throws the target's UNKNOWN_TABLE at planning on master (StorageAlias.cpp:579); the error code does not change.
4 💡 Description over-claimed (DeltaLake untested, "no-op for other tables", repro missing allow_insert_into_iceberg) AGREE, fixed in the description none
5 💡 merge() refreshes every inferred data lake child, plus once more at read DISAGREE Disclosed and measured in the description: 20 tables, 4 ms to 7 ms, 21 refreshes.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261012-111200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Pin the snapshot with a direct read, commit through a second table object on the same path, read through merge(): 1000 rows instead of 1010, every time. The new test fails 50/50 on the base build.
b Root cause explained? updateExternalDynamicMetadataIfExists pins a data lake snapshot into the shared in-memory metadata and read refreshes only when nothing is pinned. The analyzer calls the hook only for the storage it resolves (the Merge/Buffer wrapper; none for the merge table function), so the child kept the snapshot of its last direct query.
c Fix matches root cause? Yes. The hook is called where the nested snapshot is taken (ReadFromMerge::createChildrenPlans, StorageBuffer::read, Merge structure inference), as StorageMaterializedView::read does. No guard, no setting.
d Test intent preserved / new tests added? New 05366_merge_buffer_data_lake_snapshot_refresh.sh: merge(), Merge, Merge over Merge, merge() over Alias, Buffer, each after its own commit, plus DESCRIBE and a read after an external RENAME COLUMN.
e Both directions demonstrated? Base build: 50/50 fail; fix build: 50/50 pass (randomized settings). One rebuild per removed call: each call has test lines that fail without it.
f Fix is general across code paths? Alias, table-function proxies and StorageObjectStorageCluster are reached through their existing forwarders; Merge over Merge through the inner read; views, materialized views and Distributed are unchanged; other storages get the default no-op.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not type-dependent. Checked with randomized settings, PREWHERE on/off, parallel replicas (local plan 1/0), Replicated database, an external ADD COLUMN and RENAME COLUMN, and commits by another writer or by an INSERT through the table.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change. Cost: one metadata refresh per data lake child per read; merge() also refreshes every inferred child (20 local tables: 4 ms to 7 ms).
i Invariants and contracts preserved? Each refresh runs after its path's access check (SELECT per child, SHOW_COLUMNS for inference as in DESCRIBE, SELECT + share lock for the Buffer destination). A refresh error propagates as for a direct read. Merge columns inferred at CREATE are persisted, so server start does not refresh.

Session id: cron:clickhouse-impl-self-slot-57:20261012-094000

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fc3b52a]

Summary: ✅


AI Review

Summary

The PR refreshes external metadata before reads through merge, Merge, and Buffer, resolves lazy stand-ins, and refreshes the columns exposed by loop. It also preserves inferred data lake snapshots for the child read and row-policy analysis. Reviewed head: fc3b52a267dfd02dc27b54db8e7d06e7ffe58efa. One previously reported wrong-result path remains deliberately accepted and documented; there are no new inline findings.

Findings

❌ Blockers

  • src/Storages/StorageMerge.cpp:1196–1206: The inferred schema and the read snapshot can still diverge for Glue/Hive catalogs. [dismissed by author -- https://github.com/Fix merge, Merge and Buffer reads of a data lake table missing rows of newer commits #125401#discussion_r4284309180]

    GlueCatalog and HiveCatalog do not supply a table UUID, and their default stateless lookup creates a different storage object for the read. Consequently, neither identity condition at line 1198 passes, and the read uses later metadata. Concrete source trace: infer SELECT sum(k) FROM merge('catalog', '^ns[.]t$') from an Iceberg table containing k = 7, then externally rename k to v before the read enumerates its children. The later metadata lacks k; missing-column handling substitutes defaults, yielding 0 instead of 7.

    This remains a correctness concern because a concurrent schema change silently replaces existing values. The author and maintainer explicitly accepted this limitation; the new comment documents it but does not prevent it. A fix would retain the inferred storage/snapshot or reject incompatible schema drift, while preserving the safeguard against transferring snapshots to replacement tables. No further thread reply or reopening is warranted.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory is available, so the remaining finding is source-traced, not independently reproduced. Current-head builds and runtime suites are still queued; the available Fast test results exclude the new no-fasttest cases. Earlier successful regression runs are reported in the discussion.
Tests
  • ⚠️ The catalog concurrency regression uses REST, whose table UUID exercises snapshot reuse. An equivalent concurrent-rename case using the existing Glue fixture would demonstrate the remaining UUID-less path and validate any eventual fix.
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.

@groeneai
groeneai requested review from alesapin and azat October 12, 2026 11:51
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 12, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). label Oct 12, 2026
…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]>
Comment thread src/Storages/StorageMerge.cpp Resolved
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]>
Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1dabd57

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR (it refreshes data lake snapshots under Merge, Buffer and Alias): Code: 60 ... Unknown table expression identifier '_materialized_cte_c_...' with parallel replicas, 0 of 126 reruns failed; it failed on about 170 other PRs and 31 master runs in the last 7 days #123121 (mine, open)
Integration tests (arm_binary, 1/4) / test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads not from this PR: Spark's own CREATE TABLE failed with RuntimeIOException: Failed to refresh the table, on the xdist worker that had run test_storage_delta/test_writes_interop.py earlier (the reused Spark JVM keeps a Hadoop filesystem bound to that module's MinIO); it failed on about 45 other PRs and 23 master runs since yesterday #125448 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #123121 and #125448 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-013014

@PedroTadim PedroTadim self-assigned this Oct 15, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️ The fix looks right to me; I reproduced the stale merge() read on master. Two concerns about cost:

  1. merge() now refreshes each data lake child twice per query: once in the structure inference, which looks at up to merge_table_max_tables_to_look_for_schema_inference tables (1000 by default), including ones a _table filter later skips, and once more in createChildrenPlans. Each refresh is configuration->update, which for Iceberg on S3 or behind a REST/Glue catalog means a remote metadata or catalog request. So merge() over N such tables now costs 2N round trips per query; the 4 ms → 7 ms in the description was measured on local files. Could each storage be refreshed only once per query, for example by skipping the refresh in createChildrenPlans when the inference of the same query has already refreshed that storage?

  2. In a lazy_load_tables database, resolveStorageProxyLoading(t) in the inference loads every stand-in that merge() reaches, whatever its engine. Only engines whose schema lives outside ClickHouse (data lakes) can have stale CREATE columns. For MergeTree and the like, ALTER rewrites the metadata file, so the stand-in already reports the right columns. Could the load be limited to stand-ins of data lake engines, so merge() over such a database leaves the other tables lazy?

Comment thread src/Storages/StorageMerge.cpp Outdated
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);

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.

❌ 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.

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.

Fixed in ee793e4: the merge read reuses the metadata its structure inference took, and 05401 covers the concurrent rename.

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.

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.

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.

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.

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.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, both addressed in ee793e4.

  1. Done. The storage of the merge table function now keeps the metadata its structure inference read for each source table, and the read uses it instead of refreshing again. Counting refreshes with iceberg_use_version_hint = 1 (one IcebergVersionHintUsed each), merge() over two Iceberg tables went from 4 to 2 per query, and with WHERE _table = 't1' from 3 to 2. The inference still refreshes the tables a _table filter skips, since their columns are part of the inferred structure; a Merge table refreshes each child once in its read, as before. Reusing the snapshot also fixes the interleaving the bot reported (a rename committed between inference and read made sum(k) return 0); the new test 05401 pauses there and fails on the previous head. One window stays: StorageAlias::read builds its own target snapshot, so if a third query refreshes the target of an Alias child in between, the read fails with NOT_FOUND_COLUMN_IN_BLOCK (it returned 0 before this commit).

  2. A SELECT through merge() already loads every matched stand-in on master: in a lazy_load_tables database with t1, t2, t3, after SELECT sum(k) FROM merge('dl', '^t') WHERE _table = 't1' all three are MergeTree in system.tables (master 2cb89c8). So the load in the inference changes only DESCRIBE merge(...). A stand-in that is not loaded yet does not expose its engine (getName returns TableProxy), so limiting the load to data lakes would mean reading each table's CREATE query from disk and matching engine names. I would keep it as is; if you want DESCRIBE to stay lazy, I will add that.

@clickhouse-gh clickhouse-gh Bot added comp-storage-merge Merge table engine (logical union over tables) and related mechanics. and removed comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). labels Oct 15, 2026
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit fc3b52a267dfd02dc27b54db8e7d06e7ffe58efa was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 06e3f38

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it changes Merge, Buffer and Alias reads of data lake tables, not text indexes): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane, 85 of 85 same-settings reruns passed; it failed on 73 PRs and 12 times on master in the last 30 days #125892 (mine, open)
Mergeable Check, PR rollups of the row above #125892 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261015-220013

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

The reuse of the inferred snapshot aborts the server in the private build. On the sync PR (clickhouse-private#80916), test_merge_reads_the_snapshot_it_inferred_from fails in both the flaky-check and the db disk 5/8 integration jobs:

Logical error: 'Metadata is not initialized'
  DataLakeConfiguration<StorageS3Configuration, IcebergMetadata>::getMetadata()   DataLakeConfiguration.h:624
  StorageObjectStorage::read(...)                                                StorageObjectStorage.cpp:786
  ReadFromMerge::createPlanForTable(...)                                          StorageMerge.cpp:1988
  ReadFromMerge::createChildrenPlans(...)                                         StorageMerge.cpp:1415

The server goes down, so every later test in test_database_iceberg fails with Connection refused. That accounts for the "62 new" in CH Inc sync.

Why only the private build: for a DataLakeCatalog child, the read's lookup returns a new StorageObjectStorage, which is why 06e3f38fb0b keys the map by StorageID. This branch hands that new object a snapshot that the inference lookup pinned on a different object. The new object's configuration was never initialized: nothing called update or updateExternalDynamicMetadataIfExists on it, and read skips its own initialization because a snapshot is already pinned.

  • Public: read never needs the configuration's metadata when a snapshot is pinned, so all 8 public runs of the test pass.
  • Private: read also leases the pinned snapshot through configuration->getExternalMetadata(), which calls getMetadata() and throws.

Public code allows the combination "pinned snapshot, uninitialized configuration", but nothing guarantees it. Two ways to remove it:

  1. In this branch, initialize the object the read actually got, without re-pinning it. The inferred snapshot then still decides what is read.
  2. In StorageObjectStorage::read, initialize a data-lake configuration that hasn't been initialized yet even when a snapshot is pinned (lazyInitializeIfNeeded for a table function, as the unpinned branch does), before anything else uses the configuration. This is public code, so the private build gets it through the sync, and any other caller that brings its own pinned snapshot is covered too.

After the fix, the private flaky-check job is the one to re-run: it runs the whole module.

groeneai and others added 2 commits October 16, 2026 11:47
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed, thanks.

  • 5324357 (your option 2): StorageObjectStorage::read calls lazyInitializeIfNeeded on a data lake configuration when a state is already pinned. It never re-pins, so the inferred snapshot still decides what is read, and it is a no-op for an initialized configuration. To reproduce the private abort, I added a local-only configuration->getExternalMetadata() call after the pinning block: without the fix, test_merge_reads_the_snapshot_it_inferred_from aborts with Logical error: 'Metadata is not initialized' at your frames (StorageMerge.cpp:1988, :1415) and the next test gets Connection refused; with it, the test passes, and the whole test_database_iceberg module has 66 passed (the 13 local failures are environment gaps: missing pyiceberg_core, /backups permissions).
  • 3e34185: RowPolicyData still read the child's current metadata instead of the snapshot the read uses, so with a row policy on the catalog table the same rename failed with Missing columns: 'k' while processing: 'k > 0'. It now gets the read's snapshot. The integration test has a row policy now: it fails without this commit and on master, and passes 3/3 with it.

Could you re-run the private flaky-check job? I have no access to clickhouse-private.

Comment thread src/Storages/StorageMerge.cpp Resolved
…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]>
@groeneai

groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 15bc6e4

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 3/4) / test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py (both tests) not from this PR: red on master since 09:59Z and on many other PRs. The old server image now runs the remote_url_allow_hosts check for SQL disks, so the first CREATE fails with Code: 491 ... is not allowed in configuration file. This run tested master from before the fix #126289 (mine, merged)
Performance Comparison (arm_release, master_head, 6/6) / logical_functions_medium #7 dashboard confirmed_regression +16.3%, +13.3% after restart. The query is or() over materialized constants from zeros(100000000) with max_threads = 1; this diff only changes merge(), Buffer, Alias and object storage reads, none of which this query runs #125949 together with #124676 (both mine, open; neither alone removes it, measured in #125949 (comment))
Mergeable Check, PR praktika rollups of the rows above #126289, #125949 and #124676 (the owners of the first two rows)

Session id: cron:our-pr-ci-monitor:20261016-193006

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PRs for the logical_functions_medium #7 arm_release perf red: #125949 together with #124676. Neither removes it alone: both servers had the same base modulo 2 MiB, but this PR build places its code 0xF0000 lower in the file than the official reference, and for this query that code position decides the speed. Measurements: #125949 (comment)

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"

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.

@groeneai why do you need 3 test files? Can you remove at least one of them?

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.

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)

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.

@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?

@groeneai groeneai Oct 17, 2026 •

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.

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.

@PedroTadim

PedroTadim commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

🕵️ @groeneai

  1. Engines that read another table: Distributed is fine. Every shard, including the local replica (createLocalPlan), analyzes the shard query, so its analyzer resolves the data lake table and calls updateExternalDynamicMetadataIfExists, and INSERT ... SELECT through Distributed calls it explicitly. View, MaterializedView, Alias and StorageTableFunctionProxy are covered too. loop() looks like a gap: StorageLoop reads inner_storage directly and never calls the hook, so loop(db, iceberg_table) probably keeps a stale snapshot. Please check it and fix it here if it is stale.

  2. Glue/Hive catalogs (the last bot comment): their tables have no UUID and the catalog builds a new storage object on each lookup, so the read refreshes again and a schema change committed between the inference and the read is still possible. That needs a concurrent change inside one query, and it is better than the always-stale read on master, so I would not add another identity rule for it. Please document it in the InferredSourceMetadata comment instead.

  3. Don't forget the loop function,

groeneai and others added 2 commits October 17, 2026 20:09
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
  1. loop: the rows were already fresh. For a table in the catalog, LoopSource::initLoop runs SELECT ... FROM db.t through the analyzer on every pass (ReadFromLoopStep.cpp:117), so the direct inner_storage->read is reached only after the table has left the catalog. The columns were stale, though: TableFunctionLoop read them from the in-memory metadata without the hook. After an external RENAME COLUMN k TO v, DESCRIBE loop(db, t) still showed k, and SELECT v FROM loop(db, t) failed with UNKNOWN_IDENTIFIER until another query refreshed the table, on master and on this PR.

    Fixed in fc3b52a: getActualTableStructure and executeImpl call the hook first, which adds one refresh per loop query. An Alias whose target was dropped is skipped, so loop over it still reports no columns (04945). 05366 has one line per call, and each line fails without its call.

  2. Glue/Hive: documented in the InferredSourceMetadata comment, with no new identity rule.

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 20, 2026
Merged via the queue into ClickHouse:master with commit 8bbee3d Oct 20, 2026
178 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 20, 2026
nikitamikhaylov pushed a commit that referenced this pull request Nov 11, 2026
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]>
nikitamikhaylov pushed a commit that referenced this pull request Nov 11, 2026
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]>
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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants