Skip to content

Iceberg: propagate table UUID from REST catalog to avoid metadata cac… - #99981

Open
bacek wants to merge 110 commits into
ClickHouse:masterfrom
bacek:bacek/iceberg-metadata-cache
Open

bacek wants to merge 110 commits into
ClickHouse:masterfrom
bacek:bacek/iceberg-metadata-cache

Conversation

@bacek

@bacek bacek commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

REST catalog inline responses already contain the table UUID and metadata location. Propagate the UUID through DataLakeSpecificProperties ->
StorageObjectStorageConfiguration.catalog_uuid_hint -> initializePersistentTableComponents so the metadata cache is checked before fetching
metadata.json from network storage.

Performance mechanism

Before: On first table initialization, getMetadataJSONObject is called without a known UUID. The cache probe is skipped (table_uuid == nullopt), so metadata.json is always fetched from remote storage as a cold read. Even if the same table is initialized again later, the cache
was never populated on the first pass.

After: The REST catalog provides the table UUID upfront via catalog_uuid_hint. getMetadataJSONObject probes the cache with uuid:path
key before doing any remote I/O. If the metadata was previously cached (e.g., by a prior query that retroactively populated it), the cold read
is eliminated entirely. If not, the cold read still happens but the result is cached with the correct UUID for future lookups.

Impact: Deterministic reduction in remote metadata.json fetches for REST catalog tables. Each avoided fetch saves one round-trip to
S3/GCS/ABFS plus deserialization overhead.

Changelog category (leave one):

  • Performance Improvement

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

Improve Iceberg catalog metadata caching by using table UUID from catalog responses to warm the metadata cache, avoiding a redundant remote metadata.json read on table initialization.

Documentation entry for user-facing changes

Improve Iceberg catalog metadata caching.


Note

Medium Risk
Medium risk because it changes Iceberg metadata cache key composition and the metadata-loading path to use a new UUID hint, which could affect cache hit rates or correctness if UUIDs/paths are inconsistent.

Overview
Improves Iceberg REST catalog metadata caching by propagating the table UUID from REST inline responses through DataLakeSpecificProperties into StorageObjectStorageConfiguration as catalog_uuid_hint, so the first metadata fetch can probe the metadata cache before doing extra remote IO.

Updates metadata loading to accept an optional known UUID, capture raw metadata JSON for reuse, and retroactively populate the cache once the real UUID is discovered. Also fixes potential cache-key collisions by changing IcebergMetadataFilesCache::getKey to use a uuid:path delimiter, and adds gtest coverage for key uniqueness and cache hit/miss behavior.

Reviewed by Cursor Bugbot for commit 2e7400b. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@bacek

bacek commented Mar 19, 2026

Copy link
Copy Markdown
Contributor Author

@divanik @kssenii @alesapin fyi

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aadcaad]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 4/6) FAIL
test_keeper_4lw_reconfiguration/test.py::test_reconfig_option2 FAIL cidb
test_keeper_4lw_reconfiguration/test.py::test_precondition_failure FAIL cidb

AI Review

Summary

This PR materially improves Iceberg metadata handling: it namespaces cache keys by backend identity, validates REST catalog_uuid_hint hits against the table location, fixes several stale-cache invalidation paths, and adds focused cache/codec regressions. I still see two write-side gaps around metadata compression on reused IcebergMetadata objects, so I would not merge it yet.

Findings

⚠️ Majors

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:200, 746-754, 1430-1438, 1466-1473] Both OPTIMIZE TABLE and OPTIMIZE TABLE ... MANIFEST still seed their FileNamesGenerator from PersistentTableComponents::metadata_compression_method, i.e. the codec captured when the table object was first opened. If another writer switches the table from vN.metadata.json to vN.gz.metadata.json between queries, compaction now reads the current file with resolved_compression_method but still commits the next metadata file back with the stale codec. Mutations.cpp:706-709 and ExpireSnapshotsExecute.cpp:683-701 already retarget their generators to the freshly resolved codec; compaction needs the same update.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp:1328-1345] The metadata-conflict retry path refreshes compression_method from the current latest metadata file, but it never calls filename_generator.setCompressionMethod(compression_method) before returning to the outer retry loop. A concurrent writer that changes metadata compression can therefore make a retried INSERT/append commit v{N+1} with the stale open-time codec even though the retry is now based on a differently compressed current metadata file.
Tests
  • ⚠️ Add a focused OPTIMIZE regression that reuses one IcebergMetadata object across an external metadata-codec switch and verifies the next metadata file keeps the current codec for both full and manifest-only compaction.
  • ⚠️ Add a write-conflict retry test where a concurrent writer changes metadata compression between attempts; the retried INSERT should reopen the new metadata file and emit the next v{N+1} file with the same codec.
