Skip to content

Support remove_orphan_files for Iceberg tables - #99127

Merged
murphy-4o merged 49 commits into
ClickHouse:masterfrom
murphy-4o:murphy_issue_99030
Apr 15, 2026
Merged

murphy-4o merged 49 commits into
ClickHouse:masterfrom
murphy-4o:murphy_issue_99030

Conversation

@murphy-4o

@murphy-4o murphy-4o commented Mar 10, 2026 •

Copy link
Copy Markdown
Member

Fixes: #99030

Implements remove_orphan_files for Iceberg tables. Orphan files — files on storage not referenced by any snapshot in the Iceberg metadata graph — accumulate from failed writes, partial compaction cleanup, and interrupted operations, causing unbounded storage growth. This PR adds a new ALTER TABLE ... EXECUTE remove_orphan_files(...) command to identify and delete them.

Algorithm

  1. Collect reachable files — traverse the full metadata graph (metadata JSON files from the metadata-log, manifest lists from all snapshots, manifest files, data/delete files, statistics files, and version-hint.text) to build a set of all referenced paths.
  2. List actual files — scan object storage under the table location (or a user-specified subdirectory).
  3. Compute orphans — set difference (actual minus reachable), filtered by an older_than timestamp threshold to protect in-progress writes.
  4. Delete — remove orphan files unless dry_run is enabled.

Changelog category (leave one):

  • Experimental Feature

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

Add ALTER TABLE ... EXECUTE remove_orphan_files for Iceberg tables to identify and remove unreferenced files from object storage.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

example:

-- With defaults (older_than = 3 days ago)
ALTER TABLE t EXECUTE remove_orphan_files()

-- Positional timestamp
ALTER TABLE t EXECUTE remove_orphan_files('2026-03-01 00:00:00')

-- Named parameters
ALTER TABLE t EXECUTE remove_orphan_files(older_than = '2026-03-01 00:00:00', location = 'data/', dry_run = 1)

Version info

  • Merged into: 26.4.1.948

Signed-off-by: murphy-4o <[email protected]>
Signed-off-by: murphy-4o <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2df5afb]

Summary: ✅


AI Review

Summary

This PR adds ALTER TABLE ... EXECUTE remove_orphan_files for Iceberg tables, including argument parsing, reachable-file traversal, orphan detection, guarded deletion, metrics output, docs, settings, and integration tests. I re-reviewed the current PR head with focus on correctness/safety paths (remove_orphan_files, expire_snapshots, traversal, and parser behavior) and did not find additional high-confidence issues beyond those already discussed in prior inline reviews.

ClickHouse Rules
Item Status Notes
Deletion logging ✅
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 10, 2026
- Abort on metadata traversal errors instead of silently continuing
  with an incomplete reachable set (fail-closed for destructive ops)
- Skip files without last_modified metadata conservatively (don't
  delete when age cannot be verified)
- Report `skipped_missing_metadata_count` in result metrics and log
  a WARNING summary when files are skipped due to missing metadata
- Track successful deletions and report accurate counters (previously
  counters were incremented before deletion, misreporting on failure)
- Include `partition-statistics` entries in reachable-set collection
  per the Iceberg spec (previously only `statistics` was handled,
  which could cause valid partition statistics files to be orphaned)
- Update test assertions for the new metric count (7 -> 8 metrics)

Made-with: Cursor
…mandArgs

Extract the ad-hoc argument parsing for Iceberg EXECUTE commands into a
reusable `ExecuteCommandArgs` class that supports declarative schema
registration:

- Positional arguments (matched by index, also accepted as named)
- Named arguments (key = value syntax)
- Type validation per argument
- Default values
- Post-parse callbacks for derived defaults

Both `expire_snapshots` and `remove_orphan_files` now define their
argument schema declaratively via `makeExpireSnapshotsSchema` and
`makeRemoveOrphanFilesSchema`, replacing ~100 lines of manual
if/else parsing with ~30 lines of schema definitions. New EXECUTE
commands only need to register their schema and read the Result.

Made-with: Cursor
…ent_deletes.

Share snapshot file graph traversal between `expire_snapshots` and `remove_orphan_files` to avoid duplicate logic, and remove the `max_concurrent_deletes` option from command parsing, docs, and integration tests.

Made-with: Cursor
Move file classification logic from `remove_orphan_files` into reusable utility helpers and switch orphan cleanup metrics tally to the shared `FileCatagory` enum/function.

Made-with: Cursor
…n tests

- Register `allow_iceberg_remove_orphan_files` and
  `iceberg_orphan_files_older_than_seconds` in `SettingsChangesHistory.cpp`
  to fix the `02995_new_settings_history` test
- Cast `strftime` return value to void to silence clang-tidy
  `cert-err33-c` warning in `IcebergMetadata.cpp` (arm_tidy build)
- Fix `test_remove_orphan_files_no_orphans`: superseded metadata JSON
  files are legitimate orphans after multiple writes; only assert that
  data/manifest/statistics counts are zero
- Fix `test_remove_orphan_files_location`: rename fake orphan metadata
  file from `orphan-meta.metadata.json` to `v99.metadata.json` so it
  follows the Iceberg naming convention and doesn't trip the metadata
  file version parser

https: //s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99127&sha=5d755a291a580e17e9802b5b232207515c66a823&name%5F0=PR
Made-with: Cursor
@alexbakharew

Copy link
Copy Markdown
Contributor

Hi @murphy-4o,
please merge master into your branch, it will fix the LLVM issue

Resolve conflicts in Settings.cpp, enableAllExperimentalSettings.cpp,
and IcebergMetadata.cpp: keep both new settings (allow_iceberg_remove_orphan_files,
allow_experimental_expire_snapshots) and adopt master's parseExpireSnapshotsOptions
for expire_snapshots while retaining ExecuteCommandArgs for remove_orphan_files.

Made-with: Cursor
Refactor expire_snapshots to use the same ExecuteCommandArgs declarative
parser as remove_orphan_files, replacing the ad-hoc ExecuteOptionsParser.
Enhance ExecuteCommandArgs with type-unchecked arg overloads for complex
field types (Array, polymorphic bool/int) that need custom conversion via
IcebergFieldParseHelpers. Delete ExecuteOptionsParser.cpp/.h.

Also fix test_remove_orphan_files_location: rename orphan metadata file
from v99 to v0 so it doesn't hijack metadata version resolution (v99
was treated as the current metadata, corrupting the reachable set).

Made-with: Cursor
- Reject duplicate arguments in ExecuteCommandArgs: both duplicate named
  args and positional+named collisions on the same parameter now throw
  BAD_ARGUMENTS instead of silently overwriting.
- Fix typo: rename FileCatagory -> FileCategory and getFileCatagory ->
  getFileCategory across Utils.h, Utils.cpp, and OrphanFilesRemoval.cpp.

Made-with: Cursor
The default cutoff was computed as a time_t, formatted to a UTC string
via gmtime_r, then parsed back by readDateTimeText which uses the
server-local timezone. On non-UTC servers this shifts the effective
retention window, potentially making cleanup more aggressive than
configured.

Fix by computing the default older_than directly as a time_t without
a string round-trip. User-provided timestamp strings still go through
readDateTimeText as expected.

Made-with: Cursor
Move expire_snapshots and remove_orphan_files command logic (schema
declaration, options building, result formatting) into dedicated
ExpireSnapshotsExecute and RemoveOrphanFilesExecute files, leaving
executeCommand as a thin dispatcher.

Made-with: Cursor
- Move collectReachableFiles into SnapshotFilesTraversal, split out
  collectMetadataRootFiles for metadata-log/statistics/version-hint
- Decompose removeOrphanFiles into resolveScanPath,
  resolveOlderThanThreshold, findOrphanFiles, deleteOrphanFiles,
  and tallyByCategory
- Use iceberg_orphan_files_older_than_seconds setting instead of
  hardcoded constant for the fallback age threshold

Made-with: Cursor
…stEnv

- Switch SnapshotReferencedFiles and collectReachableFiles from
  std::set to std::unordered_set for O(1) average lookups
- Introduce OrphanTestEnv class to eliminate repeated boilerplate
  across test cases
- Parametrize all orphan removal tests with both local and s3

Made-with: Cursor
Comment thread review_99030.md Resolved
…lete

Equality delete filenames (e.g. eq-delete-*.parquet) contain "-delete-"
and were incorrectly matched by the position-delete branch first.

Made-with: Cursor
Strip leading "./" and ensure trailing "/" so that location="data" does
not accidentally match sibling paths like "data_backup/".

Made-with: Cursor
@murphy-4o
murphy-4o force-pushed the murphy_issue_99030 branch from d90d744 to 06f4535 Compare March 15, 2026 13:51
Only append trailing '/' when location is explicitly provided, so that
the default table-path scan is not altered. Also reject older_than
timestamps in the future to preserve the in-progress-write safety window.

Made-with: Cursor
@murphy-4o
murphy-4o force-pushed the murphy_issue_99030 branch from 42ec662 to edb2714 Compare March 16, 2026 00:40
Remove redundant static keyword inside anonymous namespace.
Fix main_branch_walked being set unconditionally even when the main
ref points to a missing snapshot, which skipped the fallback walk
from current_snapshot_id and could expire all snapshots.

Made-with: Cursor
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

…tadata

Resolve merge conflict in Mutations.cpp (expire code moved to
ExpireSnapshotsExecute.cpp). Replace UNREACHABLE() with BAD_ARGUMENTS
for unknown ref types. Port force_fetch_latest_metadata and
ignore_explicit_metadata_file_path to expireSnapshots call.

Made-with: Cursor
Move version-hint.text into the reachable file set computed by
collectMetadataRootFiles instead of relying on a hardcoded exclusion
in findOrphanFiles.

Re-read metadata version after the orphan scan and before deletion;
abort with BAD_ARGUMENTS if the version changed, preventing deletion
of files that became referenced by a concurrent commit.

Made-with: Cursor
…a test

collectReachableFiles now passes ignore_explicit_metadata_file_path=true
to getLatestOrExplicitMetadataFileAndVersion, ensuring remove_orphan_files
and expire_snapshots always scan the actual latest metadata regardless of
any iceberg_metadata_file_path setting on the table. Without this, a table
pinned to an older metadata version for time-travel reads could cause
remove_orphan_files to treat newer valid data files as orphans.

Also adds an integration test that creates a table pinned to older metadata
and verifies remove_orphan_files does not delete data from newer snapshots.

PR changelog category updated from New Feature to Experimental Feature.

Made-with: Cursor
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-feature Pull request with new product feature labels Apr 10, 2026
The arm_tidy build failed because DataTypeString was only
forward-declared, causing 'incomplete type' and 'no matching
constructor' errors when constructing ColumnWithTypeAndName
with std::make_shared<DataTypeString>().

Made-with: Cursor
@murphy-4o
murphy-4o enabled auto-merge April 15, 2026 02:39
@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 3.39% (26/768) · Uncovered code

Full report · Diff report

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental Feature 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.

Support ALTER TABLE ... EXECUTE remove_orphan_files for Iceberg tables

5 participants