Skip to content

Iceberg: invalidate metadata cache on ALTER - #104419

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-stale-metadata-cache-104295
May 14, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-stale-metadata-cache-104295

Conversation

@groeneai

@groeneai groeneai commented May 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #104295.

Iceberg::alter writes a new metadata file but never invalidated the metadata files cache. With iceberg_metadata_staleness_ms non-zero, the cache kept serving the pre-ALTER schema for the staleness window. The follow-up INSERT then ran with two inconsistent views of the table:

  • IcebergStorageSink always reads fresh metadata (force=true), so it sees the post-ALTER schema (one column).
  • The upstream INSERT pipeline reads through the cached storage metadata, so it produces chunks shaped by the pre-ALTER schema (two columns).

DataFileStatistics::getColumnSizes iterates column_sizes.size() (set from the chunk, two entries) and indexes field_ids (set from the sink's current_schema, one entry), causing an out-of-bounds vector access at DataFileStatistics.cpp:68 and aborting the server.

The fix mirrors the cache invalidation already present in IcebergStorageSink::initializeMetadata: after Iceberg::alter successfully writes a new metadata file, drop the table's entries from metadata_cache so subsequent operations re-read the fresh schema.

Reproducer (from the issue, plus an iceberg_metadata_log config entry to surface the staleness path):

CREATE TABLE t0 (c0 Int, c1 Int) ENGINE = IcebergLocal('...');
INSERT INTO TABLE t0 (c1, c0) VALUES (1, 1);
SET iceberg_metadata_staleness_ms = 60000;
ALTER TABLE t0 DROP COLUMN c0;
INSERT INTO TABLE t0 (c1) SELECT 2;  -- aborted before the fix

Stack trace from the abort (matches the issue):

DataFileStatistics::getColumnSizes() const   @ DataFileStatistics.cpp:68
generateManifestFile(...)                    @ IcebergWrites.cpp:357
IcebergStorageSink::initializeMetadata()     @ IcebergWrites.cpp:999
IcebergStorageSink::finalizeBuffers()        @ IcebergWrites.cpp:857

Validated locally with the debug build:

  • Without the fix: 100% reproducible abort with the stack above.
  • With the fix: 10/10 deterministic passes of the new regression test, plus the existing iceberg ALTER tests (04033, 04042, 04043, 04061) keep passing.

Added a stateless regression test (04214_iceberg_alter_drop_column_stale_metadata_cache_104295) that runs the exact reproducer.

A few related write paths (Iceberg::mutate::writeMetadataFiles, Iceberg::Compaction::writeMetadataFiles) also write new metadata files without invalidating the cache. Those don't change schema, so they don't trigger the column-count mismatch path, but they could still leave stale snapshot/manifest information cached. Left as a follow-up to keep this PR focused on the crash fix.

Session: cron:clickhouse-ci-task-worker:20260508-191500

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):

Fix a server abort in IcebergLocal/IcebergS3 writes when ALTER TABLE ... DROP COLUMN is followed by an INSERT with iceberg_metadata_staleness_ms greater than zero. ALTER now invalidates the local Iceberg metadata files cache so subsequent reads and writes see the new schema.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.642

Closes ClickHouse#104295.

`Iceberg::alter` writes a new metadata file but never invalidated the
metadata files cache. With `iceberg_metadata_staleness_ms` non-zero, the
cache kept serving the pre-`ALTER` schema for the staleness window. The
follow-up `INSERT` then ran with two inconsistent views of the table:

  - `IcebergStorageSink` always reads fresh metadata (`force=true`), so
    it sees the post-`ALTER` schema (one column).
  - The upstream `INSERT` pipeline reads through the cached storage
    metadata, so it produces chunks shaped by the pre-`ALTER` schema
    (two columns).

`DataFileStatistics::getColumnSizes` iterates `column_sizes.size()` (set
from the chunk, two entries) and indexes `field_ids` (set from the
sink's `current_schema`, one entry), causing an out-of-bounds vector
access at `DataFileStatistics.cpp:68` and aborting the server.

The fix mirrors the cache invalidation already present in
`IcebergStorageSink::initializeMetadata`: after `Iceberg::alter`
successfully writes a new metadata file, drop the table's entries from
`metadata_cache` so subsequent operations re-read the fresh schema.

Reproducer (from the issue, plus an entry in
`config.d/iceberg_metadata_log.xml` to surface the staleness path):

  CREATE TABLE t0 (c0 Int, c1 Int) ENGINE = IcebergLocal('...');
  INSERT INTO TABLE t0 (c1, c0) VALUES (1, 1);
  SET iceberg_metadata_staleness_ms = 60000;
  ALTER TABLE t0 DROP COLUMN c0;
  INSERT INTO TABLE t0 (c1) SELECT 2;  -- aborted before the fix

Added a stateless regression test
(`04214_iceberg_alter_drop_column_stale_metadata_cache_104295`) that
runs the exact reproducer, verifies the second `INSERT` succeeds, and
checks the resulting rows.
@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4):

# Check Result
a Deterministic repro? Yes — issue's exact 5-statement reproducer aborts the debug server 100% of the time before the fix (with iceberg_metadata_log enabled and iceberg_metadata_staleness_ms = 60000). Without iceberg_metadata_staleness_ms the same sequence completes successfully — the bug is gated on the staleness cache.
b Root cause explained? Yes. IcebergStorageSink constructor reads metadata with force_fetch_latest_metadata=true, so it always sees the post-ALTER schema and constructs DataFileStatistics with field_ids.size() == post_alter_field_count. The upstream INSERT pipeline reads the storage-level snapshot, which is served from the staleness cache and still reflects the pre-ALTER schema. The chunks reaching the sink therefore carry the pre-ALTER column count, and DataFileStatistics::update resizes column_sizes to that larger count. getColumnSizes then indexes field_ids[column_sizes.size() - 1], which is out of bounds. The reason the cache stays stale is that Iceberg::alter writes a new metadata file but never calls metadata_cache->remove(...), while every other write path that mutates table metadata (e.g. IcebergStorageSink::initializeMetadata lines 1088-1096) does invalidate the cache.
c Fix matches root cause? Yes — invalidates the metadata cache after ALTER writes a new metadata file, mirroring the existing invalidation in IcebergStorageSink::initializeMetadata. No defensive guard or symptom-masking.
d Test intent preserved? / New tests added? New stateless test 04214_iceberg_alter_drop_column_stale_metadata_cache_104295 runs the issue's exact reproducer end-to-end, exercises the ALTER DROP COLUMN + INSERT path with iceberg_metadata_staleness_ms = 60000, and asserts the resulting two rows.
e Demonstrated in both directions? Yes. Without the fix: 100% reproducible abort with the stack DataFileStatistics::getColumnSizes → generateManifestFile → IcebergStorageSink::initializeMetadata → finalizeBuffers. With the fix: 10/10 deterministic passes of the new test, and the existing iceberg ALTER tests (04033, 04042, 04043, 04061) continue to pass.
f Fix is general, not narrow? Yes for the crash class. Iceberg::mutate::writeMetadataFiles and Iceberg::Compaction::writeMetadataFiles are the only other paths in DataLakes/Iceberg that write new metadata files without invalidating the cache. Both are mutations / file rearrangement that don't change the schema, so they don't trigger the column-count mismatch path that aborts the server. They can still leave stale snapshot/manifest data in the cache, but I'm leaving that as a focused follow-up to keep this PR isolated to the crash fix.

Session: cron:clickhouse-ci-task-worker:20260508-191500

@groeneai

groeneai commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @Michicosun @scanhex12 @kssenii — could you review? Iceberg manager + comp-datalake experts. Also cc @PedroTadim per the directive on #104295.

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

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c2f8daf]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) FAIL
02346_text_index_queries FAIL cidb, issue ISSUE CREATED
02801_backup_native_copy FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

