Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#12049] feat(iceberg-rest-server): add JDBC idempotency storage (#14972)

Akshay Thorata37c655bd268
diff --git a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
index 4f5b2a4868..e1eb7461e9 100644
--- a/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
+++ b/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java
@@ -229,4 +229,7 @@ public class IcebergConstants {
/** Capacity of the in-memory idempotency store. */
public static final String ICEBERG_IDEMPOTENCY_MAX_ENTRIES = "idempotency-max-entries";
+
+ /** Interval between JDBC idempotency cleanup passes. */
+ public static final String ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL = "idempotency-cleanup-interval";
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
index d46c8d9544..ee5cfecf4c 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
@@ -233,6 +233,7 @@ public class TestSQLScripts extends TestJDBCBackend {
if ("2.0.0".equals(versionScripts.getKey())) {
assertCleanupIndexes("schema " + versionScripts.getKey());
assertNameColumnWidths("schema " + versionScripts.getKey());
+ assertIdempotencySchema("schema " + versionScripts.getKey());
}
}
@@ -275,6 +276,7 @@ public class TestSQLScripts extends TestJDBCBackend {
if ("2.0.0".equals(upgradeMatcher.group(2))) {
assertCleanupIndexes(upgradeScript.getName());
assertNameColumnWidths(upgradeScript.getName());
+ assertIdempotencySchema(upgradeScript.getName());
}
}
}
@@ -855,6 +857,45 @@ 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"))
+ .findFirst()
+ .orElseThrow(
+ () -> new AssertionFailedError("Missing idempotency table after " + source));
+ Assertions.assertEquals(
+ Set.of(
+ "idempotency_key",
+ "http_method",
+ "request_uri",
+ "generation",
+ "http_status",
+ "response_summary",
+ "audit_info",
+ "created_at",
+ "expires_at"),
+ Set.copyOf(columns.get(table).stream().map(name -> name.toLowerCase(Locale.ROOT)).toList()),
+ "Idempotency columns after " + source);
+ Assertions.assertTrue(
+ readSchemaIndexes(Set.of(table)).stream()
+ .anyMatch(
+ index -> index.equalsIgnoreCase(table + ":idx_iim_expires:1:expires_at:true")),
+ "Missing idempotency expiry index after " + source);
+ }
+
private void assertCleanupIndexes(String source) throws SQLException {
Map<String, String> leadingColumns =
Map.of(
diff --git a/design-docs/iceberg-idempotency-key.md b/design-docs/iceberg-idempotency-key.md
index 4e6723bfe9..227464e779 100644
--- a/design-docs/iceberg-idempotency-key.md
+++ b/design-docs/iceberg-idempotency-key.md
@@ -130,7 +130,8 @@ timestamp is used only as a defense-in-depth sanity check and for diagnostics.
- Cross-datacenter replication of idempotency records.
- Idempotency for read (GET/HEAD) operations.
- Guaranteed delivery (client-side concern).
-- Heartbeat/liveness tracking (mutations are sub-second).
+- Heartbeat/liveness tracking. Deployments must bound mutation duration and
+ clock skew below the configured reuse window; see Section 5.4.
---
@@ -146,8 +147,8 @@ Client Load Balancer Node A / Node B
| | +--------------+---------------+
| | | 1. Validate UUIDv7 format |
| | | 2. store.reserve(key) |
- | | | +- RESERVED -> execute |
- | | | +- DUPLICATE -> replay |
+ | | | +- Claim -> execute |
+ | | | +- Empty -> replay |
| | | 3. Execute mutation |
| | | 4. store.finalize(key, resp) |
| | +--------------+---------------+
@@ -161,17 +162,15 @@ A storage-agnostic interface that any backend can implement:
```java
public interface IdempotencyStore extends Closeable {
- enum ReserveResult { RESERVED, DUPLICATE }
-
/**
- * Attempt to reserve a key. Returns DUPLICATE if already reserved or finalized.
+ * Attempt to reserve a key. Returns empty if already reserved or finalized.
*
* @param idempotencyKey the client-provided UUIDv7 key
* @param operationBinding request identity, e.g. "POST /v1/cat1/namespaces/ns1/tables"
- * @param expiresAt instant after which this record may be purged
- * @return RESERVED if newly claimed, DUPLICATE if already exists
+ * @param expiresAtMs deadline in Unix epoch milliseconds
+ * @return a fresh fencing token if acquired, empty if the key is live
*/
- ReserveResult reserve(String idempotencyKey, String operationBinding, Instant expiresAt);
+ OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs);
/**
* Load a finalized record for replay.
@@ -185,26 +184,28 @@ 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 finalize(String idempotencyKey, int httpStatus, String responseSummary);
+ void finalizeRecord(String idempotencyKey, long claim, 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);
+ void release(String idempotencyKey, long claim);
/**
* Purge expired records. Called periodically by a background task.
*
- * @param before cutoff instant; records expiring before this time are removed
+ * @param beforeMs inclusive expiry cutoff in Unix epoch milliseconds
* @return number of records purged
*/
- int purgeExpired(Instant before);
+ int purgeExpired(long beforeMs);
}
```
@@ -214,6 +215,7 @@ public interface IdempotencyStore extends Closeable {
public class IdempotencyRecord {
private final String idempotencyKey; // UUIDv7 (RFC 9562), 36-char canonical form
private final String operationBinding; // e.g., "POST /v1/cat1/namespaces/ns1/tables"
+ private final long claim; // store-issued fencing token
private final Integer httpStatus; // null while reserved / in-progress
private final String responseSummary; // serialized response body (JSON)
private final long createdAtMs; // unix epoch millis (matches BIGINT column)
@@ -228,10 +230,10 @@ existing metadata tables (e.g., the `deleted_at` / `timestamp` columns in
### 3.4 Storage Implementations
-| Implementation | Use Case | Durability | Multi-Node |
-| ---------------------------- | --------------------- | ---------- | ---------- |
-| `InMemoryIdempotencyStore` | Dev, testing, single | No | No |
-| `JdbcIdempotencyStore` | Production | Yes | Yes |
+| Implementation | Use Case | Durability | Multi-Node |
+| -------------------------- | -------------------- | ---------- | ---------- |
+| `InMemoryIdempotencyStore` | Dev, testing, single | No | No |
+| `JdbcIdempotencyStore` | Production | Yes | Yes |
The JDBC implementation leverages Gravitino's existing relational backend
(H2 for dev, MySQL or PostgreSQL for production).
@@ -279,39 +281,60 @@ MEDIUMTEXT `audit_info` column, per-column `COMMENT`s, and
MySQL:
```sql
-CREATE TABLE IF NOT EXISTS `iceberg_idempotency_key_meta` (
- `idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key',
- `operation_binding` VARCHAR(512) NOT NULL COMMENT 'request identity, e.g. POST /v1/{prefix}/namespaces/{ns}/tables',
- `http_status` INT 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',
- `created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record created at (unix epoch millis)',
- `expires_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record expires at (unix epoch millis)',
- PRIMARY KEY (`idempotency_key`),
- KEY `idx_iik_expires` (`expires_at`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Iceberg REST idempotency key records';
+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',
+ `created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record created at (unix epoch millis)',
+ `expires_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record expires at (unix epoch millis)',
+ 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 follow the same column names and types (with
-database-specific keywords) and are shipped alongside the existing scripts as
-`scripts/h2/iceberg-idempotency-schema-<version>-h2.sql` and
-`scripts/postgresql/iceberg-idempotency-schema-<version>-postgresql.sql`,
-mirroring the layout of the existing `iceberg-metrics-schema-<version>-*.sql`
-files.
+The H2 and PostgreSQL variants use the same columns. All three backends ship the
+table 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.
+
+The HTTP method is stored in `http_method`. The `request_uri` column stores
+the encoded path plus the sorted, encoded query string when present. MySQL
+uses `MEDIUMTEXT` because the default HTTP request limit permits targets
+longer than MySQL's 64 KiB `TEXT` limit.
### 4.1 Row Lifecycle
1. **RESERVED**: Row inserted with `http_status = NULL`. Mutation is executing.
2. **FINALIZED**: `http_status` and `response_summary` written. Ready for replay.
-3. **EXPIRED**: `expires_at < now()`. Purged by background cleanup
+3. **EXPIRED**: `expires_at <= now()`. Eligible for reclaim or background cleanup
(see [Section 5.4](#54-expiry-and-cleanup-of-outdated-data)).
### 4.2 Conflict Handling
-`reserve()` uses `INSERT ... ON CONFLICT DO NOTHING` (PostgreSQL),
-`INSERT IGNORE` (MySQL), or equivalent. If zero rows inserted, the key is
-already reserved or finalized - return `DUPLICATE` and load the existing record
-for replay.
+`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
+cutoff in case purge or release freed the key. If neither attempt claims the
+key, it returns empty. Other SQL errors propagate. Only finalized, unexpired
+records can be loaded for replay.
---
@@ -323,28 +346,39 @@ 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)`.
-5. Result = `RESERVED`: execute mutation, call `store.finalize(key, status, body)`.
+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)`.
6. Return response to client.
### 5.2 Replay Path (Duplicate Key)
1. Extract and validate header.
-2. Call `store.reserve(key, binding, expiresAt)` - returns `DUPLICATE`.
+2. Call `store.reserve(key, binding, expiresAt)`. An empty result indicates a duplicate.
3. Call `store.load(key)`:
- If finalized: reconstruct and return cached response.
- If in-progress (not yet finalized): return `409 Conflict` with
- `Retry-After` header (another node is still executing).
+ `Retry-After` header (the mutation may still be executing, or its response was not retained).
4. Return cached response.
### 5.3 Execution Failure
-If the mutation throws an exception:
-
-- **Retryable errors** (e.g., transient DB failure): call `store.release(key)`
- so the client can retry with the same key.
+The manager distinguishes failures before execution, mutation outcomes, and
+response-persistence failures:
+
+- **Reservation or replay lookup failure**: return `503 Service Unavailable`
+ with `Retry-After` without executing the mutation. Do not release a reservation
+ whose commit acknowledgement may have been lost. Retry with the same key
+ within 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
+ can retry with the same key. A mutation failure can still have an uncertain
+ catalog outcome; a `5xx` is not proof that the catalog was unchanged.
- **Terminal errors** (e.g., `AlreadyExistsException`): call
- `store.finalize(key, 409, errorBody)` so retries get the same error response.
+ `store.finalizeRecord(key, claim, 409, errorBody)` so retries get the same error response.
+- **Terminal response cannot be retained** (serialization, write, read-back
+ failure, or a no-op finalize): return the original mutation response and leave
+ any existing reservation until expiry. This prevents immediate re-execution;
+ a retry receives an in-flight `409` while the unfinalized reservation remains.
This matches the Iceberg REST spec's finalization rules for the
`Idempotency-Key` header:
@@ -360,20 +394,33 @@ Every record carries `expires_at = created_at + idempotency-key-lifetime`. The
spec states catalogs SHOULD NOT expire keys before the advertised lifetime, so
cleanup only ever removes records whose window has already elapsed.
-**JDBC store.** A background task scheduled every
-`idempotency-cleanup-interval` calls `store.purgeExpired(now)`, which runs:
+There is no heartbeat or in-flight renewal. The configured lifetime must exceed
+the maximum reservation-to-response-persistence duration, maximum replica clock
+skew, and a safety margin. This bound includes lock waits, backend retries, and
+JVM pauses; an HTTP timeout alone does not stop a catalog mutation. If those
+bounds cannot be enforced, expiry can allow overlapping execution, so callers
+must not rely on an at-most-once guarantee or blindly retry after the window.
+
+**JDBC store.** Each store owns a background task scheduled every
+`idempotency-cleanup-interval` that calls `store.purgeExpired(now)`. Use one
+store per service instance and close it at service shutdown. MySQL and H2 use:
```sql
-DELETE FROM iceberg_idempotency_key_meta WHERE expires_at < ? LIMIT ?;
+DELETE FROM iceberg_idempotency_meta WHERE expires_at <= ? LIMIT ?;
```
-- Deletes are performed in bounded batches (using `LIMIT` / repeated execution)
- to avoid long-held locks and large transactions.
-- The `idx_iik_expires` index makes the predicate efficient.
-- The delete is safe to run concurrently on multiple nodes: it is idempotent
- and only targets already-expired rows, so no leader election or distributed
- lock is required. A small grace period is added to the cutoff to tolerate
- clock skew between nodes.
+- Deletes are performed in at most 100 batches of 1,000 rows per pass to avoid
+ long-held locks and large transactions. Larger backlogs wait for later passes;
+ expiry is enforced on access independently of cleanup.
+- The `idx_iim_expires` index makes the predicate efficient.
+- PostgreSQL selects a bounded set of candidate keys in a subquery and rechecks
+ expiry on the target row. MySQL and H2 recheck the target-row predicate after
+ a lock wait, preserving reservations concurrently reclaimed with a future
+ deadline.
+- Concurrent cleanup does not require leader election. Replicas must synchronize
+ system clocks: there is no clock-skew grace period, and a fast replica can
+ reclaim or purge a key another replica still considers live. Monitor clock
+ offset and synchronization health as a replay-safety requirement.
**In-memory store.** No separate task is needed: Caffeine's
`expireAfterWrite(lifetime)` removes expired entries lazily/automatically, and
@@ -389,13 +436,13 @@ server. Only `idempotency-key-lifetime` is defined by the Iceberg REST spec and
advertised to clients; every other key is Gravitino server-side configuration
and is **not** exposed via `GET /v1/config`.
-| Config Key | Default | Description |
-| ------------------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------- |
-| `gravitino.iceberg-rest.idempotency-enabled` | `false` | Master switch. Disabled by default (matching Polaris). When `false`, the `Idempotency-Key` header is ignored and no lifetime is advertised. |
-| `gravitino.iceberg-rest.idempotency-key-lifetime`| `PT30M` | Client reuse window (ISO-8601 duration). Advertised to clients as the spec-defined `idempotency-key-lifetime` in `GET /v1/config`. |
-| `gravitino.iceberg-rest.idempotency-store-type` | `in-memory` | `in-memory` or `jdbc`. |
-| `gravitino.iceberg-rest.idempotency-max-entries` | `10000` | Max cached entries (in-memory store only). See [Section 3.5](#35-in-memory-store-capacity-and-eviction).|
-| `gravitino.iceberg-rest.idempotency-cleanup-interval` | `PT5M` | Interval for the background task that purges expired records (jdbc store). |
+| Config Key | Default | Description |
+| ----------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| `gravitino.iceberg-rest.idempotency-enabled` | `false` | Master switch. Disabled by default (matching Polaris). When `false`, the `Idempotency-Key` header is ignored and no lifetime is advertised. |
+| `gravitino.iceberg-rest.idempotency-key-lifetime` | `PT30M` | Client reuse window (ISO-8601 duration). Advertised to clients as the spec-defined `idempotency-key-lifetime` in `GET /v1/config`. |
+| `gravitino.iceberg-rest.idempotency-store-type` | `in-memory` | `in-memory` or `jdbc`. |
+| `gravitino.iceberg-rest.idempotency-max-entries` | `10000` | Max cached entries (in-memory store only). See [Section 3.5](#35-in-memory-store-capacity-and-eviction). |
+| `gravitino.iceberg-rest.idempotency-cleanup-interval` | `PT5M` | Interval for the background task that purges expired records (jdbc store). |
### 6.1 Iceberg Spec Configuration
@@ -423,39 +470,38 @@ clients MUST assume idempotency is not supported.
### 6.2 Database Configuration (`jdbc` store)
-When `idempotency-store-type=jdbc`, the store connects to a relational database
-using the following keys, mirroring the JDBC configuration style already used by
-Gravitino's Iceberg REST metrics store:
-
-| Config Key | Default | Description |
-| ------------------------------------------------------- | ------- | ------------------------------------------------------------------ |
-| `gravitino.iceberg-rest.idempotency-jdbc-url` | (none) | JDBC connection URL, e.g. `jdbc:mysql://host:3306/gravitino`. |
-| `gravitino.iceberg-rest.idempotency-jdbc-driver` | (none) | JDBC driver class name. |
-| `gravitino.iceberg-rest.idempotency-jdbc-user` | (none) | Database user. |
-| `gravitino.iceberg-rest.idempotency-jdbc-password` | (none) | Database password. Supplied via secret/env; never logged. |
-| `gravitino.iceberg-rest.idempotency-jdbc-max-pool-size` | `10` | Maximum JDBC connection pool size. |
+When `idempotency-store-type=jdbc`, the store reuses the initialized Gravitino
+relational entity store's connection pool in auxiliary mode. It supports H2,
+MySQL, and PostgreSQL and has no separate `idempotency-jdbc-*` connection
+settings. Multiple replicas must connect to the same shared MySQL or PostgreSQL
+database. The store does not own or close the shared pool.
-By default the `jdbc` store reuses the same backend as Gravitino's relational
-entity store; the keys above allow pointing it at a dedicated database when
-needed.
+Standalone Iceberg REST servers cannot use this backend. The Iceberg REST
+server JAR contains the store interface, factory, and both built-in
+implementations. The factory resolves the `in-memory` and `jdbc` aliases to
+those implementations. The configuration keys live in `iceberg-common`.
+Apply the schema or upgrade scripts before enabling the store. See the
+[JDBC operations guidance](../docs/iceberg-rest-service.md#jdbc-idempotency-storage)
+for clock synchronization, cleanup limits, and deployment requirements.
---
## 7. Comparison with Polaris
-| Aspect | Polaris (PR #3205) | This Design |
-| ------------------- | ------------------------------- | ----------------------------------------------- |
-| Storage | Postgres-specific | Gravitino relational backend (H2/MySQL/PG) |
-| Heartbeat | Yes (long-running ops) | No (mutations are sub-second) |
-| Reconciliation | Yes (crash recovery) | Simplified: TTL-based expiry + release on fail |
-| Executor ownership | Yes (multi-worker) | No (single-owner per key via DB constraint) |
-| Response storage | Minimal summary + pointer | Full response body (mutation responses are small)|
-
-Gravitino's Iceberg mutations (create/drop/update) are typically sub-second,
-which makes heartbeat-based liveness and crash reconciliation unnecessary
-complexity. The simpler reserve-execute-finalize model is sufficient. If
-long-running operations are added in the future (e.g., async purge), heartbeat
-support can be added to the SPI without breaking existing implementations.
+| Aspect | Polaris (PR #3205) | This Design |
+| ------------------ | ------------------------- | ----------------------------------------------------------------- |
+| Storage | Postgres-specific | Gravitino relational backend (H2/MySQL/PG) |
+| Heartbeat | Yes (long-running ops) | No; requires bounded mutation duration and clock skew |
+| Reconciliation | Yes (crash recovery) | TTL-based expiry; retain reservations on response-storage failure |
+| Executor ownership | Yes (multi-worker) | No (single-owner per key via DB constraint) |
+| Response storage | Minimal summary + pointer | Full response body (mutation responses are small) |
+
+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 and
+cannot guarantee at-most-once execution for unbounded mutations. Supporting
+those operations safely would require a separate lease-renewal and
+catalog-side fencing design; record claim tokens alone cannot stop an already
+running catalog mutation.
---
@@ -463,8 +509,7 @@ support can be added to the SPI without breaking existing implementations.
### Phase 1: SPI and In-Memory Store
-- Define `IdempotencyStore` interface and `IdempotencyRecord` in
- `iceberg/iceberg-common`.
+- Define the `IdempotencyStore` interface and `IdempotencyRecord`.
- Implement `InMemoryIdempotencyStore` using Caffeine cache.
- Wire into endpoint operations with `@HeaderParam("Idempotency-Key")`.
- Advertise `idempotency-key-lifetime` in `GET /v1/config`.
@@ -472,8 +517,9 @@ support can be added to the SPI without breaking existing implementations.
### Phase 2: JDBC Store
-- Add `iceberg_idempotency_key_meta` table schema for H2, MySQL, and PostgreSQL.
+- Add `iceberg_idempotency_meta` table schema for H2, MySQL, and PostgreSQL.
- Implement `JdbcIdempotencyStore` using Gravitino's existing connection pool.
+- Package the store interface, implementations, and factory in `iceberg/iceberg-rest-server`.
- Background cleanup task for expired records.
- Integration tests with testcontainers.
diff --git a/docs/iceberg-rest-service.md b/docs/iceberg-rest-service.md
index d3f5e17b38..0653aaa407 100644
--- a/docs/iceberg-rest-service.md
+++ b/docs/iceberg-rest-service.md
@@ -108,9 +108,9 @@ The server-level `gravitino.fetchFile.blockUnsafeRemoteUri` configuration contro
#### Auxiliary Service
-| Configuration item | Description | Default value | Required |
-|------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
-| `gravitino.auxService.names` | The auxiliary service name of the Gravitino Iceberg REST catalog service. Use **`iceberg-rest`**. | (none) | Yes |
+| Configuration item | Description | Default value | Required |
+|------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.auxService.names` | The auxiliary service name of the Gravitino Iceberg REST catalog service. Use **`iceberg-rest`**. | (none) | Yes |
| `gravitino.iceberg-rest.classpath` | The classpath of the Gravitino Iceberg REST catalog service. Use `iceberg-rest-server/libs, iceberg-rest-server/conf` for the regular Iceberg dependencies or `iceberg-rest-server-experiment/libs, iceberg-rest-server-experiment/conf` for the experimental dependencies. It supports both absolute and relative paths. | (none) | Yes |
These settings apply only to `gravitino.conf`.
@@ -148,7 +148,7 @@ distribution published under the `com.datastrato` Maven group. Its version is pi
| `gravitino.iceberg-rest.includeErrorStackTrace` | Whether error responses include server-side stack traces. Set this to `false` in new deployments because responses can expose internal implementation details. | `true` | No |
| `gravitino.iceberg-rest.metrics.enabled` | Whether standalone mode serves metrics endpoints. Ignored in auxiliary mode; use the Gravitino server endpoint there. Enable only on a trusted network. | `false` | No |
| `gravitino.iceberg-rest.customFilters` | Comma-separated list of filter class names to apply to the APIs. | (none) | No |
-| `gravitino.iceberg-rest.trustedProxies` | Comma-separated list of IP addresses or CIDR blocks of reverse proxies whose `X-Forwarded-For` header is trusted when recording the client address in audit events. | (none) | No |
+| `gravitino.iceberg-rest.trustedProxies` | Comma-separated list of IP addresses or CIDR blocks of reverse proxies whose `X-Forwarded-For` header is trusted when recording the client address in audit events. | (none) | No |
| `gravitino.iceberg-rest.advertised-uri` | The public endpoint reported to clients that discover the service through the Gravitino server. Must be an absolute `http`/`https` URI with a host and no query or fragment. | (none) | No |
The filter in `customFilters` should be a standard javax servlet filter.
@@ -192,24 +192,115 @@ Support is disabled by default. Once enabled, the reuse window is advertised as
The header applies to the create, update, drop, register, and rename endpoints for tables, namespaces, and views. Its value must be a UUIDv7 in string form ([RFC 9562](https://www.rfc-editor.org/rfc/rfc9562)); anything else returns `400 Bad Request`. Keys must be globally unique: reusing one with a different HTTP method, path, or query returns `409 Conflict`, and so does a retry that arrives while the first request is still running (with a `Retry-After` header). Successful and deterministic terminal `4xx` responses are stored and replayed, while `5xx`, `401`, `403`, and `419` responses release the key so the client can retry with it.
-| Configuration item | Description | Default value | Required |
-|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
-| `gravitino.iceberg-rest.idempotency-enabled` | Whether to honor the `Idempotency-Key` header. When `false`, the header is ignored and no lifetime is advertised. | `false` | No |
-| `gravitino.iceberg-rest.idempotency-key-lifetime` | The client reuse window for a key, an ISO-8601 duration such as `PT30M`. Advertised to clients as `idempotency-key-lifetime`. | `PT30M` | No |
-| `gravitino.iceberg-rest.idempotency-store-type` | The store holding idempotency records, either the `in-memory` short name or the fully-qualified class name of an `IdempotencyStore` implementation. | `in-memory` | No |
-| `gravitino.iceberg-rest.idempotency-max-entries` | The maximum number of records retained by the in-memory store. Records beyond it are evicted before their reuse window elapses. | `10000` | No |
+| Configuration item | Description | Default value | Required |
+|---------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.iceberg-rest.idempotency-enabled` | Whether to honor the `Idempotency-Key` header. When `false`, the header is ignored and no lifetime is advertised. | `false` | No |
+| `gravitino.iceberg-rest.idempotency-key-lifetime` | The client reuse window for a key, an ISO-8601 duration such as `PT30M`. Advertised to clients as `idempotency-key-lifetime`. | `PT30M` | No |
+| `gravitino.iceberg-rest.idempotency-store-type` | The store holding idempotency records: `in-memory`, `jdbc` in auxiliary mode, or the fully-qualified class name of an `IdempotencyStore` implementation. | `in-memory` | No |
+| `gravitino.iceberg-rest.idempotency-max-entries` | The maximum number of records retained by the in-memory store. Records beyond it are evicted before their reuse window elapses. | `10000` | No |
-Phase-1 limitations:
+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. A retry can then execute again. Claim fencing protects replacement records, but cannot undo or fence catalog side effects.
-- This phase does not schedule `IdempotencyStore.purgeExpired`. The in-memory store reclaims expired entries through Caffeine. Custom stores must enforce expiry on reads/reservations and arrange their own cleanup; durable-store purge scheduling belongs to the JDBC follow-up.
+- 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 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
Enabling `idempotency-enabled=true` with the default `idempotency-store-type=in-memory` on more than one replica does **not** provide cluster-wide deduplication: retries can execute a mutation twice. The `in-memory` store is node-local and not durable. A retry routed to another replica, or to a replica that restarted, finds no record and re-executes the mutation, and its size bound can evict a record before its reuse window elapses, including an in-flight reservation. A retry can then run concurrently with the original mutation. Use it for single-node deployments, development, and testing.
:::
+### JDBC Idempotency Storage
+
+The `jdbc` idempotency store persists request reservations and response bodies in Gravitino's
+relational entity store. Replicas connected to the same database share records, and finalized
+responses survive Iceberg REST service restarts. Set `gravitino.iceberg-rest.idempotency-enabled=true`
+and `gravitino.iceberg-rest.idempotency-store-type=jdbc` to enable durable request replay on the
+mutation endpoints described above.
+
+Use this backend in auxiliary mode, with an initialized relational entity store. Standalone Iceberg
+REST servers cannot use it. It reuses Gravitino's connection pool and supports H2, MySQL, and
+PostgreSQL. For multiple replicas, use the same shared MySQL or PostgreSQL database; separate local
+H2 databases do not provide cross-replica deduplication.
+
+Create one store instance per Iceberg REST service instance and share it across requests. Each
+store starts its own cleanup scheduler; creating stores per request adds redundant purge work and
+database lock contention. Close the store when stopping the service to shut down its scheduler.
+
+| Configuration item | Description | Default value | Required |
+|-------------------------------------------------------|----------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.iceberg-rest.idempotency-store-type` | Select `jdbc` for durable storage, `in-memory` for node-local storage, or a custom implementation class. | `in-memory` | No |
+| `gravitino.iceberg-rest.idempotency-cleanup-interval` | Time between bounded JDBC cleanup passes, as an ISO-8601 duration of at least one millisecond. | `PT5M` | No |
+
+Initialize 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.
+
+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
+the schema. Update all replicas to the current request binding format together. On MySQL, the
+current `request_uri` column uses `MEDIUMTEXT` to accommodate long request targets.
+
+The store interface and record type are in `org.apache.gravitino.iceberg.service.idempotency` in
+the 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.
+
+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.
+
+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
+100 batches of 1,000 expired rows, and transient failures are retried on the next pass.
+
+:::warning Clock synchronization is required for safe replay
+All replicas sharing the JDBC store must maintain synchronized system clocks, for example through
+NTP or chrony. Monitor clock offset and synchronization health. Stop the Iceberg REST service on an
+unsynchronized replica until its clock is corrected so neither requests nor its cleanup task can
+expire records early. A fast clock can reclaim or purge a key while another replica still considers
+it live, allowing the mutation to execute again within that
+replica's reuse window. This affects replay safety, not just cleanup timing. The store does not add
+a clock-skew grace period; changing the cleanup interval does not prevent early reclaim by
+`reserve()`.
+:::
+
+:::warning The reuse window must outlast the mutation
+There is no heartbeat or in-flight lease renewal. Configure `idempotency-key-lifetime` to exceed
+the maximum elapsed time from starting reservation through completing the mutation and persisting
+its response, plus maximum clock skew and a safety margin. Include database lock waits, backend
+retries, serialization time, and JVM pauses in that bound; typical or percentile latency is not
+sufficient. A client or HTTP timeout does not necessarily stop an already-running catalog mutation.
+
+Once the deadline passes, another replica may reclaim the key while the original mutation is still
+running. If a duration or clock-skew bound cannot be enforced, do not rely on this mechanism for
+at-most-once execution. Reconcile catalog state before retrying outside the reuse window, and do not
+use a new key to bypass an existing reservation for the same logical operation.
+:::
+
+If reservation or replay lookup fails, the server returns `503 Service Unavailable` with
+`Retry-After` and does not execute the mutation in that attempt. The reservation may still have
+committed before a connection failure, so it is retained and a retry with the same key may receive
+`409` until the reservation expires. Retry with the same key within the advertised window; after
+the window, inspect catalog state before deciding whether to execute the operation again. A generic
+mutation `5xx` can still have an uncertain catalog outcome and must not be treated as proof that
+nothing changed.
+
+The 100,000-row cleanup cap applies to each pass, and remaining expired rows wait for later passes.
+Monitor expired-row backlog and database storage growth; shorten the cleanup interval if cleanup
+falls behind, while checking database load and lock waits. Cleanup lag does not extend record
+validity because expiry is checked on access.
+
+Durable storage does not make catalog mutations and response persistence one transaction. Failed
+response 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.
+
### Catalog Backend Configuration
:::info
@@ -313,20 +404,20 @@ If IRC2 does not enforce authorization, keeping `gravitino.iceberg-rest.disable-
By default IRC1 forwards each user's access token to IRC2, so IRC2 must trust the same identity provider and authorize every user itself. To federate a catalog that cannot do that, such as a managed catalog that accepts only its own API token, connect IRC1 to IRC2 as a service account. IRC1 then presents one configured credential on every request to IRC2 and authorizes each user against Gravitino's own grants before anything is proxied. A catalog connected as a service account always enforces authorization in IRC1, whatever `disable-rest-authz` is set to, and IRC1 refuses to serve it when authorization is disabled. Because IRC2 vends storage credentials for the service account rather than for the calling user, such a catalog also always issues storage credentials through Gravitino, as described below.
-| Configuration item | Description | Default value | Required |
-|-------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|---------------|---------------------------------------------|
-| `gravitino.iceberg-rest.rest-backend-auth-type` | How IRC1 authenticates to IRC2. `user-token` forwards the calling user's access token. `service-account` connects with the credential below. | `user-token` | No |
-| `gravitino.iceberg-rest.rest-backend-token` | Static bearer token the service account presents to IRC2. | (none) | One of token or credential with `service-account` |
-| `gravitino.iceberg-rest.rest-backend-credential` | OAuth2 client credential (`client_id:client_secret`) the service account exchanges for a token. | (none) | One of token or credential with `service-account` |
-| `gravitino.iceberg-rest.rest-backend-oauth2-server-uri` | OAuth2 token endpoint for the client credential. Defaults to IRC2's own token endpoint. | (none) | No |
-| `gravitino.iceberg-rest.rest-backend-scope` | OAuth2 scope requested with the client credential. | (none) | No |
+| Configuration item | Description | Default value | Required |
+|---------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|---------------|---------------------------------------------------|
+| `gravitino.iceberg-rest.rest-backend-auth-type` | How IRC1 authenticates to IRC2. `user-token` forwards the calling user's access token. `service-account` connects with the credential below. | `user-token` | No |
+| `gravitino.iceberg-rest.rest-backend-token` | Static bearer token the service account presents to IRC2. | (none) | One of token or credential with `service-account` |
+| `gravitino.iceberg-rest.rest-backend-credential` | OAuth2 client credential (`client_id:client_secret`) the service account exchanges for a token. | (none) | One of token or credential with `service-account` |
+| `gravitino.iceberg-rest.rest-backend-oauth2-server-uri` | OAuth2 token endpoint for the client credential. Defaults to IRC2's own token endpoint. | (none) | No |
+| `gravitino.iceberg-rest.rest-backend-scope` | OAuth2 scope requested with the client credential. | (none) | No |
##### Gravitino-issued storage credentials
By default IRC1 passes through the storage credentials IRC2 vends. Some catalogs vend broad, long-lived credentials, for example the catalog token's own storage keys scoped to the whole bucket. Set `rest-backend-storage-credential-source` to `local` and IRC1 stops asking IRC2 for credentials. It issues them through its own `credential-providers` instead, scoped to the table location, read-only unless the caller holds write privileges on the table, exactly as for a local catalog. Credentials IRC2 returns unasked are dropped. Here `local` means credentials issued by IRC1; `remote` means credentials issued by IRC2. This setting controls storage credentials, independently of the credentials IRC1 uses to authenticate to IRC2.
-| Configuration item | Description | Default value | Required |
-|---------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| Configuration item | Description | Default value | Required |
+|-----------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
| `gravitino.iceberg-rest.rest-backend-storage-credential-source` | Who issues storage credentials for tables of the federated catalog. `remote` passes through IRC2's credentials. `local` uses IRC1's `credential-providers`. A `service-account` catalog always uses `local`, regardless of this setting. | `remote` | No |
IRC1 configuration example federating a catalog that accepts only a static API token, with Gravitino issuing the storage credentials:
@@ -776,8 +867,8 @@ gravitino.iceberg-rest.jdbc.options = -c plan_cache_mode=force_custom_plan
That maps to Iceberg's `jdbc.options` JDBC connection property, so you do not need database-owner privileges.
-| Configuration item | Description | Default value | Required |
-|---------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| Configuration item | Description | Default value | Required |
+|---------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
| `gravitino.iceberg-rest.jdbc.options` | Extra JDBC connection options passed through to the Iceberg JDBC catalog. For PostgreSQL, `-c plan_cache_mode=force_custom_plan` keeps existence checks on custom plans. | (none) | No |
#### Event Listeners
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
index be6701b9b5..efca10d92b 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
+++ b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java
@@ -484,13 +484,23 @@ public class IcebergConfig extends Config implements OverwriteDefaultConfig {
public static final ConfigEntry<String> ICEBERG_IDEMPOTENCY_STORE_TYPE =
new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE)
.doc(
- "The store holding Iceberg idempotency records, either the `in-memory` short name or "
+ "The store holding Iceberg idempotency records, the `in-memory` or `jdbc` short name, or "
+ "the fully-qualified class name of an `IdempotencyStore` implementation")
.version(ConfigConstants.VERSION_2_0_0)
.stringConf()
.checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
.createWithDefault("in-memory");
+ /** Interval between bounded cleanup passes in the JDBC idempotency store. */
+ public static final ConfigEntry<String> ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL =
+ new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL)
+ .doc("Interval between JDBC idempotency cleanup passes, as a positive ISO-8601 duration")
+ .version(ConfigConstants.VERSION_2_0_0)
+ .stringConf()
+ .checkValue(
+ IcebergConfig::isPositiveDuration, "The value must be a positive ISO-8601 duration")
+ .createWithDefault("PT5M");
+
/** Capacity of the in-memory idempotency store. */
public static final ConfigEntry<Integer> ICEBERG_IDEMPOTENCY_MAX_ENTRIES =
new ConfigBuilder(IcebergConstants.ICEBERG_IDEMPOTENCY_MAX_ENTRIES)
diff --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.java
index 75b71c92a7..b2710bc79a 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
@@ -22,7 +22,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
-import com.google.common.hash.Hashing;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@@ -30,10 +29,10 @@ 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;
-import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
@@ -44,14 +43,10 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.iceberg.common.IcebergConfig;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.apache.iceberg.exceptions.ServiceUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -71,11 +66,12 @@ import org.slf4j.LoggerFactory;
* <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
* with different body/header values replays the first response; clients must use a new key for a
* different logical operation. The catalog mutation and response storage are not transactional:
- * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ * eviction, expiry, a crash, or a post-commit exception can permit re-execution. If retaining a
+ * terminal response fails, its reservation is kept until expiry to prevent an immediate retry from
+ * re-executing the mutation.
*
- * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
- * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
- * scheduling durable cleanup belongs to the JDBC-store integration.
+ * <p>Stores enforce deadlines and arrange their own cleanup. The in-memory store uses Caffeine for
+ * reclamation; the JDBC store owns its purge scheduler.
*/
public class IcebergIdempotencyManager {
@@ -160,30 +156,42 @@ public class IcebergIdempotencyManager {
}
IdempotencyStore idempotencyStore = store.get();
- String binding =
- Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
- // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
- // request takes the key, our finalize or release lands on nothing instead of on its record.
- long claim = ThreadLocalRandom.current().nextLong();
- if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
- return replay(idempotencyStore, key, binding);
+ long claim;
+ try {
+ OptionalLong reservation = idempotencyStore.reserve(key, operationBinding, expiresAtMs);
+ if (reservation.isEmpty()) {
+ 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);
+ // A lost commit acknowledgement may leave a reservation. Do not release or execute it.
+ return Response.fromResponse(
+ IcebergExceptionMapper.toRESTResponse(
+ new ServiceUnavailableException(
+ "Idempotency store unavailable; this attempt did not execute the mutation. "
+ + "Retry with the same Idempotency-Key within its reuse window.")))
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
}
- boolean finalized = false;
+ boolean release = true;
try {
Response response = action.get();
int status = response.getStatus();
- // Store successful and terminal client responses. Release 5xx and auth outcomes so retries
- // can re-evaluate them; serialization/finalization failure also releases only our claim.
+ // Retain terminal outcomes even if recording the response fails: the mutation may have
+ // committed, so freeing its reservation would allow an immediate duplicate execution.
if (status < Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
&& !NON_FINALIZABLE_STATUSES.contains(status)) {
- finalized = tryFinalize(idempotencyStore, key, claim, response);
+ release = false;
+ tryFinalize(idempotencyStore, key, claim, response);
}
return response;
} finally {
- if (!finalized) {
- // Only release this attempt's claim when the response is retryable or was not retained.
+ 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);
}
@@ -196,8 +204,7 @@ public class IcebergIdempotencyManager {
*
* <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
* and behavior-changing headers are not compared; clients must use a fresh key for a different
- * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
- * store's bounded binding column without truncating distinct requests.
+ * logical operation.
*
* @param httpMethod the HTTP method of the endpoint
* @param uriInfo the request URI, may be {@code null} outside a request context
@@ -213,7 +220,7 @@ public class IcebergIdempotencyManager {
if (queryParameters != null && !queryParameters.isEmpty()) {
// Sorted, so that clients that order query parameters differently between a request and its
// retry still land on the same binding.
- StringJoiner query = new StringJoiner("&", "?", "");
+ StringJoiner query = new StringJoiner("&");
for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
query.add(
@@ -222,7 +229,7 @@ public class IcebergIdempotencyManager {
+ URLEncoder.encode(value, StandardCharsets.UTF_8));
}
}
- binding.append(query);
+ binding.append('?').append(query);
}
return binding.toString();
}
@@ -262,9 +269,8 @@ public class IcebergIdempotencyManager {
}
LOG.info(
- "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ "Replaying the stored response for Idempotency-Key: {}, http status: {}.",
idempotencyKey,
- binding,
found.httpStatus());
Response.ResponseBuilder builder = Response.status(found.httpStatus());
if (found.responseSummary() != null) {
@@ -273,7 +279,7 @@ public class IcebergIdempotencyManager {
return builder.build();
}
- private boolean tryFinalize(
+ private void tryFinalize(
IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
String responseSummary;
try {
@@ -285,26 +291,24 @@ public class IcebergIdempotencyManager {
} else {
responseSummary = icebergObjectMapper.writeValueAsString(entity);
}
- } catch (JsonProcessingException e) {
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim; "
+ + "leaving any reservation until expiry",
+ idempotencyKey);
+ }
+ } catch (JsonProcessingException | RuntimeException e) {
LOG.warn(
- "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ "Failed to retain the response for Idempotency-Key: {}; leaving any reservation until expiry",
idempotencyKey,
e);
- return false;
- }
- idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
- boolean finalized =
- idempotencyStore
- .load(idempotencyKey)
- .filter(record -> record.isFinalized() && record.claim() == claim)
- .isPresent();
- if (!finalized) {
- LOG.warn(
- "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
}
- // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
- // retry an operation that already committed. Release is fenced to our claim in the caller.
- return finalized;
}
private static Response conflict(String message, boolean retryable) {
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyKeys.java
similarity index 98%
rename from iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java
rename to iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyKeys.java
index 341cd1787a..2b874babaf 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyKeys.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
import java.util.Locale;
import java.util.UUID;
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.java
similarity index 99%
rename from iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java
rename to iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.java
index 8b121148b7..30324f956e 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyRecord.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
import com.google.common.base.Preconditions;
import java.util.Objects;
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.java
similarity index 78%
rename from iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java
rename to iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.java
index 645e682fd0..0652a6dcdc 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStore.java
@@ -16,11 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+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;
/**
@@ -50,14 +51,6 @@ import javax.annotation.Nullable;
*/
public interface IdempotencyStore extends Closeable {
- /** Outcome of an attempt to claim a key. */
- enum ReserveResult {
- /** The key was newly claimed by this caller, which now owns the mutation. */
- RESERVED,
- /** A non-expired reservation or finalized record already exists for the key. */
- DUPLICATE
- }
-
/**
* Initializes the store from the Iceberg REST server configuration.
*
@@ -69,23 +62,21 @@ public interface IdempotencyStore extends Closeable {
* Atomically attempts to claim a key. An expired record is treated as absent, so the key can be
* reserved again without waiting for a purge.
*
- * <p>The store retains the operation binding but does not compare it when returning {@link
- * ReserveResult#DUPLICATE}. The REST handler owns binding checks: when {@link #load} returns a
- * finalized record, the handler must reject a different binding with {@code 409 Conflict} instead
- * of replaying it. When the key is still in flight, {@code load} returns empty and the handler
- * returns the same in-flight {@code 409 Conflict}, regardless of whether the bindings match.
+ * <p>The store retains the operation binding but does not compare it when a reservation already
+ * exists. The REST handler owns binding checks: when {@link #load} returns a finalized record,
+ * the handler must reject a different binding with {@code 409 Conflict} instead of replaying it.
+ * When the key is still in flight, {@code load} returns empty and the handler returns the same
+ * in-flight {@code 409 Conflict}, regardless of whether the bindings match.
*
* @param idempotencyKey the client-provided UUIDv7 key
- * @param operationBinding request identity, for example {@code POST
- * /v1/cat1/namespaces/ns1/tables}
- * @param claim a fencing token identifying this attempt, which the caller must generate afresh
- * for every reservation and pass back to {@link #finalizeRecord} and {@link #release}
+ * @param 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 {@link ReserveResult#RESERVED} if newly claimed, {@link ReserveResult#DUPLICATE} if a
- * non-expired reservation or finalized record for this key already exists
+ * @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}.
*/
- ReserveResult reserve(
- String idempotencyKey, String operationBinding, long claim, long expiresAtMs);
+ OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs);
/**
* Loads a finalized record for replay.
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStoreFactory.java
similarity index 91%
rename from iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java
rename to iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStoreFactory.java
index ef789624e6..3849f91550 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyStoreFactory.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
import com.google.common.collect.ImmutableMap;
import org.apache.gravitino.iceberg.common.IcebergConfig;
@@ -33,7 +33,11 @@ public class IdempotencyStoreFactory {
* fully-qualified class name for them.
*/
private static final ImmutableMap<String, String> STORE_CLASS_NAMES =
- ImmutableMap.of("in-memory", InMemoryIdempotencyStore.class.getCanonicalName());
+ ImmutableMap.of(
+ "in-memory",
+ InMemoryIdempotencyStore.class.getCanonicalName(),
+ "jdbc",
+ JdbcIdempotencyStore.class.getCanonicalName());
private IdempotencyStoreFactory() {}
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.java
similarity index 92%
rename from iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java
rename to iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.java
index 017b0e0701..a50e8df1de 100644
--- a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/InMemoryIdempotencyStore.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@@ -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;
@@ -61,6 +61,7 @@ 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;
@@ -123,26 +124,23 @@ public class InMemoryIdempotencyStore implements IdempotencyStore {
}
@Override
- public ReserveResult reserve(
- String idempotencyKey, String operationBinding, long claim, long expiresAtMs) {
+ public OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {
String key = IdempotencyKeys.canonicalize(idempotencyKey);
IdempotencyRecord reserved =
- IdempotencyRecord.reserved(key, operationBinding, claim, clock.getAsLong(), expiresAtMs);
+ IdempotencyRecord.reserved(
+ key, operationBinding, generations.incrementAndGet(), clock.getAsLong(), expiresAtMs);
// A record past its deadline is treated as absent rather than waiting for the cache to reclaim
// it, so behavior turns on the record's own expiry instead of when maintenance happens to run.
- AtomicBoolean claimed = new AtomicBoolean();
- cache
- .asMap()
- .compute(
- key,
- (cacheKey, existing) -> {
- if (existing == null || isExpired(existing)) {
- claimed.set(true);
- return reserved;
- }
- return existing;
- });
- return claimed.get() ? ReserveResult.RESERVED : ReserveResult.DUPLICATE;
+ 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();
}
@Override
diff --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.java
new file mode 100644
index 0000000000..7437491076
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalLong;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper;
+import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Durable idempotency records shared by replicas using the same Gravitino relational entity store.
+ * Requires an initialized entity store, as provided in auxiliary mode. The database schema must be
+ * upgraded before this store is enabled.
+ *
+ * <p>Reservations commit independently of catalog transactions. Claim tokens fence stale finalize
+ * and release calls, but cannot undo catalog side effects or make the catalog mutation and response
+ * persistence atomic. Expired keys can be reserved again without waiting for background cleanup.
+ * Replicas must synchronize system clocks: a fast clock can reclaim a key another replica still
+ * considers live. There is no clock-skew grace period. 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>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;
+
+ private final Clock clock;
+ private SqlSessionFactory sessionFactory;
+ private ScheduledExecutorService purgeScheduler;
+
+ /** Creates a store using the system UTC clock. */
+ public JdbcIdempotencyStore() {
+ this(Clock.systemUTC());
+ }
+
+ @VisibleForTesting
+ JdbcIdempotencyStore(Clock clock) {
+ this.clock = clock;
+ }
+
+ @Override
+ public void initialize(Map<String, String> properties) {
+ Preconditions.checkState(
+ sessionFactory == null, "JDBC idempotency store is already initialized");
+ Duration interval =
+ Duration.parse(
+ new IcebergConfig(properties).get(IcebergConfig.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL));
+ long intervalMs = interval.toMillis();
+ Preconditions.checkArgument(
+ intervalMs > 0, "Idempotency cleanup interval must be at least 1ms");
+ SqlSessionFactory factory;
+ try {
+ factory = SqlSessionFactoryHelper.getInstance().getSqlSessionFactory();
+ } catch (IllegalStateException e) {
+ throw new IllegalStateException(
+ "JDBC idempotency storage requires an initialized Gravitino relational entity store "
+ + "(auxiliary mode); it is not available in the standalone Iceberg REST server",
+ e);
+ }
+ // Core cannot discover mappers in the auxiliary service's class loader during its startup.
+ Configuration configuration = factory.getConfiguration();
+ synchronized (configuration) {
+ if (!configuration.hasMapper(IcebergIdempotencyKeyMapper.class)) {
+ configuration.addMapper(IcebergIdempotencyKeyMapper.class);
+ }
+ }
+ // Fail startup, rather than the first mutation, when the database has not been upgraded.
+ try (SqlSession session = factory.openSession()) {
+ IcebergIdempotencyKeyMapper mapper = session.getMapper(IcebergIdempotencyKeyMapper.class);
+ mapper.selectRecord("00000000-0000-7000-8000-000000000000", clock.millis());
+ mapper.selectGeneration(0);
+ session.commit();
+ }
+ sessionFactory = factory;
+ purgeScheduler =
+ Executors.newSingleThreadScheduledExecutor(
+ runnable -> {
+ Thread thread = new Thread(runnable, "iceberg-idempotency-purge");
+ thread.setDaemon(true);
+ return thread;
+ });
+ purgeScheduler.scheduleWithFixedDelay(
+ this::purgeExpiredRecords, intervalMs, intervalMs, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public OptionalLong 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(
+ mapper -> {
+ long generation = nextGeneration(mapper, key);
+ mapper.insert(
+ IcebergIdempotencyKeyPO.reserved(
+ key, operationBinding, generation, nowMs, expiresAtMs));
+ return OptionalLong.of(generation);
+ });
+ } 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 =
+ 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;
+ }
+ // Purge or release may have removed the row. Retry once with a fresh expiry cutoff.
+ }
+ return OptionalLong.empty();
+ }
+
+ @Override
+ public Optional<IdempotencyRecord> load(String idempotencyKey) {
+ String key = IdempotencyKeys.canonicalize(idempotencyKey);
+ return Optional.ofNullable(execute(mapper -> mapper.selectRecord(key, clock.millis())))
+ .map(IcebergIdempotencyKeyPO::toIdempotencyRecord);
+ }
+
+ @Override
+ public void finalizeRecord(
+ String idempotencyKey, long claim, int httpStatus, @Nullable String responseSummary) {
+ String key = IdempotencyKeys.canonicalize(idempotencyKey);
+ int updated =
+ execute(
+ mapper ->
+ mapper.finalizeRecord(key, claim, httpStatus, responseSummary, clock.millis()));
+ if (updated == 0) {
+ LOG.debug("No live unfinalized reservation to finalize for key {} and claim {}", key, claim);
+ }
+ }
+
+ @Override
+ public void release(String idempotencyKey, long claim) {
+ String key = IdempotencyKeys.canonicalize(idempotencyKey);
+ int deleted = execute(mapper -> mapper.deleteReservation(key, claim));
+ if (deleted == 0) {
+ LOG.debug("No unfinalized reservation to release for key {} and claim {}", key, claim);
+ }
+ }
+
+ @Override
+ public int purgeExpired(long beforeMs) {
+ int purged = 0;
+ for (int batch = 0; batch < MAX_PURGE_BATCHES; batch++) {
+ int deleted = execute(mapper -> mapper.deleteExpiredBatch(beforeMs, PURGE_BATCH_SIZE));
+ purged += deleted;
+ if (deleted < PURGE_BATCH_SIZE) {
+ break;
+ }
+ }
+ return purged;
+ }
+
+ @Override
+ public void close() {
+ if (purgeScheduler != null) {
+ purgeScheduler.shutdown();
+ try {
+ if (!purgeScheduler.awaitTermination(5, TimeUnit.SECONDS)) {
+ purgeScheduler.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ purgeScheduler.shutdownNow();
+ Thread.currentThread().interrupt();
+ }
+ }
+ // The entity store owns the shared connection pool and closes it after auxiliary services.
+ }
+
+ @VisibleForTesting
+ void purgeExpiredRecords() {
+ try {
+ purgeExpired(clock.millis());
+ } catch (Exception e) {
+ // A transient database failure must not cancel all future scheduled cleanup attempts.
+ LOG.warn("Purging expired Iceberg idempotency records failed", e);
+ }
+ }
+
+ @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));
+ session.commit();
+ return result;
+ }
+ }
+}
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.java
new file mode 100644
index 0000000000..b4cb643405
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeyMapper.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency.mapper;
+
+import javax.annotation.Nullable;
+import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import 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;
+
+/**
+ * MyBatis mapper for the {@code iceberg_idempotency_meta} table. SQL is supplied per backend by
+ * {@link IcebergIdempotencyKeySQLProviderFactory} and executed through the Gravitino entity store's
+ * shared {@code SqlSessionFactory}, so the durable idempotency store reuses the relational
+ * backend's connection pool and multi-backend handling instead of opening its own JDBC connections.
+ */
+public interface IcebergIdempotencyKeyMapper {
+
+ /** Table containing reservations and replayable responses. */
+ String TABLE_NAME = "iceberg_idempotency_meta";
+
+ /**
+ * Inserts a reservation; a duplicate key is handled by the store.
+ *
+ * @param po reservation to persist
+ * @return number of affected rows
+ */
+ @InsertProvider(type = IcebergIdempotencyKeySQLProviderFactory.class, method = "insert")
+ int insert(@Param("po") IcebergIdempotencyKeyPO po);
+
+ /**
+ * Replaces an expired reservation with a new generation.
+ *
+ * @param po reservation to persist
+ * @return number of affected rows
+ */
+ @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.
+ *
+ * @param idempotencyKey canonical UUIDv7 key
+ * @param nowMs current time in unix epoch milliseconds
+ * @return matching response, or null
+ */
+ @SelectProvider(type = IcebergIdempotencyKeySQLProviderFactory.class, method = "selectRecord")
+ @Nullable
+ IcebergIdempotencyKeyPO selectRecord(
+ @Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long nowMs);
+
+ /**
+ * Finalizes a live reservation owned by the given claim.
+ *
+ * @param idempotencyKey canonical UUIDv7 key
+ * @param claim reservation fencing token
+ * @param httpStatus response status
+ * @param responseSummary serialized response body, or null for an empty body
+ * @param nowMs current time in unix epoch milliseconds
+ * @return number of affected rows
+ */
+ @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.
+ *
+ * @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);
+
+ /**
+ * Deletes only rows matching the statement's ownership or expiry guard.
+ *
+ * @param beforeMs inclusive expiry cutoff in unix epoch milliseconds
+ * @param batchSize maximum number of rows to delete
+ * @return number of affected rows
+ */
+ @DeleteProvider(
+ type = IcebergIdempotencyKeySQLProviderFactory.class,
+ method = "deleteExpiredBatch")
+ int 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/mapper/IcebergIdempotencyKeySQLProviderFactory.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeySQLProviderFactory.java
new file mode 100644
index 0000000000..8a83039913
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/IcebergIdempotencyKeySQLProviderFactory.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency.mapper;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import org.apache.gravitino.iceberg.service.idempotency.mapper.provider.base.IcebergIdempotencyKeyBaseSQLProvider;
+import org.apache.gravitino.iceberg.service.idempotency.mapper.provider.postgresql.IcebergIdempotencyKeyPostgreSQLProvider;
+import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.ibatis.annotations.Param;
+
+/** Selects SQL for the shared entity store's database dialect. */
+public class IcebergIdempotencyKeySQLProviderFactory {
+
+ private static final IcebergIdempotencyKeyBaseSQLProvider BASE_PROVIDER =
+ new IcebergIdempotencyKeyBaseSQLProvider();
+
+ private static final Map<JDBCBackendType, IcebergIdempotencyKeyBaseSQLProvider> PROVIDERS =
+ ImmutableMap.of(
+ JDBCBackendType.MYSQL, BASE_PROVIDER,
+ JDBCBackendType.H2, BASE_PROVIDER,
+ JDBCBackendType.POSTGRESQL, new IcebergIdempotencyKeyPostgreSQLProvider());
+
+ /**
+ * Returns the statement for the configured entity-store database.
+ *
+ * @param po reservation to persist
+ * @return SQL statement
+ */
+ public static String insert(@Param("po") IcebergIdempotencyKeyPO po) {
+ return getProvider().insert(po);
+ }
+
+ /**
+ * Returns the expired reservation replacement statement.
+ *
+ * @param po reservation to persist
+ * @return SQL statement
+ */
+ public static String replaceExpired(@Param("po") IcebergIdempotencyKeyPO po) {
+ 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.
+ *
+ * @param idempotencyKey canonical UUIDv7 key
+ * @param nowMs current time in unix epoch milliseconds
+ * @return SQL statement
+ */
+ public static String selectRecord(
+ @Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long nowMs) {
+ return getProvider().selectRecord(idempotencyKey, nowMs);
+ }
+
+ /**
+ * 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
+ * @return SQL statement
+ */
+ 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * Returns the statement for the configured entity-store database.
+ *
+ * @param beforeMs inclusive expiry cutoff in unix epoch milliseconds
+ * @param batchSize maximum number of rows to delete
+ * @return SQL statement
+ */
+ public static String deleteExpiredBatch(
+ @Param("beforeMs") long beforeMs, @Param("batchSize") int batchSize) {
+ return getProvider().deleteExpiredBatch(beforeMs, batchSize);
+ }
+
+ private static IcebergIdempotencyKeyBaseSQLProvider getProvider() {
+ String databaseId =
+ SqlSessionFactoryHelper.getInstance()
+ .getSqlSessionFactory()
+ .getConfiguration()
+ .getDatabaseId();
+ return PROVIDERS.get(JDBCBackendType.fromString(databaseId));
+ }
+}
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.java
new file mode 100644
index 0000000000..69b9ecf194
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency.mapper.provider.base;
+
+import static org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper.TABLE_NAME;
+
+import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.ibatis.annotations.Param;
+
+/** SQL statements shared by the MySQL and H2 entity stores. */
+public class IcebergIdempotencyKeyBaseSQLProvider {
+ /**
+ * Returns the reservation INSERT.
+ *
+ * @param po reservation to persist
+ * @return SQL statement
+ */
+ public String insert(@Param("po") IcebergIdempotencyKeyPO po) {
+ return "INSERT INTO "
+ + TABLE_NAME
+ + " (idempotency_key, http_method, request_uri, generation, audit_info, created_at, expires_at)"
+ + " VALUES (#{po.idempotencyKey}, #{po.httpMethod}, #{po.requestUri}, #{po.generation},"
+ + " #{po.auditInfo}, #{po.createdAt}, #{po.expiresAt})";
+ }
+
+ /**
+ * Returns an atomic replacement of an expired reservation or response.
+ *
+ * @param po reservation to persist
+ * @return SQL statement
+ */
+ public String replaceExpired(@Param("po") IcebergIdempotencyKeyPO po) {
+ return "UPDATE "
+ + TABLE_NAME
+ + " SET http_method = #{po.httpMethod}, request_uri = #{po.requestUri}, generation = #{po.generation},"
+ + " 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.
+ *
+ * @param idempotencyKey canonical UUIDv7 key
+ * @param nowMs current time in unix epoch milliseconds
+ * @return SQL statement
+ */
+ public String selectRecord(
+ @Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long nowMs) {
+ return "SELECT idempotency_key AS idempotencyKey, http_method AS httpMethod, request_uri AS requestUri,"
+ + " generation, http_status AS httpStatus, response_summary AS responseSummary,"
+ + " audit_info AS auditInfo, created_at AS createdAt, expires_at AS expiresAt FROM "
+ + TABLE_NAME
+ + " WHERE idempotency_key = #{idempotencyKey}"
+ + " AND http_status IS NOT NULL AND expires_at > #{nowMs}";
+ }
+
+ /**
+ * Returns a finalization guarded by the reservation's claim and expiry.
+ *
+ * @param idempotencyKey canonical UUIDv7 key
+ * @param claim reservation fencing token
+ * @param httpStatus response status
+ * @param responseSummary serialized response body, or null for an empty body
+ * @param nowMs current time in unix epoch milliseconds
+ * @return SQL statement
+ */
+ public String finalizeRecord(
+ @Param("idempotencyKey") String idempotencyKey,
+ @Param("claim") long claim,
+ @Param("httpStatus") int httpStatus,
+ @Param("responseSummary") String responseSummary,
+ @Param("nowMs") long nowMs) {
+ return "UPDATE "
+ + TABLE_NAME
+ + " SET http_status = #{httpStatus}, response_summary = #{responseSummary}"
+ + " WHERE idempotency_key = #{idempotencyKey} AND generation = #{claim}"
+ + " AND http_status IS NULL AND expires_at > #{nowMs}";
+ }
+
+ /**
+ * Returns a release guarded by the reservation's claim. Finalized responses are retained.
+ *
+ * @param idempotencyKey canonical UUIDv7 key
+ * @param claim reservation fencing token
+ * @return SQL statement
+ */
+ public String deleteReservation(
+ @Param("idempotencyKey") String idempotencyKey, @Param("claim") long claim) {
+ return "DELETE FROM "
+ + TABLE_NAME
+ + " WHERE idempotency_key = #{idempotencyKey} AND generation = #{claim} AND http_status IS NULL";
+ }
+
+ /**
+ * Returns an indexed, bounded deletion including the exact expiry cutoff.
+ *
+ * @param beforeMs inclusive expiry cutoff in unix epoch milliseconds
+ * @param batchSize maximum number of rows to delete
+ * @return SQL statement
+ */
+ public String deleteExpiredBatch(
+ @Param("beforeMs") long beforeMs, @Param("batchSize") int batchSize) {
+ // The target-row predicate is rechecked after a lock wait by InnoDB and H2. Unlike the
+ // PostgreSQL batch subquery, this statement never selects candidate keys separately.
+ return "DELETE FROM " + TABLE_NAME + " WHERE expires_at <= #{beforeMs} LIMIT #{batchSize}";
+ }
+}
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.java
new file mode 100644
index 0000000000..deef83143a
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/postgresql/IcebergIdempotencyKeyPostgreSQLProvider.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency.mapper.provider.postgresql;
+
+import static org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper.TABLE_NAME;
+
+import org.apache.gravitino.iceberg.service.idempotency.mapper.provider.base.IcebergIdempotencyKeyBaseSQLProvider;
+import org.apache.ibatis.annotations.Param;
+
+/** PostgreSQL statements for generation allocation and 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";
+ }
+
+ @Override
+ public String deleteExpiredBatch(
+ @Param("beforeMs") long beforeMs, @Param("batchSize") int batchSize) {
+ // Recheck the outer row's expiry after waiting for a concurrent reservation replacement.
+ return "DELETE FROM "
+ + TABLE_NAME
+ + " WHERE expires_at <= #{beforeMs} AND idempotency_key IN (SELECT idempotency_key FROM "
+ + TABLE_NAME
+ + " WHERE expires_at <= #{beforeMs} LIMIT #{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.java
new file mode 100644
index 0000000000..8d27afa68b
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/po/IcebergIdempotencyKeyPO.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency.po;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.io.UncheckedIOException;
+import java.time.Instant;
+import javax.annotation.Nullable;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import org.apache.gravitino.iceberg.service.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.utils.PrincipalUtils;
+
+/**
+ * Persistence object for one {@code iceberg_idempotency_meta} row. Mirrors the table columns and is
+ * 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")
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+@AllArgsConstructor(access = AccessLevel.PRIVATE)
+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;
+ private Long createdAt;
+ private Long expiresAt;
+
+ /**
+ * Builds a new reserved (not yet finalized) row.
+ *
+ * @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) {
+ int separator = operationBinding.indexOf(' ');
+ String method = separator < 0 ? operationBinding : operationBinding.substring(0, separator);
+ String uri = separator < 0 ? "" : operationBinding.substring(separator + 1);
+ return builder()
+ .withIdempotencyKey(idempotencyKey)
+ .withHttpMethod(method)
+ .withRequestUri(uri)
+ .withGeneration(generation)
+ .withHttpStatus(null)
+ .withResponseSummary(null)
+ .withAuditInfo(auditInfoJson(createdAtMs))
+ .withCreatedAt(createdAtMs)
+ .withExpiresAt(expiresAtMs)
+ .build();
+ }
+
+ /**
+ * Converts this row to the domain record.
+ *
+ * @return the domain record, finalized iff the row carries an HTTP status
+ */
+ public IdempotencyRecord toIdempotencyRecord() {
+ String binding = requestUri.isEmpty() ? httpMethod : httpMethod + " " + requestUri;
+ IdempotencyRecord record =
+ IdempotencyRecord.reserved(idempotencyKey, binding, generation, createdAt, expiresAt);
+ return httpStatus == null ? record : record.withResponse(httpStatus, responseSummary);
+ }
+
+ // Record the reserving principal before the catalog mutation begins.
+ private static String auditInfoJson(long createdAtMs) {
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.ofEpochMilli(createdAtMs))
+ .build();
+ try {
+ return JsonUtils.anyFieldMapper().writeValueAsString(auditInfo);
+ } catch (JsonProcessingException e) {
+ throw new UncheckedIOException("Failed to serialize the idempotency record audit info", e);
+ }
+ }
+}
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.java
index b167057260..68dbb590f3 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,6 +23,7 @@ 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;
@@ -32,13 +33,8 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
import org.apache.gravitino.iceberg.common.IcebergConfig;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
-import org.apache.gravitino.iceberg.common.idempotency.InMemoryIdempotencyStore;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
public class TestIcebergIdempotencyManager {
@@ -232,10 +228,8 @@ public class TestIcebergIdempotencyManager {
@Test
void testRetryWhileTheFirstRequestIsRunningIsRetryable() {
IdempotencyStore store = Mockito.mock(IdempotencyStore.class);
- Mockito.when(
- store.reserve(
- Mockito.anyString(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong()))
- .thenReturn(ReserveResult.DUPLICATE);
+ Mockito.when(store.reserve(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()))
+ .thenReturn(OptionalLong.empty());
Mockito.when(store.load(KEY)).thenReturn(Optional.empty());
IcebergIdempotencyManager manager =
new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));
@@ -268,46 +262,74 @@ public class TestIcebergIdempotencyManager {
}
@Test
- void testNoOpFinalizeReleasesOnlyItsOwnClaim() {
+ void testNoOpFinalizeRetainsReservation() {
IdempotencyStore store = Mockito.mock(IdempotencyStore.class);
- Mockito.when(
- store.reserve(
- Mockito.eq(KEY), Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong()))
- .thenReturn(ReserveResult.RESERVED);
+ Mockito.when(store.reserve(Mockito.eq(KEY), Mockito.anyString(), Mockito.anyLong()))
+ .thenReturn(OptionalLong.of(1));
IcebergIdempotencyManager manager =
new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));
Response response = execute(manager, KEY, new AtomicInteger());
Assertions.assertEquals(200, response.getStatus());
- ArgumentCaptor<Long> claim = ArgumentCaptor.forClass(Long.class);
- Mockito.verify(store)
- .reserve(Mockito.eq(KEY), Mockito.anyString(), claim.capture(), Mockito.anyLong());
- Mockito.verify(store).release(KEY, claim.getValue());
+ Mockito.verify(store, Mockito.never()).release(Mockito.anyString(), Mockito.anyLong());
}
@Test
- void testFinalizeWithReplacementClaimReleasesOnlyOriginalClaim() {
+ void testFinalizeWithReplacementClaimDoesNotRelease() {
IdempotencyStore store = Mockito.mock(IdempotencyStore.class);
- Mockito.when(
- store.reserve(
- Mockito.eq(KEY), Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong()))
+ Mockito.when(store.reserve(Mockito.eq(KEY), Mockito.anyString(), Mockito.anyLong()))
.thenAnswer(
invocation -> {
- long originalClaim = invocation.getArgument(2);
Mockito.when(store.load(KEY))
.thenReturn(
Optional.of(
- IdempotencyRecord.reserved(
- KEY, BINDING, originalClaim + 1, 0, Long.MAX_VALUE)
+ IdempotencyRecord.reserved(KEY, BINDING, 2, 0, Long.MAX_VALUE)
.withResponse(200, "replacement")));
- return ReserveResult.RESERVED;
+ return OptionalLong.of(1);
});
IcebergIdempotencyManager manager =
new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));
Assertions.assertEquals(200, execute(manager, KEY, new AtomicInteger()).getStatus());
- ArgumentCaptor<Long> claim = ArgumentCaptor.forClass(Long.class);
- Mockito.verify(store)
- .reserve(Mockito.eq(KEY), Mockito.anyString(), claim.capture(), Mockito.anyLong());
- Mockito.verify(store).release(KEY, claim.getValue());
+ Mockito.verify(store, Mockito.never()).release(Mockito.anyString(), Mockito.anyLong());
+ }
+
+ @Test
+ void testSerializationFailureRetainsReservation() {
+ IcebergIdempotencyManager manager = newManager(ImmutableMap.of());
+ AtomicInteger executions = new AtomicInteger();
+ try (Response first =
+ manager.replayOrExecute(
+ KEY,
+ BINDING,
+ () -> {
+ executions.incrementAndGet();
+ return Response.ok(new UnserializableResponse()).build();
+ });
+ Response retry = execute(manager, KEY, executions)) {
+ Assertions.assertEquals(200, first.getStatus());
+ Assertions.assertEquals(409, retry.getStatus());
+ Assertions.assertEquals("1", retry.getHeaderString(HttpHeaders.RETRY_AFTER));
+ Assertions.assertEquals(1, executions.get());
+ }
+ }
+
+ @Test
+ void testReadFailureAfterFinalizeKeepsOriginalResponse() {
+ InMemoryIdempotencyStore store = Mockito.spy(new InMemoryIdempotencyStore());
+ store.initialize(ImmutableMap.of());
+ Mockito.doThrow(new IllegalStateException("read unavailable"))
+ .doCallRealMethod()
+ .when(store)
+ .load(KEY);
+ IcebergIdempotencyManager manager =
+ new IcebergIdempotencyManager(enabledConfig(ImmutableMap.of()), Optional.of(store));
+ AtomicInteger executions = new AtomicInteger();
+ try (Response first = execute(manager, KEY, executions);
+ Response retry = execute(manager, KEY, executions)) {
+ 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());
+ }
}
@Test
@@ -322,6 +344,8 @@ public class TestIcebergIdempotencyManager {
"POST /v1/namespaces/ns%2Fone/tables?a%26b=x%3Dy%26c&a%26b=z&a%26b=z", binding);
query.put("a&b", Arrays.asList("z", "z", "x=y&c"));
Assertions.assertEquals(binding, IcebergIdempotencyManager.operationBinding("POST", uri));
+ query.put("a&b", Arrays.asList("x=y&c", "z"));
+ Assertions.assertNotEquals(binding, IcebergIdempotencyManager.operationBinding("POST", uri));
}
private static Response execute(
@@ -362,4 +386,11 @@ public class TestIcebergIdempotencyManager {
merged.put(IcebergConstants.ICEBERG_IDEMPOTENCY_ENABLED, "true");
return new IcebergConfig(merged);
}
+
+ private static class UnserializableResponse {
+ /** Simulates a response whose body cannot be serialized. */
+ public String getValue() {
+ throw new IllegalStateException("serialization failure");
+ }
+ }
}
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyKeys.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyKeys.java
similarity index 98%
rename from iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyKeys.java
rename to iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyKeys.java
index c889b36782..622c5a267b 100644
--- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyKeys.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyKeys.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyStoreFactory.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.java
similarity index 96%
rename from iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyStoreFactory.java
rename to iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.java
index 37b8e97006..6cb5a715b9 100644
--- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestIdempotencyStoreFactory.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestIdempotencyStoreFactory.java
@@ -16,12 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
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;
@@ -127,9 +128,8 @@ public class TestIdempotencyStoreFactory {
}
@Override
- public ReserveResult reserve(
- String idempotencyKey, String operationBinding, long claim, long expiresAtMs) {
- return ReserveResult.RESERVED;
+ public OptionalLong reserve(String idempotencyKey, String operationBinding, long expiresAtMs) {
+ return OptionalLong.of(1);
}
@Override
diff --git a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestInMemoryIdempotencyStore.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.java
similarity index 69%
rename from iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestInMemoryIdempotencyStore.java
rename to iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.java
index b86f21147b..5df0b11ad5 100644
--- a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/idempotency/TestInMemoryIdempotencyStore.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestInMemoryIdempotencyStore.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.iceberg.common.idempotency;
+package org.apache.gravitino.iceberg.service.idempotency;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
@@ -24,6 +24,7 @@ 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;
@@ -31,9 +32,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongSupplier;
-import java.util.stream.Collectors;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
-import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -46,7 +45,6 @@ public class TestInMemoryIdempotencyStore {
private static final String OTHER_KEY = "017f22e2-79b0-7cc3-98c4-dc0c0c073990";
private static final String BINDING = "POST v1/cat1/namespaces/ns1/tables";
private static final long FAR_FUTURE_MS = Long.MAX_VALUE;
- private static final long CLAIM = 1L;
private InMemoryIdempotencyStore store;
@@ -62,25 +60,20 @@ public class TestInMemoryIdempotencyStore {
@Test
void testReserveClaimsKeyOnlyOnce() {
- Assertions.assertEquals(
- ReserveResult.RESERVED, store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS));
- Assertions.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, CLAIM + 1, FAR_FUTURE_MS));
- Assertions.assertEquals(
- ReserveResult.RESERVED, store.reserve(OTHER_KEY, BINDING, CLAIM, FAR_FUTURE_MS));
+ 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());
}
@Test
void testKeyCaseVariantsAddressTheSameRecord() {
- Assertions.assertEquals(
- ReserveResult.RESERVED, store.reserve(KEY_UPPER, BINDING, CLAIM, FAR_FUTURE_MS));
- Assertions.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, CLAIM + 1, FAR_FUTURE_MS));
+ long claim = store.reserve(KEY_UPPER, BINDING, FAR_FUTURE_MS).orElseThrow();
+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());
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, claim, 200, "{\"a\":1}");
IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);
Assertions.assertEquals(KEY, record.idempotencyKey());
Assertions.assertEquals(200, record.httpStatus().intValue());
@@ -88,10 +81,10 @@ public class TestInMemoryIdempotencyStore {
@Test
void testLoadReturnsEmptyUntilFinalized() {
- store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
Assertions.assertEquals(Optional.empty(), store.load(KEY));
- store.finalizeRecord(KEY, CLAIM, 200, "{\"a\":1}");
+ store.finalizeRecord(KEY, claim, 200, "{\"a\":1}");
IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);
Assertions.assertTrue(record.isFinalized());
@@ -108,8 +101,8 @@ public class TestInMemoryIdempotencyStore {
@Test
void testFinalizeWithoutBodyIsReplayable() {
- store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
- store.finalizeRecord(KEY, CLAIM, 204, null);
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+ store.finalizeRecord(KEY, claim, 204, null);
IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);
Assertions.assertEquals(204, record.httpStatus().intValue());
@@ -118,48 +111,42 @@ public class TestInMemoryIdempotencyStore {
@Test
void testFinalizeDoesNotResurrectAPurgedRecord() {
- store.finalizeRecord(KEY, CLAIM, 200, "{}");
+ store.finalizeRecord(KEY, 1L, 200, "{}");
Assertions.assertEquals(Optional.empty(), store.load(KEY));
Assertions.assertEquals(0, store.size());
}
@Test
void testReleaseFreesTheKeyForRetry() {
- store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
- store.release(KEY, CLAIM);
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+ store.release(KEY, claim);
- Assertions.assertEquals(
- ReserveResult.RESERVED, store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS));
+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent());
}
@Test
void testReleaseKeepsAFinalizedRecord() {
- store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
- store.finalizeRecord(KEY, CLAIM, 200, "{}");
- store.release(KEY, CLAIM);
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+ store.finalizeRecord(KEY, claim, 200, "{}");
+ store.release(KEY, claim);
Assertions.assertTrue(store.load(KEY).isPresent());
- Assertions.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS));
+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());
}
@Test
void testStaleFinalizeAfterReReservationIsIgnored() {
- long staleClaim = 1L;
- long currentClaim = 2L;
- store.reserve(KEY, BINDING, staleClaim, FAR_FUTURE_MS);
+ 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);
- Assertions.assertEquals(
- ReserveResult.RESERVED, store.reserve(KEY, BINDING, currentClaim, FAR_FUTURE_MS));
+ long currentClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
store.finalizeRecord(KEY, staleClaim, 200, "{\"stale\":true}");
// The current owner is still mid-flight: nothing to replay, and the key stays taken.
Assertions.assertEquals(Optional.empty(), store.load(KEY));
- Assertions.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, 3L, FAR_FUTURE_MS));
+ 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}");
@@ -169,32 +156,27 @@ public class TestInMemoryIdempotencyStore {
@Test
void testStaleReleaseAfterReReservationIsIgnored() {
- long staleClaim = 1L;
- long currentClaim = 2L;
- store.reserve(KEY, BINDING, staleClaim, FAR_FUTURE_MS);
+ long staleClaim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
store.release(KEY, staleClaim);
- store.reserve(KEY, BINDING, currentClaim, FAR_FUTURE_MS);
+ 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.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, 3L, FAR_FUTURE_MS));
+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());
}
@Test
void testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal() {
String otherBinding = "DELETE v1/cat1/namespaces/ns1/tables/t1";
- store.reserve(KEY, BINDING, CLAIM, FAR_FUTURE_MS);
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
- Assertions.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, otherBinding, CLAIM + 1, FAR_FUTURE_MS));
+ Assertions.assertTrue(store.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());
Assertions.assertEquals(Optional.empty(), store.load(KEY));
- store.finalizeRecord(KEY, CLAIM, 201, "{}");
- Assertions.assertEquals(
- ReserveResult.DUPLICATE, store.reserve(KEY, otherBinding, CLAIM + 1, FAR_FUTURE_MS));
+ store.finalizeRecord(KEY, claim, 201, "{}");
+ Assertions.assertTrue(store.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());
Assertions.assertEquals(
BINDING, store.load(KEY).orElseThrow(AssertionError::new).operationBinding());
}
@@ -204,18 +186,16 @@ public class TestInMemoryIdempotencyStore {
AtomicLong now = new AtomicLong(1_000_000L);
InMemoryIdempotencyStore clockedStore = newStore(ImmutableMap.of(), now::get);
try {
- clockedStore.reserve(KEY, BINDING, CLAIM, now.get() + 1_000L);
- clockedStore.reserve(OTHER_KEY, BINDING, CLAIM, now.get() + 60_000L);
+ clockedStore.reserve(KEY, BINDING, now.get() + 1_000L);
+ clockedStore.reserve(OTHER_KEY, BINDING, now.get() + 60_000L);
// Only the first record's window has elapsed.
now.addAndGet(1_000L);
Assertions.assertEquals(1, clockedStore.purgeExpired(now.get()));
- Assertions.assertEquals(
- ReserveResult.RESERVED, clockedStore.reserve(KEY, BINDING, CLAIM, now.get() + 1_000L));
- Assertions.assertEquals(
- ReserveResult.DUPLICATE,
- clockedStore.reserve(OTHER_KEY, BINDING, CLAIM, now.get() + 60_000L));
+ Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, now.get() + 1_000L).isPresent());
+ Assertions.assertTrue(
+ clockedStore.reserve(OTHER_KEY, BINDING, now.get() + 60_000L).isEmpty());
} finally {
clockedStore.close();
}
@@ -227,19 +207,17 @@ public class TestInMemoryIdempotencyStore {
InMemoryIdempotencyStore clockedStore = newStore(ImmutableMap.of(), now::get);
try {
long deadline = now.get() + 1_000L;
- Assertions.assertEquals(
- ReserveResult.RESERVED, clockedStore.reserve(KEY, BINDING, CLAIM, deadline));
+ long claim = clockedStore.reserve(KEY, BINDING, deadline).orElseThrow();
// 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, claim, 200, "{}");
Assertions.assertTrue(clockedStore.load(KEY).isPresent());
now.set(deadline);
Assertions.assertEquals(Optional.empty(), clockedStore.load(KEY));
- Assertions.assertEquals(
- ReserveResult.RESERVED, clockedStore.reserve(KEY, BINDING, CLAIM, now.get() + 1_000L));
+ Assertions.assertTrue(clockedStore.reserve(KEY, BINDING, now.get() + 1_000L).isPresent());
} finally {
clockedStore.close();
}
@@ -251,7 +229,7 @@ public class TestInMemoryIdempotencyStore {
newStore(ImmutableMap.of(IcebergConstants.ICEBERG_IDEMPOTENCY_MAX_ENTRIES, "2"));
try {
for (int i = 0; i < 50; i++) {
- boundedStore.reserve(uuidKey(i), BINDING, CLAIM, FAR_FUTURE_MS);
+ boundedStore.reserve(uuidKey(i), BINDING, FAR_FUTURE_MS);
}
// Caffeine evicts during maintenance, so the bound is reached shortly after the writes
// rather than synchronously with them.
@@ -272,16 +250,15 @@ public class TestInMemoryIdempotencyStore {
ExecutorService executor = Executors.newFixedThreadPool(threads);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(threads);
- List<ReserveResult> results = Collections.synchronizedList(new ArrayList<>());
+ List<OptionalLong> results = Collections.synchronizedList(new ArrayList<>());
AtomicReference<Throwable> failure = new AtomicReference<>();
try {
for (int i = 0; i < threads; i++) {
- long claim = i;
executor.submit(
() -> {
try {
start.await();
- results.add(store.reserve(KEY, BINDING, claim, FAR_FUTURE_MS));
+ results.add(store.reserve(KEY, BINDING, FAR_FUTURE_MS));
} catch (Throwable t) {
failure.compareAndSet(null, t);
} finally {
@@ -292,11 +269,8 @@ public class TestInMemoryIdempotencyStore {
start.countDown();
Assertions.assertTrue(done.await(30, TimeUnit.SECONDS));
Assertions.assertNull(failure.get(), "no reserve should fail");
- Map<ReserveResult, Long> counts =
- results.stream().collect(Collectors.groupingBy(result -> result, Collectors.counting()));
Assertions.assertEquals(threads, results.size(), "every caller should report a result");
- Assertions.assertEquals(1L, counts.getOrDefault(ReserveResult.RESERVED, 0L));
- Assertions.assertEquals(threads - 1L, counts.getOrDefault(ReserveResult.DUPLICATE, 0L));
+ Assertions.assertEquals(1, results.stream().filter(OptionalLong::isPresent).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.java
new file mode 100644
index 0000000000..3754227820
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.java
@@ -0,0 +1,774 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency;
+
+import static org.awaitility.Awaitility.await;
+
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.file.Files;
+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;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper;
+import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.ibatis.executor.Executor;
+import org.apache.ibatis.jdbc.ScriptRunner;
+import org.apache.ibatis.mapping.MappedStatement;
+import org.apache.ibatis.plugin.Interceptor;
+import org.apache.ibatis.plugin.Intercepts;
+import org.apache.ibatis.plugin.Invocation;
+import org.apache.ibatis.plugin.Signature;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestTemplate;
+import org.mockito.Mockito;
+
+/**
+ * Shared {@link JdbcIdempotencyStore} test logic exercised against the same relational backend
+ * matrix as core metadata service tests. {@link TestJDBCBackend} initializes H2 by default, adds
+ * MySQL and PostgreSQL when {@code dockerTest=true}, and empties backend tables before each
+ * invocation.
+ */
+public class TestJdbcIdempotencyStore extends TestJDBCBackend {
+
+ private static final String KEY = "017f22e2-79b0-7cc3-98c4-dc0c0c07398f";
+ private static final String OTHER_KEY = "017f22e2-79b0-7cc3-98c4-dc0c0c073990";
+ private static final String BINDING = "POST v1/cat1/namespaces/ns1/tables";
+ private static final long FAR_FUTURE_MS = Long.MAX_VALUE;
+
+ private final AtomicLong now = new AtomicLong();
+ private Clock clock;
+ private JdbcIdempotencyStore store;
+ private JdbcIdempotencyStore peer;
+
+ // TestJDBCBackend's BackendTestExtension overwrites GravitinoEnv's singleton "config" and
+ // "idGenerator" fields with a backend-only Mockito mock and never restores them. Because the
+ // whole iceberg-rest-server module runs in one JVM, that mock would leak into later test classes
+ // (e.g. credential vending), where MetadataAuthzHelper.enableAuthorization() unboxes the
+ // unstubbed config.get(ENABLE_AUTHORIZATION) -> null and NPEs. Snapshot the pre-test fields and
+ // restore them after this class so it leaves GravitinoEnv exactly as it found it.
+ private Object originalConfig;
+ private Object originalIdGenerator;
+
+ /** Saves the process-wide environment before the backend test fixture replaces it. */
+ @BeforeAll
+ public void snapshotGravitinoEnv() throws IllegalAccessException {
+ originalConfig = FieldUtils.readField(GravitinoEnv.getInstance(), "config", true);
+ originalIdGenerator = FieldUtils.readField(GravitinoEnv.getInstance(), "idGenerator", true);
+ }
+
+ /** Restores the environment so other REST server tests retain their original configuration. */
+ @AfterAll
+ public void restoreGravitinoEnv() throws IllegalAccessException {
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", originalConfig, true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "idGenerator", originalIdGenerator, true);
+ }
+
+ /** Creates two store instances sharing the test database and a controllable clock. */
+ @BeforeEach
+ public void prepareIdempotencyStore() {
+ now.set(1_000_000L);
+ clock = Mockito.mock(Clock.class);
+ Mockito.when(clock.millis()).thenAnswer(invocation -> now.get());
+ store = new JdbcIdempotencyStore(clock);
+ peer = new JdbcIdempotencyStore(clock);
+ // A long interval keeps the background task out of the way: every test below drives the purge
+ // itself, so a concurrent scheduled run would only make assertions racy.
+ store.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H"));
+ peer.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H"));
+ }
+
+ /** Stops the stores' cleanup tasks without closing the fixture's connection pool. */
+ @AfterEach
+ public void closeIdempotencyStore() {
+ store.close();
+ peer.close();
+ }
+
+ @TestTemplate
+ void testFactoryCreatesInitializedJdbcStore() throws IOException {
+ IcebergConfig config =
+ new IcebergConfig(
+ ImmutableMap.of(
+ IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE, "jdbc",
+ 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.assertEquals(BINDING, peer.load(KEY).orElseThrow().operationBinding());
+ }
+ }
+
+ @TestTemplate
+ void 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());
+ }
+
+ @TestTemplate
+ void testConcurrentReserveOnOneKeyHasExactlyOneWinner() throws InterruptedException {
+ int threads = 16;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ CountDownLatch start = new CountDownLatch(1);
+ CountDownLatch done = new CountDownLatch(threads);
+ AtomicInteger reserved = new AtomicInteger();
+ AtomicInteger failed = new AtomicInteger();
+
+ try {
+ for (int i = 0; i < threads; i++) {
+ JdbcIdempotencyStore contender = i % 2 == 0 ? store : peer;
+ executor.submit(
+ () -> {
+ try {
+ start.await();
+ if (contender.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent()) {
+ reserved.incrementAndGet();
+ }
+ } catch (Exception e) {
+ // A duplicate-key error rather than a zero-row insert would break the contract as
+ // surely as two winners would, so count it instead of letting it vanish.
+ failed.incrementAndGet();
+ } finally {
+ done.countDown();
+ }
+ });
+ }
+ start.countDown();
+ Assertions.assertTrue(done.await(60, TimeUnit.SECONDS));
+ } finally {
+ executor.shutdownNow();
+ }
+
+ Assertions.assertEquals(0, failed.get(), "reserve should never raise on a lost race");
+ Assertions.assertEquals(1, reserved.get(), "exactly one caller should claim the key");
+ }
+
+ @TestTemplate
+ void testLoadReturnsEmptyUntilFinalized() {
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+ Assertions.assertEquals(Optional.empty(), store.load(KEY));
+
+ store.finalizeRecord(KEY, claim, 200, "{\"a\":1}");
+
+ IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);
+ Assertions.assertTrue(record.isFinalized());
+ Assertions.assertEquals(KEY, record.idempotencyKey());
+ Assertions.assertEquals(BINDING, record.operationBinding());
+ Assertions.assertEquals(200, record.httpStatus().intValue());
+ Assertions.assertEquals("{\"a\":1}", record.responseSummary());
+ Assertions.assertEquals(FAR_FUTURE_MS, record.expiresAtMs());
+ }
+
+ @TestTemplate
+ void testFinalizeWithoutBodyIsReplayable() {
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+ store.finalizeRecord(KEY, claim, 204, null);
+
+ IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new);
+ Assertions.assertEquals(204, record.httpStatus().intValue());
+ Assertions.assertNull(record.responseSummary());
+ }
+
+ @TestTemplate
+ void testFinalizeDoesNotResurrectPurgedRecord() {
+ store.finalizeRecord(KEY, 1, 200, "{}");
+ Assertions.assertEquals(Optional.empty(), store.load(KEY));
+ }
+
+ @TestTemplate
+ void 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();
+
+ store.finalizeRecord(KEY, newClaim, 201, "{\"b\":2}");
+ store.release(KEY, newClaim);
+ 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();
+
+ 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");
+ 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());
+ }
+
+ @TestTemplate
+ void testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal() {
+ String otherBinding = "DELETE v1/cat1/namespaces/ns1/tables/t1";
+ long claim = store.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+
+ Assertions.assertTrue(peer.reserve(KEY, otherBinding, FAR_FUTURE_MS).isEmpty());
+ Assertions.assertTrue(peer.load(KEY).isEmpty());
+
+ store.finalizeRecord(KEY, claim, 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.assertEquals(original, peer.load(KEY).orElseThrow());
+ }
+
+ @TestTemplate
+ void testPurgeExpiredRemovesOnlyExpiredRecords() {
+ long now = this.now.get();
+ store.reserve(KEY, BINDING, now - 1);
+ store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS);
+
+ Assertions.assertEquals(1, store.purgeExpired(now));
+
+ Assertions.assertTrue(store.reserve(KEY, BINDING, FAR_FUTURE_MS).isPresent());
+ Assertions.assertTrue(
+ store.reserve(OTHER_KEY, BINDING, FAR_FUTURE_MS).isEmpty(),
+ "an unexpired record must survive the purge");
+ }
+
+ @TestTemplate
+ void 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, "{}");
+ store.purgeExpiredRecords();
+ Assertions.assertEquals(1, rowCount());
+ Assertions.assertTrue(store.load(OTHER_KEY).isPresent());
+ }
+
+ @TestTemplate
+ void testPurgeExpiredDeletesMoreThanOneBatch() {
+ long now = this.now.get();
+ int records = JdbcIdempotencyStore.PURGE_BATCH_SIZE + 5;
+ for (int i = 0; i < records; i++) {
+ store.reserve(newKey(), BINDING, now - 1);
+ }
+ 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());
+ }
+
+ @TestTemplate
+ void 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(peer.load(KEY).isEmpty());
+ String response = "{\"metadata\":\"" + "x".repeat(100_000) + "\"}";
+ store.finalizeRecord(KEY, claim, 200, response);
+ IdempotencyRecord original = peer.load(KEY).orElseThrow();
+ Assertions.assertEquals(claim, original.claim());
+ store.close();
+ try (IdempotencyStore restarted =
+ IdempotencyStoreFactory.create(
+ new IcebergConfig(ImmutableMap.of("idempotency-store-type", "jdbc")))) {
+ Assertions.assertEquals(original, restarted.load(KEY).orElseThrow());
+ Assertions.assertEquals(response, restarted.load(KEY).orElseThrow().responseSummary());
+ }
+ // Closing the store must not close the entity store's connection pool.
+ Assertions.assertEquals(original, peer.load(KEY).orElseThrow());
+ }
+
+ @TestTemplate
+ void testDeletedReservationCannotReuseItsFencingToken() {
+ long oldClaim = store.reserve(KEY, BINDING, now.get()).orElseThrow();
+ Assertions.assertEquals(1, peer.purgeExpired(now.get()));
+ long newClaim = peer.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+
+ 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");
+ Assertions.assertEquals("current", store.load(KEY).orElseThrow().responseSummary());
+ }
+
+ @TestTemplate
+ void testExpiredReservationIsReclaimedAndOldOwnerIsFenced() {
+ long oldClaim = store.reserve(KEY, BINDING, now.get() + 1).orElseThrow();
+ 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");
+ IdempotencyRecord record = store.load(KEY).orElseThrow();
+ Assertions.assertEquals(newClaim, record.claim());
+ Assertions.assertEquals("PUT /replacement", record.operationBinding());
+ Assertions.assertEquals("new", record.responseSummary());
+ }
+
+ @TestTemplate
+ void testReserveReclaimsKeyThatExpiresBeforeSecondAttempt() {
+ long oldClaim = store.reserve(KEY, BINDING, now.get() + 1).orElseThrow();
+ 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");
+ IdempotencyRecord record = store.load(KEY).orElseThrow();
+ Assertions.assertEquals(newClaim, record.claim());
+ Assertions.assertEquals("PUT /replacement", record.operationBinding());
+ Assertions.assertEquals("current", record.responseSummary());
+ }
+
+ @TestTemplate
+ void testExpiredResponseIsNotLoadedAndCanBeReplacedWithoutPurge() {
+ long oldClaim = store.reserve(KEY, BINDING, now.get() + 1).orElseThrow();
+ store.finalizeRecord(KEY, oldClaim, 200, "old");
+ now.incrementAndGet();
+ Assertions.assertTrue(peer.load(KEY).isEmpty());
+ long newClaim = peer.reserve(KEY, BINDING, FAR_FUTURE_MS).orElseThrow();
+ Assertions.assertTrue(peer.load(KEY).isEmpty());
+ peer.finalizeRecord(KEY, newClaim, 204, null);
+ Assertions.assertNull(store.load(KEY).orElseThrow().responseSummary());
+ }
+
+ @TestTemplate
+ void testFinalizeDoesNotResurrectExpiredReservation() throws Exception {
+ long claim = store.reserve(KEY, BINDING, now.get()).orElseThrow();
+ store.finalizeRecord(KEY, claim, 200, "expired");
+ // Inspect persisted state so a read-time expiry filter cannot hide an incorrect finalization.
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ var statement = session.getConnection().createStatement();
+ var result = statement.executeQuery("SELECT http_status FROM iceberg_idempotency_meta")) {
+ Assertions.assertTrue(result.next());
+ Assertions.assertNull(result.getObject(1));
+ }
+ }
+
+ @TestTemplate
+ void testPurgeIncludesExactCutoff() {
+ 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());
+ }
+
+ @TestTemplate
+ void 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.assertEquals(KEY, store.load(upper).orElseThrow().idempotencyKey());
+ }
+
+ @TestTemplate
+ void testInvalidInputDoesNotReserveAKey() throws Exception {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> store.reserve("invalid", BINDING, FAR_FUTURE_MS));
+ 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.finalizeRecord("invalid", 1, 200, null));
+ Assertions.assertEquals(0, rowCount());
+ }
+
+ @TestTemplate
+ void testReservationCommitsIndependentlyOfCallerTransaction() {
+ SessionUtils.beginTransaction();
+ try {
+ store.reserve(KEY, BINDING, FAR_FUTURE_MS);
+ } finally {
+ SessionUtils.rollbackTransaction();
+ }
+ Assertions.assertTrue(peer.reserve(KEY, BINDING, FAR_FUTURE_MS).isEmpty());
+ }
+
+ @TestTemplate
+ void testOnlyOneCallerCanReclaimExpiredKey() throws InterruptedException {
+ store.reserve(KEY, BINDING, now.get());
+ testConcurrentReserveOnOneKeyHasExactlyOneWinner();
+ }
+
+ @TestTemplate
+ void testStoresMethodAndCompleteRequestUri() throws Exception {
+ // 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.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")) {
+ 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"));
+ }
+ }
+
+ @TestTemplate
+ void testCleanupContinuesAfterTransientFailure() throws Exception {
+ store.reserve(KEY, BINDING, now.get());
+ AtomicInteger attempts = new AtomicInteger();
+ CountDownLatch cleaned = new CountDownLatch(1);
+ try (JdbcIdempotencyStore scheduled =
+ new JdbcIdempotencyStore() {
+ @Override
+ public int purgeExpired(long beforeMs) {
+ if (attempts.incrementAndGet() == 1) {
+ throw new IllegalStateException("temporary database failure");
+ }
+ int deleted = super.purgeExpired(beforeMs);
+ cleaned.countDown();
+ return deleted;
+ }
+ }) {
+ scheduled.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT0.01S"));
+ Assertions.assertTrue(cleaned.await(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(attempts.get() >= 2);
+ Assertions.assertEquals(0, rowCount());
+ }
+ }
+
+ @TestTemplate
+ void testMissingSchemaFailsInitializationAndCanRetryAfterRepair() throws Exception {
+ try (JdbcIdempotencyStore retrying = new JdbcIdempotencyStore();
+ SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ var statement = session.getConnection().createStatement()) {
+ statement.execute("ALTER TABLE iceberg_idempotency_meta RENAME TO saved_idempotency_keys");
+ try {
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ IdempotencyStoreFactory.create(
+ new IcebergConfig(ImmutableMap.of("idempotency-store-type", "jdbc"))));
+ Assertions.assertThrows(
+ RuntimeException.class, () -> store.reserve(KEY, BINDING, FAR_FUTURE_MS));
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () -> retrying.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H")));
+ } finally {
+ 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.assertEquals("recovered", peer.load(KEY).orElseThrow().responseSummary());
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> retrying.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H")));
+ }
+ }
+
+ @TestTemplate
+ void testUpgradeCreatesUsableIdempotencyTable() throws Exception {
+ String script =
+ Files.readString(
+ Path.of(
+ System.getenv("GRAVITINO_ROOT_DIR"),
+ "scripts",
+ backendType,
+ "upgrade-1.3.0-to-2.0.0-" + backendType + ".sql"));
+ // Exercise this feature's additive migration against each database, without rerunning unrelated
+ // 1.3-to-2.0 migrations on the fixture's already-current metadata tables.
+ int tablePosition = script.indexOf("iceberg_idempotency_meta");
+ int start = script.lastIndexOf("CREATE TABLE", tablePosition);
+ Assertions.assertTrue(start >= 0);
+ try (SqlSession session =
+ 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);
+ runner.runScript(new StringReader(script.substring(start)));
+ session.commit();
+ }
+ 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());
+ }
+ }
+
+ @TestTemplate
+ void testReserveRetriesWhenPurgeRemovesExpiredRow() throws Exception {
+ reserveDuringPurge(false);
+ }
+
+ @TestTemplate
+ void testReserveRetryPreservesPeerReservation() throws Exception {
+ reserveDuringPurge(true);
+ }
+
+ @TestTemplate
+ void testBlockedPurgePreservesReclaimedRow() throws Exception {
+ store.reserve(KEY, BINDING, now.get());
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (SqlSession holder =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession()) {
+ String sessionIdQuery;
+ switch (backendType) {
+ case "h2":
+ sessionIdQuery = "SELECT SESSION_ID()";
+ break;
+ case "mysql":
+ sessionIdQuery = "SELECT CONNECTION_ID()";
+ break;
+ case "postgresql":
+ sessionIdQuery = "SELECT pg_backend_pid()";
+ break;
+ default:
+ throw new IllegalStateException("Unsupported backend: " + backendType);
+ }
+ long holderId;
+ try (var statement = holder.getConnection().createStatement();
+ var result = statement.executeQuery(sessionIdQuery)) {
+ Assertions.assertTrue(result.next());
+ 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)));
+ Future<Integer> purge =
+ executor.submit(
+ () -> {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession()) {
+ // Keep the engine timeout above the deadline for observing its row-lock wait.
+ try (var statement = session.getConnection().createStatement()) {
+ switch (backendType) {
+ case "h2":
+ statement.execute("SET LOCK_TIMEOUT 30000");
+ break;
+ case "mysql":
+ statement.execute("SET SESSION innodb_lock_wait_timeout = 30");
+ break;
+ case "postgresql":
+ statement.execute("SET LOCAL lock_timeout = '30s'");
+ break;
+ default:
+ throw new IllegalStateException("Unsupported backend: " + backendType);
+ }
+ }
+ int deleted =
+ session
+ .getMapper(IcebergIdempotencyKeyMapper.class)
+ .deleteExpiredBatch(now.get(), JdbcIdempotencyStore.PURGE_BATCH_SIZE);
+ session.commit();
+ return deleted;
+ }
+ });
+ awaitBlockedPurge(purge, holderId);
+ holder.commit();
+ Assertions.assertEquals(0, purge.get(30, TimeUnit.SECONDS));
+ peer.finalizeRecord(KEY, generation, 201, "renewed");
+ Assertions.assertEquals("renewed", store.load(KEY).orElseThrow().responseSummary());
+ } finally {
+ executor.shutdownNow();
+ Assertions.assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+ }
+ }
+
+ private void reserveDuringPurge(boolean peerWins) throws Exception {
+ store.reserve(KEY, BINDING, now.get());
+ CountDownLatch duplicateInsert = new CountDownLatch(1);
+ CountDownLatch purged = new CountDownLatch(1);
+ SqlSessionFactoryHelper.getInstance()
+ .getSqlSessionFactory()
+ .getConfiguration()
+ .addInterceptor(new PauseReplacement(duplicateInsert, purged));
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ Future<OptionalLong> 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;
+ 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");
+ 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 {
+ purged.countDown();
+ executor.shutdownNow();
+ Assertions.assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+ }
+ }
+
+ private void awaitBlockedPurge(Future<Integer> purge, long holderId) throws Exception {
+ String query;
+ switch (backendType) {
+ case "h2":
+ query = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SESSIONS WHERE BLOCKER_ID = " + holderId;
+ break;
+ case "mysql":
+ // InnoDB can attribute a wait on an uncommitted index entry to the waiting thread itself.
+ query =
+ "SELECT COUNT(*) FROM performance_schema.data_lock_waits w"
+ + " JOIN performance_schema.threads r ON r.THREAD_ID = w.REQUESTING_THREAD_ID"
+ + " JOIN performance_schema.threads b ON b.THREAD_ID = w.BLOCKING_THREAD_ID"
+ + " WHERE b.PROCESSLIST_ID = "
+ + holderId
+ + " OR b.THREAD_ID = r.THREAD_ID";
+ break;
+ case "postgresql":
+ query =
+ "SELECT COUNT(*) FROM pg_stat_activity a WHERE "
+ + holderId
+ + " = ANY(pg_blocking_pids(a.pid))";
+ break;
+ default:
+ throw new IllegalStateException("Unsupported backend: " + backendType);
+ }
+ try (SqlSession observer =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {
+ await()
+ .pollInSameThread()
+ .atMost(10, TimeUnit.SECONDS)
+ .pollInterval(10, TimeUnit.MILLISECONDS)
+ .until(
+ () -> {
+ Assertions.assertFalse(
+ purge.isDone(), "purge must block on the uncommitted replacement");
+ try (var statement = observer.getConnection().createStatement();
+ var result = statement.executeQuery(query)) {
+ return result.next() && result.getLong(1) > 0;
+ }
+ });
+ }
+ }
+
+ // Pause before locking the counter for replacement, after the duplicate INSERT rolls back.
+ @Intercepts(
+ @Signature(
+ type = Executor.class,
+ method = "update",
+ args = {MappedStatement.class, Object.class}))
+ private static class PauseReplacement implements Interceptor {
+ private final AtomicInteger attempts = new AtomicInteger();
+ private final CountDownLatch duplicateInsert;
+ private final CountDownLatch purged;
+
+ private PauseReplacement(CountDownLatch duplicateInsert, CountDownLatch purged) {
+ this.duplicateInsert = duplicateInsert;
+ this.purged = purged;
+ }
+
+ @Override
+ public Object intercept(Invocation invocation) throws Throwable {
+ if (((MappedStatement) invocation.getArgs()[0])
+ .getId()
+ .equals(IcebergIdempotencyKeyMapper.class.getName() + ".advanceGeneration")
+ && attempts.incrementAndGet() == 2) {
+ duplicateInsert.countDown();
+ Assertions.assertTrue(purged.await(30, TimeUnit.SECONDS));
+ }
+ return invocation.proceed();
+ }
+ }
+
+ private int rowCount() throws Exception {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ var statement = session.getConnection().createStatement();
+ var result = statement.executeQuery("SELECT COUNT(*) FROM iceberg_idempotency_meta")) {
+ result.next();
+ return result.getInt(1);
+ }
+ }
+
+ private static String newKey() {
+ UUID uuid = UUID.randomUUID();
+ return new UUID(
+ (uuid.getMostSignificantBits() & ~0xf000L) | 0x7000L, uuid.getLeastSignificantBits())
+ .toString();
+ }
+}
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStoreInitialization.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStoreInitialization.java
new file mode 100644
index 0000000000..ec395c70cc
--- /dev/null
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStoreInitialization.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.iceberg.service.idempotency;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Collections;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+class TestJdbcIdempotencyStoreInitialization {
+ @Test
+ void testStandaloneFailsWithActionableError() {
+ SqlSessionFactoryHelper helper = Mockito.mock(SqlSessionFactoryHelper.class);
+ Mockito.when(helper.getSqlSessionFactory())
+ .thenThrow(new IllegalStateException("not initialized"));
+ try (MockedStatic<SqlSessionFactoryHelper> mocked =
+ Mockito.mockStatic(SqlSessionFactoryHelper.class)) {
+ mocked.when(SqlSessionFactoryHelper::getInstance).thenReturn(helper);
+ RuntimeException failure =
+ Assertions.assertThrows(
+ RuntimeException.class,
+ () ->
+ IdempotencyStoreFactory.create(
+ new IcebergConfig(ImmutableMap.of("idempotency-store-type", "jdbc"))));
+ Assertions.assertTrue(failure.getCause().getMessage().contains("auxiliary mode"));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"PT0S", "-PT1S", "PT0.000001S", "invalid"})
+ void testInvalidCleanupIntervalFailsBeforeAllocatingResources(String interval) {
+ try (JdbcIdempotencyStore store = new JdbcIdempotencyStore()) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> store.initialize(ImmutableMap.of("idempotency-cleanup-interval", interval)));
+ }
+ }
+
+ @Test
+ void testDefaultCleanupInterval() {
+ Assertions.assertEquals(
+ "PT5M",
+ new IcebergConfig(Collections.emptyMap())
+ .get(IcebergConfig.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL));
+ }
+}
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.java
index 03890a6e35..3dc391f784 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,6 +22,7 @@ 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;
@@ -29,8 +30,8 @@ import javax.ws.rs.core.Application;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
-import org.apache.gravitino.iceberg.common.idempotency.InMemoryIdempotencyStore;
import org.apache.gravitino.iceberg.service.idempotency.IcebergIdempotencyManager;
+import org.apache.gravitino.iceberg.service.idempotency.InMemoryIdempotencyStore;
import org.apache.gravitino.server.ServerConfig;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.iceberg.catalog.Namespace;
@@ -38,10 +39,11 @@ import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
-/** HTTP coverage of a committed mutation whose response cannot be retained. */
+/** HTTP coverage of idempotency storage failures before and after catalog mutations. */
public class TestIcebergIdempotencyFinalizeFailure extends IcebergTestBase {
@Override
protected Application configure() {
@@ -54,7 +56,7 @@ public class TestIcebergIdempotencyFinalizeFailure extends IcebergTestBase {
IcebergConstants.ICEBERG_IDEMPOTENCY_ENABLED,
"true",
IcebergConstants.ICEBERG_IDEMPOTENCY_STORE_TYPE,
- NoOpFinalizeStore.class.getName()));
+ FaultInjectingStore.class.getName()));
config.register(
new AbstractBinder() {
@Override
@@ -68,12 +70,13 @@ public class TestIcebergIdempotencyFinalizeFailure extends IcebergTestBase {
return config;
}
- @Test
- void testRetryExecutesAgainAfterSuccessfulMutationCannotFinalize() {
+ @ParameterizedTest
+ @ValueSource(ints = {0, 1, 2})
+ void testRetryDoesNotReexecuteAfterFinalizationFailure(int failureMode) {
Namespace namespace = Namespace.of("finalize_failure");
CreateNamespaceRequest request =
CreateNamespaceRequest.builder().withNamespace(namespace).build();
- String key = "017f22e2-79b0-7cc3-98c4-dc0c0c07398f";
+ String key = "017f22e2-79b0-7cc3-98c4-dc0c0c07398" + failureMode;
try (Response first =
getNamespaceClientBuilder()
.header(IcebergIdempotencyManager.IDEMPOTENCY_KEY, key)
@@ -88,21 +91,71 @@ public class TestIcebergIdempotencyFinalizeFailure extends IcebergTestBase {
getNamespaceClientBuilder()
.header(IcebergIdempotencyManager.IDEMPOTENCY_KEY, key)
.post(Entity.json(request))) {
- // Release permits execution again: this is the catalog's AlreadyExists response,
- // not an in-flight idempotency conflict or a replayed 200.
- Assertions.assertEquals(409, retry.getStatus());
- Assertions.assertNull(retry.getHeaderString(HttpHeaders.RETRY_AFTER));
- Assertions.assertEquals(
- "AlreadyExistsException",
- retry.readEntity(JsonNode.class).get("error").get("type").asText());
+ if (failureMode == 2) {
+ Assertions.assertEquals(200, retry.getStatus(), "a committed response remains replayable");
+ } else {
+ Assertions.assertEquals(409, retry.getStatus());
+ Assertions.assertEquals("1", retry.getHeaderString(HttpHeaders.RETRY_AFTER));
+ Assertions.assertEquals(
+ "IdempotencyConflictException",
+ retry.readEntity(JsonNode.class).get("error").get("type").asText());
+ }
}
}
- /** Fault-injection store that accepts reservations but never retains final responses. */
- public static class NoOpFinalizeStore extends InMemoryIdempotencyStore {
+ @ParameterizedTest
+ @ValueSource(ints = {3, 4})
+ void testReservationFailureDoesNotExecuteMutation(int failureMode) {
+ Namespace namespace = Namespace.of("reserve_failure");
+ CreateNamespaceRequest request =
+ CreateNamespaceRequest.builder().withNamespace(namespace).build();
+ String key = "017f22e2-79b0-7cc3-98c4-dc0c0c07398" + failureMode;
+ try (Response first =
+ getNamespaceClientBuilder()
+ .header(IcebergIdempotencyManager.IDEMPOTENCY_KEY, key)
+ .post(Entity.json(request))) {
+ Assertions.assertEquals(503, first.getStatus());
+ Assertions.assertEquals("1", first.getHeaderString(HttpHeaders.RETRY_AFTER));
+ JsonNode error = first.readEntity(JsonNode.class).get("error");
+ Assertions.assertEquals("ServiceUnavailableException", error.get("type").asText());
+ Assertions.assertTrue(error.get("message").asText().contains("did not execute"));
+ }
+ try (Response retry =
+ getNamespaceClientBuilder()
+ .header(IcebergIdempotencyManager.IDEMPOTENCY_KEY, key)
+ .post(Entity.json(request))) {
+ Assertions.assertEquals(failureMode == 3 ? 503 : 409, retry.getStatus());
+ Assertions.assertEquals("1", retry.getHeaderString(HttpHeaders.RETRY_AFTER));
+ }
+ try (Response loaded = getNamespaceClientBuilder(Optional.of(namespace)).get()) {
+ Assertions.assertEquals(404, loaded.getStatus(), "neither attempt may mutate the catalog");
+ }
+ }
+
+ /** 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) {
+ if (key.endsWith("3")) {
+ throw new IllegalStateException("reservation unavailable");
+ }
+ OptionalLong result = super.reserve(key, binding, expiresAtMs);
+ if (key.endsWith("4") && result.isPresent()) {
+ throw new IllegalStateException("reservation committed but acknowledgement lost");
+ }
+ return result;
+ }
+
@Override
public void finalizeRecord(String key, long claim, int status, @Nullable String summary) {
- // Deliberately leave the record reserved to exercise the manager's release path.
+ if (key.endsWith("2")) {
+ super.finalizeRecord(key, claim, status, summary);
+ throw new IllegalStateException("response committed but acknowledgement lost");
+ }
+ if (key.endsWith("1")) {
+ throw new IllegalStateException("response write failed");
+ }
+ // Leave the reservation intact when the response cannot be retained.
}
}
}
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.java
index 4b7c005932..e0e2449f1d 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
@@ -204,11 +204,22 @@ public class TestIcebergIdempotencyKey extends IcebergNamespaceTestBase {
void testLongQueryBindingsDoNotAlias() {
Assertions.assertEquals(200, doCreateNamespace(NAMESPACE).getStatus());
String prefix = "x".repeat(600);
- try (Response first = createTableWithQuery("long_query", ImmutableMap.of("tag", prefix + "a"));
+ try (Response first =
+ createTableWithQuery(
+ "long_query", ImmutableMap.of("tag", prefix + "a", "mode", "sync"));
+ Response reordered =
+ createTableWithQuery(
+ "long_query", ImmutableMap.of("mode", "sync", "tag", prefix + "a"));
Response different =
- createTableWithQuery("long_query", ImmutableMap.of("tag", prefix + "b"))) {
+ createTableWithQuery(
+ "long_query", ImmutableMap.of("tag", prefix + "b", "mode", "sync"))) {
Assertions.assertEquals(200, first.getStatus());
+ Assertions.assertEquals(200, reordered.getStatus());
+ Assertions.assertEquals(first.readEntity(String.class), reordered.readEntity(String.class));
Assertions.assertEquals(409, different.getStatus());
+ Assertions.assertEquals(
+ "IdempotencyConflictException",
+ different.readEntity(JsonNode.class).get("error").get("type").asText());
}
}
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index cdc64526bf..f1927990c5 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -828,3 +828,23 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB;
+
+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',
+ `created_at` BIGINT NOT NULL COMMENT 'record created at (unix epoch millis)',
+ `expires_at` BIGINT NOT NULL COMMENT 'record expires at (unix epoch millis)',
+ PRIMARY KEY (`idempotency_key`)
+) 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;
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.sql
index bedb91a308..1e033ce5f5 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
@@ -425,3 +425,23 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB;
+
+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',
+ `created_at` BIGINT NOT NULL COMMENT 'record created at (unix epoch millis)',
+ `expires_at` BIGINT NOT NULL COMMENT 'record expires at (unix epoch millis)',
+ PRIMARY KEY (`idempotency_key`)
+) 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;
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index c95284821d..6134638977 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -816,3 +816,23 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain parent relation';
+
+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',
+ `created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record created at (unix epoch millis)',
+ `expires_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record expires at (unix epoch millis)',
+ 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;
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.sql
index 39214079cc..9131758f81 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
@@ -923,3 +923,23 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain parent relation';
+
+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',
+ `created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record created at (unix epoch millis)',
+ `expires_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record expires at (unix epoch millis)',
+ 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;
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index 520a180fec..3591d4a9d7 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -1415,3 +1415,32 @@ COMMENT ON COLUMN domain_rel.audit_info IS 'domain relation audit info';
COMMENT ON COLUMN domain_rel.current_version IS 'domain relation current version';
COMMENT ON COLUMN domain_rel.last_version IS 'domain relation last version';
COMMENT ON COLUMN domain_rel.deleted_at IS 'domain relation deleted at';
+
+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,
+ created_at BIGINT NOT NULL,
+ expires_at BIGINT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_iim_expires ON iceberg_idempotency_meta (expires_at);
+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
+);
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.sql
index c4c1fb651d..f8a8687d41 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
@@ -554,3 +554,32 @@ COMMENT ON COLUMN domain_rel.audit_info IS 'domain relation audit info';
COMMENT ON COLUMN domain_rel.current_version IS 'domain relation current version';
COMMENT ON COLUMN domain_rel.last_version IS 'domain relation last version';
COMMENT ON COLUMN domain_rel.deleted_at IS 'domain relation deleted at';
+
+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,
+ created_at BIGINT NOT NULL,
+ expires_at BIGINT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_iim_expires ON iceberg_idempotency_meta (expires_at);
+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
+);