World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15390] refactor(iceberg-rest): treat hard-deleted Idempotency-Key rows as new keys (#15391)
MaSaic905f8f68c0d
diff --git a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.javaindex 9996a1b7a2..d408db5af6 100644--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java@@ -861,17 +861,6 @@ public class TestSQLScripts extends TestJDBCBackend {private void assertIdempotencySchema(String source) throws SQLException {Map<String, Set<String>> columns = readSchemaColumns();- String counterTable =- columns.keySet().stream()- .filter(name -> name.equalsIgnoreCase("iceberg_idempotency_generation_meta"))- .findFirst()- .orElseThrow(- () -> new AssertionFailedError("Missing idempotency counters after " + source));- Assertions.assertEquals(- Set.of("stripe", "generation"),- Set.copyOf(- columns.get(counterTable).stream().map(name -> name.toLowerCase(Locale.ROOT)).toList()),- "Idempotency counter columns after " + source);String table =columns.keySet().stream().filter(name -> name.equalsIgnoreCase("iceberg_idempotency_meta"))@@ -883,7 +872,6 @@ public class TestSQLScripts extends TestJDBCBackend {"idempotency_key","http_method","request_uri",- "generation","http_status","response_summary","audit_info",diff --git a/design-docs/iceberg-idempotency-key.md b/design-docs/iceberg-idempotency-key.mdindex 227464e779..db8a6418d9 100644--- a/design-docs/iceberg-idempotency-key.md+++ b/design-docs/iceberg-idempotency-key.md@@ -168,9 +168,9 @@ public interface IdempotencyStore extends Closeable {* @param idempotencyKey the client-provided UUIDv7 key* @param operationBinding request identity, e.g. "POST /v1/cat1/namespaces/ns1/tables"* @param expiresAtMs deadline in Unix epoch milliseconds- * @return a fresh fencing token if acquired, empty if the key is live+ * @return true if acquired, false if the key is live*/- OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs);+ boolean reserve(String idempotencyKey, String operationBinding, long expiresAtMs);/*** Load a finalized record for replay.@@ -184,20 +184,18 @@ public interface IdempotencyStore extends Closeable {* Mark a reserved key as finalized with the response to replay on duplicates.** @param idempotencyKey the client-provided key- * @param claim the fencing token returned by reserve* @param httpStatus the HTTP status code of the original response* @param responseSummary serialized response body (JSON string)*/- void finalizeRecord(String idempotencyKey, long claim, int httpStatus, String responseSummary);+ void finalizeRecord(String idempotencyKey, int httpStatus, String responseSummary);/*** Release a reservation so the client can retry with the same key.* Called when the mutation fails with a retryable error.** @param idempotencyKey the client-provided key- * @param claim the fencing token returned by reserve*/- void release(String idempotencyKey, long claim);+ void release(String idempotencyKey);/*** Purge expired records. Called periodically by a background task.@@ -215,7 +213,6 @@ public interface IdempotencyStore extends Closeable {public class IdempotencyRecord {private final String idempotencyKey; // UUIDv7 (RFC 9562), 36-char canonical formprivate final String operationBinding; // e.g., "POST /v1/cat1/namespaces/ns1/tables"- private final long claim; // store-issued fencing tokenprivate final Integer httpStatus; // null while reserved / in-progressprivate final String responseSummary; // serialized response body (JSON)private final long createdAtMs; // unix epoch millis (matches BIGINT column)@@ -285,7 +282,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (`idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key',`http_method` VARCHAR(16) NOT NULL COMMENT 'HTTP method of the request',`request_uri` MEDIUMTEXT NOT NULL COMMENT 'encoded request path and sorted query string',- `generation` BIGINT NOT NULL COMMENT 'reservation fencing token',`http_status` INT(10) UNSIGNED DEFAULT NULL COMMENT 'HTTP status of finalized response, NULL while reserved',`response_summary` MEDIUMTEXT DEFAULT NULL COMMENT 'serialized response body (JSON) for replay',`audit_info` MEDIUMTEXT NOT NULL COMMENT 'idempotency record audit info',@@ -294,25 +290,16 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (PRIMARY KEY (`idempotency_key`),KEY `idx_iim_expires` (`expires_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Iceberg REST idempotency records';---CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-) ENGINE=InnoDB;```The H2 and PostgreSQL variants use the same columns. All three backends ship thetable in `scripts/<backend>/schema-2.0.0-<backend>.sql` and`scripts/<backend>/upgrade-1.3.0-to-2.0.0-<backend>.sql`.-A key's final byte selects one of 256 generation counters in-`iceberg_idempotency_generation_meta`. The database advances that counter in-the same transaction that acquires the reservation, so a key's generations-increase across replicas. Release and purge leave the counters in place.-A per-key counter initialized to 1 would repeat after deletion and let a late-owner touch the new reservation. The store returns the generation as the claim-that finalize and release match against the current row.+Hard-deleted, released, or purged keys are treated as never seen. That matches+common HTTP `Idempotency-Key` stores and the Iceberg REST reuse window (clients+SHOULD NOT reuse a key after expiry). Size the reuse window so mutations finish+before expiry.The HTTP method is stored in `http_method`. The `request_uri` column storesthe encoded path plus the sorted, encoded query string when present. MySQL@@ -328,10 +315,8 @@ longer than MySQL's 64 KiB `TEXT` limit.### 4.2 Conflict Handling-`reserve()` advances the key's generation counter and attempts a plain-`INSERT` in one transaction. After a duplicate-key rollback, a separate-transaction advances the counter and replaces the matching row only if it is-expired. If no expired row matches, the store retries once with a fresh expiry+`reserve()` attempts a plain `INSERT`. After a duplicate-key rollback, a separate+transaction replaces the matching row only if it is expired. If no expired row matches, the store retries once with a fresh expirycutoff in case purge or release freed the key. If neither attempt claims thekey, it returns empty. Other SQL errors propagate. Only finalized, unexpiredrecords can be loaded for replay.@@ -346,8 +331,8 @@ records can be loaded for replay.ignore the `Idempotency-Key` header and execute the mutation directly.2. Extract `Idempotency-Key` header; validate UUIDv7 format (400 if invalid).3. If header absent, execute mutation directly (no idempotency overhead).-4. Call `store.reserve(key, binding, now + lifetime)` to acquire the key and receive a claim.-5. If a claim was returned, execute the mutation and call `store.finalizeRecord(key, claim, status, body)`.+4. Call `store.reserve(key, binding, now + lifetime)` to acquire the key.+5. If reserve returns true, execute the mutation and call `store.finalizeRecord(key, status, body)`.6. Return response to client.### 5.2 Replay Path (Duplicate Key)@@ -370,11 +355,11 @@ response-persistence failures:whose commit acknowledgement may have been lost. Retry with the same keywithin its reuse window; reconcile catalog state before retrying outside it.- **Retryable mutation errors** (`5xx`, authentication/authorization outcomes,- or a thrown action exception): call `store.release(key, claim)` so the client+ or a thrown action exception): call `store.release(key)` so the clientcan retry with the same key. A mutation failure can still have an uncertaincatalog outcome; a `5xx` is not proof that the catalog was unchanged.- **Terminal errors** (e.g., `AlreadyExistsException`): call- `store.finalizeRecord(key, claim, 409, errorBody)` so retries get the same error response.+ `store.finalizeRecord(key, 409, errorBody)` so retries get the same error response.- **Terminal response cannot be retained** (serialization, write, read-backfailure, or a no-op finalize): return the original mutation response and leaveany existing reservation until expiry. This prevents immediate re-execution;@@ -500,7 +485,7 @@ This design uses a fixed reuse window rather than heartbeat-based ownership.It therefore requires the duration and clock-skew bounds in Section 5.4 andcannot guarantee at-most-once execution for unbounded mutations. Supportingthose operations safely would require a separate lease-renewal and-catalog-side fencing design; record claim tokens alone cannot stop an already+catalog-side design; the idempotency record alone cannot stop an alreadyrunning catalog mutation.---diff --git a/docs/iceberg-rest-service.md b/docs/iceberg-rest-service.mdindex 0653aaa407..aedf87fde5 100644--- a/docs/iceberg-rest-service.md+++ b/docs/iceberg-rest-service.md@@ -203,7 +203,7 @@ Limitations:- Request identity covers the HTTP method, path, and query parameters. It does **not** compare request bodies or behavior-changing headers such as `X-Iceberg-Access-Delegation`. Reusing a key on the same URL with a changed body or header replays the first response; it does not apply the changed request. Always generate a new key for a different logical operation. Request validation runs before replay, so a retry with an invalid body can return `400 Bad Request` even if the key already has a stored success.- Replay preserves the status and JSON body but omits response headers such as `ETag`. Load the table again if the client needs its current ETag.-- The catalog mutation and response persistence are not one transaction. A crash, serialization failure, lost reservation, or post-commit failure can leave a successful mutation without a replayable response. When saving a terminal response fails, the manager keeps any existing reservation until expiry and returns the original mutation response. Retries receive `409` with `Retry-After` while an unfinalized reservation remains. Expiry, eviction, or a released reservation can still permit re-execution. Claim fencing protects replacement records, but cannot undo or fence catalog side effects.+- The catalog mutation and response persistence are not one transaction. A crash, serialization failure, lost reservation, or post-commit failure can leave a successful mutation without a replayable response. When saving a terminal response fails, the manager keeps any existing reservation until expiry and returns the original mutation response. Retries receive `409` with `Retry-After` while an unfinalized reservation remains. Expiry, eviction, or a released reservation treats the key as never seen and can permit re-execution.- The in-memory store reclaims expired entries through Caffeine. The JDBC store schedules bounded cleanup as described below. Custom stores must enforce expiry on reads/reservations and arrange their own cleanup.:::caution@@ -234,9 +234,9 @@ database lock contention. Close the store when stopping the service to shut downInitialize a new database with the 2.0.0 schema or apply the 1.3.0-to-2.0.0 upgrade before selecting`jdbc`. An existing development 2.0.0 database created before this table was added must also apply-the `iceberg_idempotency_meta` and `iceberg_idempotency_generation_meta` tables and the expiry index-from the matching database's schema script. Store initialization fails if either table is missing.-These tables are additive and do not modify catalog metadata.+the `iceberg_idempotency_meta` table and the expiry index from the matching database's schema+script. Store initialization fails if `iceberg_idempotency_meta` is missing. The table is additive+and does not modify catalog metadata.When switching from an earlier development build that used `iceberg_idempotency_key_meta` or`query_digest`, drain in-flight mutations and let existing reuse windows expire before changing@@ -245,15 +245,13 @@ current `request_uri` column uses `MEDIUMTEXT` to accommodate long request targeThe store interface and record type are in `org.apache.gravitino.iceberg.service.idempotency` inthe Iceberg REST server JAR. Rebuild custom stores from earlier development versions against this-package and update `reserve` to return the store's fencing token, or an empty result for a-duplicate key. If an earlier configuration names the built-in in-memory store by its old class-name, use the `in-memory` alias.+package and update `reserve` to return whether the key was acquired. If an earlier configuration+names the built-in in-memory store by its old class name, use the `in-memory` alias.-Reservations are atomic across replicas. The database assigns a new generation even when the-previous reservation for the same key was released or purged. Finalization and release match that-generation to protect a newer reservation from an old request. The table stores the HTTP method-separately from `request_uri`, which contains the encoded path followed by the sorted, encoded-query string when present.+Reservations are atomic across replicas. After release or purge, the same key is treated as never+seen and reserved again, matching common HTTP `Idempotency-Key` stores. Clients SHOULD NOT reuse a+key after the advertised lifetime. The table stores the HTTP method separately from `request_uri`,+which contains the encoded path followed by the sorted, encoded query string when present.Expiry is enforced on reads, finalization, and reservation attempts;reusing an expired key does not depend on the cleanup schedule. Each cleanup pass deletes at most@@ -298,8 +296,8 @@ validity because expiry is checked on access.Durable storage does not make catalog mutations and response persistence one transaction. Failedresponse persistence leaves any reservation in place until expiry, but cannot recover a missing-response after a crash. Claim fencing protects idempotency records, not external catalog side-effects. A request running beyond its reuse window can overlap a retry.+response after a crash. Idempotency records do not fence catalog side effects. A request running+beyond its reuse window can overlap a retry.### Catalog Backend Configurationdiff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.javaindex b2710bc79a..faa8327888 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java@@ -29,7 +29,6 @@ import java.time.Duration;import java.util.List;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;import java.util.Set;import java.util.StringJoiner;import java.util.TreeMap;@@ -157,13 +156,10 @@ public class IcebergIdempotencyManager {IdempotencyStore idempotencyStore = store.get();long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();- long claim;try {- OptionalLong reservation = idempotencyStore.reserve(key, operationBinding, expiresAtMs);- if (reservation.isEmpty()) {+ if (!idempotencyStore.reserve(key, operationBinding, expiresAtMs)) {return replay(idempotencyStore, key, operationBinding);}- claim = reservation.getAsLong();} catch (RuntimeException e) {LOG.warn("Failed to access idempotency state for key {} before executing the mutation", key, e);@@ -186,14 +182,21 @@ public class IcebergIdempotencyManager {if (status < Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()&& !NON_FINALIZABLE_STATUSES.contains(status)) {release = false;- tryFinalize(idempotencyStore, key, claim, response);+ tryFinalize(idempotencyStore, key, response);}return response;} finally {if (release) {- // Release only when the action throws or returns a retryable/auth response.- // A replacement owner's reservation must remain untouched.- idempotencyStore.release(key, claim);+ // Release only when the action throws or returns a retryable/auth response. Swallow store+ // failures so they cannot replace the mutation response or the thrown exception.+ try {+ idempotencyStore.release(key);+ } catch (RuntimeException e) {+ LOG.warn(+ "Failed to release Idempotency-Key: {}; leaving any reservation until expiry",+ key,+ e);+ }}}}@@ -280,7 +283,7 @@ public class IcebergIdempotencyManager {}private void tryFinalize(- IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {+ IdempotencyStore idempotencyStore, String idempotencyKey, Response response) {String responseSummary;try {Object entity = response.getEntity();@@ -291,16 +294,12 @@ public class IcebergIdempotencyManager {} else {responseSummary = icebergObjectMapper.writeValueAsString(entity);}- idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);+ idempotencyStore.finalizeRecord(idempotencyKey, response.getStatus(), responseSummary);boolean finalized =- idempotencyStore- .load(idempotencyKey)- .filter(record -> record.isFinalized() && record.claim() == claim)- .isPresent();+ idempotencyStore.load(idempotencyKey).filter(IdempotencyRecord::isFinalized).isPresent();if (!finalized) {LOG.warn(- "Response for Idempotency-Key: {} was not retained under this claim; "- + "leaving any reservation until expiry",+ "Response for Idempotency-Key: {} was not retained; leaving any reservation until expiry",idempotencyKey);}} catch (JsonProcessingException | RuntimeException e) {diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.javaindex 30324f956e..9b6001a838 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.java@@ -34,7 +34,6 @@ 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;@@ -43,14 +42,12 @@ public final class IdempotencyRecord {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;@@ -63,21 +60,16 @@ public final class IdempotencyRecord {* @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) {+ String idempotencyKey, String operationBinding, 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);+ idempotencyKey, operationBinding, null, null, createdAtMs, expiresAtMs);}/**@@ -89,20 +81,7 @@ public final class IdempotencyRecord {*/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;+ idempotencyKey, operationBinding, status, summary, createdAtMs, expiresAtMs);}/**@@ -183,7 +162,6 @@ public final class IdempotencyRecord {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)@@ -193,13 +171,7 @@ public final class IdempotencyRecord {@Overridepublic int hashCode() {return Objects.hash(- idempotencyKey,- operationBinding,- claim,- httpStatus,- responseSummary,- createdAtMs,- expiresAtMs);+ idempotencyKey, operationBinding, httpStatus, responseSummary, createdAtMs, expiresAtMs);}@Overridediff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.javaindex 0652a6dcdc..9a79870550 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.java@@ -21,7 +21,6 @@ package org.apache.gravitino.iceberg.service.idempotency;import java.io.Closeable;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;import javax.annotation.Nullable;/**@@ -36,11 +35,10 @@ import javax.annotation.Nullable;* 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.+ * under memory pressure, and a purge can remove it once it expires. The key is then free and+ * treated as never seen, so another caller can reserve it while the first is still running.+ * Built-in stores match common HTTP {@code Idempotency-Key} practice and the Iceberg REST reuse+ * window: after hard delete there is no per-reservation token.** <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@@ -59,7 +57,7 @@ public interface IdempotencyStore extends Closeable {void initialize(Map<String, String> properties);/**- * Atomically attempts to claim a key. An expired record is treated as absent, so the key can be+ * Atomically attempts to reserve 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 a reservation already@@ -72,11 +70,9 @@ public interface IdempotencyStore extends Closeable {* @param operationBinding request identity, as the HTTP method, a space, and the encoded path. A* query fingerprint may follow the path, separated by a question mark.* @param expiresAtMs time after which the record may be purged, in unix epoch millis- * @return a fresh fencing token when the reservation is acquired, or empty if the key is live.- * Tokens must not repeat for a key after release, eviction, or purge, and callers must pass- * the returned token to {@link #finalizeRecord} or {@link #release}.+ * @return {@code true} when the reservation is acquired, or {@code false} if the key is live*/- OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs);+ boolean reserve(String idempotencyKey, String operationBinding, long expiresAtMs);/*** Loads a finalized record for replay.@@ -91,28 +87,23 @@ public interface IdempotencyStore extends Closeable {* 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.+ * resurrected, and when the key is already finalized or absent.** @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);+ void finalizeRecord(String idempotencyKey, 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.+ * <p>The call is a no-op when the key is already finalized or absent.** @param idempotencyKey the client-provided key- * @param claim the claim this caller reserved with*/- void release(String idempotencyKey, long claim);+ void release(String idempotencyKey);/*** Purges records whose reuse window has elapsed.diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.javaindex a50e8df1de..d179de0e13 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.java@@ -26,8 +26,8 @@ import com.google.common.annotations.VisibleForTesting;import java.util.Iterator;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;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;@@ -43,11 +43,10 @@ import org.slf4j.LoggerFactory;* 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.+ * execution therefore depends on the reservation remaining cached. Hard-deleted or evicted keys are+ * treated as never seen; size the cache and reuse window so that does not overlap live work.+ * 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@@ -61,7 +60,6 @@ public class InMemoryIdempotencyStore implements IdempotencyStore {/** 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 generations = new AtomicLong();private final AtomicLong sizeEvictions = new AtomicLong();private final LongSupplier clock;@@ -124,23 +122,25 @@ public class InMemoryIdempotencyStore implements IdempotencyStore {}@Override- public OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {+ public boolean reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {String key = IdempotencyKeys.canonicalize(idempotencyKey);IdempotencyRecord reserved =- IdempotencyRecord.reserved(- key, operationBinding, generations.incrementAndGet(), clock.getAsLong(), expiresAtMs);+ IdempotencyRecord.reserved(key, operationBinding, 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.- IdempotencyRecord actual =- cache- .asMap()- .compute(- key,- (cacheKey, existing) ->- existing == null || isExpired(existing) ? reserved : existing);- return actual.claim() == reserved.claim()- ? OptionalLong.of(reserved.claim())- : OptionalLong.empty();+ AtomicBoolean acquired = new AtomicBoolean();+ cache+ .asMap()+ .compute(+ key,+ (cacheKey, existing) -> {+ if (existing == null || isExpired(existing)) {+ acquired.set(true);+ return reserved;+ }+ return existing;+ });+ return acquired.get();}@Override@@ -152,29 +152,27 @@ public class InMemoryIdempotencyStore implements IdempotencyStore {@Overridepublic 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.+ String idempotencyKey, int httpStatus, @Nullable String responseSummary) {+ // computeIfPresent, so a record purged while the mutation was running is not resurrected.cache.asMap().computeIfPresent(IdempotencyKeys.canonicalize(idempotencyKey),(key, record) ->- record.claim() == claim && !isExpired(record)+ !record.isFinalized() && !isExpired(record)? record.withResponse(httpStatus, responseSummary): record);}@Override- public void release(String idempotencyKey, long claim) {+ public void release(String idempotencyKey) {// 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.+ // cannot drop a response another request may still replay.cache.asMap().computeIfPresent(IdempotencyKeys.canonicalize(idempotencyKey),- (key, record) -> record.isFinalized() || record.claim() != claim ? record : null);+ (key, record) -> record.isFinalized() ? record : null);}@Overridediff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.javaindex 7437491076..106923682b 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java@@ -25,7 +25,6 @@ import java.time.Clock;import java.time.Duration;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;@@ -47,22 +46,21 @@ import org.slf4j.LoggerFactory;* 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. There is also no in-flight renewal: the- * configured lifetime must exceed the maximum duration from reservation through mutation completion- * and response persistence, plus maximum clock skew and a safety margin. Expiry can otherwise allow- * overlapping mutations.+ * <p>Reservations commit independently of catalog transactions. Expired, released, or purged keys+ * are treated as never seen: a later {@link #reserve} inserts a new row. That matches common HTTP+ * {@code Idempotency-Key} stores and the Iceberg REST reuse window (clients SHOULD NOT reuse a key+ * after expiry). Size the reuse window so mutations finish before expiry. Replicas must synchronize+ * system clocks: a fast clock can reclaim a key another replica still considers live. There is no+ * clock-skew grace period and no in-flight renewal: the configured lifetime must exceed the maximum+ * duration from reservation through mutation completion and response persistence, plus maximum+ * clock skew and a safety margin.** <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);- // The UUID tail spreads unrelated keys across 256 independently locked counters.- private static final int COUNTER_HEX_DIGITS = 2;+@VisibleForTesting static final int PURGE_BATCH_SIZE = 1000;@VisibleForTesting static final int MAX_PURGE_BATCHES = 100;@@ -110,7 +108,6 @@ public class JdbcIdempotencyStore implements IdempotencyStore {try (SqlSession session = factory.openSession()) {IcebergIdempotencyKeyMapper mapper = session.getMapper(IcebergIdempotencyKeyMapper.class);mapper.selectRecord("00000000-0000-7000-8000-000000000000", clock.millis());- mapper.selectGeneration(0);session.commit();}sessionFactory = factory;@@ -126,43 +123,38 @@ public class JdbcIdempotencyStore implements IdempotencyStore {}@Override- public OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {+ public boolean reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {String key = IdempotencyKeys.canonicalize(idempotencyKey);Preconditions.checkArgument(operationBinding != null, "operationBinding should not be null");for (int attempt = 0; attempt < 2; attempt++) {long nowMs = clock.millis();try {- return execute(+ execute(mapper -> {- long generation = nextGeneration(mapper, key);mapper.insert(- IcebergIdempotencyKeyPO.reserved(- key, operationBinding, generation, nowMs, expiresAtMs));- return OptionalLong.of(generation);+ IcebergIdempotencyKeyPO.reserved(key, operationBinding, nowMs, expiresAtMs));+ return null;});+ return true;} catch (RuntimeException e) {if (!ExceptionUtils.isDuplicateKey(e)) {throw e;}}- // Allocate and replace in the same transaction so the next owner cannot obtain an older- // generation. The separate transaction avoids upgrading a failed INSERT's MySQL locks.- OptionalLong replacement =+ // Replace in a separate transaction so a failed INSERT's MySQL locks are not upgraded.+ boolean replaced =execute(- mapper -> {- long generation = nextGeneration(mapper, key);- int replaced =- mapper.replaceExpired(- IcebergIdempotencyKeyPO.reserved(- key, operationBinding, generation, nowMs, expiresAtMs));- return replaced == 0 ? OptionalLong.empty() : OptionalLong.of(generation);- });- if (replacement.isPresent()) {- return replacement;+ mapper ->+ mapper.replaceExpired(+ IcebergIdempotencyKeyPO.reserved(+ key, operationBinding, nowMs, expiresAtMs))+ > 0);+ if (replaced) {+ return true;}// Purge or release may have removed the row. Retry once with a fresh expiry cutoff.}- return OptionalLong.empty();+ return false;}@Override@@ -174,23 +166,21 @@ public class JdbcIdempotencyStore implements IdempotencyStore {@Overridepublic void finalizeRecord(- String idempotencyKey, long claim, int httpStatus, @Nullable String responseSummary) {+ String idempotencyKey, int httpStatus, @Nullable String responseSummary) {String key = IdempotencyKeys.canonicalize(idempotencyKey);int updated =- execute(- mapper ->- mapper.finalizeRecord(key, claim, httpStatus, responseSummary, clock.millis()));+ execute(mapper -> mapper.finalizeRecord(key, httpStatus, responseSummary, clock.millis()));if (updated == 0) {- LOG.debug("No live unfinalized reservation to finalize for key {} and claim {}", key, claim);+ LOG.debug("No live unfinalized reservation to finalize for key {}", key);}}@Override- public void release(String idempotencyKey, long claim) {+ public void release(String idempotencyKey) {String key = IdempotencyKeys.canonicalize(idempotencyKey);- int deleted = execute(mapper -> mapper.deleteReservation(key, claim));+ int deleted = execute(mapper -> mapper.deleteReservation(key));if (deleted == 0) {- LOG.debug("No unfinalized reservation to release for key {} and claim {}", key, claim);+ LOG.debug("No unfinalized reservation to release for key {}", key);}}@@ -233,13 +223,6 @@ public class JdbcIdempotencyStore implements IdempotencyStore {}}- @VisibleForTesting- static long nextGeneration(IcebergIdempotencyKeyMapper mapper, String key) {- int stripe = Integer.parseInt(key.substring(key.length() - COUNTER_HEX_DIGITS), 16);- mapper.advanceGeneration(stripe);- return mapper.selectGeneration(stripe);- }-private <T> T execute(Function<IcebergIdempotencyKeyMapper, T> operation) {try (SqlSession session = sessionFactory.openSession()) {T result = operation.apply(session.getMapper(IcebergIdempotencyKeyMapper.class));diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeyMapper.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeyMapper.javaindex b4cb643405..94756a44e0 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeyMapper.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeyMapper.java@@ -24,7 +24,6 @@ import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyimport org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.Param;-import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.SelectProvider;import org.apache.ibatis.annotations.UpdateProvider;@@ -49,7 +48,7 @@ public interface IcebergIdempotencyKeyMapper {int insert(@Param("po") IcebergIdempotencyKeyPO po);/**- * Replaces an expired reservation with a new generation.+ * Replaces an expired reservation with a new one.** @param po reservation to persist* @return number of affected rows@@ -57,26 +56,6 @@ public interface IcebergIdempotencyKeyMapper {@UpdateProvider(type = IcebergIdempotencyKeySQLProviderFactory.class, method = "replaceExpired")int replaceExpired(@Param("po") IcebergIdempotencyKeyPO po);- /**- * Advances a counter under a transaction lock or creates it on first use.- *- * @param stripe counter selected by the key's final byte- */- @InsertProvider(- type = IcebergIdempotencyKeySQLProviderFactory.class,- method = "advanceGeneration")- void advanceGeneration(@Param("stripe") int stripe);-- /**- * Reads the counter advanced by the current transaction.- *- * @param stripe counter selected by the key's final byte- * @return current generation, or null when the stripe has never been used- */- @Select("SELECT generation FROM iceberg_idempotency_generation_meta WHERE stripe = #{stripe}")- @Nullable- Long selectGeneration(@Param("stripe") int stripe);-/*** Loads a finalized response within its reuse window.*@@ -90,10 +69,9 @@ public interface IcebergIdempotencyKeyMapper {@Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long nowMs);/**- * Finalizes a live reservation owned by the given claim.+ * Finalizes a live unfinalized reservation.** @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@@ -102,22 +80,20 @@ public interface IcebergIdempotencyKeyMapper {@UpdateProvider(type = IcebergIdempotencyKeySQLProviderFactory.class, method = "finalizeRecord")int finalizeRecord(@Param("idempotencyKey") String idempotencyKey,- @Param("claim") long claim,@Param("httpStatus") int httpStatus,@Param("responseSummary") @Nullable String responseSummary,@Param("nowMs") long nowMs);/**- * Deletes only rows matching the statement's ownership or expiry guard.+ * Deletes an unfinalized reservation.** @param idempotencyKey canonical UUIDv7 key- * @param claim reservation fencing token* @return number of affected rows*/@DeleteProvider(type = IcebergIdempotencyKeySQLProviderFactory.class,method = "deleteReservation")- int deleteReservation(@Param("idempotencyKey") String idempotencyKey, @Param("claim") long claim);+ int deleteReservation(@Param("idempotencyKey") String idempotencyKey);/*** Deletes only rows matching the statement's ownership or expiry guard.diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeySQLProviderFactory.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeySQLProviderFactory.javaindex 8a83039913..57a4f69012 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeySQLProviderFactory.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeySQLProviderFactory.java@@ -60,16 +60,6 @@ public class IcebergIdempotencyKeySQLProviderFactory {return getProvider().replaceExpired(po);}- /**- * Returns the counter advance statement for the configured entity store.- *- * @param stripe counter selected by the key's final byte- * @return SQL statement- */- public static String advanceGeneration(@Param("stripe") int stripe) {- return getProvider().advanceGeneration(stripe);- }-/*** Returns the statement for the configured entity-store database.*@@ -86,7 +76,6 @@ public class IcebergIdempotencyKeySQLProviderFactory {* Returns the statement for the configured entity-store database.** @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@@ -94,23 +83,20 @@ public class IcebergIdempotencyKeySQLProviderFactory {*/public static String finalizeRecord(@Param("idempotencyKey") String idempotencyKey,- @Param("claim") long claim,@Param("httpStatus") int httpStatus,@Param("responseSummary") String responseSummary,@Param("nowMs") long nowMs) {- return getProvider().finalizeRecord(idempotencyKey, claim, httpStatus, responseSummary, nowMs);+ return getProvider().finalizeRecord(idempotencyKey, httpStatus, responseSummary, nowMs);}/*** Returns the statement for the configured entity-store database.** @param idempotencyKey canonical UUIDv7 key- * @param claim reservation fencing token* @return SQL statement*/- public static String deleteReservation(- @Param("idempotencyKey") String idempotencyKey, @Param("claim") long claim) {- return getProvider().deleteReservation(idempotencyKey, claim);+ public static String deleteReservation(@Param("idempotencyKey") String idempotencyKey) {+ return getProvider().deleteReservation(idempotencyKey);}/**diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.javaindex 69b9ecf194..bbbf23ac0c 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java@@ -35,8 +35,8 @@ public class IcebergIdempotencyKeyBaseSQLProvider {public String insert(@Param("po") IcebergIdempotencyKeyPO po) {return "INSERT INTO "+ TABLE_NAME- + " (idempotency_key, http_method, request_uri, generation, audit_info, created_at, expires_at)"- + " VALUES (#{po.idempotencyKey}, #{po.httpMethod}, #{po.requestUri}, #{po.generation},"+ + " (idempotency_key, http_method, request_uri, audit_info, created_at, expires_at)"+ + " VALUES (#{po.idempotencyKey}, #{po.httpMethod}, #{po.requestUri},"+ " #{po.auditInfo}, #{po.createdAt}, #{po.expiresAt})";}@@ -49,23 +49,12 @@ public class IcebergIdempotencyKeyBaseSQLProvider {public String replaceExpired(@Param("po") IcebergIdempotencyKeyPO po) {return "UPDATE "+ TABLE_NAME- + " SET http_method = #{po.httpMethod}, request_uri = #{po.requestUri}, generation = #{po.generation},"+ + " SET http_method = #{po.httpMethod}, request_uri = #{po.requestUri},"+ " 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 the counter advance statement.- *- * @param stripe counter selected by the key's final byte- * @return SQL statement- */- public String advanceGeneration(@Param("stripe") int stripe) {- return "INSERT INTO iceberg_idempotency_generation_meta (stripe, generation) VALUES (#{stripe}, 1)"- + " ON DUPLICATE KEY UPDATE generation = generation + 1";- }-/*** Returns only a finalized, unexpired response.*@@ -76,7 +65,7 @@ public class IcebergIdempotencyKeyBaseSQLProvider {public String selectRecord(@Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long nowMs) {return "SELECT idempotency_key AS idempotencyKey, http_method AS httpMethod, request_uri AS requestUri,"- + " generation, http_status AS httpStatus, response_summary AS responseSummary,"+ + " 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}"@@ -84,10 +73,9 @@ public class IcebergIdempotencyKeyBaseSQLProvider {}/**- * Returns a finalization guarded by the reservation's claim and expiry.+ * Returns a finalization guarded by expiry for an unfinalized reservation.** @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@@ -95,29 +83,26 @@ public class IcebergIdempotencyKeyBaseSQLProvider {*/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 generation = #{claim}"+ + " WHERE idempotency_key = #{idempotencyKey}"+ " AND http_status IS NULL AND expires_at > #{nowMs}";}/**- * Returns a release guarded by the reservation's claim. Finalized responses are retained.+ * Returns a release of an unfinalized reservation. 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) {+ public String deleteReservation(@Param("idempotencyKey") String idempotencyKey) {return "DELETE FROM "+ TABLE_NAME- + " WHERE idempotency_key = #{idempotencyKey} AND generation = #{claim} AND http_status IS NULL";+ + " WHERE idempotency_key = #{idempotencyKey} AND http_status IS NULL";}/**diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/postgresql/IcebergIdempotencyKeyPostgreSQLProvider.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/postgresql/IcebergIdempotencyKeyPostgreSQLProvider.javaindex deef83143a..051b6bef00 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/postgresql/IcebergIdempotencyKeyPostgreSQLProvider.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/postgresql/IcebergIdempotencyKeyPostgreSQLProvider.java@@ -24,15 +24,8 @@ import static org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdeimport org.apache.gravitino.iceberg.service.idempotency.mapper.provider.base.IcebergIdempotencyKeyBaseSQLProvider;import org.apache.ibatis.annotations.Param;-/** PostgreSQL statements for generation allocation and bounded purge. */+/** PostgreSQL statements for bounded purge. */public class IcebergIdempotencyKeyPostgreSQLProvider extends IcebergIdempotencyKeyBaseSQLProvider {- @Override- public String advanceGeneration(@Param("stripe") int stripe) {- return "INSERT INTO iceberg_idempotency_generation_meta (stripe, generation) VALUES (#{stripe}, 1)"- + " ON CONFLICT (stripe) DO UPDATE SET generation ="- + " iceberg_idempotency_generation_meta.generation + 1";- }-@Overridepublic String deleteExpiredBatch(@Param("beforeMs") long beforeMs, @Param("batchSize") int batchSize) {diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/po/IcebergIdempotencyKeyPO.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/po/IcebergIdempotencyKeyPO.javaindex 8d27afa68b..d325422083 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/po/IcebergIdempotencyKeyPO.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/po/IcebergIdempotencyKeyPO.java@@ -39,7 +39,6 @@ import org.apache.gravitino.utils.PrincipalUtils;* mapped by {@link IcebergIdempotencyKeyMapper}, and converts to the {@link IdempotencyRecord} the* store SPI hands back. Instances are created through the generated {@code builder()} (or populated* by MyBatis via field reflection through the private no-arg constructor) and expose no setters.- * The store supplies the fencing token when it inserts or replaces the reservation.*/@Getter@Builder(setterPrefix = "with")@@ -50,7 +49,6 @@ public class IcebergIdempotencyKeyPO {private String idempotencyKey;private String httpMethod;private String requestUri;- private Long generation;@Nullable private Integer httpStatus;@Nullable private String responseSummary;private String auditInfo;@@ -63,17 +61,12 @@ public class IcebergIdempotencyKeyPO {* @param idempotencyKey the client-provided UUIDv7 key* @param operationBinding request identity, for example {@code POST* /v1/cat1/namespaces/ns1/tables}- * @param generation the reservation 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 the persistence object*/public static IcebergIdempotencyKeyPO reserved(- String idempotencyKey,- String operationBinding,- long generation,- long createdAtMs,- long expiresAtMs) {+ String idempotencyKey, String operationBinding, long createdAtMs, long expiresAtMs) {int separator = operationBinding.indexOf(' ');String method = separator < 0 ? operationBinding : operationBinding.substring(0, separator);String uri = separator < 0 ? "" : operationBinding.substring(separator + 1);@@ -81,7 +74,6 @@ public class IcebergIdempotencyKeyPO {.withIdempotencyKey(idempotencyKey).withHttpMethod(method).withRequestUri(uri)- .withGeneration(generation).withHttpStatus(null).withResponseSummary(null).withAuditInfo(auditInfoJson(createdAtMs))@@ -98,7 +90,7 @@ public class IcebergIdempotencyKeyPO {public IdempotencyRecord toIdempotencyRecord() {String binding = requestUri.isEmpty() ? httpMethod : httpMethod + " " + requestUri;IdempotencyRecord record =- IdempotencyRecord.reserved(idempotencyKey, binding, generation, createdAt, expiresAt);+ IdempotencyRecord.reserved(idempotencyKey, binding, createdAt, expiresAt);return httpStatus == null ? record : record.withResponse(httpStatus, responseSummary);}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.javaindex 1bd4f2e5ba..56a88fc461 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java@@ -264,7 +264,6 @@ public class IcebergNamespaceOperations {CreateNamespaceRequest createNamespaceRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(createNamespaceRequest, "CreateNamespaceRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -272,12 +271,13 @@ public class IcebergNamespaceOperations {}private Response doCreateNamespace(String prefix, CreateNamespaceRequest createNamespaceRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- LOG.info(- "Create Iceberg namespace, catalog: {}, createNamespaceRequest: {}",- catalogName,- createNamespaceRequest);try {+ IcebergRESTUtils.validateRequest(createNamespaceRequest, "CreateNamespaceRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ LOG.info(+ "Create Iceberg namespace, catalog: {}, createNamespaceRequest: {}",+ catalogName,+ createNamespaceRequest);return Utils.doAs(httpRequest,() -> {@@ -307,8 +307,6 @@ public class IcebergNamespaceOperations {UpdateNamespacePropertiesRequest updateNamespacePropertiesRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(- updateNamespacePropertiesRequest, "UpdateNamespacePropertiesRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -319,15 +317,18 @@ public class IcebergNamespaceOperations {String prefix,String namespace,UpdateNamespacePropertiesRequest updateNamespacePropertiesRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- LOG.info(- "Update Iceberg namespace, catalog: {}, namespace: {}, updateNamespacePropertiesRequest: {}",- catalogName,- icebergNS,- SerializeUpdateNamespacePropertiesRequest(updateNamespacePropertiesRequest));try {+ IcebergRESTUtils.validateRequest(+ updateNamespacePropertiesRequest, "UpdateNamespacePropertiesRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ LOG.info(+ "Update Iceberg namespace, catalog: {}, namespace: {}, updateNamespacePropertiesRequest: {}",+ catalogName,+ icebergNS,+ SerializeUpdateNamespacePropertiesRequest(updateNamespacePropertiesRequest));return Utils.doAs(httpRequest,() -> {@@ -363,7 +364,6 @@ public class IcebergNamespaceOperations {@HeaderParam(IcebergTableOperations.X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(registerTableRequest, "RegisterTableRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -375,19 +375,21 @@ public class IcebergNamespaceOperations {String namespace,RegisterTableRequest registerTableRequest,String accessDelegation) {- boolean isCredentialVending = IcebergTableOperations.isCredentialVending(accessDelegation);- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- LOG.info(- "Register Iceberg table, catalog: {}, namespace: {}, registerTableRequest: {}, "- + "accessDelegation: {}, isCredentialVending: {}",- catalogName,- icebergNS,- registerTableRequest,- accessDelegation,- isCredentialVending);try {+ IcebergRESTUtils.validateRequest(registerTableRequest, "RegisterTableRequest");+ boolean isCredentialVending = IcebergTableOperations.isCredentialVending(accessDelegation);+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ LOG.info(+ "Register Iceberg table, catalog: {}, namespace: {}, registerTableRequest: {}, "+ + "accessDelegation: {}, isCredentialVending: {}",+ catalogName,+ icebergNS,+ registerTableRequest,+ accessDelegation,+ isCredentialVending);return Utils.doAs(httpRequest,() -> {@@ -418,7 +420,6 @@ public class IcebergNamespaceOperations {RegisterViewRequest registerViewRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(registerViewRequest, "RegisterViewRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -427,15 +428,17 @@ public class IcebergNamespaceOperations {private Response doRegisterView(String prefix, String namespace, RegisterViewRequest registerViewRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- LOG.info(- "Register Iceberg view, catalog: {}, namespace: {}, registerViewRequest: {}",- catalogName,- icebergNS,- registerViewRequest);try {+ IcebergRESTUtils.validateRequest(registerViewRequest, "RegisterViewRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ LOG.info(+ "Register Iceberg view, catalog: {}, namespace: {}, registerViewRequest: {}",+ catalogName,+ icebergNS,+ registerViewRequest);return Utils.doAs(httpRequest,() -> {diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.javaindex 9d1c153db4..45ba165ceb 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java@@ -190,7 +190,6 @@ public class IcebergTableOperations {@HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -202,19 +201,21 @@ public class IcebergTableOperations {String namespace,CreateTableRequest createTableRequest,String accessDelegation) {- boolean isCredentialVending = isCredentialVending(accessDelegation);- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- LOG.info(- "Create Iceberg table, catalog: {}, namespace: {}, create table request: {}, "- + "accessDelegation: {}, isCredentialVending: {}",- catalogName,- icebergNS,- createTableRequest,- accessDelegation,- isCredentialVending);try {+ IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest");+ boolean isCredentialVending = isCredentialVending(accessDelegation);+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ LOG.info(+ "Create Iceberg table, catalog: {}, namespace: {}, create table request: {}, "+ + "accessDelegation: {}, isCredentialVending: {}",+ catalogName,+ icebergNS,+ createTableRequest,+ accessDelegation,+ isCredentialVending);return Utils.doAs(httpRequest,() -> {@@ -247,7 +248,6 @@ public class IcebergTableOperations {UpdateTableRequest updateTableRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(updateTableRequest, "UpdateTableRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -256,19 +256,21 @@ public class IcebergTableOperations {private Response doUpdateTable(String prefix, String namespace, String table, UpdateTableRequest updateTableRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- String tableName = RESTUtil.decodeString(table);- if (LOG.isInfoEnabled()) {- LOG.info(- "Update Iceberg table, catalog: {}, namespace: {}, table: {}, updateTableRequest: {}",- catalogName,- icebergNS,- table,- SerializeUpdateTableRequest(updateTableRequest));- }try {+ IcebergRESTUtils.validateRequest(updateTableRequest, "UpdateTableRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ String tableName = RESTUtil.decodeString(table);+ if (LOG.isInfoEnabled()) {+ LOG.info(+ "Update Iceberg table, catalog: {}, namespace: {}, table: {}, updateTableRequest: {}",+ catalogName,+ icebergNS,+ table,+ SerializeUpdateTableRequest(updateTableRequest));+ }return Utils.doAs(httpRequest,() -> {diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableRenameOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableRenameOperations.javaindex 810c5a66a2..ce2cb4d83a 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableRenameOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableRenameOperations.java@@ -85,7 +85,6 @@ public class IcebergTableRenameOperations {RenameTableRequest renameTableRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(renameTableRequest, "RenameTableRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -93,13 +92,14 @@ public class IcebergTableRenameOperations {}private Response doRenameTable(String prefix, RenameTableRequest renameTableRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- LOG.info(- "Rename Iceberg tables, catalog: {}, source: {}, destination: {}.",- catalogName,- renameTableRequest.source(),- renameTableRequest.destination());try {+ IcebergRESTUtils.validateRequest(renameTableRequest, "RenameTableRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ LOG.info(+ "Rename Iceberg tables, catalog: {}, source: {}, destination: {}.",+ catalogName,+ renameTableRequest.source(),+ renameTableRequest.destination());return Utils.doAs(httpRequest,() -> {diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.javaindex 6b06aa4eb2..388c6aeef9 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java@@ -155,7 +155,6 @@ public class IcebergViewOperations {CreateViewRequest createViewRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(createViewRequest, "CreateViewRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -164,15 +163,17 @@ public class IcebergViewOperations {private Response doCreateView(String prefix, String namespace, CreateViewRequest createViewRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- LOG.info(- "Create Iceberg view, catalog: {}, namespace: {}, createViewRequest: {}",- catalogName,- icebergNS,- createViewRequest);try {+ IcebergRESTUtils.validateRequest(createViewRequest, "CreateViewRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ LOG.info(+ "Create Iceberg view, catalog: {}, namespace: {}, createViewRequest: {}",+ catalogName,+ icebergNS,+ createViewRequest);return Utils.doAs(httpRequest,() -> {@@ -248,7 +249,6 @@ public class IcebergViewOperations {UpdateTableRequest replaceViewRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(replaceViewRequest, "UpdateTableRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -257,17 +257,19 @@ public class IcebergViewOperations {private Response doReplaceView(String prefix, String namespace, String view, UpdateTableRequest replaceViewRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- Namespace icebergNS =- RESTUtil.decodeNamespace(namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);- String viewName = RESTUtil.decodeString(view);- LOG.info(- "Replace Iceberg view, catalog: {}, namespace: {}, view: {}, replaceViewRequest: {}",- catalogName,- icebergNS,- viewName,- SerializeReplaceViewRequest(replaceViewRequest));try {+ IcebergRESTUtils.validateRequest(replaceViewRequest, "UpdateTableRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ Namespace icebergNS =+ RESTUtil.decodeNamespace(+ namespace, IcebergRESTUtils.NAMESPACE_SEPARATOR_URLENCODED_UTF_8);+ String viewName = RESTUtil.decodeString(view);+ LOG.info(+ "Replace Iceberg view, catalog: {}, namespace: {}, view: {}, replaceViewRequest: {}",+ catalogName,+ icebergNS,+ viewName,+ SerializeReplaceViewRequest(replaceViewRequest));return Utils.doAs(httpRequest,() -> {diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewRenameOperations.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewRenameOperations.javaindex e64285b588..76bdd72acc 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewRenameOperations.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewRenameOperations.java@@ -84,7 +84,6 @@ public class IcebergViewRenameOperations {RenameTableRequest renameViewRequest,@HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,@Context UriInfo uriInfo) {- IcebergRESTUtils.validateRequest(renameViewRequest, "RenameTableRequest");return idempotencyManager.replayOrExecute(idempotencyKey,IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),@@ -92,13 +91,14 @@ public class IcebergViewRenameOperations {}private Response doRenameView(String prefix, RenameTableRequest renameViewRequest) {- String catalogName = IcebergRESTUtils.getCatalogName(prefix);- LOG.info(- "Rename Iceberg view, catalog: {}, source: {}, destination: {}.",- catalogName,- renameViewRequest.source(),- renameViewRequest.destination());try {+ IcebergRESTUtils.validateRequest(renameViewRequest, "RenameTableRequest");+ String catalogName = IcebergRESTUtils.getCatalogName(prefix);+ LOG.info(+ "Rename Iceberg view, catalog: {}, source: {}, destination: {}.",+ catalogName,+ renameViewRequest.source(),+ renameViewRequest.destination());return Utils.doAs(httpRequest,() -> {diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIcebergIdempotencyManager.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIcebergIdempotencyManager.javaindex 68dbb590f3..5733343f1a 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIcebergIdempotencyManager.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIcebergIdempotencyManager.java@@ -23,7 +23,6 @@ import java.util.Arrays;import java.util.HashMap;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;import java.util.concurrent.atomic.AtomicInteger;import javax.ws.rs.core.HttpHeaders;import javax.ws.rs.core.MediaType;@@ -149,6 +148,23 @@ public class TestIcebergIdempotencyManager {Assertions.assertEquals(2, executions.get());}+ @Test+ void testReleaseFailureKeepsMutationResponse() {+ IdempotencyStore store = Mockito.mock(IdempotencyStore.class);+ Mockito.when(store.reserve(Mockito.eq(KEY), Mockito.anyString(), Mockito.anyLong()))+ .thenReturn(true);+ Mockito.doThrow(new IllegalStateException("release unavailable"))+ .when(store)+ .release(Mockito.anyString());+ IcebergIdempotencyManager manager =+ new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));++ Response response = respondWith(manager, 500, new AtomicInteger());++ Assertions.assertEquals(500, response.getStatus());+ Mockito.verify(store).release(KEY);+ }+@Testvoid testUnauthorizedResponseReleasesTheKey() {IcebergIdempotencyManager manager = newManager(ImmutableMap.of());@@ -229,7 +245,7 @@ public class TestIcebergIdempotencyManager {void testRetryWhileTheFirstRequestIsRunningIsRetryable() {IdempotencyStore store = Mockito.mock(IdempotencyStore.class);Mockito.when(store.reserve(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()))- .thenReturn(OptionalLong.empty());+ .thenReturn(false);Mockito.when(store.load(KEY)).thenReturn(Optional.empty());IcebergIdempotencyManager manager =new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));@@ -265,12 +281,12 @@ public class TestIcebergIdempotencyManager {void testNoOpFinalizeRetainsReservation() {IdempotencyStore store = Mockito.mock(IdempotencyStore.class);Mockito.when(store.reserve(Mockito.eq(KEY), Mockito.anyString(), Mockito.anyLong()))- .thenReturn(OptionalLong.of(1));+ .thenReturn(true);IcebergIdempotencyManager manager =new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));Response response = execute(manager, KEY, new AtomicInteger());Assertions.assertEquals(200, response.getStatus());- Mockito.verify(store, Mockito.never()).release(Mockito.anyString(), Mockito.anyLong());+ Mockito.verify(store, Mockito.never()).release(Mockito.anyString());}@Test@@ -282,14 +298,14 @@ public class TestIcebergIdempotencyManager {Mockito.when(store.load(KEY)).thenReturn(Optional.of(- IdempotencyRecord.reserved(KEY, BINDING, 2, 0, Long.MAX_VALUE)+ IdempotencyRecord.reserved(KEY, BINDING, 0, Long.MAX_VALUE).withResponse(200, "replacement")));- return OptionalLong.of(1);+ return true;});IcebergIdempotencyManager manager =new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));Assertions.assertEquals(200, execute(manager, KEY, new AtomicInteger()).getStatus());- Mockito.verify(store, Mockito.never()).release(Mockito.anyString(), Mockito.anyLong());+ Mockito.verify(store, Mockito.never()).release(Mockito.anyString());}@Test@@ -328,7 +344,7 @@ public class TestIcebergIdempotencyManager {Assertions.assertEquals(200, first.getStatus());Assertions.assertEquals(first.getEntity(), retry.getEntity());Assertions.assertEquals(1, executions.get());- Mockito.verify(store, Mockito.never()).release(Mockito.anyString(), Mockito.anyLong());+ Mockito.verify(store, Mockito.never()).release(Mockito.anyString());}}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.javaindex 6cb5a715b9..e614c3604f 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.java@@ -22,7 +22,6 @@ import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;import org.apache.gravitino.iceberg.common.IcebergConfig;import org.junit.jupiter.api.Assertions;@@ -128,8 +127,8 @@ public class TestIdempotencyStoreFactory {}@Override- public OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {- return OptionalLong.of(1);+ public boolean reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {+ return true;}@Override@@ -138,11 +137,10 @@ public class TestIdempotencyStoreFactory {}@Override- public void finalizeRecord(- String idempotencyKey, long claim, int httpStatus, String responseSummary) {}+ public void finalizeRecord(String idempotencyKey, int httpStatus, String responseSummary) {}@Override- public void release(String idempotencyKey, long claim) {}+ public void release(String idempotencyKey) {}@Overridepublic int purgeExpired(long beforeMs) {diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.javaindex 5df0b11ad5..14923b6c16 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.java@@ -24,7 +24,6 @@ import java.util.Collections;import java.util.List;import java.util.Map;import java.util.Optional;-import java.util.OptionalLong;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -60,20 +59,20 @@ public class TestInMemoryIdempotencyStore {@Testvoid testReserveClaimsKeyOnlyOnce() {- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent());- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());- Assertions.assertTrue(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).isPresent());+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ Assertions.assertFalse(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ Assertions.assertTrue(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS));}@Testvoid testKeyCaseVariantsAddressTheSameRecord() {- long claim = store.reserve(KEY_UPPER, BINDING, FAR_FUTURE_MS).orElseThrow();- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ Assertions.assertTrue(store.reserve(KEY_UPPER, BINDING, FAR_FUTURE_MS));+ Assertions.assertFalse(store.reserve(KEY, BINDING, 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}");+ store.finalizeRecord(KEY_UPPER, 200, "{\"a\":1}");IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);Assertions.assertEquals(KEY, record.idempotencyKey());Assertions.assertEquals(200, record.httpStatus().intValue());@@ -81,10 +80,10 @@ public class TestInMemoryIdempotencyStore {@Testvoid testLoadReturnsEmptyUntilFinalized() {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));Assertions.assertEquals(Optional.empty(), store.load(KEY));- store.finalizeRecord(KEY, claim, 200, "{\"a\":1}");+ store.finalizeRecord(KEY, 200, "{\"a\":1}");IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);Assertions.assertTrue(record.isFinalized());@@ -101,8 +100,8 @@ public class TestInMemoryIdempotencyStore {@Testvoid testFinalizeWithoutBodyIsReplayable() {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(KEY, claim, 204, null);+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.finalizeRecord(KEY, 204, null);IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);Assertions.assertEquals(204, record.httpStatus().intValue());@@ -111,72 +110,50 @@ public class TestInMemoryIdempotencyStore {@Testvoid testFinalizeDoesNotResurrectAPurgedRecord() {- store.finalizeRecord(KEY, 1L, 200, "{}");+ store.finalizeRecord(KEY, 200, "{}");Assertions.assertEquals(Optional.empty(), store.load(KEY));Assertions.assertEquals(0, store.size());}@Testvoid testReleaseFreesTheKeyForRetry() {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.release(KEY, claim);+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.release(KEY);- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent());+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));}@Testvoid testReleaseKeepsAFinalizedRecord() {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(KEY, claim, 200, "{}");- store.release(KEY, claim);+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.finalizeRecord(KEY, 200, "{}");+ store.release(KEY);Assertions.assertTrue(store.load(KEY).isPresent());- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(store.reserve(KEY, BINDING, FAR_FUTURE_MS));}@Test- void testStaleFinalizeAfterReReservationIsIgnored() {- long staleClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- // 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);- long currentClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ void testReReserveAfterReleaseReusesFixedClaim() {+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.release(KEY);+ Assertions.assertTrue(store.reserve(KEY, BINDING, 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.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());-- // And the current owner can still finalize its own response.- store.finalizeRecord(KEY, currentClaim, 201, "{\"stale\":false}");+ store.finalizeRecord(KEY, 201, "{\"ok\":true}");Assertions.assertEquals(- "{\"stale\":false}", store.load(KEY).orElseThrow(AssertionError::new).responseSummary());- }-- @Test- void testStaleReleaseAfterReReservationIsIgnored() {- long staleClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.release(KEY, staleClaim);- store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();-- 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.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ "{\"ok\":true}", store.load(KEY).orElseThrow(AssertionError::new).responseSummary());}@Testvoid testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal() {String otherBinding = "DELETE v1/cat1/namespaces/ns1/tables/t1";- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));- Assertions.assertTrue(store.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(store.reserve(KEY, otherBinding, FAR_FUTURE_MS));Assertions.assertEquals(Optional.empty(), store.load(KEY));- store.finalizeRecord(KEY, claim, 201, "{}");- Assertions.assertTrue(store.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());+ store.finalizeRecord(KEY, 201, "{}");+ Assertions.assertFalse(store.reserve(KEY, otherBinding, FAR_FUTURE_MS));Assertions.assertEquals(BINDING, store.load(KEY).orElseThrow(AssertionError::new).operationBinding());}@@ -193,9 +170,8 @@ public class TestInMemoryIdempotencyStore {now.addAndGet(1_000L);Assertions.assertEquals(1, clockedStore.purgeExpired(now.get()));- Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, now.get() + 1_000L).isPresent());- Assertions.assertTrue(- clockedStore.reserve(OTHER_KEY, BINDING, now.get() + 60_000L).isEmpty());+ Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, now.get() + 1_000L));+ Assertions.assertFalse(clockedStore.reserve(OTHER_KEY, BINDING, now.get() + 60_000L));} finally {clockedStore.close();}@@ -207,17 +183,17 @@ public class TestInMemoryIdempotencyStore {InMemoryIdempotencyStore clockedStore = newStore(ImmutableMap.of(), now::get);try {long deadline = now.get() + 1_000L;- long claim = clockedStore.reserve(KEY, BINDING, deadline).orElseThrow();+ Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, 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, "{}");+ clockedStore.finalizeRecord(KEY, 200, "{}");Assertions.assertTrue(clockedStore.load(KEY).isPresent());now.set(deadline);Assertions.assertEquals(Optional.empty(), clockedStore.load(KEY));- Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, now.get() + 1_000L).isPresent());+ Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, now.get() + 1_000L));} finally {clockedStore.close();}@@ -250,7 +226,7 @@ public class TestInMemoryIdempotencyStore {ExecutorService executor = Executors.newFixedThreadPool(threads);CountDownLatch start = new CountDownLatch(1);CountDownLatch done = new CountDownLatch(threads);- List<OptionalLong> results = Collections.synchronizedList(new ArrayList<>());+ List<Boolean> results = Collections.synchronizedList(new ArrayList<>());AtomicReference<Throwable> failure = new AtomicReference<>();try {for (int i = 0; i < threads; i++) {@@ -270,7 +246,7 @@ public class TestInMemoryIdempotencyStore {Assertions.assertTrue(done.await(30, TimeUnit.SECONDS));Assertions.assertNull(failure.get(), "no reserve should fail");Assertions.assertEquals(threads, results.size(), "every caller should report a result");- Assertions.assertEquals(1, results.stream().filter(OptionalLong::isPresent).count());+ Assertions.assertEquals(1, results.stream().filter(Boolean::booleanValue).count());} finally {executor.shutdownNow();}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.javaindex 3754227820..27e84ae316 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.java@@ -29,7 +29,6 @@ import java.nio.file.Path;import java.time.Clock;import java.util.Locale;import java.util.Optional;-import java.util.OptionalLong;import java.util.UUID;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;@@ -134,17 +133,17 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {IcebergConstants.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL, "PT1H"));try (IdempotencyStore configured = IdempotencyStoreFactory.create(config)) {Assertions.assertInstanceOf(JdbcIdempotencyStore.class, configured);- long generation = configured.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- configured.finalizeRecord(KEY, generation, 200, "{}");+ Assertions.assertTrue(configured.reserve(KEY, BINDING, FAR_FUTURE_MS));+ configured.finalizeRecord(KEY, 200, "{}");Assertions.assertEquals(BINDING, peer.load(KEY).orElseThrow().operationBinding());}}@TestTemplatevoid testReserveClaimsKeyOnlyOnce() {- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent());- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());- Assertions.assertTrue(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).isPresent());+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ Assertions.assertFalse(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ Assertions.assertTrue(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS));}@TestTemplate@@ -163,7 +162,7 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {() -> {try {start.await();- if (contender.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent()) {+ if (contender.reserve(KEY, BINDING, FAR_FUTURE_MS)) {reserved.incrementAndGet();}} catch (Exception e) {@@ -187,10 +186,10 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {@TestTemplatevoid testLoadReturnsEmptyUntilFinalized() {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));Assertions.assertEquals(Optional.empty(), store.load(KEY));- store.finalizeRecord(KEY, claim, 200, "{\"a\":1}");+ store.finalizeRecord(KEY, 200, "{\"a\":1}");IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);Assertions.assertTrue(record.isFinalized());@@ -203,8 +202,8 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {@TestTemplatevoid testFinalizeWithoutBodyIsReplayable() {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(KEY, claim, 204, null);+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.finalizeRecord(KEY, 204, null);IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);Assertions.assertEquals(204, record.httpStatus().intValue());@@ -213,70 +212,47 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {@TestTemplatevoid testFinalizeDoesNotResurrectPurgedRecord() {- store.finalizeRecord(KEY, 1, 200, "{}");+ store.finalizeRecord(KEY, 200, "{}");Assertions.assertEquals(Optional.empty(), store.load(KEY));}@TestTemplatevoid testReleaseFreesReservationButKeepsFinalizedResponse() {- long oldClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.release(KEY, oldClaim);- long newClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.release(KEY);+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));- store.finalizeRecord(KEY, newClaim, 201, "{\"b\":2}");- store.release(KEY, newClaim);+ store.finalizeRecord(KEY, 201, "{\"b\":2}");+ store.release(KEY);Assertions.assertTrue(store.load(KEY).isPresent(), "a finalized response survives a release");}@TestTemplate- void testStaleFinalizeAfterReReservationIsIgnored() {- long oldClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.release(KEY, oldClaim);- long newClaim = peer.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ void testReReserveAfterReleaseReusesFixedClaim() {+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ store.release(KEY);+ Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS));- store.finalizeRecord(KEY, oldClaim, 500, "stale");-- Assertions.assertTrue(peer.load(KEY).isEmpty());- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());- peer.finalizeRecord(KEY, newClaim, 201, "current");+ peer.finalizeRecord(KEY, 201, "current");IdempotencyRecord record = store.load(KEY).orElseThrow();- Assertions.assertEquals(newClaim, record.claim());- Assertions.assertEquals(201, record.httpStatus());- Assertions.assertEquals("current", record.responseSummary());- }-- @TestTemplate- void testStaleReleaseAfterReReservationIsIgnored() {- long oldClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.release(KEY, oldClaim);- long newClaim = peer.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();-- store.release(KEY, oldClaim);-- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());- Assertions.assertTrue(peer.load(KEY).isEmpty());- peer.finalizeRecord(KEY, newClaim, 201, "current");- IdempotencyRecord record = store.load(KEY).orElseThrow();- Assertions.assertEquals(newClaim, record.claim());Assertions.assertEquals("current", record.responseSummary());}@TestTemplatevoid testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal() {String otherBinding = "DELETE v1/cat1/namespaces/ns1/tables/t1";- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));- Assertions.assertTrue(peer.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(peer.reserve(KEY, otherBinding, FAR_FUTURE_MS));Assertions.assertTrue(peer.load(KEY).isEmpty());- store.finalizeRecord(KEY, claim, 201, "original");+ store.finalizeRecord(KEY, 201, "original");IdempotencyRecord original = store.load(KEY).orElseThrow();- Assertions.assertEquals(claim, original.claim());Assertions.assertEquals(BINDING, original.operationBinding());Assertions.assertEquals(201, original.httpStatus());Assertions.assertEquals("original", original.responseSummary());Assertions.assertEquals(FAR_FUTURE_MS, original.expiresAtMs());- Assertions.assertTrue(peer.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(peer.reserve(KEY, otherBinding, FAR_FUTURE_MS));Assertions.assertEquals(original, peer.load(KEY).orElseThrow());}@@ -288,17 +264,17 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {Assertions.assertEquals(1, store.purgeExpired(now));- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent());+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));Assertions.assertTrue(- store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).isEmpty(),+ !store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS),"an unexpired record must survive the purge");}@TestTemplatevoid testPurgeTaskRemovesOnlyExpiredRecords() throws Exception {store.reserve(KEY, BINDING, now.get());- long claim = store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(OTHER_KEY, claim, 200, "{}");+ Assertions.assertTrue(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS));+ store.finalizeRecord(OTHER_KEY, 200, "{}");store.purgeExpiredRecords();Assertions.assertEquals(1, rowCount());Assertions.assertTrue(store.load(OTHER_KEY).isPresent());@@ -314,18 +290,17 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS);Assertions.assertEquals(records, store.purgeExpired(now));- Assertions.assertTrue(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS));}@TestTemplatevoid testReplaySurvivesStoreRestartAndIsVisibleToPeer() throws Exception {- long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ Assertions.assertFalse(peer.reserve(KEY, BINDING, FAR_FUTURE_MS));Assertions.assertTrue(peer.load(KEY).isEmpty());String response = "{\"metadata\":\"" + "x".repeat(100_000) + "\"}";- store.finalizeRecord(KEY, claim, 200, response);+ store.finalizeRecord(KEY, 200, response);IdempotencyRecord original = peer.load(KEY).orElseThrow();- Assertions.assertEquals(claim, original.claim());store.close();try (IdempotencyStore restarted =IdempotencyStoreFactory.create(@@ -338,66 +313,55 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {}@TestTemplate- void testDeletedReservationCannotReuseItsFencingToken() {- long oldClaim = store.reserve(KEY, BINDING, now.get()).orElseThrow();+ void testPurgedKeyCanBeReservedAgainWithFixedClaim() {+ Assertions.assertTrue(store.reserve(KEY, BINDING, now.get()));Assertions.assertEquals(1, peer.purgeExpired(now.get()));- long newClaim = peer.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS));- Assertions.assertTrue(newClaim > oldClaim);- store.finalizeRecord(KEY, oldClaim, 500, "stale");- Assertions.assertTrue(peer.load(KEY).isEmpty());- store.release(KEY, oldClaim);- peer.finalizeRecord(KEY, newClaim, 201, "current");+ peer.finalizeRecord(KEY, 201, "current");Assertions.assertEquals("current", store.load(KEY).orElseThrow().responseSummary());}@TestTemplate- void testExpiredReservationIsReclaimedAndOldOwnerIsFenced() {- long oldClaim = store.reserve(KEY, BINDING, now.get() + 1).orElseThrow();+ void testExpiredReservationIsReclaimedAsNewKey() {+ Assertions.assertTrue(store.reserve(KEY, BINDING, now.get() + 1));now.incrementAndGet();- long newClaim = peer.reserve(KEY, "PUT /replacement", FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(KEY, oldClaim, 500, "stale");- store.release(KEY, oldClaim);- Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());- Assertions.assertTrue(peer.load(KEY).isEmpty());- peer.finalizeRecord(KEY, newClaim, 201, "new");+ Assertions.assertTrue(peer.reserve(KEY, "PUT /replacement", FAR_FUTURE_MS));+ Assertions.assertFalse(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ peer.finalizeRecord(KEY, 201, "new");IdempotencyRecord record = store.load(KEY).orElseThrow();- Assertions.assertEquals(newClaim, record.claim());Assertions.assertEquals("PUT /replacement", record.operationBinding());Assertions.assertEquals("new", record.responseSummary());}@TestTemplatevoid testReserveReclaimsKeyThatExpiresBeforeSecondAttempt() {- long oldClaim = store.reserve(KEY, BINDING, now.get() + 1).orElseThrow();+ Assertions.assertTrue(store.reserve(KEY, BINDING, now.get() + 1));Mockito.when(clock.millis()).thenReturn(now.get(), now.get() + 1);- long newClaim = peer.reserve(KEY, "PUT /replacement", FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(KEY, oldClaim, 500, "stale");- store.release(KEY, oldClaim);- peer.finalizeRecord(KEY, newClaim, 201, "current");+ Assertions.assertTrue(peer.reserve(KEY, "PUT /replacement", FAR_FUTURE_MS));+ peer.finalizeRecord(KEY, 201, "current");IdempotencyRecord record = store.load(KEY).orElseThrow();- Assertions.assertEquals(newClaim, record.claim());Assertions.assertEquals("PUT /replacement", record.operationBinding());Assertions.assertEquals("current", record.responseSummary());}@TestTemplatevoid testExpiredResponseIsNotLoadedAndCanBeReplacedWithoutPurge() {- long oldClaim = store.reserve(KEY, BINDING, now.get() + 1).orElseThrow();- store.finalizeRecord(KEY, oldClaim, 200, "old");+ Assertions.assertTrue(store.reserve(KEY, BINDING, now.get() + 1));+ store.finalizeRecord(KEY, 200, "old");now.incrementAndGet();Assertions.assertTrue(peer.load(KEY).isEmpty());- long newClaim = peer.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();+ Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS));Assertions.assertTrue(peer.load(KEY).isEmpty());- peer.finalizeRecord(KEY, newClaim, 204, null);+ peer.finalizeRecord(KEY, 204, null);Assertions.assertNull(store.load(KEY).orElseThrow().responseSummary());}@TestTemplatevoid testFinalizeDoesNotResurrectExpiredReservation() throws Exception {- long claim = store.reserve(KEY, BINDING, now.get()).orElseThrow();- store.finalizeRecord(KEY, claim, 200, "expired");+ Assertions.assertTrue(store.reserve(KEY, BINDING, now.get()));+ store.finalizeRecord(KEY, 200, "expired");// Inspect persisted state so a read-time expiry filter cannot hide an incorrect finalization.try (SqlSession session =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();@@ -413,17 +377,17 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {store.reserve(KEY, BINDING, now.get());store.reserve(OTHER_KEY, BINDING, now.get() + 1);Assertions.assertEquals(1, store.purgeExpired(now.get()));- Assertions.assertTrue(peer.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(peer.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS));}@TestTemplatevoid testKeyCaseNormalizationOnAllOperations() {String upper = KEY.toUpperCase(Locale.ROOT);- long oldClaim = store.reserve(upper, BINDING, FAR_FUTURE_MS).orElseThrow();- Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());- peer.release(upper, oldClaim);- long newClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- peer.finalizeRecord(upper, newClaim, 200, "{}");+ Assertions.assertTrue(store.reserve(upper, BINDING, FAR_FUTURE_MS));+ Assertions.assertFalse(peer.reserve(KEY, BINDING, FAR_FUTURE_MS));+ peer.release(upper);+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ peer.finalizeRecord(upper, 200, "{}");Assertions.assertEquals(KEY, store.load(upper).orElseThrow().idempotencyKey());}@@ -434,9 +398,9 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {Assertions.assertThrows(IllegalArgumentException.class, () -> store.reserve(KEY, null, FAR_FUTURE_MS));Assertions.assertThrows(IllegalArgumentException.class, () -> store.load("invalid"));- Assertions.assertThrows(IllegalArgumentException.class, () -> store.release("invalid", 1));+ Assertions.assertThrows(IllegalArgumentException.class, () -> store.release("invalid"));Assertions.assertThrows(- IllegalArgumentException.class, () -> store.finalizeRecord("invalid", 1, 200, null));+ IllegalArgumentException.class, () -> store.finalizeRecord("invalid", 200, null));Assertions.assertEquals(0, rowCount());}@@ -448,7 +412,7 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {} finally {SessionUtils.rollbackTransaction();}- Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());+ Assertions.assertFalse(peer.reserve(KEY, BINDING, FAR_FUTURE_MS));}@TestTemplate@@ -462,21 +426,20 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {// Jetty accepts request targets longer than MySQL's 64 KiB TEXT limit by default.String uri = "/v1/cat1/namespaces/ns%2Fone/tables?tag=" + "x".repeat(70_000) + "%26y";String binding = "POST " + uri;- long claim = store.reserve(KEY, binding, FAR_FUTURE_MS).orElseThrow();- store.finalizeRecord(KEY, claim, 200, "{}");+ Assertions.assertTrue(store.reserve(KEY, binding, FAR_FUTURE_MS));+ store.finalizeRecord(KEY, 200, "{}");Assertions.assertEquals(binding, peer.load(KEY).orElseThrow().operationBinding());try (SqlSession session =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();var statement = session.getConnection().createStatement();var result =statement.executeQuery(- "SELECT http_method, request_uri, generation FROM iceberg_idempotency_meta")) {+ "SELECT http_method, request_uri FROM iceberg_idempotency_meta")) {Assertions.assertTrue(result.next());Assertions.assertEquals("POST", result.getString("http_method"));String storedUri = result.getString("request_uri");Assertions.assertEquals(uri.length(), storedUri.length());Assertions.assertEquals(uri, storedUri);- Assertions.assertEquals(claim, result.getLong("generation"));}}@@ -526,8 +489,8 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {statement.execute("ALTER TABLE saved_idempotency_keys RENAME TO iceberg_idempotency_meta");}retrying.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H"));- long claim = retrying.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- retrying.finalizeRecord(KEY, claim, 201, "recovered");+ Assertions.assertTrue(retrying.reserve(KEY, BINDING, FAR_FUTURE_MS));+ retrying.finalizeRecord(KEY, 201, "recovered");Assertions.assertEquals("recovered", peer.load(KEY).orElseThrow().responseSummary());Assertions.assertThrows(IllegalStateException.class,@@ -553,7 +516,6 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();var statement = session.getConnection().createStatement()) {statement.execute("DROP TABLE iceberg_idempotency_meta");- statement.execute("DROP TABLE iceberg_idempotency_generation_meta");ScriptRunner runner = new ScriptRunner(session.getConnection());runner.setLogWriter(null);runner.setStopOnError(true);@@ -563,9 +525,8 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {try (IdempotencyStore migrated =IdempotencyStoreFactory.create(new IcebergConfig(ImmutableMap.of("idempotency-store-type", "jdbc")))) {- long claim = migrated.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();- migrated.finalizeRecord(KEY, claim, 200, "{}");- Assertions.assertEquals(claim, migrated.load(KEY).orElseThrow().claim());+ Assertions.assertTrue(migrated.reserve(KEY, BINDING, FAR_FUTURE_MS));+ migrated.finalizeRecord(KEY, 200, "{}");}}@@ -606,12 +567,10 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {holderId = result.getLong(1);}IcebergIdempotencyKeyMapper mapper = holder.getMapper(IcebergIdempotencyKeyMapper.class);- long generation = JdbcIdempotencyStore.nextGeneration(mapper, KEY);Assertions.assertEquals(1,mapper.replaceExpired(- IcebergIdempotencyKeyPO.reserved(- KEY, BINDING, generation, now.get(), FAR_FUTURE_MS)));+ IcebergIdempotencyKeyPO.reserved(KEY, BINDING, now.get(), FAR_FUTURE_MS)));Future<Integer> purge =executor.submit(() -> {@@ -644,7 +603,7 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {awaitBlockedPurge(purge, holderId);holder.commit();Assertions.assertEquals(0, purge.get(30, TimeUnit.SECONDS));- peer.finalizeRecord(KEY, generation, 201, "renewed");+ peer.finalizeRecord(KEY, 201, "renewed");Assertions.assertEquals("renewed", store.load(KEY).orElseThrow().responseSummary());} finally {executor.shutdownNow();@@ -662,18 +621,17 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {.addInterceptor(new PauseReplacement(duplicateInsert, purged));ExecutorService executor = Executors.newSingleThreadExecutor();try {- Future<OptionalLong> result =- executor.submit(() -> store.reserve(KEY, BINDING, FAR_FUTURE_MS));+ Future<Boolean> result = executor.submit(() -> store.reserve(KEY, BINDING, FAR_FUTURE_MS));Assertions.assertTrue(duplicateInsert.await(30, TimeUnit.SECONDS));Assertions.assertEquals(1, peer.purgeExpired(now.get()));- long peerClaim = peerWins ? peer.reserve(KEY, "PUT /peer", FAR_FUTURE_MS).orElseThrow() : 0;+ if (peerWins) {+ Assertions.assertTrue(peer.reserve(KEY, "PUT /peer", FAR_FUTURE_MS));+ }purged.countDown();- OptionalLong reservation = result.get(30, TimeUnit.SECONDS);- Assertions.assertEquals(!peerWins, reservation.isPresent());- long claim = reservation.orElse(peerClaim);- peer.finalizeRecord(KEY, claim, 201, "retained");+ boolean reserved = result.get(30, TimeUnit.SECONDS);+ Assertions.assertEquals(!peerWins, reserved);+ peer.finalizeRecord(KEY, 201, "retained");IdempotencyRecord record = store.load(KEY).orElseThrow();- Assertions.assertEquals(claim, record.claim());Assertions.assertEquals(peerWins ? "PUT /peer" : BINDING, record.operationBinding());Assertions.assertEquals("retained", record.responseSummary());} finally {@@ -726,7 +684,7 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {}}- // Pause before locking the counter for replacement, after the duplicate INSERT rolls back.+ // Pause before replaceExpired locks the row, after the duplicate INSERT rolls back.@Intercepts(@Signature(type = Executor.class,@@ -746,8 +704,8 @@ public class TestJdbcIdempotencyStore extends TestJDBCBackend {public Object intercept(Invocation invocation) throws Throwable {if (((MappedStatement) invocation.getArgs()[0]).getId()- .equals(IcebergIdempotencyKeyMapper.class.getName() + ".advanceGeneration")- && attempts.incrementAndGet() == 2) {+ .equals(IcebergIdempotencyKeyMapper.class.getName() + ".replaceExpired")+ && attempts.incrementAndGet() == 1) {duplicateInsert.countDown();Assertions.assertTrue(purged.await(30, TimeUnit.SECONDS));}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyFinalizeFailure.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyFinalizeFailure.javaindex 3dc391f784..e4029e56b4 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyFinalizeFailure.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyFinalizeFailure.java@@ -22,7 +22,6 @@ import com.fasterxml.jackson.databind.JsonNode;import com.google.common.collect.ImmutableMap;import java.util.Collections;import java.util.Optional;-import java.util.OptionalLong;import javax.annotation.Nullable;import javax.servlet.http.HttpServletRequest;import javax.ws.rs.client.Entity;@@ -135,21 +134,21 @@ public class TestIcebergIdempotencyFinalizeFailure extends IcebergTestBase {/** Fault-injection store simulating missing writes and lost commit acknowledgements. */public static class FaultInjectingStore extends InMemoryIdempotencyStore {@Override- public OptionalLong reserve(String key, String binding, long expiresAtMs) {+ public boolean reserve(String key, String binding, long expiresAtMs) {if (key.endsWith("3")) {throw new IllegalStateException("reservation unavailable");}- OptionalLong result = super.reserve(key, binding, expiresAtMs);- if (key.endsWith("4") && result.isPresent()) {+ boolean reserved = super.reserve(key, binding, expiresAtMs);+ if (key.endsWith("4") && reserved) {throw new IllegalStateException("reservation committed but acknowledgement lost");}- return result;+ return reserved;}@Override- public void finalizeRecord(String key, long claim, int status, @Nullable String summary) {+ public void finalizeRecord(String key, int status, @Nullable String summary) {if (key.endsWith("2")) {- super.finalizeRecord(key, claim, status, summary);+ super.finalizeRecord(key, status, summary);throw new IllegalStateException("response committed but acknowledgement lost");}if (key.endsWith("1")) {diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyKey.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyKey.javaindex e0e2449f1d..a726e41950 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyKey.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/rest/TestIcebergIdempotencyKey.java@@ -248,6 +248,25 @@ public class TestIcebergIdempotencyKey extends IcebergNamespaceTestBase {}}+ @Test+ void testInvalidBodyOnRetryStillReplays() {+ Assertions.assertEquals(200, doCreateNamespace(NAMESPACE).getStatus());+ try (Response first = createTable("valid_then_invalid", KEY);+ Response invalidRetry =+ getTableClientBuilder(NAMESPACE, Optional.empty())+ .header(IcebergIdempotencyManager.IDEMPOTENCY_KEY, KEY)+ .post(Entity.json("{}"))) {+ Assertions.assertEquals(200, first.getStatus());+ String firstBody = first.readEntity(String.class);+ Assertions.assertEquals(200, invalidRetry.getStatus());+ Assertions.assertEquals(firstBody, invalidRetry.readEntity(String.class));+ }+ try (Response missing =+ getTableClientBuilder(NAMESPACE, Optional.of("valid_then_invalid")).get()) {+ Assertions.assertEquals(200, missing.getStatus());+ }+ }+@Testvoid testReplayPreservesWireJsonAndOmitsEtag() {Assertions.assertEquals(200, doCreateNamespace(NAMESPACE).getStatus());diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sqlindex 48b0181b21..cd05b1fd29 100644--- a/scripts/h2/schema-2.0.0-h2.sql+++ b/scripts/h2/schema-2.0.0-h2.sql@@ -858,7 +858,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (`idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key',`http_method` VARCHAR(16) NOT NULL COMMENT 'HTTP method of the request',`request_uri` TEXT NOT NULL COMMENT 'encoded request path and sorted query string',- `generation` BIGINT NOT NULL COMMENT 'reservation fencing token',`http_status` INT NULL COMMENT 'HTTP status of finalized response, NULL while reserved',`response_summary` CLOB NULL COMMENT 'serialized response body (JSON) for replay',`audit_info` CLOB NOT NULL COMMENT 'idempotency record audit info',@@ -868,12 +867,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` () COMMENT='Iceberg REST idempotency records';CREATE INDEX IF NOT EXISTS `idx_iim_expires` ON `iceberg_idempotency_meta` (`expires_at`);--CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-) ENGINE=InnoDB;-CREATE TABLE IF NOT EXISTS `ontology_meta` (`ontology_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'ontology id',`ontology_name` VARCHAR(128) NOT NULL COMMENT 'ontology name',diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sqlindex 0e5750c940..6887e4a1c2 100644--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql@@ -447,7 +447,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (`idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key',`http_method` VARCHAR(16) NOT NULL COMMENT 'HTTP method of the request',`request_uri` TEXT NOT NULL COMMENT 'encoded request path and sorted query string',- `generation` BIGINT NOT NULL COMMENT 'reservation fencing token',`http_status` INT NULL COMMENT 'HTTP status of finalized response, NULL while reserved',`response_summary` CLOB NULL COMMENT 'serialized response body (JSON) for replay',`audit_info` CLOB NOT NULL COMMENT 'idempotency record audit info',@@ -457,12 +456,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` () COMMENT='Iceberg REST idempotency records';CREATE INDEX IF NOT EXISTS `idx_iim_expires` ON `iceberg_idempotency_meta` (`expires_at`);--CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-) ENGINE=InnoDB;--- Index live metadata lists and relationship cleanup by their lookup keys and deletion status.CREATE INDEX IF NOT EXISTS `idx_tag_meta_live` ON `tag_meta` (`metalake_id`, `deleted_at`);CREATE INDEX IF NOT EXISTS `idx_policy_meta_live` ON `policy_meta` (`metalake_id`, `deleted_at`);diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sqlindex 2976e62e9e..1f0bff7181 100644--- a/scripts/mysql/schema-2.0.0-mysql.sql+++ b/scripts/mysql/schema-2.0.0-mysql.sql@@ -846,7 +846,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (`idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key',`http_method` VARCHAR(16) NOT NULL COMMENT 'HTTP method of the request',`request_uri` MEDIUMTEXT NOT NULL COMMENT 'encoded request path and sorted query string',- `generation` BIGINT NOT NULL COMMENT 'reservation fencing token',`http_status` INT(10) UNSIGNED DEFAULT NULL COMMENT 'HTTP status of finalized response, NULL while reserved',`response_summary` MEDIUMTEXT DEFAULT NULL COMMENT 'serialized response body (JSON) for replay',`audit_info` MEDIUMTEXT NOT NULL COMMENT 'idempotency record audit info',@@ -856,12 +855,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (KEY `idx_iim_expires` (`expires_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Iceberg REST idempotency records';--CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-) ENGINE=InnoDB;-CREATE TABLE IF NOT EXISTS `ontology_meta` (`ontology_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'ontology id',`ontology_name` VARCHAR(128) NOT NULL COMMENT 'ontology name',diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sqlindex 92e2ed4479..9180351c96 100644--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql@@ -945,7 +945,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (`idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key',`http_method` VARCHAR(16) NOT NULL COMMENT 'HTTP method of the request',`request_uri` MEDIUMTEXT NOT NULL COMMENT 'encoded request path and sorted query string',- `generation` BIGINT NOT NULL COMMENT 'reservation fencing token',`http_status` INT(10) UNSIGNED DEFAULT NULL COMMENT 'HTTP status of finalized response, NULL while reserved',`response_summary` MEDIUMTEXT DEFAULT NULL COMMENT 'serialized response body (JSON) for replay',`audit_info` MEDIUMTEXT NOT NULL COMMENT 'idempotency record audit info',@@ -955,12 +954,6 @@ CREATE TABLE IF NOT EXISTS `iceberg_idempotency_meta` (KEY `idx_iim_expires` (`expires_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Iceberg REST idempotency records';--CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-) ENGINE=InnoDB;--- Index live metadata lists and relationship cleanup by their lookup keys and deletion status.SET @ddl = IF(EXISTS(SELECT 1 FROM information_schema.statisticsWHERE table_schema = DATABASE() AND table_name = 'tag_meta' AND index_name = 'idx_tag_meta_live'),diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sqlindex 3d9ef78a7c..35431d4181 100644--- a/scripts/postgresql/schema-2.0.0-postgresql.sql+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql@@ -1458,7 +1458,6 @@ CREATE TABLE IF NOT EXISTS iceberg_idempotency_meta (idempotency_key VARCHAR(36) NOT NULL PRIMARY KEY,http_method VARCHAR(16) NOT NULL,request_uri TEXT NOT NULL,- generation BIGINT NOT NULL,http_status INT,response_summary TEXT,audit_info TEXT NOT NULL,@@ -1470,19 +1469,12 @@ COMMENT ON TABLE iceberg_idempotency_meta IS 'Iceberg REST idempotency records';COMMENT ON COLUMN iceberg_idempotency_meta.idempotency_key IS 'client-provided UUIDv7 idempotency key';COMMENT ON COLUMN iceberg_idempotency_meta.http_method IS 'HTTP method of the request';COMMENT ON COLUMN iceberg_idempotency_meta.request_uri IS 'encoded request path and sorted query string';-COMMENT ON COLUMN iceberg_idempotency_meta.generation IS 'reservation fencing token';COMMENT ON COLUMN iceberg_idempotency_meta.http_status IS 'HTTP status of finalized response, NULL while reserved';COMMENT ON COLUMN iceberg_idempotency_meta.response_summary IS 'serialized response body (JSON) for replay';COMMENT ON COLUMN iceberg_idempotency_meta.audit_info IS 'idempotency record audit info';COMMENT ON COLUMN iceberg_idempotency_meta.created_at IS 'record created at (unix epoch millis)';COMMENT ON COLUMN iceberg_idempotency_meta.expires_at IS 'record expires at (unix epoch millis)';--CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-);-CREATE TABLE IF NOT EXISTS ontology_meta (ontology_id BIGINT NOT NULL,ontology_name VARCHAR(128) NOT NULL,diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sqlindex af34666550..d5dbc2eaff 100644--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql@@ -589,7 +589,6 @@ CREATE TABLE IF NOT EXISTS iceberg_idempotency_meta (idempotency_key VARCHAR(36) NOT NULL PRIMARY KEY,http_method VARCHAR(16) NOT NULL,request_uri TEXT NOT NULL,- generation BIGINT NOT NULL,http_status INT,response_summary TEXT,audit_info TEXT NOT NULL,@@ -601,19 +600,12 @@ COMMENT ON TABLE iceberg_idempotency_meta IS 'Iceberg REST idempotency records';COMMENT ON COLUMN iceberg_idempotency_meta.idempotency_key IS 'client-provided UUIDv7 idempotency key';COMMENT ON COLUMN iceberg_idempotency_meta.http_method IS 'HTTP method of the request';COMMENT ON COLUMN iceberg_idempotency_meta.request_uri IS 'encoded request path and sorted query string';-COMMENT ON COLUMN iceberg_idempotency_meta.generation IS 'reservation fencing token';COMMENT ON COLUMN iceberg_idempotency_meta.http_status IS 'HTTP status of finalized response, NULL while reserved';COMMENT ON COLUMN iceberg_idempotency_meta.response_summary IS 'serialized response body (JSON) for replay';COMMENT ON COLUMN iceberg_idempotency_meta.audit_info IS 'idempotency record audit info';COMMENT ON COLUMN iceberg_idempotency_meta.created_at IS 'record created at (unix epoch millis)';COMMENT ON COLUMN iceberg_idempotency_meta.expires_at IS 'record expires at (unix epoch millis)';--CREATE TABLE IF NOT EXISTS iceberg_idempotency_generation_meta (- stripe INT NOT NULL PRIMARY KEY,- generation BIGINT NOT NULL-);--- Keep retained deletions out of live metadata lists and relationship cleanup scans.CREATE INDEX IF NOT EXISTS idx_tag_meta_live ON tag_meta (metalake_id) WHERE deleted_at = 0;CREATE INDEX IF NOT EXISTS idx_policy_meta_live ON policy_meta (metalake_id) WHERE deleted_at = 0;