Final Verdict

Not ready yet. The cache-key and invalidation work is materially better, but the remaining stale-codec write paths mean reused Iceberg objects can still commit metadata with an out-of-date compression format after concurrent changes.

LLVM Coverage Report

Measured on commit aadcaad.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 721/756 (95.37%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 19, 2026
@bacek
bacek force-pushed the bacek/iceberg-metadata-cache branch from a4cecc5 to 848958a Compare March 19, 2026 09:51
@bacek
bacek force-pushed the bacek/iceberg-metadata-cache branch 2 times, most recently from cce3fb9 to 58f0515 Compare March 19, 2026 10:38
…he misses

REST catalog inline responses already contain the table UUID and metadata
location. Propagate the UUID through DataLakeSpecificProperties ->
iceberg_metadata_table_uuid setting -> initializePersistentTableComponents
so the metadata cache is checked before fetching metadata.json from
network storage.

On first fetch the UUID is unknown, so retroactively populate the cache
after reading the file so subsequent queries get a cache hit.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@bacek
bacek force-pushed the bacek/iceberg-metadata-cache branch from 57ea780 to 98868be Compare May 8, 2026 09:50
The cache key was a simple concatenation of table_uuid + data_path,
which could produce collisions: ("a", "bc") and ("ab", "c") both
yielded "abc". Use ":" as the separator to make the key composition
collision-free.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Avoids an unconditional full copy of `metadata_json_str` into
`raw_json_out` on a hot metadata-read path. Use `std::move` and
parse from `raw_json_out`.
@bacek

bacek commented May 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov can we land it?

Setting `iceberg_metadata_table_uuid` marks it as changed, which triggers
the O(N) UUID-based metadata-file scan in
`getLatestOrExplicitMetadataFileAndVersion` (even when
`iceberg_metadata_file_path` is also set, because
`initializePersistentTableComponents` passes
`ignore_explicit_metadata_file_path=true`).

Instead, store the catalog-provided UUID in a non-setting field
`catalog_uuid_hint` on `StorageObjectStorageConfiguration`.
`initializePersistentTableComponents` reads it to populate `known_uuid`
for cache key composition without touching the setting, so
`iceberg_metadata_table_uuid.changed` stays false and the default O(1)
file-selection path is taken.

The `iceberg_metadata_table_uuid` setting path (O(N)) is preserved for
the case when a user explicitly specifies a UUID for file selection.
…xists

When `known_uuid` matches the parsed `table_uuid`, `getMetadataJSONObject`
already populated the cache under that key. The unconditional
`getOrSetTableMetadata` call was returning a full copy of the cached JSON
string on every initialization and discarding it. Condition the retroactive
insert on `known_uuid != table_uuid` to avoid the wasted copy.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
bacek and others added 4 commits May 15, 2026 09:39
`IcebergMetadataFilesCache` is only defined when `USE_AVRO` is set.
The test file was compiled unconditionally, causing build failures in
configurations without Avro support.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@bacek

bacek commented May 24, 2026

Copy link
Copy Markdown
Contributor Author

CI failure in Finish Workflow is due to CI infrastructure issue (play.clickhouse.com connection refused). All actual tests passed. @groeneai, please investigate the CI DB insertion failure in check_report_messages.py and provide a fix in a separate PR if needed.

@groeneai

Copy link
Copy Markdown
Collaborator

Hi @bacek, confirmed this is the chronic Post Hooks / Finish Workflow pseudo-test failure. play.clickhouse.com connection refused is a server-side CIDB outage, not anything wrong with your PR or with check_report_messages.py.

Canonical signature on commit 2e7400b8: test_name='Post Hooks', status FAIL, duration ~1.7s, empty test_context_raw. 30d CIDB stats for this exact failure: 582 distinct PRs affected, 1219 total hits, 0 master hits. Last 7d: 369 PRs, 709 hits. Tracked on our side as a P2 monitoring umbrella since 2026-04-25.

On the script: ci/jobs/scripts/workflow_hooks/check_report_messages.py itself does not touch CIDB. It only reads workflow-level errors/warnings from Result.from_fs(info.workflow_name) and exits 1 if any are present. The actual insert lives in ci/praktika/cidb.py:insert_rows (3 retries, no exponential backoff). When play.clickhouse.com is unreachable, insert_rows raises a RuntimeError, the upstream post-hook records a workflow warning, and check_report_messages.py then propagates it as Post Hooks: FAIL.

No fix PR from my side for this run, since the failure is server-side infrastructure that clears itself once CIDB ingestion is healthy. A Finish Workflow re-run is the standard resolution and typically goes green. A broader hardening of insert_rows (longer backoff, distinguishing connection-refused from real failures) would be a praktika framework discussion rather than a per-PR fix.

Test that verifies the UUID-based cache probe mechanism through the REST
catalog path using pyiceberg. Exercises the ProfileEvents counters
(IcebergMetadataFilesCacheHits, IcebergMetadataFilesCacheMisses) via
system.query_log to prove:
- First query misses (reads from remote storage)
- Second query hits (reads from cache)
- After SYSTEM CLEAR ICEBERG METADATA CACHE, miss again
- With cache disabled, neither hits nor misses

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
bacek added 3 commits August 31, 2026 00:57
Two Iceberg table roots can carry the same `table-uuid`: copying a table's
directory copies its metadata verbatim. On the ordinary (non-explicit-UUID)
path `getOrSetLatestMetadataVersion` referenced its cell by `table-uuid`
whenever one was available, so a query on the clone cached its own `metadata/`
selection under the shared UUID and a later query on the original reused it,
reading a metadata file that lives under the other root -- the data files it
names do not exist there.

The same reference also let a reused `IcebergMetadata` object serve the
open-time `PersistentTableComponents::table_uuid`, which is never refreshed,
after a same-path table replacement.

Which file under `metadata/` is the latest one is a property of the table root,
not of the UUID recorded inside it, and on this path the loader ignores the UUID
entirely, so the UUID-side reference was pure staleness risk. Key the cell by
`(data_source_description, table_path)` alone: `getLatestVersionKey` loses its
`is_uuid` keyspace tag, `getOrSetLatestMetadataVersion` loses its `table_uuid`
parameter, and `PersistentTableComponents::invalidateMetadataCache` removes the
single key. The explicit `iceberg_metadata_table_uuid` way still bypasses this
cache altogether.

Addresses review feedback on
ClickHouse#99981 (comment)
…adata-cache

# Conflicts:
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp
`compactIcebergTable` seeds the compaction from the table's *metadata* codec,
and the full-table rewrite path mishandled it twice.

`writeDataFiles` passed that codec as the compression hint for reading every
data file. `chooseCompressionMethod` only inspects the path when the hint is
empty or `auto`, so a non-empty `gzip` hint wins outright and a plain
`.parquet` data file is read as if it were `gzip`:

    Code: 271. DB::Exception: Not a gzip stream: While reading from:
    .../data/data-53be8355-....parquet. (CANNOT_DECOMPRESS)

leaving a zero-length compacted data file behind. The codec describes the
metadata JSON and says nothing about a data file, so the hint is now `auto` and
the data file's own extension decides. The parameter has no other use and is
gone.

`writeMetadataFiles` then wrote the new `metadata.json` with a raw
`writeObject`, while `generated_metadata_info.path` already carries the codec
suffix -- plain JSON under a `vN.gz.metadata.json` name, which the next read
fails to decompress once `getCompressionMethodFromMetadataFile` infers `gzip`
from the suffix. It now goes through `Iceberg::writeMessageToFile` with
`generated_metadata_info.compression_method`, like every other metadata write.

`04815_iceberg_optimize_position_delete_row_count_113745` covers this path with
the default uncompressed metadata, where the raw write happens to be correct.
The new test drives the same positional-delete-driven compaction on a `gzip`
metadata table.

Addresses review feedback on
ClickHouse#99981 (comment)
@bacek

bacek commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99981&sha=be3358765af7ee9be59783d0875ac8f160e2cbd8 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) — the only "failed test" is the pseudo-test Timeout; no real test failed:

