This is an automated email from the ASF dual-hosted git repository.

roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new b6d3834175 [#12049] feat(iceberg-common): add Idempotency-Key storage 
SPI and in-memory store (#14927)
b6d3834175 is described below

commit b6d383417525dddd8d25f188b2cbf1a77b4dfa48
Author: Akshay Thorat <[email protected]>
AuthorDate: Thu Nov 12 18:42:19 2026 -0800

    [#12049] feat(iceberg-common): add Idempotency-Key storage SPI and 
in-memory store (#14927)
    
    ### What changes were proposed in this pull request?
    
    Add the Idempotency-Key storage SPI, UUIDv7 validation and
    canonicalization, immutable records, an in-memory store, and a
    configurable store factory. Claim tokens fence stale finalize/release
    calls; expiry follows each record's deadline.
    
    Replaces #12470 at reviewer request, with identical code including all
    review fixes. Endpoint integration remains in #12474; the JDBC store is
    a separate follow-up.
    
    ### Why are the changes needed?
    
    Provide the storage foundation for replaying responses when clients
    retry Iceberg mutations, and an interface for a future shared, durable
    backend.
    
    Part of #12049.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Adds four configuration properties under `gravitino.iceberg-rest.`:
    `idempotency-enabled` (default `false`), `idempotency-key-lifetime`
    (`PT30M`), `idempotency-store-type` (`in-memory`), and
    `idempotency-max-entries` (`10000`). No endpoint behavior changes until
    #12474 lands.
    
    The in-memory store is best-effort: capacity eviction can remove
    in-flight reservations and allow duplicate execution. This limitation is
    documented explicitly.
    
    ### How was this patch tested?
    
    Ran `./gradlew spotlessApply` and `./gradlew
    :iceberg:iceberg-common:test -PskipITs` on JDK 17: 174 tests passed.
    
    Coverage includes concurrent reservation, UUID case normalization, claim
    fencing, expiry, binding preservation, and factory cleanup.
    Initialization cleanup and exact-cutoff purge regression tests failed
    before their fixes and passed afterward.
---
 .../lakehouse/iceberg/IcebergConstants.java        |  12 +
 .../gravitino/iceberg/common/IcebergConfig.java    |  58 ++++
 .../common/idempotency/IdempotencyKeys.java        | 107 +++++++
 .../common/idempotency/IdempotencyRecord.java      | 219 ++++++++++++++
 .../common/idempotency/IdempotencyStore.java       | 134 +++++++++
 .../idempotency/IdempotencyStoreFactory.java       |  69 +++++
 .../idempotency/InMemoryIdempotencyStore.java      | 229 +++++++++++++++
 .../common/idempotency/TestIdempotencyKeys.java    |  93 ++++++
 .../idempotency/TestIdempotencyStoreFactory.java   | 155 ++++++++++
 .../idempotency/TestInMemoryIdempotencyStore.java  | 320 +++++++++++++++++++++
 10 files changed, 1396 insertions(+)

diff --git 
a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
 
b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
index 7b528d5478..4f5b2a4868 100644
--- 
a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
+++ 
b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
@@ -217,4 +217,16 @@ public class IcebergConstants {
   public static final String SCAN_PLAN_CACHE_IMPL = "scan-plan-cache-impl";
   public static final String SCAN_PLAN_CACHE_CAPACITY = 
"scan-plan-cache-capacity";
   public static final String SCAN_PLAN_CACHE_EXPIRE_MINUTES = 
"scan-plan-cache-expire-minutes";
+
+  /** Whether the Iceberg REST server honors the {@code Idempotency-Key} 
header. */
+  public static final String ICEBERG_IDEMPOTENCY_ENABLED = 
"idempotency-enabled";
+
+  /** Client reuse window for an idempotency key, as an ISO-8601 duration. */
+  public static final String ICEBERG_IDEMPOTENCY_KEY_LIFETIME = 
"idempotency-key-lifetime";
+
+  /** Storage backend holding idempotency records. */
+  public static final String ICEBERG_IDEMPOTENCY_STORE_TYPE = 
"idempotency-store-type";
+
+  /** Capacity of the in-memory idempotency store. */
+  public static final String ICEBERG_IDEMPOTENCY_MAX_ENTRIES = 
"idempotency-max-entries";
 }
diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
index c8046ce331..be6701b9b5 100644
--- 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
@@ -21,6 +21,8 @@ package org.apache.gravitino.iceberg.common;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableMap;
+import java.time.Duration;
+import java.time.format.DateTimeParseException;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -454,6 +456,53 @@ public class IcebergConfig extends Config implements 
OverwriteDefaultConfig {
           .checkValue(value -> value > 0, 
ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
           .createWithDefault(720);
 
+  /**
+   * Master switch for {@code Idempotency-Key} support. Disabled by default: 
when off the header is
+   * ignored and no key lifetime is advertised in {@code GET /v1/config}, 
which per the Iceberg REST
+   * spec tells clients the server does not support idempotency.
+   */
+  public static final ConfigEntry<Boolean> ICEBERG_IDEMPOTENCY_ENABLED =
+      new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_ENABLED)
+          .doc("Whether to honor the Idempotency-Key header on Iceberg REST 
mutation endpoints")
+          .version(ConfigConstants.VERSION_2_0_0)
+          .booleanConf()
+          .createWithDefault(false);
+
+  /** Client reuse window for an idempotency key, as an ISO-8601 duration. */
+  public static final ConfigEntry<String> ICEBERG_IDEMPOTENCY_KEY_LIFETIME =
+      new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_KEY_LIFETIME)
+          .doc(
+              "The client reuse window for an Idempotency-Key, an ISO-8601 
duration such as PT30M. "
+                  + "Advertised to clients as `idempotency-key-lifetime` in 
the config response")
+          .version(ConfigConstants.VERSION_2_0_0)
+          .stringConf()
+          .checkValue(
+              IcebergConfig::isPositiveDuration, "The value must be a positive 
ISO-8601 duration")
+          .createWithDefault("PT30M");
+
+  /** Storage backend holding idempotency records. */
+  public static final ConfigEntry<String> ICEBERG_IDEMPOTENCY_STORE_TYPE =
+      new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE)
+          .doc(
+              "The store holding Iceberg idempotency records, either the 
`in-memory` short name or "
+                  + "the fully-qualified class name of an `IdempotencyStore` 
implementation")
+          .version(ConfigConstants.VERSION_2_0_0)
+          .stringConf()
+          .checkValue(StringUtils::isNotBlank, 
ConfigConstants.NOT_BLANK_ERROR_MSG)
+          .createWithDefault("in-memory");
+
+  /** Capacity of the in-memory idempotency store. */
+  public static final ConfigEntry<Integer> ICEBERG_IDEMPOTENCY_MAX_ENTRIES =
+      new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_MAX_ENTRIES)
+          .doc(
+              "The maximum number of idempotency records retained by the 
in-memory store, records "
+                  + "beyond it are evicted before their reuse window elapses. 
Eviction can include "
+                  + "in-flight reservations, allowing retries to execute the 
mutation concurrently")
+          .version(ConfigConstants.VERSION_2_0_0)
+          .intConf()
+          .checkValue(value -> value > 0, 
ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)
+          .createWithDefault(10000);
+
   public String getJdbcDriver() {
     return get(JDBC_DRIVER);
   }
@@ -497,4 +546,13 @@ public class IcebergConfig extends Config implements 
OverwriteDefaultConfig {
         ConfigConstants.WEBSERVER_HTTPS_PORT,
         String.valueOf(DEFAULT_ICEBERG_REST_SERVICE_HTTPS_PORT));
   }
+
+  private static boolean isPositiveDuration(String value) {
+    try {
+      Duration duration = Duration.parse(value);
+      return !duration.isNegative() && !duration.isZero();
+    } catch (DateTimeParseException e) {
+      return false;
+    }
+  }
 }
diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java
new file mode 100644
index 0000000000..341cd1787a
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java
@@ -0,0 +1,107 @@
+/*
+ * 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.common.idempotency;
+
+import java.util.Locale;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+/**
+ * Validation helpers for the {@code Idempotency-Key} header.
+ *
+ * <p>The Iceberg REST spec requires the header value to be a UUIDv7 in string 
form as defined by <a
+ * href="https://www.rfc-editor.org/rfc/rfc9562";>RFC 9562</a>, with a fixed 
length of 36 characters.
+ * Rejecting malformed keys before touching the store keeps invalid requests 
off the storage path
+ * and guarantees the key space stays time-ordered, which keeps the 
primary-key index of a database
+ * backed store insert-friendly.
+ */
+public final class IdempotencyKeys {
+
+  /** Canonical (hyphenated) length of a UUID in string form, mandated by the 
Iceberg REST spec. */
+  public static final int KEY_LENGTH = 36;
+
+  /** UUID version reported by a UUIDv7 as defined by RFC 9562. */
+  private static final int UUID_VERSION_7 = 7;
+
+  /**
+   * Variant reported by {@link UUID#variant()} for the RFC 9562 variant, 
whose two most significant
+   * variant bits are {@code 10}.
+   */
+  private static final int RFC_9562_VARIANT = 2;
+
+  private static final Pattern CANONICAL_UUID =
+      Pattern.compile(
+          
"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
+
+  private IdempotencyKeys() {}
+
+  /**
+   * Returns whether the value is a UUIDv7 in canonical string form.
+   *
+   * @param idempotencyKey the raw header value, may be {@code null}
+   * @return {@code true} if the value is a valid RFC 9562 UUIDv7
+   */
+  public static boolean isValid(String idempotencyKey) {
+    if (idempotencyKey == null || idempotencyKey.length() != KEY_LENGTH) {
+      return false;
+    }
+    if (!CANONICAL_UUID.matcher(idempotencyKey).matches()) {
+      return false;
+    }
+    UUID uuid = UUID.fromString(idempotencyKey);
+    return uuid.version() == UUID_VERSION_7 && uuid.variant() == 
RFC_9562_VARIANT;
+  }
+
+  /**
+   * Validates the value and throws when it is not a UUIDv7 in canonical 
string form.
+   *
+   * @param idempotencyKey the raw header value, may be {@code null}
+   * @throws IllegalArgumentException if the value is not a valid RFC 9562 
UUIDv7, which the Iceberg
+   *     REST server maps to {@code 400 Bad Request}
+   */
+  public static void validate(String idempotencyKey) {
+    if (!isValid(idempotencyKey)) {
+      throw new IllegalArgumentException(
+          "Idempotency-Key: "
+              + idempotencyKey
+              + " is illegal, the Iceberg REST spec requires a UUIDv7 in 
string form (RFC 9562), "
+              + "for example 017f22e2-79b0-7cc3-98c4-dc0c0c07398f");
+    }
+  }
+
+  /**
+   * Validates the value and returns it in the lower-case form used for 
storage and comparison.
+   *
+   * <p>RFC 9562 section 4 defines the hexadecimal digits of a UUID as 
case-insensitive on input
+   * while specifying lower case on output, so {@code 017F22E2-...} and {@code 
017f22e2-...} name
+   * the same key. A client that retries with a differently-cased key is 
retrying the same logical
+   * operation, and folding the case here is what keeps that retry from being 
taken for a new
+   * request and re-running the mutation. It also keeps a database-backed 
store correct under a
+   * case-sensitive collation such as {@code utf8mb4_bin}, since only the 
folded form is ever
+   * written.
+   *
+   * @param idempotencyKey the raw header value, may be {@code null}
+   * @return the key folded to lower case
+   * @throws IllegalArgumentException if the value is not a valid RFC 9562 
UUIDv7
+   */
+  public static String canonicalize(String idempotencyKey) {
+    validate(idempotencyKey);
+    return idempotencyKey.toLowerCase(Locale.ROOT);
+  }
+}
diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java
new file mode 100644
index 0000000000..8b121148b7
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java
@@ -0,0 +1,219 @@
+/*
+ * 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.common.idempotency;
+
+import com.google.common.base.Preconditions;
+import java.util.Objects;
+import javax.annotation.Nullable;
+
+/**
+ * One stored idempotency record: the reservation for an in-flight mutation, 
and after finalization
+ * the response replayed to retries carrying the same key.
+ *
+ * <p>Instances are immutable; {@link #withResponse(int, String)} returns a 
new record rather than
+ * mutating this one. Timestamps are unix epoch milliseconds so that a 
database backed store can map
+ * them onto the {@code BIGINT} columns used by Gravitino's other metadata 
tables.
+ */
+public final class IdempotencyRecord {
+
+  private final String idempotencyKey;
+  private final String operationBinding;
+  private final long claim;
+  @Nullable private final Integer httpStatus;
+  @Nullable private final String responseSummary;
+  private final long createdAtMs;
+  private final long expiresAtMs;
+
+  private IdempotencyRecord(
+      String idempotencyKey,
+      String operationBinding,
+      long claim,
+      @Nullable Integer httpStatus,
+      @Nullable String responseSummary,
+      long createdAtMs,
+      long expiresAtMs) {
+    this.idempotencyKey = idempotencyKey;
+    this.operationBinding = operationBinding;
+    this.claim = claim;
+    this.httpStatus = httpStatus;
+    this.responseSummary = responseSummary;
+    this.createdAtMs = createdAtMs;
+    this.expiresAtMs = expiresAtMs;
+  }
+
+  /**
+   * Creates a reserved (not yet finalized) record.
+   *
+   * @param idempotencyKey the client-provided UUIDv7 key
+   * @param operationBinding request identity, for example {@code POST
+   *     /v1/cat1/namespaces/ns1/tables}
+   * @param claim the reserving caller's fencing token
+   * @param createdAtMs reservation time in unix epoch millis
+   * @param expiresAtMs time after which the record may be purged, in unix 
epoch millis
+   * @return a record in the reserved state
+   */
+  public static IdempotencyRecord reserved(
+      String idempotencyKey,
+      String operationBinding,
+      long claim,
+      long createdAtMs,
+      long expiresAtMs) {
+    Preconditions.checkArgument(idempotencyKey != null, "idempotencyKey should 
not be null");
+    Preconditions.checkArgument(operationBinding != null, "operationBinding 
should not be null");
+    return new IdempotencyRecord(
+        idempotencyKey, operationBinding, claim, null, null, createdAtMs, 
expiresAtMs);
+  }
+
+  /**
+   * Returns a copy of this record in the finalized state, carrying the 
response to replay.
+   *
+   * @param status HTTP status of the original response
+   * @param summary serialized response body, {@code null} for responses 
without a body
+   * @return a new finalized record
+   */
+  public IdempotencyRecord withResponse(int status, @Nullable String summary) {
+    return new IdempotencyRecord(
+        idempotencyKey, operationBinding, claim, status, summary, createdAtMs, 
expiresAtMs);
+  }
+
+  /**
+   * Returns the fencing token of the caller that reserved this record.
+   *
+   * <p>A store accepts a finalize or release only from the caller holding 
this token, so a caller
+   * whose reservation was already dropped cannot disturb the record of 
whoever reserved the key
+   * next.
+   *
+   * @return the reserving caller's claim
+   */
+  public long claim() {
+    return claim;
+  }
+
+  /**
+   * Returns the client-provided idempotency key.
+   *
+   * @return the UUIDv7 key in canonical string form
+   */
+  public String idempotencyKey() {
+    return idempotencyKey;
+  }
+
+  /**
+   * Returns the request identity this key was first used for. Retries that 
present the same key for
+   * a different operation violate the Iceberg REST spec and are rejected 
instead of replayed.
+   *
+   * @return the operation binding
+   */
+  public String operationBinding() {
+    return operationBinding;
+  }
+
+  /**
+   * Returns the HTTP status of the finalized response.
+   *
+   * @return the status code, or {@code null} while the record is still 
reserved
+   */
+  @Nullable
+  public Integer httpStatus() {
+    return httpStatus;
+  }
+
+  /**
+   * Returns the serialized response body replayed to retries.
+   *
+   * @return the response body, or {@code null} while the record is reserved 
or for responses
+   *     without a body
+   */
+  @Nullable
+  public String responseSummary() {
+    return responseSummary;
+  }
+
+  /**
+   * Returns when the key was reserved.
+   *
+   * @return reservation time in unix epoch millis
+   */
+  public long createdAtMs() {
+    return createdAtMs;
+  }
+
+  /**
+   * Returns when the record becomes eligible for purging.
+   *
+   * @return expiry time in unix epoch millis
+   */
+  public long expiresAtMs() {
+    return expiresAtMs;
+  }
+
+  /**
+   * Returns whether the mutation finished and its response can be replayed.
+   *
+   * @return {@code true} once the record carries a response
+   */
+  public boolean isFinalized() {
+    return httpStatus != null;
+  }
+
+  @Override
+  public boolean equals(Object other) {
+    if (this == other) {
+      return true;
+    }
+    if (!(other instanceof IdempotencyRecord)) {
+      return false;
+    }
+    IdempotencyRecord that = (IdempotencyRecord) other;
+    return createdAtMs == that.createdAtMs
+        && expiresAtMs == that.expiresAtMs
+        && claim == that.claim
+        && Objects.equals(idempotencyKey, that.idempotencyKey)
+        && Objects.equals(operationBinding, that.operationBinding)
+        && Objects.equals(httpStatus, that.httpStatus)
+        && Objects.equals(responseSummary, that.responseSummary);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(
+        idempotencyKey,
+        operationBinding,
+        claim,
+        httpStatus,
+        responseSummary,
+        createdAtMs,
+        expiresAtMs);
+  }
+
+  @Override
+  public String toString() {
+    return "IdempotencyRecord{idempotencyKey="
+        + idempotencyKey
+        + ", operationBinding="
+        + operationBinding
+        + ", httpStatus="
+        + httpStatus
+        + ", createdAtMs="
+        + createdAtMs
+        + ", expiresAtMs="
+        + expiresAtMs
+        + "}";
+  }
+}
diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java
new file mode 100644
index 0000000000..645e682fd0
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java
@@ -0,0 +1,134 @@
+/*
+ * 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.common.idempotency;
+
+import java.io.Closeable;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+
+/**
+ * Storage for {@code Idempotency-Key} records, pluggable so that a deployment 
can trade durability
+ * for latency.
+ *
+ * <p>The server drives a store through a reserve-execute-finalize cycle: 
exactly one caller wins
+ * {@link #reserve}, executes the mutation, and then either {@link 
#finalizeRecord finalizes} the
+ * response for later replay or {@link #release releases} the reservation so 
the client can retry
+ * with the same key. Implementations must make {@link #reserve} atomic across 
every caller that can
+ * see the same storage, since that is the only thing standing between a 
retried request and a
+ * duplicate mutation.
+ *
+ * <p>A reservation does not always survive until its owner finishes: a 
bounded store can drop it
+ * under memory pressure, and a purge can remove it once it expires. The key 
is then free, and
+ * another caller can reserve it while the first is still running. Every call 
that mutates an
+ * existing record therefore carries the {@code claim} its caller reserved 
with, and implementations
+ * must ignore the call when the stored claim differs, so a caller that has 
lost its reservation
+ * cannot finalize or release a record that now belongs to someone else.
+ *
+ * <p>Keys are compared in the folded form returned by {@link 
IdempotencyKeys#canonicalize}, so
+ * implementations must canonicalize before reading or writing storage rather 
than trusting the
+ * caller to have done it.
+ *
+ * <p>Implementations must be thread-safe and are expected to have a public 
no-argument constructor
+ * so they can be loaded by class name.
+ */
+public interface IdempotencyStore extends Closeable {
+
+  /** Outcome of an attempt to claim a key. */
+  enum ReserveResult {
+    /** The key was newly claimed by this caller, which now owns the mutation. 
*/
+    RESERVED,
+    /** A non-expired reservation or finalized record already exists for the 
key. */
+    DUPLICATE
+  }
+
+  /**
+   * Initializes the store from the Iceberg REST server configuration.
+   *
+   * @param properties the full Iceberg REST server configuration
+   */
+  void initialize(Map<String, String> properties);
+
+  /**
+   * Atomically attempts to claim a key. An expired record is treated as 
absent, so the key can be
+   * reserved again without waiting for a purge.
+   *
+   * <p>The store retains the operation binding but does not compare it when 
returning {@link
+   * ReserveResult#DUPLICATE}. The REST handler owns binding checks: when 
{@link #load} returns a
+   * finalized record, the handler must reject a different binding with {@code 
409 Conflict} instead
+   * of replaying it. When the key is still in flight, {@code load} returns 
empty and the handler
+   * returns the same in-flight {@code 409 Conflict}, regardless of whether 
the bindings match.
+   *
+   * @param idempotencyKey the client-provided UUIDv7 key
+   * @param operationBinding request identity, for example {@code POST
+   *     /v1/cat1/namespaces/ns1/tables}
+   * @param claim a fencing token identifying this attempt, which the caller 
must generate afresh
+   *     for every reservation and pass back to {@link #finalizeRecord} and 
{@link #release}
+   * @param expiresAtMs time after which the record may be purged, in unix 
epoch millis
+   * @return {@link ReserveResult#RESERVED} if newly claimed, {@link 
ReserveResult#DUPLICATE} if a
+   *     non-expired reservation or finalized record for this key already 
exists
+   */
+  ReserveResult reserve(
+      String idempotencyKey, String operationBinding, long claim, long 
expiresAtMs);
+
+  /**
+   * Loads a finalized record for replay.
+   *
+   * @param idempotencyKey the client-provided key
+   * @return the record, or {@link Optional#empty()} if the key is unknown, 
expired, or still
+   *     reserved by an in-flight request
+   */
+  Optional<IdempotencyRecord> load(String idempotencyKey);
+
+  /**
+   * Marks a reserved key finalized, storing the response replayed to later 
retries.
+   *
+   * <p>The call is a no-op when the record has already expired or been 
purged, so it is not
+   * resurrected, and when the stored claim differs, so a caller that has lost 
its reservation
+   * cannot overwrite the record of whoever holds the key now.
+   *
+   * @param idempotencyKey the client-provided key
+   * @param claim the claim this caller reserved with
+   * @param httpStatus HTTP status of the original response
+   * @param responseSummary serialized response body, {@code null} for 
responses without a body
+   */
+  void finalizeRecord(
+      String idempotencyKey, long claim, int httpStatus, @Nullable String 
responseSummary);
+
+  /**
+   * Releases a reservation so the client can retry with the same key. Called 
when the mutation
+   * failed in a way the Iceberg REST spec treats as retryable, which is any 
{@code 5xx} response.
+   *
+   * <p>The call is a no-op when the stored claim differs, so a caller that 
has lost its reservation
+   * cannot free a key another caller is currently executing under.
+   *
+   * @param idempotencyKey the client-provided key
+   * @param claim the claim this caller reserved with
+   */
+  void release(String idempotencyKey, long claim);
+
+  /**
+   * Purges records whose reuse window has elapsed.
+   *
+   * @param beforeMs cutoff in unix epoch millis; records expiring at or 
before this time are
+   *     removed
+   * @return the number of records purged
+   */
+  int purgeExpired(long beforeMs);
+}
diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java
new file mode 100644
index 0000000000..ef789624e6
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java
@@ -0,0 +1,69 @@
+/*
+ * 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.common.idempotency;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Loads the {@link IdempotencyStore} named by {@code 
idempotency-store-type}. */
+public class IdempotencyStoreFactory {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(IdempotencyStoreFactory.class);
+
+  /**
+   * Short names for the built-in stores, so that a deployment does not have 
to spell out a
+   * fully-qualified class name for them.
+   */
+  private static final ImmutableMap<String, String> STORE_CLASS_NAMES =
+      ImmutableMap.of("in-memory", 
InMemoryIdempotencyStore.class.getCanonicalName());
+
+  private IdempotencyStoreFactory() {}
+
+  /**
+   * Creates and initializes the configured store.
+   *
+   * @param icebergConfig the Iceberg REST server configuration
+   * @return an initialized store
+   * @throws RuntimeException if the store cannot be instantiated or 
initialized
+   */
+  public static IdempotencyStore create(IcebergConfig icebergConfig) {
+    String storeType = 
icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_STORE_TYPE);
+    String storeClassName = STORE_CLASS_NAMES.getOrDefault(storeType, 
storeType);
+    LOG.info("Load Iceberg idempotency store: {}.", storeClassName);
+    IdempotencyStore store = null;
+    try {
+      store =
+          (IdempotencyStore) 
Class.forName(storeClassName).getDeclaredConstructor().newInstance();
+      store.initialize(icebergConfig.getAllConfig());
+      return store;
+    } catch (Exception e) {
+      if (store != null) {
+        try {
+          store.close();
+        } catch (Exception closeFailure) {
+          e.addSuppressed(closeFailure);
+        }
+      }
+      throw new RuntimeException(
+          "Failed to create Iceberg idempotency store by name " + storeType, 
e);
+    }
+  }
+}
diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java
new file mode 100644
index 0000000000..017b0e0701
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java
@@ -0,0 +1,229 @@
+/*
+ * 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.common.idempotency;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.Expiry;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import com.google.common.annotations.VisibleForTesting;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Node-local {@link IdempotencyStore} backed by a Caffeine cache.
+ *
+ * <p>This store is best-effort and intended for single-node deployments, 
development, and tests. It
+ * is not durable, and it is not shared between replicas: a retry routed to 
another node, or to a
+ * node that restarted, finds no record and re-executes the mutation. Its size 
bound can also evict
+ * a record before its reuse window elapses, including an in-flight 
reservation. A retry can then
+ * reserve the same key and run the mutation concurrently with the original 
request. At-most-once
+ * execution therefore depends on the reservation remaining cached; claim 
fencing prevents stale
+ * writes to a replacement record but cannot prevent duplicate mutations after 
eviction. Size the
+ * cache for all keys within the reuse window, including in-flight requests. 
Production deployments
+ * that need durable deduplication or run more than one replica should use a 
shared, durable store
+ * instead.
+ *
+ * <p>Each record's own {@code expiresAtMs} decides whether it still counts, 
so a record past its
+ * deadline reads as absent whether or not the cache has reclaimed it yet. 
Caffeine's expiry only
+ * reclaims memory, which keeps behavior independent of when maintenance runs 
and matches how a
+ * database-backed store compares {@code expires_at} in its queries.
+ */
+public class InMemoryIdempotencyStore implements IdempotencyStore {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(InMemoryIdempotencyStore.class);
+
+  /** Evictions between two warnings, so an undersized cache is visible 
without flooding the log. */
+  private static final long EVICTION_LOG_INTERVAL = 1000;
+
+  private final AtomicLong sizeEvictions = new AtomicLong();
+  private final LongSupplier clock;
+
+  private Cache<String, IdempotencyRecord> cache;
+
+  /** Creates a store reading wall-clock time. */
+  public InMemoryIdempotencyStore() {
+    this(System::currentTimeMillis);
+  }
+
+  @VisibleForTesting
+  InMemoryIdempotencyStore(LongSupplier clock) {
+    this.clock = clock;
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    IcebergConfig icebergConfig = new IcebergConfig(properties);
+    int maxEntries = 
icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_MAX_ENTRIES);
+    this.cache =
+        Caffeine.newBuilder()
+            // Expiry off each record's own deadline rather than 
expireAfterWrite, which restarts on
+            // every write: finalizing a record is a write, and would 
otherwise push a record
+            // finalized late in its window well past the lifetime advertised 
to clients.
+            .expireAfter(
+                new Expiry<String, IdempotencyRecord>() {
+                  @Override
+                  public long expireAfterCreate(
+                      String key, IdempotencyRecord record, long 
currentTimeNanos) {
+                    return remainingNanos(record);
+                  }
+
+                  @Override
+                  public long expireAfterUpdate(
+                      String key,
+                      IdempotencyRecord record,
+                      long currentTimeNanos,
+                      long currentDurationNanos) {
+                    return remainingNanos(record);
+                  }
+
+                  @Override
+                  public long expireAfterRead(
+                      String key,
+                      IdempotencyRecord record,
+                      long currentTimeNanos,
+                      long currentDurationNanos) {
+                    return remainingNanos(record);
+                  }
+                })
+            .maximumSize(maxEntries)
+            .removalListener(
+                (String key, IdempotencyRecord record, RemovalCause cause) -> {
+                  if (cause == RemovalCause.SIZE) {
+                    onSizeEviction(maxEntries);
+                  }
+                })
+            .build();
+    LOG.info("Initialized in-memory Iceberg idempotency store, max entries: 
{}.", maxEntries);
+  }
+
+  @Override
+  public ReserveResult reserve(
+      String idempotencyKey, String operationBinding, long claim, long 
expiresAtMs) {
+    String key = IdempotencyKeys.canonicalize(idempotencyKey);
+    IdempotencyRecord reserved =
+        IdempotencyRecord.reserved(key, operationBinding, claim, 
clock.getAsLong(), expiresAtMs);
+    // A record past its deadline is treated as absent rather than waiting for 
the cache to reclaim
+    // it, so behavior turns on the record's own expiry instead of when 
maintenance happens to run.
+    AtomicBoolean claimed = new AtomicBoolean();
+    cache
+        .asMap()
+        .compute(
+            key,
+            (cacheKey, existing) -> {
+              if (existing == null || isExpired(existing)) {
+                claimed.set(true);
+                return reserved;
+              }
+              return existing;
+            });
+    return claimed.get() ? ReserveResult.RESERVED : ReserveResult.DUPLICATE;
+  }
+
+  @Override
+  public Optional<IdempotencyRecord> load(String idempotencyKey) {
+    return 
Optional.ofNullable(cache.getIfPresent(IdempotencyKeys.canonicalize(idempotencyKey)))
+        .filter(record -> !isExpired(record))
+        .filter(IdempotencyRecord::isFinalized);
+  }
+
+  @Override
+  public void finalizeRecord(
+      String idempotencyKey, long claim, int httpStatus, @Nullable String 
responseSummary) {
+    // computeIfPresent, so a record purged while the mutation was running is 
not resurrected. The
+    // claim check leaves a record reserved by someone else untouched.
+    cache
+        .asMap()
+        .computeIfPresent(
+            IdempotencyKeys.canonicalize(idempotencyKey),
+            (key, record) ->
+                record.claim() == claim && !isExpired(record)
+                    ? record.withResponse(httpStatus, responseSummary)
+                    : record);
+  }
+
+  @Override
+  public void release(String idempotencyKey, long claim) {
+    // Returning null removes the entry. A finalized record is left alone so 
that a late release
+    // cannot drop a response another request may still replay, and so is a 
record whose claim has
+    // moved on, so a caller that lost its reservation cannot free a key 
someone else is executing.
+    cache
+        .asMap()
+        .computeIfPresent(
+            IdempotencyKeys.canonicalize(idempotencyKey),
+            (key, record) -> record.isFinalized() || record.claim() != claim ? 
record : null);
+  }
+
+  @Override
+  public int purgeExpired(long beforeMs) {
+    int purged = 0;
+    Iterator<Map.Entry<String, IdempotencyRecord>> entries = 
cache.asMap().entrySet().iterator();
+    while (entries.hasNext()) {
+      Map.Entry<String, IdempotencyRecord> entry = entries.next();
+      if (entry.getValue().expiresAtMs() <= beforeMs
+          && cache.asMap().remove(entry.getKey(), entry.getValue())) {
+        purged += 1;
+      }
+    }
+    return purged;
+  }
+
+  @Override
+  public void close() {
+    if (cache != null) {
+      cache.invalidateAll();
+    }
+  }
+
+  @VisibleForTesting
+  long size() {
+    cache.cleanUp();
+    return cache.estimatedSize();
+  }
+
+  private boolean isExpired(IdempotencyRecord record) {
+    return record.expiresAtMs() <= clock.getAsLong();
+  }
+
+  private long remainingNanos(IdempotencyRecord record) {
+    long remainingMs = record.expiresAtMs() - clock.getAsLong();
+    return remainingMs <= 0 ? 0 : TimeUnit.MILLISECONDS.toNanos(remainingMs);
+  }
+
+  private void onSizeEviction(int maxEntries) {
+    long evictions = sizeEvictions.incrementAndGet();
+    if (evictions % EVICTION_LOG_INTERVAL == 1) {
+      LOG.warn(
+          "In-memory Iceberg idempotency store evicted {} record(s) before 
their reuse window "
+              + "elapsed; retries for evicted keys re-execute the mutation. 
Raise "
+              + "`idempotency-max-entries` (currently {}) or use a shared, 
durable store.",
+          evictions,
+          maxEntries);
+    }
+  }
+}
diff --git 
a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyKeys.java
 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyKeys.java
new file mode 100644
index 0000000000..c889b36782
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyKeys.java
@@ -0,0 +1,93 @@
+/*
+ * 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.common.idempotency;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class TestIdempotencyKeys {
+
+  @ParameterizedTest
+  @ValueSource(
+      strings = {
+        // The example from the Iceberg REST spec, in both cases.
+        "017F22E2-79B0-7CC3-98C4-DC0C0C07398F",
+        "017f22e2-79b0-7cc3-98c4-dc0c0c07398f",
+        // Variant octet 0b10xx, covering the whole RFC 9562 variant range.
+        "017f22e2-79b0-7cc3-88c4-dc0c0c07398f",
+        "017f22e2-79b0-7cc3-b8c4-dc0c0c07398f"
+      })
+  void testAcceptsUuidV7(String idempotencyKey) {
+    Assertions.assertTrue(IdempotencyKeys.isValid(idempotencyKey));
+    Assertions.assertDoesNotThrow(() -> 
IdempotencyKeys.validate(idempotencyKey));
+  }
+
+  @ParameterizedTest
+  @NullAndEmptySource
+  @ValueSource(
+      strings = {
+        // UUIDv4, the version nibble must be 7.
+        "f47ac10b-58cc-4372-a567-0e02b2c3d479",
+        // UUIDv1.
+        "c232ab00-9414-11ec-b3c8-9f6bdeced846",
+        // RFC 9562 requires the variant bits to be 10; this is the NCS 
variant.
+        "017f22e2-79b0-7cc3-28c4-dc0c0c07398f",
+        // The Microsoft variant.
+        "017f22e2-79b0-7cc3-c8c4-dc0c0c07398f",
+        // Not the canonical 36-character form.
+        "017f22e279b07cc398c4dc0c0c07398f",
+        "017f22e2-79b0-7cc3-98c4-dc0c0c07398",
+        "017f22e2-79b0-7cc3-98c4-dc0c0c07398ff",
+        "  017f22e2-79b0-7cc3-98c4-dc0c0c07398f  ",
+        // Right length, but not hexadecimal.
+        "017f22e2-79b0-7cc3-98c4-dc0c0c0739zz",
+        "not-a-uuid"
+      })
+  void testRejectsAnythingElse(String idempotencyKey) {
+    Assertions.assertFalse(IdempotencyKeys.isValid(idempotencyKey));
+    IllegalArgumentException exception =
+        Assertions.assertThrows(
+            IllegalArgumentException.class, () -> 
IdempotencyKeys.validate(idempotencyKey));
+    Assertions.assertTrue(exception.getMessage().contains("UUIDv7"), 
exception.getMessage());
+  }
+
+  @Test
+  void testNilUuidIsRejected() {
+    
Assertions.assertFalse(IdempotencyKeys.isValid("00000000-0000-0000-0000-000000000000"));
+  }
+
+  @Test
+  void testCanonicalizeFoldsCase() {
+    String expected = "017f22e2-79b0-7cc3-98c4-dc0c0c07398f";
+    Assertions.assertEquals(
+        expected, 
IdempotencyKeys.canonicalize("017F22E2-79B0-7CC3-98C4-DC0C0C07398F"));
+    Assertions.assertEquals(expected, IdempotencyKeys.canonicalize(expected));
+    Assertions.assertEquals(
+        expected, 
IdempotencyKeys.canonicalize("017f22E2-79b0-7CC3-98c4-DC0c0c07398F"));
+  }
+
+  @Test
+  void testCanonicalizeRejectsAnInvalidKey() {
+    Assertions.assertThrows(
+        IllegalArgumentException.class, () -> 
IdempotencyKeys.canonicalize("not-a-uuid"));
+  }
+}
diff --git 
a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyStoreFactory.java
 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyStoreFactory.java
new file mode 100644
index 0000000000..37b8e97006
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyStoreFactory.java
@@ -0,0 +1,155 @@
+/*
+ * 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.common.idempotency;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+public class TestIdempotencyStoreFactory {
+
+  @Test
+  void testCreateDefaultsToInMemoryStore() throws IOException {
+    try (IdempotencyStore store = IdempotencyStoreFactory.create(new 
IcebergConfig())) {
+      Assertions.assertInstanceOf(InMemoryIdempotencyStore.class, store);
+    }
+  }
+
+  @Test
+  void testCreateResolvesShortName() throws IOException {
+    IcebergConfig config =
+        new IcebergConfig(
+            ImmutableMap.of(IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE, 
"in-memory"));
+    try (IdempotencyStore store = IdempotencyStoreFactory.create(config)) {
+      Assertions.assertInstanceOf(InMemoryIdempotencyStore.class, store);
+    }
+  }
+
+  @Test
+  void testCreateResolvesCustomClassNameAndInitializesIt() throws IOException {
+    IcebergConfig config =
+        new IcebergConfig(
+            ImmutableMap.of(
+                IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE,
+                // Binary name, since Class.forName cannot resolve a nested 
class by canonical name.
+                RecordingIdempotencyStore.class.getName()));
+    try (IdempotencyStore store = IdempotencyStoreFactory.create(config)) {
+      Assertions.assertInstanceOf(RecordingIdempotencyStore.class, store);
+      Assertions.assertTrue(((RecordingIdempotencyStore) store).initialized);
+    }
+  }
+
+  @Test
+  void testCreateFailsForUnknownStore() {
+    IcebergConfig config =
+        new IcebergConfig(
+            ImmutableMap.of(
+                IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE, 
"com.example.NoSuchStore"));
+    Exception exception =
+        Assertions.assertThrows(
+            RuntimeException.class, () -> 
IdempotencyStoreFactory.create(config));
+    
Assertions.assertTrue(exception.getMessage().contains("com.example.NoSuchStore"));
+  }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  void testInitializationFailureClosesStoreAndPreservesCause(boolean 
failClose) {
+    FailingIdempotencyStore.closed = false;
+    IcebergConfig config =
+        new IcebergConfig(
+            ImmutableMap.of(
+                IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE,
+                FailingIdempotencyStore.class.getName(),
+                "fail-close",
+                Boolean.toString(failClose)));
+    RuntimeException failure =
+        Assertions.assertThrows(
+            RuntimeException.class, () -> 
IdempotencyStoreFactory.create(config));
+    Assertions.assertTrue(FailingIdempotencyStore.closed);
+    Assertions.assertEquals("initialization failed", 
failure.getCause().getMessage());
+    Assertions.assertEquals(failClose ? 1 : 0, 
failure.getCause().getSuppressed().length);
+    if (failClose) {
+      Assertions.assertEquals("close failed", 
failure.getCause().getSuppressed()[0].getMessage());
+    }
+  }
+
+  /** Custom store that allocates resources before failing to initialize. */
+  public static class FailingIdempotencyStore extends 
RecordingIdempotencyStore {
+    private static boolean closed;
+    private boolean failClose;
+
+    @Override
+    public void initialize(Map<String, String> properties) {
+      failClose = Boolean.parseBoolean(properties.get("fail-close"));
+      throw new IllegalStateException("initialization failed");
+    }
+
+    @Override
+    public void close() throws IOException {
+      closed = true;
+      if (failClose) {
+        throw new IOException("close failed");
+      }
+    }
+  }
+
+  /** Store loaded by class name, asserting the factory initializes what it 
constructs. */
+  public static class RecordingIdempotencyStore implements IdempotencyStore {
+
+    private boolean initialized = false;
+
+    @Override
+    public void initialize(Map<String, String> properties) {
+      this.initialized = true;
+    }
+
+    @Override
+    public ReserveResult reserve(
+        String idempotencyKey, String operationBinding, long claim, long 
expiresAtMs) {
+      return ReserveResult.RESERVED;
+    }
+
+    @Override
+    public Optional<IdempotencyRecord> load(String idempotencyKey) {
+      return Optional.empty();
+    }
+
+    @Override
+    public void finalizeRecord(
+        String idempotencyKey, long claim, int httpStatus, String 
responseSummary) {}
+
+    @Override
+    public void release(String idempotencyKey, long claim) {}
+
+    @Override
+    public int purgeExpired(long beforeMs) {
+      return 0;
+    }
+
+    @Override
+    public void close() throws IOException {}
+  }
+}
diff --git 
a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestInMemoryIdempotencyStore.java
 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestInMemoryIdempotencyStore.java
new file mode 100644
index 0000000000..b86f21147b
--- /dev/null
+++ 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestInMemoryIdempotencyStore.java
@@ -0,0 +1,320 @@
+/*
+ * 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.common.idempotency;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.LongSupplier;
+import java.util.stream.Collectors;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
+import 
org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestInMemoryIdempotencyStore {
+
+  private static final String KEY = "017f22e2-79b0-7cc3-98c4-dc0c0c07398f";
+  private static final String KEY_UPPER = 
"017F22E2-79B0-7CC3-98C4-DC0C0C07398F";
+  private static final String OTHER_KEY = 
"017f22e2-79b0-7cc3-98c4-dc0c0c073990";
+  private static final String BINDING = "POST v1/cat1/namespaces/ns1/tables";
+  private static final long FAR_FUTURE_MS = Long.MAX_VALUE;
+  private static final long CLAIM = 1L;
+
+  private InMemoryIdempotencyStore store;
+
+  @BeforeEach
+  void setUp() {
+    store = newStore(ImmutableMap.of());
+  }
+
+  @AfterEach
+  void tearDown() {
+    store.close();
+  }
+
+  @Test
+  void testReserveClaimsKeyOnlyOnce() {
+    Assertions.assertEquals(
+        ReserveResult.RESERVED, store.reserve(KEY, BINDING, CLAIM, 
FAR_FUTURE_MS));
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, CLAIM + 1, 
FAR_FUTURE_MS));
+    Assertions.assertEquals(
+        ReserveResult.RESERVED, store.reserve(OTHER_KEY, BINDING, CLAIM, 
FAR_FUTURE_MS));
+  }
+
+  @Test
+  void testKeyCaseVariantsAddressTheSameRecord() {
+    Assertions.assertEquals(
+        ReserveResult.RESERVED, store.reserve(KEY_UPPER, BINDING, CLAIM, 
FAR_FUTURE_MS));
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, CLAIM + 1, 
FAR_FUTURE_MS));
+    Assertions.assertEquals(1, store.size());
+
+    // Finalizing under one casing has to be replayable under the other, 
otherwise a retry that
+    // changes case re-executes the mutation.
+    store.finalizeRecord(KEY_UPPER, CLAIM, 200, "{\"a\":1}");
+    IdempotencyRecord record = 
store.load(KEY).orElseThrow(AssertionError::new);
+    Assertions.assertEquals(KEY, record.idempotencyKey());
+    Assertions.assertEquals(200, record.httpStatus().intValue());
+  }
+
+  @Test
+  void testLoadReturnsEmptyUntilFinalized() {
+    store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+    Assertions.assertEquals(Optional.empty(), store.load(KEY));
+
+    store.finalizeRecord(KEY, CLAIM, 200, "{\"a\":1}");
+
+    IdempotencyRecord record = 
store.load(KEY).orElseThrow(AssertionError::new);
+    Assertions.assertTrue(record.isFinalized());
+    Assertions.assertEquals(KEY, record.idempotencyKey());
+    Assertions.assertEquals(BINDING, record.operationBinding());
+    Assertions.assertEquals(200, record.httpStatus().intValue());
+    Assertions.assertEquals("{\"a\":1}", record.responseSummary());
+  }
+
+  @Test
+  void testLoadUnknownKeyReturnsEmpty() {
+    Assertions.assertEquals(Optional.empty(), store.load(KEY));
+  }
+
+  @Test
+  void testFinalizeWithoutBodyIsReplayable() {
+    store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+    store.finalizeRecord(KEY, CLAIM, 204, null);
+
+    IdempotencyRecord record = 
store.load(KEY).orElseThrow(AssertionError::new);
+    Assertions.assertEquals(204, record.httpStatus().intValue());
+    Assertions.assertNull(record.responseSummary());
+  }
+
+  @Test
+  void testFinalizeDoesNotResurrectAPurgedRecord() {
+    store.finalizeRecord(KEY, CLAIM, 200, "{}");
+    Assertions.assertEquals(Optional.empty(), store.load(KEY));
+    Assertions.assertEquals(0, store.size());
+  }
+
+  @Test
+  void testReleaseFreesTheKeyForRetry() {
+    store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+    store.release(KEY, CLAIM);
+
+    Assertions.assertEquals(
+        ReserveResult.RESERVED, store.reserve(KEY, BINDING, CLAIM, 
FAR_FUTURE_MS));
+  }
+
+  @Test
+  void testReleaseKeepsAFinalizedRecord() {
+    store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+    store.finalizeRecord(KEY, CLAIM, 200, "{}");
+    store.release(KEY, CLAIM);
+
+    Assertions.assertTrue(store.load(KEY).isPresent());
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, CLAIM, 
FAR_FUTURE_MS));
+  }
+
+  @Test
+  void testStaleFinalizeAfterReReservationIsIgnored() {
+    long staleClaim = 1L;
+    long currentClaim = 2L;
+    store.reserve(KEY, BINDING, staleClaim, FAR_FUTURE_MS);
+    // The first reservation goes away underneath its owner, as a size 
eviction or a purge would do,
+    // and a second caller takes the key.
+    store.release(KEY, staleClaim);
+    Assertions.assertEquals(
+        ReserveResult.RESERVED, store.reserve(KEY, BINDING, currentClaim, 
FAR_FUTURE_MS));
+
+    store.finalizeRecord(KEY, staleClaim, 200, "{\"stale\":true}");
+
+    // The current owner is still mid-flight: nothing to replay, and the key 
stays taken.
+    Assertions.assertEquals(Optional.empty(), store.load(KEY));
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, 3L, 
FAR_FUTURE_MS));
+
+    // And the current owner can still finalize its own response.
+    store.finalizeRecord(KEY, currentClaim, 201, "{\"stale\":false}");
+    Assertions.assertEquals(
+        "{\"stale\":false}", 
store.load(KEY).orElseThrow(AssertionError::new).responseSummary());
+  }
+
+  @Test
+  void testStaleReleaseAfterReReservationIsIgnored() {
+    long staleClaim = 1L;
+    long currentClaim = 2L;
+    store.reserve(KEY, BINDING, staleClaim, FAR_FUTURE_MS);
+    store.release(KEY, staleClaim);
+    store.reserve(KEY, BINDING, currentClaim, FAR_FUTURE_MS);
+
+    store.release(KEY, staleClaim);
+
+    // Releasing on a lost claim must not free a key the current owner is 
executing under, which
+    // would let a third request run the mutation a second time.
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, 3L, 
FAR_FUTURE_MS));
+  }
+
+  @Test
+  void testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal() {
+    String otherBinding = "DELETE v1/cat1/namespaces/ns1/tables/t1";
+    store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, otherBinding, CLAIM + 1, 
FAR_FUTURE_MS));
+    Assertions.assertEquals(Optional.empty(), store.load(KEY));
+
+    store.finalizeRecord(KEY, CLAIM, 201, "{}");
+    Assertions.assertEquals(
+        ReserveResult.DUPLICATE, store.reserve(KEY, otherBinding, CLAIM + 1, 
FAR_FUTURE_MS));
+    Assertions.assertEquals(
+        BINDING, 
store.load(KEY).orElseThrow(AssertionError::new).operationBinding());
+  }
+
+  @Test
+  void testPurgeExpiredRemovesOnlyElapsedRecords() {
+    AtomicLong now = new AtomicLong(1_000_000L);
+    InMemoryIdempotencyStore clockedStore = newStore(ImmutableMap.of(), 
now::get);
+    try {
+      clockedStore.reserve(KEY, BINDING, CLAIM, now.get() + 1_000L);
+      clockedStore.reserve(OTHER_KEY, BINDING, CLAIM, now.get() + 60_000L);
+
+      // Only the first record's window has elapsed.
+      now.addAndGet(1_000L);
+      Assertions.assertEquals(1, clockedStore.purgeExpired(now.get()));
+
+      Assertions.assertEquals(
+          ReserveResult.RESERVED, clockedStore.reserve(KEY, BINDING, CLAIM, 
now.get() + 1_000L));
+      Assertions.assertEquals(
+          ReserveResult.DUPLICATE,
+          clockedStore.reserve(OTHER_KEY, BINDING, CLAIM, now.get() + 
60_000L));
+    } finally {
+      clockedStore.close();
+    }
+  }
+
+  @Test
+  void testRecordExpiresAtItsDeadlineAndFinalizeDoesNotExtendIt() {
+    AtomicLong now = new AtomicLong(1_000_000L);
+    InMemoryIdempotencyStore clockedStore = newStore(ImmutableMap.of(), 
now::get);
+    try {
+      long deadline = now.get() + 1_000L;
+      Assertions.assertEquals(
+          ReserveResult.RESERVED, clockedStore.reserve(KEY, BINDING, CLAIM, 
deadline));
+
+      // Finalize halfway through the window. A cache expiring on last-write 
would restart the
+      // clock here and keep the record past the lifetime advertised to 
clients.
+      now.set(deadline - 500L);
+      clockedStore.finalizeRecord(KEY, CLAIM, 200, "{}");
+      Assertions.assertTrue(clockedStore.load(KEY).isPresent());
+
+      now.set(deadline);
+      Assertions.assertEquals(Optional.empty(), clockedStore.load(KEY));
+      Assertions.assertEquals(
+          ReserveResult.RESERVED, clockedStore.reserve(KEY, BINDING, CLAIM, 
now.get() + 1_000L));
+    } finally {
+      clockedStore.close();
+    }
+  }
+
+  @Test
+  void testSizeBoundEvictsRecords() throws InterruptedException {
+    InMemoryIdempotencyStore boundedStore =
+        
newStore(ImmutableMap.of(IcebergConstants.ICEBERG_IDEMPOTENCY_MAX_ENTRIES, 
"2"));
+    try {
+      for (int i = 0; i < 50; i++) {
+        boundedStore.reserve(uuidKey(i), BINDING, CLAIM, FAR_FUTURE_MS);
+      }
+      // Caffeine evicts during maintenance, so the bound is reached shortly 
after the writes
+      // rather than synchronously with them.
+      long retained = boundedStore.size();
+      for (int attempt = 0; attempt < 100 && retained > 2; attempt++) {
+        Thread.sleep(20);
+        retained = boundedStore.size();
+      }
+      Assertions.assertTrue(retained <= 2, "expected at most 2 retained 
records, got " + retained);
+    } finally {
+      boundedStore.close();
+    }
+  }
+
+  @Test
+  void testConcurrentReserveHasASingleWinner() throws InterruptedException {
+    int threads = 16;
+    ExecutorService executor = Executors.newFixedThreadPool(threads);
+    CountDownLatch start = new CountDownLatch(1);
+    CountDownLatch done = new CountDownLatch(threads);
+    List<ReserveResult> results = Collections.synchronizedList(new 
ArrayList<>());
+    AtomicReference<Throwable> failure = new AtomicReference<>();
+    try {
+      for (int i = 0; i < threads; i++) {
+        long claim = i;
+        executor.submit(
+            () -> {
+              try {
+                start.await();
+                results.add(store.reserve(KEY, BINDING, claim, FAR_FUTURE_MS));
+              } catch (Throwable t) {
+                failure.compareAndSet(null, t);
+              } finally {
+                done.countDown();
+              }
+            });
+      }
+      start.countDown();
+      Assertions.assertTrue(done.await(30, TimeUnit.SECONDS));
+      Assertions.assertNull(failure.get(), "no reserve should fail");
+      Map<ReserveResult, Long> counts =
+          results.stream().collect(Collectors.groupingBy(result -> result, 
Collectors.counting()));
+      Assertions.assertEquals(threads, results.size(), "every caller should 
report a result");
+      Assertions.assertEquals(1L, counts.getOrDefault(ReserveResult.RESERVED, 
0L));
+      Assertions.assertEquals(threads - 1L, 
counts.getOrDefault(ReserveResult.DUPLICATE, 0L));
+    } finally {
+      executor.shutdownNow();
+    }
+  }
+
+  /** Builds distinct valid UUIDv7 keys, since the store rejects anything 
else. */
+  private static String uuidKey(int index) {
+    return String.format("017f22e2-79b0-7cc3-98c4-%012x", index);
+  }
+
+  private static InMemoryIdempotencyStore newStore(Map<String, String> 
properties) {
+    return newStore(properties, System::currentTimeMillis);
+  }
+
+  private static InMemoryIdempotencyStore newStore(
+      Map<String, String> properties, LongSupplier clock) {
+    InMemoryIdempotencyStore store = new InMemoryIdempotencyStore(clock);
+    store.initialize(properties);
+    return store;
+  }
+}

Reply via email to