Skip to content

Support deleting unreferenced files after snapshot expiration - #4201

Open
dragonknightk wants to merge 3 commits into
apache:mainfrom
dragonknightk:fix/2604-expire-snapshots-delete-files
Open

dragonknightk wants to merge 3 commits into
apache:mainfrom
dragonknightk:fix/2604-expire-snapshots-delete-files

Conversation

@dragonknightk

@dragonknightk dragonknightk commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2604

Rationale for this change

expire_snapshots only updates table metadata, leaving unreferenced files on storage. This adds an opt-in clean_expired_files() step matching #2604: after the expiration commits, compare expired snapshots against retained snapshots and delete the difference without listing object storage.

Key design choices compared with Iceberg Java:

  • Reachable file diff: Like Java's ReachableFileCleanup, only manifests dropped by expired snapshots can hold newly unreferenced files, and any live entry in a retained manifest keeps its file. Unlike Java, DELETED entries in dropped manifests are also candidates, and any read error aborts cleanup rather than deleting from partial results. Reads run in parallel on the shared executor with only file paths kept in memory; fast-append tables drop no manifests and read no manifest files.
  • gc.enabled: Java rejects all expiration when gc.enabled is false because Java deletes files by default. Here, metadata-only expiration stays allowed; only clean_expired_files() checks gc.enabled in the latest table metadata.
  • Concurrent refs: commit() reloads the latest table metadata to catch refs already pointing at selected snapshots, then adds AssertRefSnapshotId for non-main refs while allowing concurrent appends to main. A new branch or tag on a selected snapshot, or a main reset to one, between reload and commit is not detected; the catalog drops that ref with the snapshot and its files are deleted.
  • Encrypted tables: commit() builds the encryption manager before committing so a missing KMS client fails without expiring snapshots, matching purge_table. Cleanup uses the pre-commit manager for expired manifest lists (in case commit drops their keys) and the post-commit manager for retained ones (so concurrent encrypted writes have their keys).

Are these changes tested?

Yes, in tests/table/test_expire_snapshots.py:

  • Default and read cost: Omitting clean_expired_files() or passing enabled=False skips manifest list reads and deletes nothing. Shared manifests are read once for live entries only, and fast-append history reads no manifests.
  • Deleted vs kept files: Unreferenced data, delete, manifest, manifest list, statistics, and partition statistics files (directly through RemoveSnapshotsUpdate) are deleted. Files needed by retained snapshots, tags, shared statistics paths, or concurrently committed snapshots stay intact.
  • Concurrent refs: Rejecting snapshots referenced before reload (including a stale table refreshed after selection), failing on non-main ref moves after reload, and allowing concurrent appends to main.
  • Encrypted tables: Missing KMS client raises before committing without deleting files. With a KMS client, cleanup decrypts both expired manifest lists (even when commit drops their keys) and a concurrently committed retained snapshot using a new post-commit key.
  • Failures and preconditions: Commit failure deletes nothing, a single-file delete OSError is skipped and logged, and a corrupt retained manifest aborts cleanup while keeping the expiration committed. Non-autocommit and gc.enabled=false raise before committing.

Are there any user-facing changes?

Yes. ExpireSnapshots adds clean_expired_files(enabled: bool = True):

table.maintenance.expire_snapshots().clean_expired_files().older_than(cutoff).commit()

After the expiration commits:

Deleted Kept
Data and delete files of expired snapshots not referenced as live by any remaining snapshot Files referenced as live by any remaining snapshot
Manifests and manifest lists of expired snapshots not used by any remaining snapshot Previous metadata files
Statistics and partition statistics files of expired snapshots Statistics and partition statistics files still referenced by metadata after commit
Orphan files never referenced by any snapshot

Preconditions (commit() raises ValueError and expires nothing if unmet):

  • An autocommit transaction.
  • gc.enabled = true in the latest table metadata.
  • No branch or tag in the latest table metadata pointing at a selected snapshot.
  • A key management client on the table when the table is encrypted.