947 passed, 26 skipped, 571 warnings in 7213.39s (2:00:13)
!!!!!!! xdist.dsession.Interrupted: session-timeout: 7200.0 sec exceeded !!!!!!!

The shard reached 99% and was interrupted with the last few tests still queued — this is the shard budget, not a hang. This looks covered by the already-open #116591 (CI: fix integration test session timeouts (shard balance and batch count)); please confirm.

Evidence it is unrelated to this pull request: all four Iceberg tests in this shard ran and passed well before the interruption —

  • test_storage_iceberg_with_spark_cache/test_metadata_cache.py::test_metadata_cache[s3] PASSED
  • test_storage_iceberg_with_spark_cache/test_metadata_cache.py::test_metadata_cache[azure] PASSED
  • test_storage_iceberg_with_spark_cache/test_filesystem_cache.py::test_filesystem_cache[s3] PASSED
  • test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads PASSED

and the tests running when the budget expired (test_delayed_remote_source, test_relative_filepath, test_thread_pool_queue_size) touch nothing this pull request changes.

@bacek

bacek commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

🕵 Upgrade check (amd_release) fails on Cannot start clickhouse-server, and it is not caused by this pull request.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99981&sha=be3358765af7ee9be59783d0875ac8f160e2cbd8&name_0=PR&name_1=Upgrade%20check%20(amd_release)