The PR fixes stale Iceberg metadata cache state after ALTER by invalidating the table-level metadata cache once Iceberg::alter successfully writes a new metadata file, and it adds a focused regression test that reproduces the original failure mode via clickhouse local. I reviewed the current diff and all prior discussion threads; the previously raised retry-loop correctness issue is fixed in the current head, and I did not find new unresolved contract, correctness, or safety issues.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 8, 2026
@kssenii kssenii self-assigned this May 11, 2026
if (persistent_table_components.metadata_cache)
{
persistent_table_components.metadata_cache->remove(persistent_table_components.table_path);
if (persistent_table_components.table_uuid)

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.

Suggested change
if (persistent_table_components.table_uuid)
if (persistent_table_components.table_uuid.has_value())

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.

Done — applied in fix-up commit 0c911724100. Switched to has_value().

Comment on lines +776 to +780
if (persistent_table_components.metadata_cache)
{
persistent_table_components.metadata_cache->remove(persistent_table_components.table_path);
if (persistent_table_components.table_uuid)
persistent_table_components.metadata_cache->remove(*persistent_table_components.table_uuid);

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.

I see the same code in IcebergWrites.cpp::1088-1095, can we unify it into a common function?

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.

Done — applied in fix-up commit 0c911724100. Added PersistentTableComponents::invalidateMetadataCache (inline in PersistentTableComponents.h) and routed both Iceberg::alter (Mutations.cpp) and IcebergStorageSink::initializeMetadata (IcebergWrites.cpp) through it. Pure refactor — observable behavior is unchanged.

Diff: +25/-20 across 3 files (PersistentTableComponents.h +17, Mutations.cpp -8, IcebergWrites.cpp -3).

Verification: regression test 04214_iceberg_alter_drop_column_stale_metadata_cache_104295 passes 10/10 with full randomization and 3/3 without.

…ents

Address @kssenii's review feedback on PR ClickHouse#104419:

  1. Use `has_value()` for the `table_uuid` `optional` check.
  2. Unify the duplicated metadata-cache-invalidation block between
     `Iceberg::alter` (`Mutations.cpp`) and `IcebergStorageSink::initializeMetadata`
     (`IcebergWrites.cpp:1088-1095`) into a single helper.

Adds `PersistentTableComponents::invalidateMetadataCache` and routes both call
sites through it. Pure refactor — behavior is unchanged. Regression test
`04214_iceberg_alter_drop_column_stale_metadata_cache_104295` passes 10/10 with
full randomization and 3/3 without.
kssenii and others added 2 commits May 11, 2026 13:01
The test uses a fully randomized table name (`t_${CLICKHOUSE_DATABASE}_${RANDOM}`)
and a `TABLE_PATH` scoped to that same name under `USER_FILES_PATH`, so it
shares no state with other parallel tests. Per `CLAUDE.md`: "do not add no-*
tags unless strictly necessarily." Confirmed locally — runs in the parallel
queue alongside other Iceberg tests without interference.

Addresses inline review feedback from `clickhouse-gh[bot]` and @kssenii on
PR ClickHouse#104419.
@alexey-milovidov

Copy link
Copy Markdown
Member

The FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly failure on this PR is a known flaky test that was fixed in #104418. Could you please update the branch with the latest master to pick up the fix?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov done — merged origin/master (HEAD now b5d1eb1) which includes PR #104418 (55a1c75). CI will re-run; the FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly failure should clear.

Diff vs master is unchanged (5 files, the same set @kssenii approved):

src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp
src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp
src/Storages/ObjectStorage/DataLakes/Iceberg/PersistentTableComponents.h
tests/queries/0_stateless/04214_iceberg_alter_drop_column_stale_metadata_cache_104295.reference
tests/queries/0_stateless/04214_iceberg_alter_drop_column_stale_metadata_cache_104295.sh

Session: cron:clickhouse-ci-task-worker:20260512-174500

`Iceberg::alter` used `while (i++ < MAX_TRANSACTION_RETRIES)` with the
post-increment in the loop condition. Two consequences:

1. On retry exhaustion, `i` becomes `MAX_TRANSACTION_RETRIES + 1`, so the
   subsequent `if (i == MAX_TRANSACTION_RETRIES)` check never fires and
   `alter` silently returns as if the metadata write had succeeded — even
   though every retry actually failed.
2. When the final iteration `i == MAX_TRANSACTION_RETRIES` succeeds, the
   same check incorrectly fires after the loop, raising
   `LIMIT_EXCEEDED` despite a successful write.

Replace the post-increment-in-condition with an explicit `bool succeeded`
flag and `++i` at the end of the loop body. This matches the existing
pattern in `IcebergStorageSink::finalizeBuffers` (`IcebergWrites.cpp`).

Spotted by `clickhouse-gh[bot]` review on PR ClickHouse#104419.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed c8267c5c7e6 addressing clickhouse-gh[bot]'s inline finding on Mutations.cpp.

Bug. Iceberg::alter used while (i++ < MAX_TRANSACTION_RETRIES) with the post-increment in the loop condition. Two consequences (the bot flagged the first, I noticed the second while writing the fix):

  1. On retry exhaustion, i == MAX_TRANSACTION_RETRIES + 1, so the subsequent if (i == MAX_TRANSACTION_RETRIES) check never fires — alter silently returns as if the write had succeeded.
  2. On a successful final iteration where i == MAX_TRANSACTION_RETRIES, the same check fires and raises LIMIT_EXCEEDED despite the write actually succeeding.

Fix. Replaced with an explicit bool succeeded flag and ++i at the end of the body, mirroring IcebergStorageSink::finalizeBuffers in IcebergWrites.cpp. Diff is +7/−2 in one method.

Verification. Existing regression test 04214_iceberg_alter_drop_column_stale_metadata_cache_104295 still passes 10/10 locally; sister tests 04033_iceberg_alter_remove_settings_segfault and 04042_iceberg_alter_modify_column_comment_segfault still pass 2/2.

cc @alesapin (Iceberg manager) — diff vs master is now 6 files; the original 5 @kssenii approved plus this one-method tweak in Mutations.cpp. CI re-running on c8267c5c7e6.

Session: cron:clickhouse-ci-task-worker:20260512-181500

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai what is the AST fuzzer (amd_tsan) failure Logical error: Expected one block from input stream? It seems to be a new bug? If it is not related to this PR, you should look to fix it in another one.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim — investigated; this is unrelated to PR #104419.

Cross-PR data (CIDB, 90-day window) for Logical error: Expected one block from input stream (STID: 4569-3618):

pull_request_number head_ref check_name first_seen last_seen
98856 external-query-result-cache AST fuzzer (amd_debug, targeted) 2026-03-17 2026-03-17
104419 fix-iceberg-stale-metadata-cache-104295 AST fuzzer (amd_tsan) 2026-05-12 2026-05-12

Two hits across 90 days, two unrelated PRs, two different sanitizer variants, 56 days apart. Zero master / release-branch failures in the same window. Rare chronic trunk bug.

Stack trace points squarely at the KILL QUERY interpreter (same line on both hits):

src/Interpreters/InterpreterKillQueryQuery.cpp:453:15: InterpreterKillQueryQuery::getSelectResult
src/Interpreters/InterpreterKillQueryQuery.cpp:255:33: InterpreterKillQueryQuery::execute
src/Interpreters/executeQuery.cpp:1851:40: executeQueryImpl

getSelectResult runs an internal SELECT and asserts that the pipeline produces at most one non-empty block:

PullingPipelineExecutor executor(io.pipeline);
while (res.empty() && executor.pull(res));
while (executor.pull(tmp_block));
if (!tmp_block.empty())
    throw Exception(LOGICAL_ERROR, "Expected one block from input stream");

The 2026-03-17 hit (PR #98856) preserved the fuzzed query: KILL QUERY … ASYNC SETTINGS use_query_cache = true. The 2026-05-12 hit (this PR) is from a fuzzed KILL QUERY in the amd_tsan AST fuzzer (the fuzzer only logs the LOGICAL_ERROR, not the query body for this STID variant). Both are fuzz-only edge cases where the internal SELECT against system.processes / system.mutations / etc. legitimately produces more than one non-empty chunk and the assertion fires.

@alexey-milovidov already touched this exact function in #99881 ("Fix exception in KILL QUERY when columns are const", merged 2026-04-08) — this STID is a residual edge case in the same area, not anything new.

PR #104419 diff vs origin/master (still the 5 files @kssenii approved + the 1-method Mutations.cpp tweak):

src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergWrites.cpp
src/Storages/ObjectStorage/DataLakes/Iceberg/Mutations.cpp
src/Storages/ObjectStorage/DataLakes/Iceberg/PersistentTableComponents.h
tests/queries/0_stateless/04214_iceberg_alter_drop_column_stale_metadata_cache_104295.{sh,reference}

No Interpreters/, no pipeline/executor changes, no system.processes touch. There is no plausible causal link to InterpreterKillQueryQuery::getSelectResult.

Proposal: treat the AST fuzzer (amd_tsan) check on this PR as a flake from this STID and don't gate on it. I'll file a separate follow-up to investigate fixing getSelectResult to tolerate multi-block internal SELECT results (consistent with the post-#99881 trajectory), but it doesn't belong in #104419.

Session: cron:clickhouse-ci-task-worker:20260513-091500

@kssenii

kssenii commented May 13, 2026

Copy link
Copy Markdown
Member

@groeneai, bugfix validation check Bugfix validation (functional tests) (pull_request) failed, meaning that this test, added in this PR, does not reproduce the bug, please check the initial issue's repro again.

The reproducer in `04214_iceberg_alter_drop_column_stale_metadata_cache_104295`
runs the buggy `INSERT` through `${CLICKHOUSE_CLIENT}`, which means the
`SIGABRT` in `DataFileStatistics::getColumnSizes` lands inside the
long-running test server. The functional-tests runner's hung-check then
detects "server is not responding" and terminates the runner before any
test result is written to `test_result.txt`. `FTResultsProcessor` only
treats the exact strings `Server died, terminating all processes` or
`Server does not respond to health check` as `server_died`; the runner's
actual `Stopping tests, terminating all processes...` message is not
matched, so the run falls into the `not success_finish` branch with
status `ERROR` and an empty `test_results` list. The `Bugfix validation`
inversion loop only flips `FAIL` -> `OK` (it iterates `test_result.results`),
so with an empty list `has_failure` stays `false` and the framework
reports `Failed to reproduce the bug` even though the bug did fire and
left a `core.QueryPipelineEx.*` core dump.

Switch the reproducer to `clickhouse local` (multi-query) so the abort
is contained to a single short-lived subprocess. The test runner then
observes a normal non-zero exit code (134) and an empty stdout; the
diff against `.reference` produces a regular `FAIL` for this test, which
`Bugfix validation` then correctly inverts to `OK`.

Verified locally:
- Binary without the fix (`Iceberg::alter` does not invalidate the cache):
  test FAILs with exit 134 and `libc++ Hardening assertion __n < size()`
  in stderr, runner records a normal `FAIL`.
- Binary with the fix (`Iceberg::alter` invalidates the cache): 10/10
  passes (`SELECT c1 FROM t0 ORDER BY c1` returns `1\n2`).

CI report for the failing bugfix-validation run on `c8267c5`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104419&sha=c8267c5c7e69922ec96a5837cc51e5bc710bf9cb&name_0=PR&name_1=Bugfix+validation+%28functional+tests%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

@kssenii thanks for catching this. Pushed c2f8daf0f9c to address the bugfix-validation failure.

Root cause of Failed to reproduce the bug

The bug is reproduced correctly (the master-HEAD binary did SIGABRT in DataFileStatistics::getColumnSizes — there's a core.QueryPipelineEx.* core dump in the job artifacts), but FTResultsProcessor doesn't classify the runner termination as server_died:

SERVER_DIED_SIGN  = "Server died, terminating all processes"
SERVER_DIED_SIGN2 = "Server does not respond to health check"

clickhouse-test's actual messages — Hung check failed: server is not responding and Stopping tests, terminating all processes... — don't match either string, so server_died stays false and we fall through to:

elif not s.success_finish:
    state = Result.Status.ERROR
    info = "The test runner was terminated unexpectedly"

The Bugfix validation inversion only flips FAIL → OK for entries in test_result.results; with an empty list (no test ever got to write a result line before the runner was killed), has_failure stays false and the framework reports Failed to reproduce the bug.

Fix

Run the reproducer in clickhouse local (multi-query) instead of ${CLICKHOUSE_CLIENT}. The abort is now contained to a single short-lived subprocess — the long-running test server stays up, the runner observes a normal non-zero exit (134) plus an empty stdout, and the diff against .reference produces a regular FAIL for this test, which Bugfix validation then correctly inverts to OK.

Verified locally:

  • Binary without the fix in Iceberg::alter: test [ FAIL ] 4.80 sec., Reason: return code: 134, libc++ Hardening assertion __n < size() failed: vector[] index out of bounds in stderr — runner records a normal FAIL, perfect for bugfix-validation inversion.
  • Binary with the fix (this PR HEAD c2f8daf): [ OK ] 0.69 sec., 10/10 deterministic passes (SELECT c1 FROM t0 ORDER BY c1 returns 1\n2).

Session: cron:clickhouse-ci-task-worker:20260513-224500

@clickhouse-gh

clickhouse-gh Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.20% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 81.82% (18/22) · Uncovered code

Full report · Diff report

@PedroTadim
PedroTadim added this pull request to the merge queue May 14, 2026
@PedroTadim

Copy link
Copy Markdown
Member

The 02801_backup_native_copy test I fixed yesterday. Created an issue for 02346_text_index_queries one

Merged via the queue into ClickHouse:master with commit 567fd39 May 14, 2026
165 of 167 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 14, 2026
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 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.

Iceberg metadata out-of-bounds

5 participants