Skip to content

Do not root Iceberg orphan cleanup at a stale version hint - #114324

Merged
murphy-4o merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-orphan-cleanup-stale-version-hint-114194
Sep 15, 2026
Merged

murphy-4o merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-orphan-cleanup-stale-version-hint-114194

Conversation

@groeneai

@groeneai groeneai commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

Do not root Iceberg orphan cleanup at a stale version hint

Closes: #114194
Related: #114108

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 permanent data loss in ALTER TABLE ... EXECUTE remove_orphan_files on Iceberg tables with iceberg_use_version_hint = 1. When metadata/version-hint.text named an older version than the newest committed metadata file, every object of the newer committed snapshot, including its data files, was deleted as an orphan. Reachability is now computed from the authoritative current metadata, and a metadata listing this command cannot order unambiguously is refused instead of resolved by listing order.

Description

getLatestOrExplicitMetadataFileAndVersion suppressed only the iceberg_metadata_file_path branch, not iceberg_use_version_hint. collectReachableFiles passes that flag precisely to get the real current state, so cleanup rooted at whatever the hint named. A lagging hint is ordinary: it is advanced only if it already exists.

The parameter becomes ignore_metadata_pointer_overrides and suppresses both; all seven true callers resolve a commit target or a cleanup root. A catalog's pointer is the committed state, so it is threaded into executeRemoveOrphanFiles, and OPTIMIZE ... MANIFEST moves onto that resolver.

But the listing is authoritative only for the scheme the table commits through, found by @ murphy-4o and reproduced here: rooting at the highest version deleted a committed snapshot from the other side. A higher vN.metadata.json must be committed, since aiming at an existing N collides; a uuid-named file need not be. Cleanup therefore drops the version a pointer names, keeps the scheme its hint spells, and requires the selected file to be the one the pointer names. What cannot be ordered is refused: both schemes with nothing declaring one, two spellings of one version, two versions sharing one last-updated-ms, a selection the pointer contradicts. New behaviour for one shape: a catalog-less table holding both schemes must name its current vN.metadata.json in metadata/version-hint.text or drop the other scheme's files, since iceberg_metadata_file_path is a read override no commit advances.

Residuals, all pre-existing: uuid-scheme numbers are still ranked within that scheme; cleanup still scans the whole table prefix, so a table sharing a metadata directory can lose files; OPTIMIZE's compaction reaches the same stale root. Since @ murphy-4o's commit here, INSERT resolves its write root through this resolver, so these refusals reach it too.

Integration coverage: stale hint, foreign-scheme root, each refusal shape, INSERT, catalog root.


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

Version info

  • Merged into: 26.9.1.1503 (included in 26.9 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (adjudicated)

An independent cold review plus a second-model gate reviewed this before it was opened. Only
the items worth a reviewer's judgement:

Known limits, both in the description. With no catalog the root comes from a listing, which
is ambiguous two ways. A tie at the chosen version is now refused outright. A same-version file
published during the scan can still be re-selected by listing order, so the path recheck
compares equal and the deletion proceeds. That is narrower than before (the recheck used to
compare version numbers, so every same-number mid-scan commit passed) but not closed; closing
it needs a publication boundary rather than another check.

The guard keys on the version number, and the resolver does not always rank by version. With
iceberg_recent_metadata_file_by_last_updated_ms_field = 1 the root is chosen by
last-updated-ms, so two files at different versions can tie and the guard will not see it.
Symmetrically, with iceberg_metadata_table_uuid in a directory shared by two tables the guard
counts the other table's file and can refuse where the resolver was never ambiguous. Both
pre-date this change on that policy (a table with no pointer setting already resolved that way),
and the right fix is for the resolver to report its own ambiguity rather than for
remove_orphan_files to re-derive the ranking. Not attempted here.

One test residual. test_remove_orphan_files_recheck_detects_same_number_pointer_switch
moves the catalog pointer once the scan has resolved its root, but nothing proves the two catalog
calls finish before the recheck; the margin is the manifest-read failpoint's 6.1 s (measured,
identical across 10 runs). Both failure directions are loud rather than silent. Happy to simplify
or drop that case if you would rather not carry it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no fault injection. IcebergLocal table with iceberg_use_version_hint = true, three INSERTs (leaves v4.metadata.json, hint 4), rewrite version-hint.text to 3, then remove_orphan_files(older_than = '<now>'). Pre-fix the newest snapshot's data file and v4.metadata.json are deleted and SELECT returns [1,2]. Also an integration case on local and s3.
b Root cause explained? The suppression parameter covered only the iceberg_metadata_file_path branch, not iceberg_use_version_hint. collectReachableFiles passes it precisely because it wants the authoritative latest, so reachability was rooted at N-1 and every object of committed snapshot N became an orphan. The TOCTOU recheck re-resolved the same hint, comparing N-1 to N-1. An unresolvable hint already fell back to listing; a hint resolving to a valid older version was trusted unconditionally.
c Fix matches root cause? Yes: the reachability ROOT is made authoritative, rather than guarding the deletion site or widening the age window. The parameter becomes ignore_metadata_pointer_overrides and suppresses both pointer branches, falling through to the listing path already default for tables without the setting. catalog is threaded into executeRemoveOrphanFiles so a catalog-backed table resolves the committed pointer instead of a raw listing. No clamp on older_than, no defensive check at the deletion site.
d Test intent preserved / new tests added? Eight new integration cases, no test weakened. Four cover the version-hint carriers (stale-hint cleanup on local and s3, dry_run, and a write under a stale hint in both test_remove_orphan_files.py and test_expire_snapshots.py). Two cover the catalog root (cleanup, and manifest compaction), each planting a well-formed higher-version metadata file that no catalog pointer names so the two resolvers genuinely disagree. One drives a real mid-scan pointer switch between two files parsing to the same version. One asserts the no-catalog ambiguity refusal. Every case carries a control arm, so a binary that simply stopped deleting cannot pass: the cleanup cases require a planted true orphan to still be deleted; the compaction case requires the planted file to still be PRESENT; the refusal case requires the command to work again once the twin is removed. Oracles are file existence plus a data read, never a deleted-COUNT. older_than is pinned to now(), since the default 3-day gate would spare every fresh object.
e Both directions demonstrated? Yes, every case, on Build-ID-verified binaries. Pre-fix, each fails on its intended assertion: cleanup with committed data files missing, dry_run with assert 1 == 0, the write cases with Code: 736 DATALAKE_DATABASE_ERROR and Code: 290 LIMIT_EXCEEDED. Mechanism read from the server log rather than inferred: the hint named v3, v4 was newest, and the writer regenerated v4 101 times, each refused; with the fix one attempt is refused and it commits v5. Dropping the catalog argument in collectReachableFiles deletes all three committed data files. Reverting the compaction resolver roots the rewrite at the planted snapshot and the REST catalog refuses every commit with HTTP 409. Reverting the recheck to the version number lets the deletion proceed while the pointer moves between two v15 files. Reverting only the ambiguity throw reddens the refusal case, which then reports deleted_metadata_files_count 2. Each mutation run carried a positive control that passed in the same run.
f Fix is general across code paths? Enumerated all 9 consumers of the resolver and all 15 removeObject* sites in the Iceberg directory. Fixed: remove_orphan_files, its format_version gate (so the gate and the scan judge one table state), and expire_snapshots (valid input rejected rather than data loss: LIMIT_EXCEEDED with zero files expired pre-fix). The write path too: an INSERT under a lagging hint regenerated an existing version 101 times before failing. Verified safe unchanged: IcebergMetadata::drop (deletes everything by design) and the write/mutation/compaction rollback paths (each deletes only what it just created). Read consumers keep false. OPTIMIZE's data compaction clearOldFiles is a real third carrier where I reproduced loss; handled separately, because getHistory also resolves through the hint and its commit has no publication boundary, so a root change alone would close the reproducer while leaving the race.
g Fix generalizes across inputs? Type wrappers are N/A: a metadata-resolution path, no columns or values. Axes covered: storage backend (local and s3 parametrized, azure shares the path), catalog-backed vs no-catalog, dry_run 0 and 1, a pinned iceberg_metadata_file_path (pre-existing case), an unresolvable hint (already fell back to listing), and a hint equal to the newest version (control). Operation axis: cleanup, dry_run, INSERT and expire_snapshots are each exercised under the same lagging-hint state.
h Backward compatible? Yes. No new setting, no changed default, so no SettingsChangesHistory.cpp entry; no on-disk format change. One deliberate behaviour change worth a reviewer's eye: pinning version-hint.text to an older version on purpose and expecting cleanup to treat the newer files as garbage now retains them. That is the over-retention direction, the right default for a destructive command, and iceberg_metadata_file_path remains the explicit read pin.
i Invariants and contracts preserved? The invariant, in one sentence: a command that deletes files computes liveness from the authoritative current metadata, never from a configured pointer that may name an older version. collectReachableFiles gains two defaulted parameters, so existing callers are unchanged; both of its call sites pass the same catalog, so the scan and its recheck read one source of truth. The renamed parameter's value is unchanged at all five explicit call sites. The recheck compares the resolved PATH rather than the parsed version: equal paths imply equal numbers, so it is strictly stronger. ReachableFilesResult gains a third field appended after the existing two, so no destructuring silently rebinds. No lock, concurrency contract or error path is touched.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @scanhex12, could you review this? remove_orphan_files computed reachability from version-hint.text instead of the newest committed metadata file, so a lagging hint made every object of the newest committed snapshot an orphan, and the TOCTOU recheck re-resolved the same hint so it compared N-1 to N-1.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [07987c8]

Summary: ✅


AI Review

Summary

This PR makes remove_orphan_files and the initial Iceberg write root stop trusting stale pointer state, and it routes catalog-backed cleanup / manifest compaction through the catalog pointer instead of a raw storage listing. The current head looks materially safer than the earlier revisions, but I cannot approve it yet because two correctness-critical branches introduced here are still missing focused regression coverage.

PR Metadata
  • Changelog category should be Critical Bug Fix (crash, data loss, RBAC), not Bug Fix, because the defect being fixed is permanent data loss.
  • Changelog entry is required and the current text is specific enough, but it should use present tense. Exact replacement:
Fixes permanent data loss in `ALTER TABLE ... EXECUTE remove_orphan_files` on Iceberg tables with `iceberg_use_version_hint = 1`. When `metadata/version-hint.text` names an older version than the newest committed metadata file, every object of the newer committed snapshot, including its data files, can be deleted as an orphan. `remove_orphan_files` now computes reachability from the authoritative current metadata and refuses ambiguous metadata listings instead of resolving them by listing order.
Tests
  • ⚠️ [src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp:1384] This resolver call is the whole correctness change for catalog-backed OPTIMIZE TABLE ... MANIFEST, but test_optimize_manifest_with_catalog still exercises only the happy path where the catalog pointer is already the highest metadata file in storage. Please add the focused regression that plants a higher uncommitted metadata file and proves manifest compaction still advances the catalog snapshot without dropping rows; otherwise reverting this line back to the listing resolver would stay green.
  • ⚠️ [src/Storages/ObjectStorage/DataLakes/Iceberg/RemoveOrphanFilesExecute.cpp:282] The path-identity recheck is now the only protection against a concurrent commit that switches the table between two distinct metadata files carrying the same parsed version, but the current test set still does not hit that branch. Please keep a focused mid-scan pointer-switch reproducer, or an equivalent test that proves this throws before any deletion; otherwise the recheck can regress back to a version-only comparison without any test failing.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: add the two focused regressions above, and update the changelog category to Critical Bug Fix (crash, data loss, RBAC) with the entry rewritten into present tense.