The previous-release server refuses to start against the current test configuration:

Code: 137. DB::Exception: Unknown elements 'enable_silk_runtime', 'silk' found in config /etc/clickhouse-server/config.xml.
If it is a new option, it should be added to ServerSettings or to the known config sections. (UNKNOWN_ELEMENT_IN_CONFIG)

enable_silk_runtime and the silk config section came from the merged #112667 and its follow-up rename; the older binary the upgrade check installs does not know either name, so it aborts before any test runs. This pull request touches no server configuration and no silk code — every commit here is confined to the Iceberg metadata cache and its tests.

The fix is already open: #117172 (Version-gate the silk test config so the upgrade check can start the previous release). Once it merges into master I will merge master here so the check goes green.

@groeneai, no action needed beyond landing that pull request.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, and no, #116591 does not cover this one.

Your triage matches CIDB: at be3358765af7, 5/6 is the only red, its single FAIL row is the pseudo-test Timeout at 0 ms, and the other five shards are green with zero failing rows. 947 passed, 26 skipped plus the xdist.dsession.Interrupted: session-timeout marker is the graceful-overrun shape, so nothing hung and nothing failed. Unrelated to your changes.

Why #116591 does not cover it: its batch-count change is integration_test_asan_master_jobs 4 -> 6, and the comment it adds to that block says so directly, "Despite the name, only release_branches.py uses these". The job you hit comes from integration_test_jobs_required, which is already at 6 and is untouched by that PR. The two are distinguishable from the check name alone: the release-branch set is named amd_asan_ubsan, db disk, N/4, yours carries old analyzer. The other half of #116591 regenerates the suite weight table, which is the shard-balance fix that already merged as #115963 and is already in your tree (HAVING dur > 1000, 1079 rows at be3358765af7).

What is left here is capacity, not balance. get_optimal_test_batch is a weight equaliser and it succeeds: replayed, the six shards sit within 1.3% of each other, so no input-side lever lowers the worst shard's wall clock (marking the concentrated suites sequential measured -16 s, and repricing at p90 still leaves 6 batches at 92.9% of budget). Only a 7th batch or a larger session budget does, and each carries a cost I should not pick on my own: a 7th batch adds a runner to every PR's required job set and renames every shard, resetting CIDB history keyed on check_name, while a larger budget accepts the imbalance permanently. I put both, with the measurements, to @ alexey-milovidov at #115963 (comment) and that is still open, so I am not opening a PR off this ping while it is.

