zhuxiangyi commented on code in PR #10199:
URL: https://github.com/apache/paimon/pull/10199#discussion_r4111566477


##########
paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/procedure/RollbackToAsLatestProcedure.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.paimon.spark.procedure;
+
+import org.apache.paimon.FileStore;
+import org.apache.paimon.Snapshot;
+import org.apache.paimon.table.FileStoreTable;
+import org.apache.paimon.table.sink.TableCommitImpl;
+import org.apache.paimon.tag.Tag;
+import org.apache.paimon.utils.Preconditions;
+import org.apache.paimon.utils.SnapshotManager;
+import org.apache.paimon.utils.StringUtils;
+import org.apache.paimon.utils.TagManager;
+
+import org.apache.spark.sql.catalyst.InternalRow;
+import org.apache.spark.sql.connector.catalog.Identifier;
+import org.apache.spark.sql.connector.catalog.TableCatalog;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.Metadata;
+import org.apache.spark.sql.types.StructField;
+import org.apache.spark.sql.types.StructType;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.UUID;
+
+import static org.apache.spark.sql.types.DataTypes.LongType;
+import static org.apache.spark.sql.types.DataTypes.StringType;
+
+/**
+ * Rollback to a snapshot or tag as the latest snapshot, without dropping the 
snapshots and tags
+ * created after it (unlike {@link RollbackProcedure}). Mirrors Flink's {@code
+ * rollback_to_as_latest} procedure.
+ */
+public class RollbackToAsLatestProcedure extends BaseProcedure {
+
+    private static final String ROLLBACK_TO_AS_LATEST_TAG_PREFIX = 
"rollback-to-as-latest-";
+
+    private static final ProcedureParameter[] PARAMETERS =
+            new ProcedureParameter[] {
+                ProcedureParameter.required("table", StringType),
+                ProcedureParameter.optional("tag", StringType),
+                ProcedureParameter.optional("snapshot_id", LongType)
+            };
+
+    private static final StructType OUTPUT_TYPE =
+            new StructType(
+                    new StructField[] {
+                        new StructField(
+                                "previous_snapshot_id",
+                                DataTypes.LongType,
+                                false,
+                                Metadata.empty()),
+                        new StructField(
+                                "rolled_back_snapshot_id",
+                                DataTypes.LongType,
+                                false,
+                                Metadata.empty()),
+                        new StructField(
+                                "current_snapshot_id", DataTypes.LongType, 
false, Metadata.empty())
+                    });
+
+    protected RollbackToAsLatestProcedure(TableCatalog tableCatalog) {
+        super(tableCatalog);
+    }
+
+    @Override
+    public ProcedureParameter[] parameters() {
+        return PARAMETERS;
+    }
+
+    @Override
+    public StructType outputType() {
+        return OUTPUT_TYPE;
+    }
+
+    @Override
+    public InternalRow[] call(InternalRow args) {
+        Identifier tableIdent = toIdentifier(args.getString(0), 
PARAMETERS[0].name());
+        String tagName = args.isNullAt(1) ? null : args.getString(1);
+        Long snapshotId = args.isNullAt(2) ? null : args.getLong(2);
+
+        return modifyPaimonTable(
+                tableIdent,
+                table -> {
+                    FileStoreTable fileStoreTable = (FileStoreTable) table;
+                    FileStore<?> store = fileStoreTable.store();
+                    Snapshot latestSnapshot = 
store.snapshotManager().latestSnapshot();
+                    Preconditions.checkNotNull(
+                            latestSnapshot, "Latest snapshot is null, can not 
roll back.");
+
+                    boolean hasTag = 
!StringUtils.isNullOrWhitespaceOnly(tagName);
+                    boolean hasSnapshot = snapshotId != null;
+                    Preconditions.checkArgument(
+                            hasTag != hasSnapshot,
+                            "Must specify exactly one of tag and 
snapshot_id.");
+
+                    TagManager tagManager = store.newTagManager();
+                    Tag targetTag;
+                    Snapshot targetSnapshot;
+                    if (hasTag) {
+                        targetTag = tagManager.getOrThrow(tagName);
+                        targetSnapshot = targetTag.trimToSnapshot();
+                    } else {
+                        targetTag = null;
+                        targetSnapshot = findSnapshot(store, tagManager, 
snapshotId);
+                    }
+
+                    String createdRollbackTag = null;
+                    String commitUser = ROLLBACK_TO_AS_LATEST_TAG_PREFIX + 
UUID.randomUUID();
+                    try {
+                        if (!hasTag) {
+                            createdRollbackTag =
+                                    createRollbackToAsLatestTag(tagManager, 
targetSnapshot);
+                            targetTag = 
tagManager.getOrThrow(createdRollbackTag);
+                        }
+                        try (TableCommitImpl commit = 
fileStoreTable.newCommit(commitUser)) {
+                            boolean success = 
commit.rollbackToAsLatest(targetTag);
+                            Preconditions.checkState(
+                                    success,
+                                    "Failed to roll back to snapshot %s as 
latest.",
+                                    targetSnapshot.id());
+                        }
+                    } catch (Exception e) {
+                        try {
+                            deleteCreatedRollbackTagIfNotCommitted(
+                                    store,
+                                    tagManager,
+                                    createdRollbackTag,
+                                    latestSnapshot.id() + 1,

Review Comment:
   Could we avoid using the previously read `latestSnapshot.id() + 1` to decide 
whether the rollback committed? `FileStoreCommitImpl.rollbackToAsLatest()` 
reads the latest snapshot again, so another writer can commit between these two 
reads without causing a commit conflict.
   
   For example:
   1. This procedure reads latest = 3.
   2. Another writer commits snapshot 4.
   3. The rollback successfully commits snapshot 5.
   4. A post-commit callback throws.
   5. Cleanup checks snapshot 4, sees a different `commitUser`, and deletes the 
protection tag even though snapshot 5 committed successfully.
   
   I reproduced this through the Spark SQL procedure using a deterministically 
interleaved real commit and an injected post-commit callback failure. Snapshot 
5 was initially readable, but the protection tag was gone; expiring the older 
snapshots then deleted the restored data file, and `SELECT` failed with 
`FileNotFoundException`. The control case with the same callback failure but no 
interleaved commit retained the tag and remained readable after expiration.
   
   Please establish the actual commit outcome rather than infer it from this 
stale snapshot ID; when the outcome is uncertain, retain the protection tag. A 
regression test should cover the interleaved commit + post-commit failure + 
subsequent snapshot expiration 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]

Reply via email to