lasdf1234 commented on code in PR #12474: URL: https://github.com/apache/gravitino/pull/12474#discussion_r4560295001
########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java: ########## @@ -0,0 +1,341 @@ +/* + * 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.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; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Optional; +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; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints. + * + * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the + * mutation, and stores its response. While that record remains available, retries carrying the same + * key get the original answer back instead of a second mutation. Idempotency is off by default; + * when it is off, or when a request carries no key, the mutation runs directly and nothing is + * stored. + * + * <p>A replayed response carries the original status and body. Response headers are not stored, so + * a replayed create or update does not carry the {@code ETag} the first response did; clients that + * rely on it simply load the table again. + * + * <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. + * + * <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. + */ +public class IcebergIdempotencyManager { + + private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class); + + /** The idempotency key header defined by the Iceberg REST spec. */ + public static final String IDEMPOTENCY_KEY = "Idempotency-Key"; + + /** Seconds a client should wait before retrying a request whose key is still in flight. */ + private static final int RETRY_AFTER_SECONDS = 1; + + /** + * Statuses that are terminal for the request but not for the key. Authentication and + * authorization outcomes depend on the caller's credentials rather than on catalog state, so + * replaying them would keep failing a retry that has since obtained valid credentials. + */ + private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419); + + private final boolean enabled; + private final Duration keyLifetime; + private final ObjectMapper icebergObjectMapper; + private final Optional<IdempotencyStore> store; + + /** + * Creates a manager, loading the configured store when idempotency is enabled. + * + * @param icebergConfig the Iceberg REST server configuration + */ + public IcebergIdempotencyManager(IcebergConfig icebergConfig) { + this( + icebergConfig, + icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED) + ? Optional.of(IdempotencyStoreFactory.create(icebergConfig)) + : Optional.empty()); + } + + @VisibleForTesting + IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) { + this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED); + this.keyLifetime = + Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME)); + this.icebergObjectMapper = IcebergObjectMapper.getInstance(); + this.store = store; + } + + /** + * Returns the key reuse window to advertise to clients. + * + * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is + * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in + * the config response as "this server does not support idempotency". + */ + public Optional<String> advertisedKeyLifetime() { + return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty(); + } + + /** + * Runs a mutation under the given idempotency key. + * + * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the + * first request claims it and stores the response; retries carrying the same key replay that + * response. A retry that arrives while the first request is still running, or that reuses a key + * already spent on a different operation, gets {@code 409 Conflict}. + * + * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null} + * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)} + * @param action the mutation, which is expected to return its own error responses rather than + * throw + * @return the response to send to the client + */ + public Response replayOrExecute( + @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) { + if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) { + return action.get(); + } + + String key; + try { + key = IdempotencyKeys.canonicalize(idempotencyKey); + } catch (IllegalArgumentException e) { + return IcebergExceptionMapper.toRESTResponse(e); + } + + 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); + } + + boolean finalized = false; + try { + Response response = action.get(); + if (isFinalizable(response.getStatus())) { + finalized = 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. + // A replacement owner's reservation must remain untouched. + idempotencyStore.release(key, claim); + } + } + } + + /** + * Builds the request identity stored alongside a key. Retries of the same logical operation + * produce the same binding, while a key reused for a different request does not. + * + * <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. + * + * @param httpMethod the HTTP method of the endpoint + * @param uriInfo the request URI, may be {@code null} outside a request context + * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables} + */ + public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) { + if (uriInfo == null) { + return httpMethod; + } + StringBuilder binding = + new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false)); + MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); + 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("&", "?", ""); + for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) { + for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) { + query.add( + URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8) + + "=" + + URLEncoder.encode(value, StandardCharsets.UTF_8)); + } + } + binding.append(query); + } + return binding.toString(); + } + + /** Closes the underlying store. */ + public void close() { + store.ifPresent( + idempotencyStore -> { + try { + idempotencyStore.close(); + } catch (IOException e) { + LOG.warn("Close Iceberg idempotency store failed.", e); + } + }); + } + + private Response replay( + IdempotencyStore idempotencyStore, String idempotencyKey, String binding) { + Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey); + if (!record.isPresent()) { + // Reserved but not finalized: the first request is still running, here or on another node. + return conflict( + "Idempotency-Key: " + + idempotencyKey + + " is being processed by another request, retry later", + true); + } + + IdempotencyRecord found = record.get(); + if (!found.operationBinding().equals(binding)) { + // Replaying here would hand the client the response of an unrelated operation. + return conflict( + "Idempotency-Key: " + + idempotencyKey + + " was already used for `" + + found.operationBinding() + + "`, the Iceberg REST spec requires a new key for a different operation", + false); + } + + LOG.info( + "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.", + idempotencyKey, + binding, + found.httpStatus()); + Response.ResponseBuilder builder = Response.status(found.httpStatus()); + if (found.responseSummary() != null) { + builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON); + } + return builder.build(); + } + + private boolean tryFinalize( + IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) { + String responseSummary; + try { + responseSummary = serializeEntity(response.getEntity()); + } catch (JsonProcessingException e) { + LOG.warn( + "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.", + 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; Review Comment: **Medium (Bugbot) — successful mutation + failed finalize still releases the key.** `tryFinalize` correctly verifies retention after `finalizeRecord`, and returning the real 2xx (instead of a synthetic 5xx) is the right call. But when serialize fails or the post-check sees no record under this claim, `return false` → caller `release` → a client retry can run the mutation again. Javadoc/docs already describe this phase-1 tradeoff. Remaining gap: no IT covering “action returns 2xx, finalize fails, same key retries and executes again”. Worth adding so the release-after-commit path does not regress when a durable store lands. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java: ########## @@ -180,8 +186,21 @@ public Response createTable( @AuthorizationMetadata(type = Entity.EntityType.SCHEMA) @Encoded() @PathParam("namespace") String namespace, CreateTableRequest createTableRequest, - @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation) { + @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation, + @HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey, + @Context UriInfo uriInfo) { IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest"); Review Comment: **Low (Bugbot) — `validateRequest` runs before `replayOrExecute`.** A retry that reuses the same `Idempotency-Key` but sends a body that fails validation gets **400** here and never reaches replay of a previously stored success. Spec-compliant clients retry the same payload, so this is an edge case; consider a one-line note in the phase-1 limitations docs, or moving validation inside the supplier if you want “same key always hits the manager first”. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java: ########## @@ -0,0 +1,341 @@ +/* + * 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.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; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Optional; +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; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints. + * + * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the + * mutation, and stores its response. While that record remains available, retries carrying the same + * key get the original answer back instead of a second mutation. Idempotency is off by default; + * when it is off, or when a request carries no key, the mutation runs directly and nothing is + * stored. + * + * <p>A replayed response carries the original status and body. Response headers are not stored, so + * a replayed create or update does not carry the {@code ETag} the first response did; clients that + * rely on it simply load the table again. + * + * <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. + * + * <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. + */ +public class IcebergIdempotencyManager { + + private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class); + + /** The idempotency key header defined by the Iceberg REST spec. */ + public static final String IDEMPOTENCY_KEY = "Idempotency-Key"; + + /** Seconds a client should wait before retrying a request whose key is still in flight. */ + private static final int RETRY_AFTER_SECONDS = 1; + + /** + * Statuses that are terminal for the request but not for the key. Authentication and + * authorization outcomes depend on the caller's credentials rather than on catalog state, so + * replaying them would keep failing a retry that has since obtained valid credentials. + */ + private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419); + + private final boolean enabled; + private final Duration keyLifetime; + private final ObjectMapper icebergObjectMapper; + private final Optional<IdempotencyStore> store; + + /** + * Creates a manager, loading the configured store when idempotency is enabled. + * + * @param icebergConfig the Iceberg REST server configuration + */ + public IcebergIdempotencyManager(IcebergConfig icebergConfig) { + this( + icebergConfig, + icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED) + ? Optional.of(IdempotencyStoreFactory.create(icebergConfig)) + : Optional.empty()); + } + + @VisibleForTesting + IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) { + this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED); + this.keyLifetime = + Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME)); + this.icebergObjectMapper = IcebergObjectMapper.getInstance(); + this.store = store; + } + + /** + * Returns the key reuse window to advertise to clients. + * + * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is + * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in + * the config response as "this server does not support idempotency". + */ + public Optional<String> advertisedKeyLifetime() { + return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty(); + } + + /** + * Runs a mutation under the given idempotency key. + * + * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the + * first request claims it and stores the response; retries carrying the same key replay that + * response. A retry that arrives while the first request is still running, or that reuses a key + * already spent on a different operation, gets {@code 409 Conflict}. + * + * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null} + * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)} + * @param action the mutation, which is expected to return its own error responses rather than + * throw + * @return the response to send to the client + */ + public Response replayOrExecute( + @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) { + if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) { + return action.get(); + } + + String key; + try { + key = IdempotencyKeys.canonicalize(idempotencyKey); + } catch (IllegalArgumentException e) { + return IcebergExceptionMapper.toRESTResponse(e); + } + + 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); + } + + boolean finalized = false; + try { + Response response = action.get(); + if (isFinalizable(response.getStatus())) { + finalized = 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. + // A replacement owner's reservation must remain untouched. + idempotencyStore.release(key, claim); + } + } + } + + /** + * Builds the request identity stored alongside a key. Retries of the same logical operation + * produce the same binding, while a key reused for a different request does not. + * + * <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. + * + * @param httpMethod the HTTP method of the endpoint + * @param uriInfo the request URI, may be {@code null} outside a request context + * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables} + */ + public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) { + if (uriInfo == null) { + return httpMethod; + } + StringBuilder binding = + new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false)); + MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); + 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("&", "?", ""); + for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) { + for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) { + query.add( + URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8) + + "=" + + URLEncoder.encode(value, StandardCharsets.UTF_8)); + } + } + binding.append(query); + } + return binding.toString(); + } + + /** Closes the underlying store. */ + public void close() { + store.ifPresent( + idempotencyStore -> { + try { + idempotencyStore.close(); + } catch (IOException e) { + LOG.warn("Close Iceberg idempotency store failed.", e); + } + }); + } + + private Response replay( + IdempotencyStore idempotencyStore, String idempotencyKey, String binding) { + Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey); + if (!record.isPresent()) { + // Reserved but not finalized: the first request is still running, here or on another node. + return conflict( + "Idempotency-Key: " + + idempotencyKey + + " is being processed by another request, retry later", + true); + } + + IdempotencyRecord found = record.get(); + if (!found.operationBinding().equals(binding)) { + // Replaying here would hand the client the response of an unrelated operation. + return conflict( + "Idempotency-Key: " + + idempotencyKey + + " was already used for `" + + found.operationBinding() Review Comment: **Low (Bugbot) — conflict message embeds the stored SHA-256 binding, not a human-readable operation.** `found.operationBinding()` is the digest passed to `reserve`, so the client sees something like `` was already used for `a1b2…` ``. Prefer omitting the binding from the client-facing message (keep the hash for equality only), or store the pre-hash binding for diagnostics while still comparing hashes. ########## docs/iceberg-rest-service.md: ########## @@ -178,6 +178,32 @@ The settings below tune the background workers and are optional. | `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No | | `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No | +#### Idempotency Key + +The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When enabled and the header is present, the server reserves the key, executes the mutation, and stores the response for replay while the record remains available. + +Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent. + +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 | + +Phase-1 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. +- 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. + +:::caution +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. Review Comment: **Low (Bugbot) — consider a sharper operator warning when enabling idempotency with the default store.** The caution already states node-local / non-durable behavior. Operators who flip `idempotency-enabled=true` and leave `idempotency-store-type=in-memory` on a multi-replica deploy may still assume cluster-wide dedup. A one-liner tying “enabled + in-memory + >1 replica ⇒ retries can double-execute” would make the footgun harder to miss (optional: log a WARN at manager startup in that config). ########## docs/iceberg-rest-service.md: ########## @@ -178,6 +178,32 @@ The settings below tune the background workers and are optional. | `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No | | `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No | +#### Idempotency Key + +The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When enabled and the header is present, the server reserves the key, executes the mutation, and stores the response for replay while the record remains available. + +Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent. + +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 | + +Phase-1 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. +- 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. Review Comment: **Info (Bugbot) — ETag omission on replay looks intentional and tested.** Class javadoc + this bullet + `testReplayPreservesWireJsonAndOmitsEtag` cover it. No change needed unless you want the HTTP test matrix to also assert create/update replay paths explicitly. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