@bacek

bacek commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

🕵 Thanks — correcting my record: #116591 was the wrong link. Its batch-count change touches integration_test_asan_master_jobs (release branches, the N/4 names), not integration_test_jobs_required, which is where the old analyzer, 5/6 job I hit comes from and which is already at 6. So this timeout is capacity, tracked on your open question at #115963 (comment), and I will not treat it as blocking here.

Remaining red on this pull request is therefore two failures, both external to it:

@bacek

bacek commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

🕵 Stress test (amd_msan) is red on a known master-wide issue, not on anything this pull request changes.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99981&sha=be3358765af7ee9be59783d0875ac8f160e2cbd8&name_0=PR&name_1=Stress%20test%20(amd_msan)

Logical error: 'Not-ready Set is passed as the second argument for function 'globalNotIn''
src/Functions/in.cpp:128: DB::(anonymous namespace)::FunctionIn::executeImpl

CI itself labels the row with the open #107619 (Logical error: Not-ready Set is passed as the second argument for function ..., open since 2026-06-16, STID 0250-41a5).

The exception is raised in FunctionIn::executeImpl while building the pipeline in InterpreterSelectQueryAnalyzer, on the globalNotIn set-readiness path. This pull request touches only the Iceberg metadata cache and its tests — no function execution, no set resolution, no analyzer code — so it cannot reach that assertion.

Remaining red here is three failures, all external: this one, the 5/6 integration shard capacity overrun (per @groeneai above, tracked at #115963 (comment)), and Upgrade check (amd_release) awaiting #117172.

/// files, which may differ from the codec of the metadata file being read here.
Poco::JSON::Object::Ptr initial_metadata_object
= getMetadataJSONObject(metadata_file_path, object_storage, persistent_table_components.metadata_cache, context, log, compression_method, persistent_table_components.table_uuid);
= getMetadataJSONObject(metadata_file_path, object_storage, effective_cache, context, log, resolved_compression_method, persistent_table_components.table_uuid, persistent_table_components.table_identity);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ This only fixes the read side of the external-codec-switch case. getPlan still constructs plan.generator from the compression_method argument before this lookup, and compactIcebergTable still passes persistent_table_components.metadata_compression_method there (src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1466-1473) — the codec captured when this IcebergMetadata object was first initialized.

If another writer switches the table from e.g. vN.metadata.json to vN.gz.metadata.json, a reused object will now read the current file correctly here, but writeMetadataFiles later emits the next metadata path from that stale generator (src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1048) and commits the compaction back with the old codec. Mutations.cpp:690-693 and ExpireSnapshotsExecute.cpp:700-701 already retarget their FileNamesGenerator to the freshly selected compression_method; compaction needs the same update. OPTIMIZE TABLE ... MANIFEST has the same problem because it still passes persistent_table_components.metadata_compression_method into writeConsolidatedManifestFile at src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1430-1438.

@abashkeev abashkeev added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 3, 2026
…adata-cache

# Conflicts:
#	src/Databases/DataLake/ICatalog.h
#	src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergMetadata.cpp
#	src/Storages/ObjectStorage/DataLakes/Iceberg/PersistentTableComponents.h
#	src/Storages/ObjectStorage/S3/Configuration.cpp
context,
getLogger("IcebergWrites").get(),
persistent_table_components.table_uuid,
persistent_table_components.table_identity,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ This retry block refreshes the current compression_method, but it never retargets filename_generator to that codec before handing control back to the outer retry loop.

If another writer changes the table from, say, vN.metadata.json to vN.gz.metadata.json between attempts, getLatestMetadataFileAndVersionWithCatalog correctly reopens the new file here, but the next initializeMetadata() call still generates v{N+1} from the stale codec captured when the sink was constructed. Mutations.cpp:706-709 and ExpireSnapshotsExecute.cpp:683-701 already call setCompressionMethod(compression_method) after the same refetch; this write path is the remaining sibling that still violates that invariant.

Please call filename_generator.setCompressionMethod(compression_method) alongside setVersion(last_version + 1) in this retry path, and add a focused conflict/retry regression that switches metadata compression between attempts.

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

This branch has not been deployed

No deployments
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-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants