Repository navigation
feat(transaction): add ExpireSnapshotsAction - #2591
Conversation
fce97ed to
9b45819
Compare
Add a metadata-only transaction action that removes snapshots, emitting a single RemoveSnapshots update. Physical file cleanup is left to a follow-up maintenance operation built on top of this action. Ref apache#1454
9b45819 to
0bdd123
Compare
laskoviymishka
left a comment
There was a problem hiding this comment.
A few things I'd fix before merge:
- Branch ancestors aren't protected. Age expiry only protects ref heads, so a shared ancestor of two branches can be expired while still reachable via parent_snapshot_id, leaving a dangling pointer. Same root cause makes retain_last global instead of per-branch (Java walks each branch's ancestry). I think this needs a per-branch ancestor walk.
- Commit requirement is too weak. We only emit UuidMatch, which leaves a race where a concurrent writer's new snapshot gets orphaned. SnapshotProducer guards this with a RefSnapshotIdMatch on main — I'd mirror that.
- expire_snapshot_ids replaces instead of accumulating, unlike add_data_files and friends.
- gc.enabled isn't checked — Java refuses to expire when it's false.
- The combined explicit + age test the description mentions doesn't actually exist.
Happy to take another pass once these are addressed.
|
|
||
| let mut snapshot_ids: Vec<i64> = to_expire.into_iter().collect(); | ||
| snapshot_ids.sort_unstable(); | ||
| Ok(snapshot_ids) |
There was a problem hiding this comment.
I think there's a subtle correctness issue here that's the deepest thing in the PR.
We protect only ref heads in protected_snapshot_ids, but age expiry walks a global pool. For two branches sharing a common base, the shared ancestor isn't a head, so it gets expired even though it's still reachable via parent_snapshot_id — afterwards that pointer dangles and tools that walk full ancestry (Flink, Trino CDC) see truncated history.
The same root cause bites retain_last: Java's computeBranchSnapshotsToRetain applies it per-branch along each ancestry chain, but here it's the N globally-most-recent across all branches. With branch A [A1,A2,A3] and branch B [B1,B2,B3], retain_last=2 keeps [B2,B3] globally and expires A2, which Java would retain.
I'd build the protected set by walking each branch's ancestor chain via parent_snapshot_id, stopping when count >= retain_last and timestamp < cutoff, then union that with the head set before age expiry. That's a bigger change, but I don't think we can ship age-based expiry without it. wdyt?
There was a problem hiding this comment.
Changed the logic so that we walk each branch's ancestor and retain based on both the count and age.
| use crate::transaction::tests::make_v2_table; | ||
|
|
||
| // `make_v2_table` carries an older snapshot (ts 1515100955770) and a current | ||
| // snapshot (ts 1555100955770). |
There was a problem hiding this comment.
UuidMatch alone leaves a race window. If another writer commits a new snapshot between snapshot_ids_to_expire and update_table, that snapshot is now live but its parent may be in our to-expire set — removing the parent orphans the new branch history, and the UUID check won't catch it because the table UUID is unchanged.
SnapshotProducer guards against exactly this with a RefSnapshotIdMatch on main (see snapshot.rs ~517). I'd add the same here:
TableRequirement::RefSnapshotIdMatch {
r#ref: "main".to_string(),
snapshot_id: table.metadata().current_snapshot_id(),
},Thoughts?
There was a problem hiding this comment.
Thanks for catching this. We have both requirements in commit now:
TableRequirement::UuidMatch {
uuid: metadata.uuid(),
},
TableRequirement::RefSnapshotIdMatch {
r#ref: MAIN_BRANCH.to_string(),
snapshot_id: metadata.current_snapshot_id(),
},
]))```
| pub fn retain_last(mut self, retain_last: usize) -> Self { | ||
| self.retain_last = Some(retain_last); | ||
| self | ||
| } |
There was a problem hiding this comment.
This replaces rather than accumulates, so expire_snapshot_ids(vec![A]).expire_snapshot_ids(vec![B]) silently drops A. Every other builder (add_data_files etc.) uses .extend(), so the inconsistency is surprising, and since this is public surface, switching to accumulate later would be a breaking change.
I'd accumulate and take an iterator to match add_data_files:
pub fn expire_snapshot_ids(mut self, snapshot_ids: impl IntoIterator<Item = i64>) -> Self {
self.snapshot_ids.extend(snapshot_ids);
self
}If replace is intentional, I'd rename to set_snapshot_ids and document it — but accumulate feels right here.
There was a problem hiding this comment.
Makes sense. Updated to self.explicit_ids_to_remove.extend(snapshot_ids);. I have also made the names of some variables more descriptive.
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::sync::Arc; |
There was a problem hiding this comment.
We never check gc.enabled before expiring. Java's RemoveSnapshots validates it in the constructor and refuses to run when it's false, since expiring metadata defeats a user's explicit decision to disable GC.
I'd read it at the top of commit (or snapshot_ids_to_expire) and bail:
if table.metadata().properties().get("gc.enabled").map(|v| v == "false").unwrap_or(false) {
return Err(Error::new(ErrorKind::DataInvalid,
"Cannot expire snapshots: gc.enabled is false"));
}|
|
||
| #[tokio::test] | ||
| async fn test_cannot_expire_current_snapshot() { | ||
| let table = make_v2_table(); |
There was a problem hiding this comment.
The PR description says the combined explicit + age path is tested, but I don't see a test that sets both — and it's the primary interaction between the two code paths, so it's the most likely regression site.
I'd add one with non-overlapping targets: expire_snapshot_ids(vec![X]).expire_older_than_ms(cutoff) where an age-qualifying snapshot Y is distinct from X, asserting both land in the result.
There was a problem hiding this comment.
Added a test for the combination of all three test_explicit_and_age_combine
Address the review on apache#2591: - Per-branch ancestor retention (Java RemoveSnapshots): protect shared ancestors reachable via parent_snapshot_id and make retain_last per-branch, honoring per-ref min_snapshots_to_keep and max_snapshot_age_ms. - Ref aging: drop non-main branches/tags whose head is older than their max_ref_age_ms, emitting RemoveSnapshotRef, and expire snapshots that only an aged-out ref retained. - Assert RefSnapshotIdMatch on main alongside UuidMatch (concurrent-writer race). - expire_snapshot_ids accumulates (impl IntoIterator) like add_data_files. - Refuse to run when gc.enabled is false; reject retain_last(0). - Combine explicit ids with age-based selection. Table-level history.expire.* defaults are left for a follow-up. Ref apache#2145
Add the history.expire.max-snapshot-age-ms / min-snapshots-to-keep / max-ref-age-ms properties to TableProperties (same shape as commit.retry.*). The expire action now falls back to these when a knob is not set explicitly, mirroring Java RemoveSnapshots' constructor: the cutoff defaults to now - max-snapshot-age-ms (5 days) so age-based selection always runs, retain_last defaults to min-snapshots-to-keep, and refs without their own max_ref_age_ms age out against max-ref-age-ms (Long.MAX_VALUE, i.e. never). Completes the history.expire.* default fallback deferred by apache#2591. Ref apache#2145
Add the history.expire.max-snapshot-age-ms / min-snapshots-to-keep / max-ref-age-ms properties to TableProperties (same shape as commit.retry.*). The expire action now falls back to these when a knob is not set explicitly, mirroring Java RemoveSnapshots' constructor: the cutoff defaults to now - max-snapshot-age-ms (5 days) so age-based selection always runs, retain_last defaults to min-snapshots-to-keep, and refs without their own max_ref_age_ms age out against max-ref-age-ms (Long.MAX_VALUE, i.e. never). Completes the history.expire.* default fallback deferred by apache#2591. Ref apache#2145
#2664) ## Which issue does this PR close? - Part of #2145. ## What changes are included in this PR? Defaults snapshot expiry to the table's `history.expire.*` properties when the corresponding knob is not set explicitly, completing the default fallback that #2591 deferred (its `plan()` carried two `TODO`s for exactly this). - `TableProperties` gains three fields (and their consts/defaults), in the same shape as the existing `commit.retry.*` properties: - `history.expire.max-snapshot-age-ms` (default 5 days) - `history.expire.min-snapshots-to-keep` (default 1) - `history.expire.max-ref-age-ms` (default `i64::MAX`, i.e. never) - `ExpireSnapshotsAction::plan()` now mirrors Java `RemoveSnapshots`' constructor: - the age cutoff defaults to `now - max-snapshot-age-ms`, so age-based selection **always runs** even for an explicit-id-only call (only file cleanup, out of scope here, keys off an explicit id in Java); - `retain_last` defaults to `min-snapshots-to-keep`; - refs without their own `max_ref_age_ms` age out against `max-ref-age-ms` (default never). Defaults and names mirror Java's `TableProperties` (`MAX_SNAPSHOT_AGE_MS_DEFAULT = 5 days`, `MIN_SNAPSHOTS_TO_KEEP_DEFAULT = 1`, `MAX_REF_AGE_MS_DEFAULT = Long.MAX_VALUE`). ## Are these changes tested? Yes — unit tests in `expire_snapshots.rs` (27 total, up from 25). Two new tests cover the always-on default cutoff (a >5-day-old snapshot is expired with no args while a recent one is kept) and the `history.expire.min-snapshots-to-keep` floor (the whole chain is retained despite age). Explicit-id-only tests pin the cutoff off to isolate that behavior now that the default age path always runs. `public-api.txt` regenerated for the new public fields/consts; clippy and fmt are clean. Co-authored-by: Dhruv Arya <[email protected]>
…ots (#2667) ## Which issue does this PR close? Part of #2145. Extends #2591 (the `ExpireSnapshotsAction`) and #2664 (the `history.expire.*` defaults). ## What changes are included in this PR? When `ExpireSnapshotsAction` expires snapshots, it now also drops the statistics and partition-statistics metadata entries tied to each expired snapshot, mirroring Java `RemoveSnapshots` (`TableMetadata.Builder.removeSnapshots`, which calls `removeStatistics`/`removePartitionStatistics` for each removed snapshot). For every expired snapshot that has a statistics entry, `commit()` emits a `RemoveStatistics` update; likewise `RemovePartitionStatistics` for a partition-statistics entry. Only entries that actually exist produce an update, matching Java's behavior of recording a change only when an entry is present. This is metadata-only, physical deletion of the puffin files those entries point at is part of the file-cleanup maintenance operation (mirroring Java's `FileCleanupStrategy`), not this PR. ## Are these changes tested? Yes. New unit tests cover: an expired snapshot's statistics and partition-statistics entries are removed while a retained snapshot keeps its own; an expired snapshot with no statistics emits no removal; and only the statistics variant that is actually present is removed. --------- Co-authored-by: Dhruv Arya <[email protected]>
Which issue does this PR close?
Revives the effort to close #2145 (originally filed as #1454), which has been attempted before but never landed. This is the metadata-only piece; physical file cleanup will build on top of it in a follow-up.
What changes are included in this PR?
Adds an
ExpireSnapshotsActionto the transaction API, reachable astx.expire_snapshots()and following the same convention as the other actions. It selects the snapshots to expire and emits the correspondingRemoveSnapshots(and, for aged-out refs,RemoveSnapshotRef) updates. It deliberately does not touch any files; that is left to a follow-up so this change stays focused on metadata.Selection follows Java
RemoveSnapshots:expire_snapshot_ids, which accumulates across calls likeadd_data_files) and age-based expiry (expire_older_than_ms) are combined — a snapshot is expired if it is named explicitly or selected by age.retain_lastsnapshots (a per-refmin_snapshots_to_keepoverrides it) plus any ancestor newer than the cutoff (a per-refmax_snapshot_age_msoverrides the cutoff for that branch). A shared ancestor reachable from a retained branch is therefore never expired, while a tag protects only its target, not its ancestry.mainbranch or tag whose head is older than itsmax_ref_age_msis removed, and snapshots that only an aged-out ref retained then become expirable.TableMetadataBuilder::remove_snapshotswould drop the ref silently).UuidMatchandRefSnapshotIdMatchonmainto guard against a concurrent writer, refuses to run whengc.enabledis false, and rejectsretain_last(0).The first commit is the original action; the second is the response to review feedback (per-branch ancestry retention, ref aging, the stronger commit requirement, the accumulating builder, and the
gc.enabled/retain_lastguards).Left for follow-ups: the table-level
history.expire.*defaults (defaulting the cutoff tonow - max-snapshot-age-ms,retain_lasttomin-snapshots-to-keep, and ref aging tomax-ref-age-ms) andcleanExpiredMetadata(removing unreferenced partition specs and schemas).Are these changes tested?
Yes — 25 unit tests cover explicit-id expiry and ref-head protection, the combined explicit + age path, per-branch retention and shared-ancestor protection, per-ref
min_snapshots_to_keepandmax_snapshot_age_ms(including differing windows across branches), the tag-vs-branch ancestry distinction, ref aging for both branches and tags, theRefSnapshotIdMatchrequirement, thegc.enabledandretain_last(0)rejections, and unreferenced-but-young retention.