On cleanup failure:

  • A file whose deletion raises OSError is skipped with a warning.
  • If a manifest list or manifest cannot be read, no files are deleted.
  • On any other exception, files not yet deleted remain on storage.
  • In the last two cases, a warning with a traceback is logged and the expiration stays committed. Because the expired snapshots are gone from metadata, leftover files can only be removed by an orphan-file job in another engine, such as Spark's remove_orphan_files procedure.

Without clean_expired_files() (or with enabled=False), expire_snapshots behaves unchanged. mkdocs/docs/api.md documents the new option under snapshot expiration.

AI Disclosure

Grok Bot, working for dragonknightk, assisted with the changes, the description, and the verification. All content was reviewed by a human, and the submitter understands and can maintain these changes.

Closes issue 2604

# Rationale for this change

`expire_snapshots` only rewrites the table metadata, so files that only expired snapshots referenced stay on the file system. Trino and Spark both clean those up.

This adds an opt-in `clean_expired_files()` step, following the approach agreed in the issue: after the expiration has committed, compare the expired snapshots against the snapshots left in the table and delete the difference, without listing the object store. ʕ•ᴥ•ʔ

### How files are chosen

Similar to Iceberg Java's `ReachableFileCleanup`, but more conservative:

1. **Candidates:** entries (including DELETED entries) of manifests used by the expired snapshots and by no snapshot left in the table.
2. **Subtract:** if there are candidates, read the live entries of every manifest left in the table and remove their paths.
3. **Abort on read failure:** if any manifest list or manifest cannot be read, nothing is deleted.

Read cost:

- When snapshots are selected, the manifest lists of the expired and the remaining snapshots are read.
- A table written only with fast appends reads no manifests, because no manifest goes away.
- Reads run in parallel on the shared executor, and only file paths are kept in memory.

### Concurrent ref changes

Without a check, the catalog would drop a branch or tag that another writer created on a snapshot being expired, and the cleanup would delete files that ref still needs. So `commit()` reloads the latest table metadata first:

| Change by another writer | Result |
|---|---|
| Before the reload: a branch or tag points at a selected snapshot | `ValueError`, nothing is expired |
| After the reload: a branch or tag other than `main` is moved or removed | commit fails (`AssertRefSnapshotId`), nothing is deleted |
| After the reload: an append to `main` | expiration succeeds (`main` is not asserted) |
| After the reload: a new branch or tag on a selected snapshot, or `main` reset to one | **not detected**: the catalog drops that ref with the snapshot, and its files are deleted |

### `gc.enabled` differs from Java

Java rejects any expiration when `gc.enabled` is false, because its expiration deletes files by default. Here, expiring without `clean_expired_files()` only changes the metadata, so it stays allowed; only `clean_expired_files()` raises a `ValueError`. This matches the consensus in the issue that deleting files is opt-in. The value is read from the latest table metadata.

## Are these changes tested?

Yes, in `tests/table/test_expire_snapshots.py`:

- **Default:** no call, or `enabled=False` after enabling, deletes nothing.
- **Deleted vs kept:** see the table under user-facing changes, including files still used by retained snapshots, tags, or snapshots another writer committed.
- **Read cost:** a shared manifest is read once and only for live entries; a fast-append history reads no manifests.
- **Concurrent refs:** every row of the table above except the undetected one, including a table object refreshed after the selection.
- **Failures:** commit failure deletes nothing; a failed delete is skipped and logged; a corrupt retained manifest stops the cleanup while the expiration stays committed; autocommit and `gc.enabled` checks.

## Are there any user-facing changes?

Yes. `ExpireSnapshots` gets a new `clean_expired_files(enabled: bool = True)` method:

```python
table.maintenance.expire_snapshots().clean_expired_files().older_than(cutoff).commit()
```

After the expiration has committed:

| Deleted | Kept |
|---|---|
| Data and delete files of the expired snapshots that no remaining snapshot references as live | Files any remaining snapshot references as live |
| Manifests and manifest lists of the expired snapshots that no remaining snapshot uses | Previous metadata files |
| Statistics and partition statistics files of the expired snapshots | Statistics and partition statistics files the metadata after the commit still references |
| | Orphan files no snapshot ever referenced |

On failure:

- A file whose deletion raises an `OSError` is skipped and a warning is logged.
- A manifest list or manifest that cannot be read: no files are deleted.
- Any other exception: files not deleted yet are kept.
- In both of the last two cases, a warning with the traceback is logged and the expiration stays committed. The expired snapshots are gone from the metadata, so the cleanup cannot be rerun; leftover files can only be removed by an orphan file cleanup in another engine, such as Spark's `remove_orphan_files` procedure.

Requirements (otherwise `commit()` raises a `ValueError` before anything is expired):

- an autocommit transaction
- `gc.enabled = true` in the latest table metadata
- no branch or tag in the latest table metadata pointing at a selected snapshot

Without `clean_expired_files()`, or with `enabled=False`, `expire_snapshots` behaves as before (๑•̀ㅂ•́)و✧ The expire-snapshots section of `mkdocs/docs/api.md` documents the new option.

## AI Disclosure

Human-led contribution. Grok Bot, working for dragonknightk, assisted with this change. All submitted content was reviewed by a human before submission.
@github-actions

Copy link
Copy Markdown

This pull request has been marked as stale due to 30 days of inactivity. It will be closed in 1 week if no further activity occurs. If you think that's incorrect or this pull request requires a review, please simply write any comment. If closed, you can revive the PR at any time and @mention a reviewer or discuss it on the dev@iceberg.apache.org list. Thank you for your contributions.

@github-actions github-actions Bot added the stale label Nov 30, 2026
@michaelteo

Copy link
Copy Markdown

We'd also find this feature valuable.

We use pyiceberg only (no Spark), and today we have no way to delete the files that stay behind after expiring snapshots. Our tables are fully overwritten every month and then compacted, so these leftover files add up quickly.

We tested this branch (b152031) in two setups, for different reasons:

1. Locally (SQL catalog): does it delete the right files?
A local setup let us try several write patterns quickly and check every file by hand.

  • After appends, a full overwrite and a compaction-style rewrite, expiring the old snapshots with clean_expired_files() deleted all 24 files that were no longer used and kept the 6 that were. The table still read the same rows.
  • Without clean_expired_files(), all 24 unused files stayed — so the test does catch the difference.
  • When only one partition was overwritten, it deleted only that partition's old files. Files still used by the current table were kept.

2. On S3 with the Glue catalog: does it work in a real setup?
We wanted to confirm it works on real cloud storage, and on files compacted by a different engine — which is where most of our leftover files come from.

  • We compacted the table with Athena (OPTIMIZE … REWRITE DATA USING BIN_PACK), then expired the older snapshots.
  • All 18 files that the compaction had replaced were deleted, and the 3 current files were kept.
  • Athena and pyiceberg both still read the same rows.

Safety checks (both setups)

  • An uncommitted file in the data folder (imitating a write in progress) was not deleted.
  • Expiring a snapshot that a tag points to was refused, and so was expiring with gc.enabled=false; nothing was expired in either case.

One small observation: with the s3fs FileIO, an empty folder-marker key (ending in /) appeared for each partition folder the cleanup emptied. This is probably s3fs behavior, not this PR.

Also noting that #4364 (now merged) closes the partition-statistics gap that the tests here work around.

Testing and this comment were prepared with AI assistance (Claude), and reviewed by me.

…pshots-delete-files

Signed-off-by: dragonknightk <37928252+dragonknightk@users.noreply.github.com>
Closes issue 2604

# Rationale for this change

`expire_snapshots` only updates table metadata, leaving unreferenced files on storage. This adds an opt-in `clean_expired_files()` step matching issue 2604: after the expiration commits, compare expired snapshots against retained snapshots and delete the difference without listing object storage.

Key design choices compared with Iceberg Java:

