lasdf1234 commented on code in PR #14972:
URL: https://github.com/apache/gravitino/pull/14972#discussion_r4594511731


##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java:
##########
@@ -0,0 +1,125 @@
+/*
+ * 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.gravitino.iceberg.service.idempotency.mapper.provider.base;
+
+import static 
org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper.TABLE_NAME;
+
+import 
org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.ibatis.annotations.Param;
+
+/** SQL statements shared by the MySQL and H2 entity stores. */
+public class IcebergIdempotencyKeyBaseSQLProvider {
+  /**
+   * Returns the reservation INSERT.
+   *
+   * @param po reservation to persist
+   * @return SQL statement
+   */
+  public String insert(@Param("po") IcebergIdempotencyKeyPO po) {
+    return "INSERT INTO "
+        + TABLE_NAME
+        + " (idempotency_key, operation_binding, claim, audit_info, 
created_at, expires_at)"
+        + " VALUES (#{po.idempotencyKey}, #{po.operationBinding}, #{po.claim}, 
#{po.auditInfo},"
+        + " #{po.createdAt}, #{po.expiresAt})";
+  }
+
+  /**
+   * Returns an atomic replacement of an expired reservation or response.
+   *
+   * @param po reservation to persist
+   * @return SQL statement
+   */
+  public String replaceExpired(@Param("po") IcebergIdempotencyKeyPO po) {
+    return "UPDATE "
+        + TABLE_NAME
+        + " SET operation_binding = #{po.operationBinding}, claim = 
#{po.claim},"
+        + " http_status = NULL, response_summary = NULL, audit_info = 
#{po.auditInfo},"
+        + " created_at = #{po.createdAt}, expires_at = #{po.expiresAt}"
+        + " WHERE idempotency_key = #{po.idempotencyKey} AND expires_at <= 
#{po.createdAt}";
+  }
+
+  /**
+   * Returns only a finalized, unexpired response.
+   *
+   * @param idempotencyKey canonical UUIDv7 key
+   * @param nowMs current time in unix epoch milliseconds
+   * @return SQL statement
+   */
+  public String selectRecord(
+      @Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long 
nowMs) {
+    return "SELECT idempotency_key AS idempotencyKey, operation_binding AS 
operationBinding,"
+        + " claim, http_status AS httpStatus, response_summary AS 
responseSummary,"
+        + " audit_info AS auditInfo, created_at AS createdAt, expires_at AS 
expiresAt FROM "
+        + TABLE_NAME
+        + " WHERE idempotency_key = #{idempotencyKey}"
+        + " AND http_status IS NOT NULL AND expires_at > #{nowMs}";
+  }
+
+  /**
+   * Returns a finalization guarded by the reservation's claim and expiry.
+   *
+   * @param idempotencyKey canonical UUIDv7 key
+   * @param claim reservation fencing token
+   * @param httpStatus response status
+   * @param responseSummary serialized response body, or null for an empty body
+   * @param nowMs current time in unix epoch milliseconds
+   * @return SQL statement
+   */
+  public String finalizeRecord(
+      @Param("idempotencyKey") String idempotencyKey,
+      @Param("claim") long claim,
+      @Param("httpStatus") int httpStatus,
+      @Param("responseSummary") String responseSummary,
+      @Param("nowMs") long nowMs) {
+    return "UPDATE "
+        + TABLE_NAME
+        + " SET http_status = #{httpStatus}, response_summary = 
#{responseSummary}"
+        + " WHERE idempotency_key = #{idempotencyKey} AND claim = #{claim}"
+        + " AND http_status IS NULL AND expires_at > #{nowMs}";
+  }
+
+  /**
+   * Returns a release guarded by the reservation's claim. Finalized responses 
are retained.
+   *
+   * @param idempotencyKey canonical UUIDv7 key
+   * @param claim reservation fencing token
+   * @return SQL statement
+   */
+  public String deleteReservation(
+      @Param("idempotencyKey") String idempotencyKey, @Param("claim") long 
claim) {
+    return "DELETE FROM "
+        + TABLE_NAME
+        + " WHERE idempotency_key = #{idempotencyKey} AND claim = #{claim} AND 
http_status IS NULL";

Review Comment:
   **Medium (interaction with manager):** `deleteReservation` is claim-fenced 
but has no expiry guard. Combined with `IcebergIdempotencyManager` (phase-1): 
if the mutation returns a non-5xx response but `tryFinalize` fails, `finalized` 
stays false and `release` removes the unfinalized row. The client already got 
success; a retry with the same key can run the mutation again.
   
   JDBC makes this more visible under DB pressure / large `response_summary` 
than in-memory. Worth hardening finalize retention or not releasing after a 
committed non-5xx response.



##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.gravitino.iceberg.service.idempotency;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import 
org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper;
+import 
org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Durable idempotency records shared by replicas using the same Gravitino 
relational entity store.
+ * Requires an initialized entity store, as provided in auxiliary mode. The 
database schema must be
+ * upgraded before this store is enabled.
+ *
+ * <p>Reservations commit independently of catalog transactions. Claim tokens 
fence stale finalize
+ * and release calls, but cannot undo catalog side effects or make the catalog 
mutation and response
+ * persistence atomic. Expired keys can be reserved again without waiting for 
background cleanup.
+ * Replicas must synchronize system clocks: a fast clock can reclaim a key 
another replica still
+ * considers live. There is no clock-skew grace period.
+ *
+ * <p>Share one store per service instance across requests. Each store owns a 
cleanup scheduler that
+ * is stopped by {@link #close()}; the relational entity store owns the shared 
connection pool.
+ */
+public class JdbcIdempotencyStore implements IdempotencyStore {
+  private static final Logger LOG = 
LoggerFactory.getLogger(JdbcIdempotencyStore.class);
+  @VisibleForTesting static final int PURGE_BATCH_SIZE = 1000;
+  @VisibleForTesting static final int MAX_PURGE_BATCHES = 100;
+
+  private final Clock clock;
+  private SqlSessionFactory sessionFactory;
+  private ScheduledExecutorService purgeScheduler;
+
+  /** Creates a store using the system UTC clock. */
+  public JdbcIdempotencyStore() {
+    this(Clock.systemUTC());
+  }
+
+  @VisibleForTesting
+  JdbcIdempotencyStore(Clock clock) {
+    this.clock = clock;
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    Preconditions.checkState(
+        sessionFactory == null, "JDBC idempotency store is already 
initialized");
+    Duration interval =
+        Duration.parse(
+            new 
IcebergConfig(properties).get(IcebergConfig.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL));
+    long intervalMs = interval.toMillis();
+    Preconditions.checkArgument(
+        intervalMs > 0, "Idempotency cleanup interval must be at least 1ms");
+    SqlSessionFactory factory;
+    try {
+      factory = SqlSessionFactoryHelper.getInstance().getSqlSessionFactory();
+    } catch (IllegalStateException e) {
+      throw new IllegalStateException(
+          "JDBC idempotency storage requires an initialized Gravitino 
relational entity store "
+              + "(auxiliary mode); it is not available in the standalone 
Iceberg REST server",
+          e);
+    }
+    // Core cannot discover mappers in the auxiliary service's class loader 
during its startup.
+    Configuration configuration = factory.getConfiguration();
+    synchronized (configuration) {
+      if (!configuration.hasMapper(IcebergIdempotencyKeyMapper.class)) {
+        configuration.addMapper(IcebergIdempotencyKeyMapper.class);
+      }
+    }
+    // Fail startup, rather than the first mutation, when the database has not 
been upgraded.
+    try (SqlSession session = factory.openSession()) {
+      session
+          .getMapper(IcebergIdempotencyKeyMapper.class)
+          .selectRecord("00000000-0000-7000-8000-000000000000", 
clock.millis());
+      session.commit();
+    }
+    sessionFactory = factory;
+    purgeScheduler =
+        Executors.newSingleThreadScheduledExecutor(
+            runnable -> {
+              Thread thread = new Thread(runnable, 
"iceberg-idempotency-purge");
+              thread.setDaemon(true);
+              return thread;
+            });
+    purgeScheduler.scheduleWithFixedDelay(
+        this::purgeExpiredRecords, intervalMs, intervalMs, 
TimeUnit.MILLISECONDS);
+  }
+
+  @Override
+  public ReserveResult reserve(
+      String idempotencyKey, String operationBinding, long claim, long 
expiresAtMs) {
+    String key = IdempotencyKeys.canonicalize(idempotencyKey);
+    Preconditions.checkArgument(operationBinding != null, "operationBinding 
should not be null");
+    IcebergIdempotencyKeyPO po =
+        IcebergIdempotencyKeyPO.reserved(key, operationBinding, claim, 
clock.millis(), expiresAtMs);
+    for (int attempt = 0; attempt < 2; attempt++) {
+      try {
+        execute(mapper -> mapper.insert(po));
+        return ReserveResult.RESERVED;
+      } catch (RuntimeException e) {
+        if (!ExceptionUtils.isDuplicateKey(e)) {
+          throw e;
+        }
+      }
+      // The failed insert has rolled back before this update, including on 
PostgreSQL.
+      // Separate transactions also avoid upgrading duplicate-insert locks on 
MySQL.
+      if (attempt == 0 && execute(mapper -> mapper.replaceExpired(po)) > 0) {

Review Comment:
   **Low:** `replaceExpired` runs only when `attempt == 0`. If the row becomes 
expired after a failed replace on attempt 0 but before the second INSERT, the 
loop returns `DUPLICATE` without another reclaim. `replay()` then treats 
unfinalized rows as empty and returns in-flight 409 + Retry-After — wrong error 
semantics in a narrow window (self-corrects on the next HTTP retry; not a 
duplicate-mutation bug).



##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.gravitino.iceberg.service.idempotency;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import 
org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper;
+import 
org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Durable idempotency records shared by replicas using the same Gravitino 
relational entity store.
+ * Requires an initialized entity store, as provided in auxiliary mode. The 
database schema must be
+ * upgraded before this store is enabled.
+ *
+ * <p>Reservations commit independently of catalog transactions. Claim tokens 
fence stale finalize
+ * and release calls, but cannot undo catalog side effects or make the catalog 
mutation and response
+ * persistence atomic. Expired keys can be reserved again without waiting for 
background cleanup.

Review Comment:
   **High:** Expiry is only enforced at reserve/finalize/load — there is no 
in-flight lease renewal. Once `expires_at <= now`, another replica can 
`replaceExpired` and run the same mutation while the original request is still 
executing; the original `finalize` becomes a no-op and `release` can still 
delete by claim alone.
   
   This is a real at-most-once break under slow mutations, short 
`idempotency-key-lifetime`, or clock skew. Consider heartbeat/lease extension 
while work is in progress, or document hard operational constraints (lifetime ≫ 
max mutation latency + clock skew).



##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java:
##########
@@ -0,0 +1,227 @@
+/*
+ * 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.gravitino.iceberg.service.idempotency;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import 
org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper;
+import 
org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Durable idempotency records shared by replicas using the same Gravitino 
relational entity store.
+ * Requires an initialized entity store, as provided in auxiliary mode. The 
database schema must be
+ * upgraded before this store is enabled.
+ *
+ * <p>Reservations commit independently of catalog transactions. Claim tokens 
fence stale finalize
+ * and release calls, but cannot undo catalog side effects or make the catalog 
mutation and response
+ * persistence atomic. Expired keys can be reserved again without waiting for 
background cleanup.
+ * Replicas must synchronize system clocks: a fast clock can reclaim a key 
another replica still
+ * considers live. There is no clock-skew grace period.
+ *
+ * <p>Share one store per service instance across requests. Each store owns a 
cleanup scheduler that
+ * is stopped by {@link #close()}; the relational entity store owns the shared 
connection pool.
+ */
+public class JdbcIdempotencyStore implements IdempotencyStore {
+  private static final Logger LOG = 
LoggerFactory.getLogger(JdbcIdempotencyStore.class);
+  @VisibleForTesting static final int PURGE_BATCH_SIZE = 1000;
+  @VisibleForTesting static final int MAX_PURGE_BATCHES = 100;
+
+  private final Clock clock;
+  private SqlSessionFactory sessionFactory;
+  private ScheduledExecutorService purgeScheduler;
+
+  /** Creates a store using the system UTC clock. */
+  public JdbcIdempotencyStore() {
+    this(Clock.systemUTC());
+  }
+
+  @VisibleForTesting
+  JdbcIdempotencyStore(Clock clock) {
+    this.clock = clock;
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    Preconditions.checkState(
+        sessionFactory == null, "JDBC idempotency store is already 
initialized");
+    Duration interval =
+        Duration.parse(
+            new 
IcebergConfig(properties).get(IcebergConfig.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL));
+    long intervalMs = interval.toMillis();
+    Preconditions.checkArgument(
+        intervalMs > 0, "Idempotency cleanup interval must be at least 1ms");
+    SqlSessionFactory factory;
+    try {
+      factory = SqlSessionFactoryHelper.getInstance().getSqlSessionFactory();
+    } catch (IllegalStateException e) {
+      throw new IllegalStateException(
+          "JDBC idempotency storage requires an initialized Gravitino 
relational entity store "
+              + "(auxiliary mode); it is not available in the standalone 
Iceberg REST server",
+          e);
+    }
+    // Core cannot discover mappers in the auxiliary service's class loader 
during its startup.
+    Configuration configuration = factory.getConfiguration();
+    synchronized (configuration) {
+      if (!configuration.hasMapper(IcebergIdempotencyKeyMapper.class)) {
+        configuration.addMapper(IcebergIdempotencyKeyMapper.class);
+      }
+    }
+    // Fail startup, rather than the first mutation, when the database has not 
been upgraded.
+    try (SqlSession session = factory.openSession()) {
+      session
+          .getMapper(IcebergIdempotencyKeyMapper.class)
+          .selectRecord("00000000-0000-7000-8000-000000000000", 
clock.millis());
+      session.commit();
+    }
+    sessionFactory = factory;
+    purgeScheduler =
+        Executors.newSingleThreadScheduledExecutor(
+            runnable -> {
+              Thread thread = new Thread(runnable, 
"iceberg-idempotency-purge");
+              thread.setDaemon(true);
+              return thread;
+            });
+    purgeScheduler.scheduleWithFixedDelay(
+        this::purgeExpiredRecords, intervalMs, intervalMs, 
TimeUnit.MILLISECONDS);
+  }
+
+  @Override
+  public ReserveResult reserve(
+      String idempotencyKey, String operationBinding, long claim, long 
expiresAtMs) {
+    String key = IdempotencyKeys.canonicalize(idempotencyKey);
+    Preconditions.checkArgument(operationBinding != null, "operationBinding 
should not be null");
+    IcebergIdempotencyKeyPO po =
+        IcebergIdempotencyKeyPO.reserved(key, operationBinding, claim, 
clock.millis(), expiresAtMs);
+    for (int attempt = 0; attempt < 2; attempt++) {
+      try {
+        execute(mapper -> mapper.insert(po));
+        return ReserveResult.RESERVED;
+      } catch (RuntimeException e) {
+        if (!ExceptionUtils.isDuplicateKey(e)) {
+          throw e;

Review Comment:
   **Medium:** Non–duplicate-key DB errors (timeout, connection loss, missing 
table) propagate as raw `RuntimeException` and surface as generic 500 via 
`IcebergExceptionMapper`. Clients cannot tell whether a reservation committed 
(`execute` commits per call), which can encourage unsafe retries.
   
   Consider mapping reserve failures to a clearer conflict/retryable response, 
or documenting that 500 on reserve must not be blindly retried with the same 
key without checking catalog state.



-- 
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