amogh-jahagirdar commented on code in PR #4578:
URL: https://github.com/apache/iceberg/pull/4578#discussion_r885250237


##########
core/src/main/java/org/apache/iceberg/RemoveSnapshots.java:
##########
@@ -161,21 +175,138 @@ public List<Snapshot> apply() {
 
   private TableMetadata internalApply() {
     this.base = ops.refresh();
+    if (base.snapshots().isEmpty()) {
+      return base;
+    }
 
     Set<Long> idsToRetain = Sets.newHashSet();
-    List<Long> ancestorIds = SnapshotUtil.ancestorIds(base.currentSnapshot(), 
base::snapshot);
-    if (minNumSnapshots >= ancestorIds.size()) {
-      idsToRetain.addAll(ancestorIds);
-    } else {
-      idsToRetain.addAll(ancestorIds.subList(0, minNumSnapshots));
+
+    // Compute branch snapshots
+    Map<SnapshotRef, Set<Long>> branchSnapshots = 
computeBranchSnapshots(base.refs().values());
+
+    // Identify dangling snapshots which should be retained
+    Set<Long> danglingSnapshotsToRetain = 
computeDanglingSnapshotsToRetain(branchSnapshots);
+    idsToRetain.addAll(danglingSnapshotsToRetain);
+
+    // Identify refs that should be removed
+    Map<String, SnapshotRef> retainedRefs = computeRetainedRefs(base.refs());
+    Map<Long, List<String>> retainedIdToRefs = Maps.newHashMap();
+    for (Map.Entry<String, SnapshotRef> retainedRefEntry : 
retainedRefs.entrySet()) {
+      long snapshotId = retainedRefEntry.getValue().snapshotId();
+      retainedIdToRefs.putIfAbsent(snapshotId, Lists.newArrayList());
+      retainedIdToRefs.get(snapshotId).add(retainedRefEntry.getKey());
+      idsToRetain.add(snapshotId);
+    }
+
+    for (long idToRemove : idsToRemove) {
+      List<String> refsForId = retainedIdToRefs.get(idToRemove);
+      Preconditions.checkArgument(refsForId == null,
+          "Cannot expire %s. Still referenced by refs: %s", idToRemove, 
refsForId);
+    }
+
+    Set<Long> branchSnapshotsToRetain = 
computeAllBranchSnapshotsToRetain(retainedRefs.values(), branchSnapshots);
+    idsToRetain.addAll(branchSnapshotsToRetain);
+    TableMetadata.Builder updatedMetaBuilder = TableMetadata.buildFrom(base);
+
+    base.snapshots().stream()
+        .map(Snapshot::snapshotId)
+        .filter(snapshot -> !idsToRetain.contains(snapshot))
+        .forEach(idsToRemove::add);
+    updatedMetaBuilder.removeSnapshots(idsToRemove);
+
+    base.refs().keySet().stream()
+        .filter(ref -> !retainedRefs.containsKey(ref))
+        .forEach(updatedMetaBuilder::removeRef);
+
+    return updatedMetaBuilder.build();
+  }
+
+  private Map<SnapshotRef, Set<Long>> 
computeBranchSnapshots(Collection<SnapshotRef> refs) {
+    Map<SnapshotRef, Set<Long>> branchSnapshots = Maps.newHashMap();
+    for (SnapshotRef ref : refs) {
+      if (ref.isBranch()) {
+        Set<Long> branchAncestors = Sets.newLinkedHashSet();
+        Iterable<Snapshot> snapshots = 
SnapshotUtil.ancestorsOf(ref.snapshotId(), base::snapshot);
+        snapshots.forEach(snapshot -> 
branchAncestors.add(snapshot.snapshotId()));
+        branchSnapshots.put(ref, branchAncestors);
+      }
+    }
+
+    return branchSnapshots;
+  }
+
+  private Map<String, SnapshotRef> computeRetainedRefs(Map<String, 
SnapshotRef> refs) {
+    Map<String, SnapshotRef> retainedRefs = Maps.newHashMap();
+    for (Map.Entry<String, SnapshotRef> refEntry : refs.entrySet()) {
+      String name = refEntry.getKey();
+      SnapshotRef ref = refEntry.getValue();
+      if (name.equals(SnapshotRef.MAIN_BRANCH)) {
+        retainedRefs.put(name, ref);
+        continue;
+      }
+
+      Snapshot snapshot = base.snapshot(ref.snapshotId());
+      long maxRefAgeMs = ref.maxRefAgeMs() != null ? ref.maxRefAgeMs() : 
defaultMaxRefAgeMs;
+      if (snapshot != null) {
+        long refAgeMs = now - snapshot.timestampMillis();
+        if (refAgeMs <= maxRefAgeMs) {
+          retainedRefs.put(name, ref);
+        }
+      } else {
+        LOG.warn("Removing invalid ref {}: snapshot {} does not exist", name, 
ref.snapshotId());
+      }
+    }
+
+    return retainedRefs;
+  }
+
+  private Set<Long> computeDanglingSnapshotsToRetain(Map<SnapshotRef, 
Set<Long>> branchSnapshots) {

Review Comment:
   @rdblue Let me know what you think of this logic to handle the case of 
unreferenced staged snapshots which should still be retained based on the 
default expiration age. I reorganized the code to minimize the computation of 
branch snapshots. I also should add a test for this case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to