LLVM Coverage Report

Measured on commit 07987c8.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.50% +0.10%

Changed lines: Changed C/C++ lines covered: 238/262 (90.84%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 12, 2026
…pointer

remove_orphan_files rooted its reachability traversal at whatever pointer the
table was configured to read: version-hint.text, or iceberg_metadata_file_path.
Either can name an older version than the newest committed metadata file, and
everything reachable only from the newer one then looks unreferenced. An
acknowledged INSERT's data was deleted by a routine cleanup.

The cleanup root must be the authoritative current state, so the resolver
parameter now suppresses both configured pointers and falls through to the
listing path that tables without the setting already use. It is a rename of the
existing flag rather than a new one: all seven callers passing true resolve a
commit target or a cleanup root, so all of them want the newest version.
Several were latently wrong under a stale hint as well, and expire_snapshots
and INSERT no longer retry against an existing target. Read paths keep false.

Where a catalog owns the table, its pointer is the committed state and a
listing would adopt an uncommitted file, so the catalog is threaded into
executeRemoveOrphanFiles, and OPTIMIZE ... MANIFEST moves onto that resolver.

Listing itself is ambiguous in two ways. The mid-scan recheck compares the
resolved path rather than the version number, because vN.metadata.json and
NNNNN-<uuid>.metadata.json both parse to N. And the resolver now reports the
candidates that ranked equal to the one it chose, since max_element returns the
first of equal elements and listing order has no relation to which state is
live; the cleanup refuses rather than guess, before any deletion, and again if
a tie appears while the scan is running.

That verdict has to come from the resolver because the selection policy varies:
iceberg_metadata_table_uuid filters candidates by uuid and
iceberg_recent_metadata_file_by_last_updated_ms_field ranks them by timestamp.
A check keyed on the parsed version number alone was wrong in both directions,
refusing valid uuid-selected shared directories and missing ties between
different versions carrying one timestamp.

Closes ClickHouse#114194.
@groeneai
groeneai force-pushed the groeneai/iceberg-orphan-cleanup-stale-version-hint-114194 branch from e5e83f9 to d6a8888 Compare August 12, 2026 02:28
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 07987c8c4 with master a5bc4cc6e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

8 object files changed (+227.82 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/SnapshotFilesTraversal.cpp.o 108.77 KiB 297.49 KiB +188.72 KiB (+173.51%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Iceberg/Utils.cpp.o 983.81 KiB 1017.84 KiB +34.03 KiB (+3.46%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

38 translation units recompiled, 391 s compile time in total, 38 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d6a8888

CI is fully finished on this head and no check failed.

Check / test Reason Owner / fixing PR
(none) - -
CH Inc sync private sync CH Inc sync (private, not actionable by me)

176 check-runs, all completed: 156 success, 20 skipped, 0 failure. Config Workflow and
Finish Workflow are both green, and the praktika report has 0 dropped jobs with 21 real skips,
each carrying a reason, so this is a run with real coverage rather than a config-time drop.

One thing worth stating so it is not misread: CIDB carries 244 FAIL rows for this commit, 122
each under Bugfix validation (integration tests, amd64/aarch64). Those two checks are
success, and praktika records them as OK with Failures: 122/133. Bugfix validation inverts
its verdict on purpose, so the failures there are the regression tests failing against the
unfixed base, which is what the check is asserting. Nothing is owed for them.

No Fast test, Style check, Docs check or Config Workflow red, so nothing is PR-caused.

Session id: cron:our-pr-ci-monitor:20260812-073000

@PedroTadim

Copy link
Copy Markdown
Member

cc @murphy-4o

@murphy-4o murphy-4o self-assigned this Aug 12, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7caaafcb-a6a9-424b-b617-40985825014e
  • MIRAI run: 974af2b0-d1fd-4aa8-b6ca-218c614cc55a
  • PR check IDs:
    • clickbench_168192_1789399198
    • clickbench_168203_1789399198
    • clickbench_168209_1789399198
    • tpch_adapted_1_official_168215_1789399198
    • tpch_adapted_1_official_168227_1789399198
    • tpch_adapted_1_official_168263_1789399198

@murphy-4o

Copy link
Copy Markdown
Member

@groeneai
I think the fix can still delete committed data, just from the other side.

Table with iceberg_use_version_hint = 1 and no catalog:

  metadata/
    v4.metadata.json            ← committed; references data/{a,b,c}.parquet
    00005-<uuid>.metadata.json  ← never committed; references data/a.parquet only
    version-hint.text           → "3"
  • Before this PR: root = v3 (the hint) → v4's files look orphaned. The reported bug.
  • After this PR: root = 00005- (highest version in the listing) → b.parquet and c.parquet look orphaned.

The cause is that the listing pool mixes naming schemes. <N>-<uuid>.metadata.json is the Metastore Tables name in format/spec.md — only a catalog-tracked writer produces it. A hint-tracked table only ever commits v<N>.metadata.json. So on this table that file should never have been a candidate.

test_remove_orphan_files_with_catalog plants exactly this file and is saved by the catalog pointer. With no catalog there's nothing to save it, and no test covers that combination.

Filtering candidates to v when the table is hint-tracked would remove the case entirely. It would also remove the ties: tied_paths, both BAD_ARGUMENTS throws and three tests exist to cope with candidates that don't belong to this table's scheme in the first place.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, and it is worse than the reachable-file count suggests: the committed metadata file goes too.

Reproduced on local storage, iceberg_use_version_hint = 1, no catalog, three acked INSERTs (v1..v4, hint = 4, three data files), then planted 00005-<uuid>.metadata.json holding v3's content and ran the cleanup.

binary planted file committed data files deleted rows after v4.metadata.json
base 2850e469 (build 7aa74157) 00005-<uuid> 0 3 present
this PR (build bb47bb17) none 0 3 present
this PR (build bb47bb17) 00005-<uuid> 1 2 deleted

SELECT count() goes 3 to 2, and v4's metadata file, manifest and manifest list are all gone while version-hint.text still reads 4. The base arm is clean, so this PR is what makes it reachable. The current head should not be merged.

Your cause is right, and it is the right layer. v<N>.metadata.json is self-certifying: the name is the compare-and-set, so existence means committed, and a higher N always carries a superset of the state. That is what makes "highest version in the listing" sound. <N>-<uuid>.metadata.json carries none of that: names never collide, the pointer lives in a metastore, and N comes from that metastore's sequence, which is not comparable with this table's. Ranking the two together compares numbers from independent sequences.

Two things I checked before agreeing.

Is the filter sufficient? Yes, for anything a writer produces. I could only get past it with files no writer emits: v5.metadata.json and v5-<uuid>.metadata.json each carrying content behind v4 lose the same row. No writer commits a metadata file whose state is behind a lower-numbered one, and the uuid form requires a transactional catalog (IcebergWrites.cpp:903, use_uuid_in_metadata = catalog && catalog->isTransactional()), so a hint-tracked table never emits it.

Does it remove the ties? Two of the three, outright. The third, ..._refuses_last_updated_ms_tie, is on a table with no hint, so the filter does not reach it, but that tie is already present on master without this PR, so it does not belong here either. It comes out as a disclosed pre-existing gap.

Next push:

  • the resolver keeps only v<N>.metadata.json candidates when the table is hint-tracked;
  • tied_paths and both BAD_ARGUMENTS throws are deleted, so the source diff shrinks;
  • tests: ten new functions down to four, in two files instead of three. Kept are the reported bug, your case as its regression test, the write path, and test_remove_orphan_files_with_catalog. test_expire_snapshots.py reverts to no new cases.

That last point is also the answer to your other comment: most of those cases exist to cope with candidates that should never have been candidates, so they leave with the machinery rather than by trimming coverage.

Review of the previous commit found that rooting the orphan scan at the highest
version in the metadata listing reintroduces the same loss from the other side.

A hint-tracked table commits through v<N>.metadata.json, where the file name is
itself the compare-and-set: a second writer aiming at version N collides with the
existing file, so existence means N is committed and a higher N always carries a
superset of the state. In <N>-<uuid>.metadata.json, the metastore-tables name, the
uuid makes collisions impossible and the commit is recorded in a metastore, so its
N counts a sequence this table does not track. Ranking the two together can root
the scan at a state that never contained the newest committed snapshot.

Measured on a local hint-tracked table with three acknowledged inserts and a
planted 00005-<uuid>.metadata.json carrying an earlier state: the previous commit
deleted one committed data file, the committed v4.metadata.json, its manifest and
its manifest list, and SELECT count() fell from 3 to 2. The base commit of this PR
leaves all of it intact, so the previous commit is what made this reachable.

So the hint declares two things and only one of them is dropped here: the cleanup
ignores the version it names, which is what lets a lagging hint stop orphaning newer
committed files, and honours the scheme it names. A hint holding a complete file name
declares that file's scheme, and a bare version number can only address v<N>, which
is how the reader resolves it too. Candidates outside the declared scheme are dropped
whichever of the two it is, so a stale v<N> file cannot outrank the uuid-named file a
hint points at either.

A hint declares a scheme only if it addresses a file that is really there, so a
dangling or malformed hint attributes no scheme and resolution is left as it is on
master. The filter also stands aside for iceberg_metadata_table_uuid, which identifies
the table's files by content rather than by name, and for a table owning no candidate
in its own scheme, which has nothing better to resolve by.

With foreign-scheme candidates excluded, the only remaining way for two candidates
to claim one version on a hint-tracked table is a plain and a compressed spelling of
the same name, and the resolver itself refuses that: both are committed under the
name-collision rule, so listing order would otherwise decide which is current. That
replaces tied_paths and the two refusals it fed outside the resolver, and it covers
the mid-scan recheck for free because the recheck goes through the same resolver. A
tie stays reachable on a table with no pointer at all under
iceberg_recent_metadata_file_by_last_updated_ms_field; that is present without this
PR and is left alone.

The three tie cases and the dry_run case go with the machinery, and a regression
test for the foreign-scheme root replaces them.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 3d43e12e with your fix.

The resolver keeps only candidates in the scheme the table's own hint declares, either one of the two, so a stale v<N> cannot outrank a uuid file a hint points at either. tied_paths, both refusals outside the resolver and the three tie tests are gone; the source diff is now +137/-666 against the previous head and the tests are ten new cases down to four in two files. Arms on a local hint-tracked table, three acked inserts, older_than pinned to now:

arm committed data files deleted rows v4.metadata.json
stale hint, no planted file (the reported bug) 0 3 present
00005-<uuid> planted (your case) 0 3 present, planted file removed as an orphan
hint names a uuid file, higher stale v8 present 0 3 present

One correction to what I said earlier: the ties do not all disappear. Two spellings of one version, v7.metadata.json and v7.gz.metadata.json, are both committed under the name-collision rule, and I measured the choice falling to listing order. The resolver refuses that one case itself, in six lines, so the mid-scan recheck is covered by the same code rather than by a second check outside it. Say the word if you would rather have a deterministic preference order there instead.

Three residuals are in the description, all reachable without this PR: uuid-scheme numbers are still ranked, a last-updated-ms tie on a pointerless table is still decided by listing order, and cleanup still scans the whole table prefix so a table sharing a metadata directory can lose files. The last one I probed against the base commit and it behaves identically there.

On coverage, three cases went with the machinery and I would rather you choose than guess:

  • expire_snapshots under a stale hint. It now relies on the shared default that INSERT also pins, so there is no per-caller knob left to break, but it has no case of its own.
  • catalog-backed OPTIMIZE ... MANIFEST. That call did move onto the catalog resolver, and nothing now covers it.
  • the mid-scan pointer switch. That is the case I offered to drop.

Restoring any of them is a few minutes; restoring all three puts about 350 test lines back.

The reader resolves the version hint to a file name and then reads that name
alone under metadata/, dropping any directory part of it. The scheme inference
added by the previous commit classified the raw hint text instead, so a hint
spelled `metadata/v4.metadata.json` matched neither scheme, the candidate filter
stood aside, and a higher uncommitted `00005-<uuid>.metadata.json` could root the
orphan scan again, which is the loss the previous commit closed.

Measured on a local hint-tracked table with three acknowledged inserts and a
planted `00005-<uuid>.metadata.json` holding an earlier state, varying only the
hint content. With `metadata/v4.metadata.json` the previous commit deleted one
committed data file, the committed `v4.metadata.json`, its manifest and its
manifest list, and this commit deletes none of them. With `v4.metadata.json` or a
bare `4` both commits keep everything.

The symmetric direction moves as well: with the live state under
`v5-<uuid>.metadata.json` and a stale higher `v8.metadata.json` present, a hint
spelled `metadata/v5-<uuid>.metadata.json` lost a committed data file before and
loses none now, while a hint holding a bare `8` still roots at `v8`, so the hint
content stays the discriminator rather than the filter becoming a blanket refusal.

The hint read is also no longer wrapped in a swallow. Deciding that a hint which
could not be read declares no scheme is a decision to rank both filename families
for a caller that is about to delete, and every one of those callers read the hint
unguarded before this PR, so letting it throw is what they did already: a table
whose `version-hint.text` is missing refuses cleanup with the same
FILE_DOESNT_EXIST it refuses with on master.

The regression arm goes into the existing foreign-scheme test, which now runs
both spellings of a hint that addresses the same version.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 18f4cd6

Every failure below has an owner: a fixing PR (ours 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
AST fuzzer (amd_tsan) / Not-ready Set is passed as the second argument for function 'A (STID 0250-41a5) pre-existing trunk logical error, unrelated to this diff: 163 CIDB rows over 128 distinct PRs in 30 days, 16 of them on master. Merged #107924 is already an ancestor of this head, so it is disqualified as the owner #109722 (ours, open)

Nothing else is red at this head: praktika reports 177 nodes with only that fuzzer leg and its parent failing, Config Workflow / Style check / Finish Workflow are all success, and the remaining non-green CIDB rows are all Bugfix validation FAILs carrying check_status=success, the documented inversion where the regression test correctly failed on master.

Session id: cron:our-pr-ci-monitor:20260826-190000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dcee5693832a2324b96d2bb1042c6f405978af9d

Every failure below has an owner: a fixing PR (ours 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
Upgrade check (amd_release) / Error message in clickhouse-server.log, Failures: 1/12 not PR-caused, trunk defect in mutation column reconciliation: MutatePlainMergeTreeTask fails Code: 47 ... Unknown expression identifier 'b'. Maybe you meant: ['a']. In scope b, b. (UNKNOWN_IDENTIFIER) and retries forever. A part re-attached before a DROP COLUMN holds a column the table no longer has; the compact branch of splitAndModifyMutationCommands cannot decide from the metadata versions on a plain MergeTree (both are 0), so it emits a READ_COLUMN for a column the interpreter's available set does not contain. The diff here is Iceberg orphan-file cleanup plus two integration tests, which cannot reach MutationsInterpreter. The same error text fires byte-identical at unrelated heads on this same check, which is what places it on master rather than in this diff. #115962 (ours, open)

That PR is the remedy for this exact block rather than a same-area coincidence: it makes the
compact branch skip such a column instead of emitting the read, matching what the wide branch has
always done, and it closes #115416, which reports this signature.

No other check failed at this head, and Config Workflow, Style check and Finish Workflow are
all success with 0 nodes DROPPED.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114324&sha=dcee5693832a2324b96d2bb1042c6f405978af9d&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

Session id: cron:our-pr-ci-monitor:20260831-083000

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 2026
…in loop

The check spelled its two conditions as a lambda taking a predicate plus two
predicate lambdas at a single call site. One pass over the listing with both
conditions named says the same thing without the indirection: the listing has
to contain the scheme the hint declares, and a hint that names a file directly
declares nothing unless that file is really there.

No behaviour change, measured on the base and refactored binaries over the six
hint forms that reach the block: path-form, plain-name and bare-number hints
addressing the committed v4, a uuid-scheme hint with and without a directory
part, and a hint naming a file that is absent. Both binaries agree on every
arm, including the discriminating control, where a bare hint naming a higher
stale v<N> still roots the scan there and deletes one committed data file. So
the filter did not become a blanket refusal.
The listing resolver ranks `v<N>.metadata.json` and `<N>-<uuid>.metadata.json`
candidates in one order, but their numbers count two unrelated sequences: a
`00005-<uuid>.metadata.json` written by another engine outranks a committed
`v1..v4` chain without carrying its state. `remove_orphan_files`, compaction and
the write retry paths pass `ignore_metadata_pointer_overrides = true`, so they
reach that resolver, root the reachability scan at the foreign file, and delete
every object only the committed snapshot references. Measured on a local table
with 3 acknowledged inserts (`v1..v4`, 3 data files) plus a planted
`00005-<uuid>.metadata.json` copied from `v2`: 2 of the 3 committed data files
and the live `v4.metadata.json` deleted, `SELECT count()` 3 -> 1.

Two changes, each closing one half of the case:

- The scheme a configured pointer spells now also comes from
  `iceberg_metadata_file_path`, not only from `version-hint.text`. These callers
  distrust the version a pointer names, which may be older than the newest
  commit, but the scheme it is spelled in is still this table's. With the pointer
  present the foreign candidate is filtered out, and the same fixture keeps all 3
  data files and reaps the planted file as an orphan.

- With no pointer at all nothing declares the scheme, and neither order is more
  plausible than the other, so a listing that holds both schemes is refused
  instead of ranked. Only files that are candidates count: with
  `iceberg_metadata_table_uuid` set, another table's metadata file in the same
  directory is selected out by its table-uuid and cannot cause a refusal.

The refusal is scoped to the callers that delete or rewrite state; reads still
resolve by ranking, unchanged. A single-scheme listing is unaffected, including a
uuid-only table written entirely by another engine, which was measured identical
before and after. The setup that pays for this is a foreign-written history that
ClickHouse continued without a catalog, which holds both schemes legitimately:
its cleanup now refuses until `iceberg_metadata_file_path` or a version hint
names the current metadata file, and with either one it reaps exactly what it
reaped before.

Requested in ClickHouse#114324 (comment)
The ambiguity check in getLatestMetadataFileAndVersion compared version
numbers, but the winner is not always chosen by version: with
iceberg_recent_metadata_file_by_last_updated_ms_field the candidates are
ranked by last-updated-ms. Two different versions carrying one timestamp
were separated only by the order the object storage listed them in, and a
version-keyed check saw nothing wrong with them, so remove_orphan_files
and the other callers that pass ignore_metadata_pointer_overrides could
root at a stale metadata file and delete committed state.

Asking the ranking predicate both ways keeps the verdict on the policy
that actually applied: under version ranking it is exactly the previous
same-version test, and under timestamp ranking it also catches the pair
that test cannot see. The check now covers these callers when no pointer
declares the scheme too, which the controls below show is otherwise
decided by listing order alone.

Measured on a local table with three acknowledged inserts (v1..v4, live
v4) plus a planted v0.metadata.json carrying v2's content and v4's
last-updated-ms. Version 0 can never win by version, so only the
timestamp policy can select it:

  arm                              before               after
  twin ahead of v4 in the listing  2 committed data     refused,
                                   files and live v4    nothing
                                   deleted, rows 3->1   deleted
  twin behind v4 in the listing    cleans normally      refused,
                                                        nothing deleted
  same fixture, ranked by version  cleans normally      cleans normally
  no twin planted                  cleans normally      cleans normally

The last two arms are the controls: the fix does not refuse a table whose
candidates the policy in force can order.

This guard was promised on this PR in review and then dropped while the
candidate filtering was reworked; it comes back here with the case the
version-keyed form could not express.
The sink constructor resolved the current metadata file through whatever
pointer the table carries, while the retry loop resolves it by listing. A
pointer naming a version behind the newest committed one made the first
attempt target a version that already exists, and with no pointer at all a
listing holding both `v<N>.metadata.json` and `<N>-<uuid>.metadata.json` let
the constructor rank two unrelated sequences together: the highest number can
name a file the table never committed, and the first INSERT commits on top of
it, dropping every snapshot after it. remove_orphan_files already refuses that
listing; the write root now refuses it too.

04079 no longer reaches the retry loop, since the first attempt already targets
the newest committed version. Its assertion is unchanged; only the narration of
a mechanism the test no longer exercises is corrected.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
For the callers that delete or rewrite metadata, a configured pointer is
distrusted for the version it names and kept only for the naming scheme it
spells, which then excludes every candidate of the other scheme. Excluding
candidates is what went wrong: the file this table committed last can be the one
excluded, and the operation then roots behind it and deletes it.

Three ways in, all measured on a local table of acknowledged inserts:

  case                          before                     after
  all uuid-named, hint names    2 of 3 committed data      refused, nothing
  00004-<uuid>, stray 00006     files deleted              deleted, rows 3
  pin names 00004-<uuid>, one   INSERT acked as v5, then   INSERT refused
  ordinary INSERT, cleanup      cleanup deleted it and     before committing,
                                its data, rows 4 -> 3      nothing deleted
  old pin v2 kept for reads,    current metadata and its   refused, current
  current file uuid-named by    data deleted, table then   metadata kept,
  the hint                      unreadable                 rows 4

The first two follow from a uuid-named pointer: `<N>-<uuid>.metadata.json`
prefixes are chosen by the writer, so with no transactional catalog a higher one
can name an abandoned write, and the prefix cannot order this table's own
`v<N>.metadata.json` commits either. Such a pointer no longer excludes anything
here, so the existing mixed-scheme refusal covers the second case, where
ClickHouse commits `v<N>` whatever the pointer is named. It is also compared
with the ranking winner, by version rather than by name, so the compressed
spelling of one file is not read as a different file.

The third is `iceberg_metadata_file_path` being an exact read override rather
than a statement of the commit scheme: letting it choose the scheme hid the
current file another engine had committed under a uuid-named name. A commit
advances the hint and never the explicit path, so where the two disagree these
callers now take the scheme from the hint. A reader still obeys the explicit
path, so pinning any metadata file for a time-travel read is unaffected.

A `v<N>` pointer still declares the scheme and still never vetoes the listing: a
higher N exists only because it was committed, which is what makes a lagging
hint recoverable in the first place. The temporary file an interrupted commit
leaves behind is skipped while reading the names, since it is not a candidate
and would otherwise describe the table by a file that can never be current.

When pointer and listing agree nothing changes: a uuid-named pointer still
cleans and still accepts INSERT, a pointerless all-uuid table (the shape
iceberg-java writes) is untouched, and a pointer naming the newest of its own
scheme still licenses cleanup past a foreign-named file.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 2ded75a5: a uuid-named metadata pointer must not exclude the file the table committed last

5eaaf471 makes the sink resolve by listing. Measured on a table whose pointer names a
<N>-<uuid>.metadata.json file, that also widens an existing hole to the write path: the pointer is
reduced to "this table commits through the uuid scheme", the v<N> chain is excluded from the
candidates, and what is left is ranked by the numeric prefix even though a prefix is not a commit
order without a transactional catalog.

Local table, three acknowledged inserts, clean master as the reference:

case before after
all uuid-named, hint names 00004-<uuid>, 00006 planted cleanup deleted 2 of the 3 committed data files refused, nothing deleted
pin names 00004-<uuid>, then one ordinary INSERT acked as v5, cleanup then deleted it and its data, rows 4 -> 3 INSERT refused before committing
old pin v2 kept for reads, current file uuid-named by the hint current metadata and its data deleted, table then unreadable; clean master reads 4 rows refused, current metadata kept, rows 4

The third case is not from your commit and not from the bot round, and it is the worst of the three:
iceberg_metadata_file_path is an exact read override, so letting it pick the scheme hid a current
file another engine had committed.

One semantics call is yours to veto. For these callers only, the scheme now comes from
version-hint.text rather than from iceberg_metadata_file_path, because a commit advances the hint
and never the explicit path. Readers keep the previous precedence, so a time-travel pin still reads
exactly what it names (asserted).

A v<N> pointer still never vetoes the listing, since a higher N exists only because it was
committed, which is what makes a lagging hint recoverable at all. What newly refuses is a uuid-named
pointer standing beside v<N> files, which is the state that was deleting acknowledged data.

Asserted unchanged: the refusal message your test_insert_refuses_undeclared_scheme matches, the
pointerless all-uuid layout iceberg-java writes, a pointer naming the newest file of its own scheme
(still cleans past a foreign-named one), the last-updated-ms guards, and reads. Three cases added,
with the helpers already in the file including your remove_metadata_file.

Two residuals stay yours to decide and are both in the description already: a pointerless all-uuid
listing is still ranked by prefix, and cleanup still scans a shared table prefix. Separately, the
04079 narration in 5eaaf471 reads as though the retry path is no longer entered, but its assertion
holds either way, so it does not pin that.

Session id: cron:clickhouse-maint-slot-12:20260914-071300

…t spell the scheme

`iceberg_recent_metadata_file_by_last_updated_ms_field` ranks metadata candidates by a field their
writer chose, so the file it selects can be one the table's own pointer contradicts, and comparing
the version number could not see it: a second file spelling the declared version passes, and so
does a lower version whose timestamp is newer. Measured on a local table with three acked inserts,
`remove_orphan_files` then deleted two of the three committed data files and the declared metadata
file itself, leaving the table unreadable from its own pointer, and an INSERT rooted there
committed a chain that had dropped two acked rows. The selected file must therefore be the file
the pointer names, with a higher `v<N>` the one exception: that number exists because a commit
wrote it, which is what keeps a lagging hint recoverable.

A pointer only says that much when the file it names is really there, so the comparison arms on
presence. A bare version number addresses a compressed spelling as well, and with the plain name
absent that spelling is the file the pointer means: without this, a `v<N>.gz.metadata.json` head
was ranked below a stale file carrying a newer timestamp and deleted, the same way on master. Two
spellings of that version name neither, and the pointer then identifies nothing, so the operation
refuses instead: measured, that layout deleted the head where master kept it.

The naming scheme now comes only from `version-hint.text`. `iceberg_metadata_file_path` is an
exact read override that no commit advances, so it can name a file written before another engine
took over the table, and taking the scheme from it hid the uuid-named file holding the current
state: measured, cleanup rooted at the newest historical `v<N>` and deleted the current metadata
plus the data committed after the pinned version, where master deleted nothing. Its cost is that
a pin no longer unblocks cleanup on a directory holding both schemes, which now refuses until a
hint names the current file or the other scheme's files are removed.

Reads are untouched: they keep obeying the explicit path, and none of these comparisons runs for
them.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 07987c8c: the selected metadata file must be the one the pointer names, and only a hint may spell the scheme

Two of the three things below were regressions against clean master on this branch, so I fixed them
rather than only reporting them. Every row was measured on a local table with three acked inserts,
master = 8ec7c5be, base = 2ded75a5.

shape clean master base 2ded75a5 now
exact <N>-<uuid> pointer, second file at that version with a larger last-updated-ms 2 of 3 data files + the declared file deleted same refused, nothing deleted
same shape, INSERT instead of cleanup commits a chain missing 2 acked rows same refused before committing
bare hint 4, stale v<N> timestamped after v4 2 of 3 + v4.metadata.json deleted, table unreadable same refused
v<N> read pin, no hint, current file uuid-named nothing deleted, 3 rows 1 of 3 + the current metadata deleted, unreadable refused
bare hint, head is v4.gz.metadata.json, plus a stale twin spelling nothing deleted 2 of 3 + head deleted refused

Under iceberg_recent_metadata_file_by_last_updated_ms_field the ranking key is a field its writer
chose, so comparing the pointer by version number could not see either disagreement: a second file
spelling the declared version has the same number, and a lower version can carry a newer timestamp.
The selected file must therefore be the file the pointer names, with a higher v<N> the one
exception, since that number exists only because a commit wrote it.

The scheme now comes only from version-hint.text. iceberg_metadata_file_path is an exact read
override that no commit advances, so it can name a file written before another engine took over the
table, and taking the scheme from it hid the uuid-named file that held the current state (row 4).
That is the principle the two tests added in 2ded75a5 already state; this closes the case where no
hint exists. The cost, stated plainly: a read pin no longer unblocks cleanup on a directory
holding both naming schemes, which now refuses until metadata/version-hint.text names the current
v<N>.metadata.json or the other scheme's files are removed. 0f8f1ca had offered the pin as that
escape hatch; it cannot be one, because the same mechanism deletes a committed head. If you would
rather keep the pin's old behaviour and accept row 4, say so and I will revert that part.

Coverage: one new case for the timestamp-versus-pointer refusals (both shapes plus a control that
the policy alone still cleans), and one phase added to the existing pin test for the no-hint case.
Not added, deliberately, against your two asks for fewer cases: the compressed-spelling shape needs
a gzip fixture and new test-side plumbing, and its behaviour is covered by the two rows above.

Unchanged and re-measured on this head: the stale-hint case #114194 is about still cleans and reaps
its orphan, the Spark-shaped uuid-only layout still cleans, a bare hint resolving to
v<N>.gz.metadata.json still cleans, the temporary-file and equal-timestamp arms are unchanged, and
a read pinned to an older file still resolves to that file.

Session id: cron:clickhouse-maint-slot-12:20260914-104700

@murphy-4o
murphy-4o enabled auto-merge September 15, 2026 02:46
@murphy-4o
murphy-4o added this pull request to the merge queue Sep 15, 2026
Merged via the queue into ClickHouse:master with commit 8d780d7 Sep 15, 2026
177 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 15, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @murphy-4o — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both findings are real and I am closing neither. I measured them on master at 45efaa435674, which contains this PR's merge, and answered each on its own issue: #120164 (version-hint.text deleted by OPTIMIZE TABLE, then Code: 107 on every read) and #120165 (committed [2,3,4] becomes [2,3], and the fourth row's data object is deleted).

Neither is introduced here: getOldFiles, clearOldFiles, getPlan, IcebergMetadata::getHistory and IcebergMetadata::optimize are byte identical on master before this merge (2615840f). The per-call-site fixes you suggest are also not sufficient, because a successful OPTIMIZE TABLE leaves the table with a single v0.metadata.json even with nothing configured, so the rewritten generation is never published. That is why #114437 refuses Iceberg data compaction in the open-source build rather than repairing the root choice and the delete list. It is open and waiting for review.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 28, 2026
Since ClickHouse#114324, remove_orphan_files resolves its reachable set by listing the
metadata files and reads version-hint.text only to learn the commit scheme
(collectReachableFiles passes ignore_metadata_pointer_overrides = true), and it
fails closed when the root is ambiguous. A stale hint no longer makes committed
files look orphaned, which test_remove_orphan_files covers
(test_remove_orphan_files_stale_version_hint_keeps_committed_snapshot). The
warning this PR added to the support matrix row and to the command's note is
therefore no longer true.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
A full-rewrite OPTIMIZE still named its commit `v<N+1>.metadata.json` while an
INSERT on a `<N>-<uuid>` table aimed at `<N+1>-<uuid>`: two names, so both
conditional writes could succeed and the compaction could publish a state
without an acknowledged INSERT. It now continues the chain like every other
writer. Its version-hint confirmation works for a uuid name because the hint
of a uuid-named commit holds the file name.

With `iceberg_use_version_hint = 1`, a hint naming `<N>-<uuid>` that lags one
commit (its update failed, or a concurrent writer reads between the commit and
the hint update) made every later write and maintenance refuse, because only a
higher `v<N>` could supersede a declared file. A higher file whose name is the
one a catalog-less commit gives its version now does too. A random uuid still
does not, so the ClickHouse#114324 guard keeps refusing files another writer left.

To make that name recognisable from the file name alone, the name-based uuid
is derived from `metadata/<N>` instead of `<table location>metadata/<N>`. The
location added nothing to the compare-and-set, which is per path.

`test_pyiceberg_v1_schema_evolution_ch_read` looked for ClickHouse's commit
among `v<N>` files only; its helper now reads both schemes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 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 comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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 with iceberg_use_version_hint=1: remove_orphan_files deletes an acked snapshot's data behind a stale version-hint (permanent data loss)

6 participants