- **Reachable file diff:** Like Java's `ReachableFileCleanup`, only manifests dropped by expired snapshots can hold newly unreferenced files, and any live entry in a retained manifest keeps its file. Unlike Java, `DELETED` entries in dropped manifests are also candidates, and any read error aborts cleanup rather than deleting from partial results. Reads run in parallel on the shared executor with only file paths kept in memory; fast-append tables drop no manifests and read no manifest files.
- **`gc.enabled`:** Java rejects all expiration when `gc.enabled` is false because Java deletes files by default. Here, metadata-only expiration stays allowed; only `clean_expired_files()` checks `gc.enabled` in the latest table metadata.
- **Concurrent refs:** `commit()` reloads the latest table metadata to catch refs already pointing at selected snapshots, then adds `AssertRefSnapshotId` for non-`main` refs while allowing concurrent appends to `main`. A new branch or tag on a selected snapshot, or a `main` reset to one, between reload and commit is not detected; the catalog drops that ref with the snapshot and its files are deleted.
- **Encrypted tables:** `commit()` builds the encryption manager before committing so a missing KMS client fails without expiring snapshots, matching `purge_table`. Cleanup uses the pre-commit manager for expired manifest lists (in case commit drops their keys) and the post-commit manager for retained ones (so concurrent encrypted writes have their keys).

## Are these changes tested?

Yes, in `tests/table/test_expire_snapshots.py`:

- **Default and read cost:** Omitting `clean_expired_files()` or passing `enabled=False` skips manifest list reads and deletes nothing. Shared manifests are read once for live entries only, and fast-append history reads no manifests.
- **Deleted vs kept files:** Unreferenced data, delete, manifest, manifest list, statistics, and partition statistics files (directly through `RemoveSnapshotsUpdate`) are deleted. Files needed by retained snapshots, tags, shared statistics paths, or concurrently committed snapshots stay intact.
- **Concurrent refs:** Rejecting snapshots referenced before reload (including a stale table refreshed after selection), failing on non-`main` ref moves after reload, and allowing concurrent appends to `main`.
- **Encrypted tables:** Missing KMS client raises before committing without deleting files. With a KMS client, cleanup decrypts both expired manifest lists (even when commit drops their keys) and a concurrently committed retained snapshot using a new post-commit key.
- **Failures and preconditions:** Commit failure deletes nothing, a single-file delete `OSError` is skipped and logged, and a corrupt retained manifest aborts cleanup while keeping the expiration committed. Non-autocommit and `gc.enabled=false` raise before committing.

## Are there any user-facing changes?

Yes. `ExpireSnapshots` adds `clean_expired_files(enabled: bool = True)`:

```python
table.maintenance.expire_snapshots().clean_expired_files().older_than(cutoff).commit()
```

After the expiration commits:

| Deleted | Kept |
|---|---|
| Data and delete files of expired snapshots not referenced as live by any remaining snapshot | Files referenced as live by any remaining snapshot |
| Manifests and manifest lists of expired snapshots not used by any remaining snapshot | Previous metadata files |
| Statistics and partition statistics files of expired snapshots | Statistics and partition statistics files still referenced by metadata after commit |
| | Orphan files never referenced by any snapshot |

Preconditions (`commit()` raises `ValueError` and expires nothing if unmet):

- An autocommit transaction.
- `gc.enabled = true` in the latest table metadata.
- No branch or tag in the latest table metadata pointing at a selected snapshot.
- A key management client on the table when the table is encrypted.

On cleanup failure:

- A file whose deletion raises `OSError` is skipped with a warning.
- If a manifest list or manifest cannot be read, no files are deleted.
- On any other exception, files not yet deleted remain on storage.
- In the last two cases, a warning with a traceback is logged and the expiration stays committed. Because the expired snapshots are gone from metadata, leftover files can only be removed by an orphan-file job in another engine, such as Spark's `remove_orphan_files` procedure.

Without `clean_expired_files()` (or with `enabled=False`), `expire_snapshots` behaves unchanged. `mkdocs/docs/api.md` documents the new option under snapshot expiration.

Signed-off-by: dragonknightk <37928252+dragonknightk@users.noreply.github.com>
@dragonknightk

Copy link
Copy Markdown
Contributor Author

Thanks so much for testing this end-to-end across both local SQL and S3/Glue with Athena compaction, @michaelteo! That's super helpful validation. The trailing-slash empty folder marker does sound like s3fs behavior since cleanup only calls FileIO.delete on individual file paths. I just merged latest main, dropped the partition-statistics test workaround now that #4364 is in, and updated cleanup to handle encrypted tables cleanly as well.

@michaelteo

Copy link
Copy Markdown

I hope the input helps as additional test so this can be merged

This branch has not been deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove deleted data files with expire_snapshots

2 participants