You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@polaris.apache.org by "huaxingao (via GitHub)" <gi...@apache.org> on 2026/02/18 01:46:37 UTC
[PR] Add Iceberg REST Idempotency-Key support [polaris]
huaxingao opened a new pull request, #3803:
URL: https://github.com/apache/polaris/pull/3803
<!--
📝 Describe what changes you're proposing, especially breaking or user-facing changes.
đź“– See https://github.com/apache/polaris/blob/main/CONTRIBUTING.md for more.
-->
This PR introduces optional Idempotency-Key handling for Iceberg REST mutation endpoints to support safe client retries.
Adds an HTTP request/response filter that:
- validates UUIDv7 keys,
- reserves keys and enforces operation/resource binding (422 on conflict),
- waits for in-progress duplicates and replays finalized responses,
- never finalizes/replays 5xx.
Persists a bounded response body plus an allowlisted set of response headers and replays with correct Content-Type.
Adds optional heartbeats and background purge of expired keys.
Advertises idempotency-key-lifetime via GET /v1/config for Polaris-managed (INTERNAL) catalogs only.
Includes small config knobs for wait/lease TTL and TTL grace.
**Note:** reconciliation/takeover for stale in-progress keys is intentionally deferred to a follow-up PR.
## Checklist
- [ ] 🛡️ Don't disclose security issues! (contact security@apache.org)
- [ ] đź”— Clearly explained why the changes are needed, or linked related issues: Fixes #
- [ ] đź§Ş Added/updated tests with good coverage, or manually tested (and explained how)
- [ ] đź’ˇ Added comments for complex logic
- [ ] đź§ľ Updated `CHANGELOG.md` (if needed)
- [ ] 📚 Updated documentation in `site/content/in-dev/unreleased` (if needed)
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2876193296
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
Review Comment:
Fixed.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithName("ttl-seconds")
+ @WithDefault("PT5M")
+ Duration ttl();
+
+ /**
+ * Additional grace added to {@link #ttl()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ *
+ * <p>Examples: {@code PT0S}, {@code 10S}.
+ */
+ @WithName("ttl-grace-seconds")
+ @WithDefault("PT0S")
Review Comment:
Fixed the java doc
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-3988780168
> However, the response bodies can be easily large or even huge...
Thanks @snazy for your comment. I agree that we can’t safely store/replay full response bodies (OOM risk with InMemoryIdempotencyStore, heavy DB/write amplification, and it’s not compatible with async/streaming responses). In my proposal, the intent is to persist only what’s needed to reproduce an equivalent response for later duplicates:
```
status (HTTP code)
response_headers (small whitelisted set, e.g., Location, ETag, Content‑Type)
response_summary (minimal body; e.g., metadata‑location, identifiers, error subtype)
```
Since this PR is already large and I’m splitting it into smaller PRs, I’ll follow up to (1) enforce a hard size bound / “not replayable” marker for large or streaming bodies (especially for in-memory), and (2) ensure heartbeat/lease updates don’t load/serialize response bodies (only touch required columns / projections).
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2868471551
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,700 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttlSeconds()).plus(configuration.ttlGraceSeconds());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtlSeconds())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline =
+ clock.instant().plus(configuration.inProgressWaitSeconds());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException ignored) {
+ // Best-effort: the main request already completed. If this fails, replay may be
+ // unavailable until a later retry or reconciliation.
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatIntervalSeconds().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return httpStatus != 401 && httpStatus != 403 && httpStatus != 408 && httpStatus != 429;
+ }
+ return false;
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
+ replay.entity(existing.responseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ String path, PolarisPrincipal principal) {
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
+ }
+
+ private static String normalizeResourceId(ContainerRequestContext rc, boolean scopedMode) {
Review Comment:
removed
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,700 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttlSeconds()).plus(configuration.ttlGraceSeconds());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtlSeconds())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline =
+ clock.instant().plus(configuration.inProgressWaitSeconds());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException ignored) {
+ // Best-effort: the main request already completed. If this fails, replay may be
+ // unavailable until a later retry or reconciliation.
Review Comment:
Added logging
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2820298268
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/IdempotencyStore.java:
##########
@@ -154,6 +154,24 @@ ReserveResult reserve(
HeartbeatResult updateHeartbeat(
String realmId, String idempotencyKey, String executorId, Instant now);
+ /**
+ * Cancels (deletes) an in-progress idempotency reservation owned by {@code executorId}.
+ *
+ * <p>This is used for cases where an idempotency key was reserved but the request should not be
+ * tracked for replay (for example, 401/403/408/429 responses per the proposal). Implementations
+ * should only cancel the record if it is still in-progress (i.e., not finalized) and owned by the
+ * given executor.
+ *
+ * @param realmId logical tenant or realm identifier
+ * @param idempotencyKey application-provided idempotency key
+ * @param executorId identifier of the executor that owns the reservation
+ * @return {@code true} if a record was cancelled, {@code false} otherwise
+ */
+ default boolean cancelInProgressReservation(
+ String realmId, String idempotencyKey, String executorId) {
+ return false;
+ }
Review Comment:
I missed the 401/403/408/429 cases in the original IdempotencyStore SPI. Since we must not finalize/replay these responses for 401/403/408/429, we need an API to cancel the in‑progress reservation so keys don’t linger This is an additive default method on the SPI (backward compatible). I can split into a follow-up PR if you prefer.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2868473126
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,700 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
Review Comment:
Added comments to explain
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2855386222
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
Review Comment:
Sounds reasonable to me. Would you mind opening a GH issue for following up on this?
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025638233
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfigurationValidator.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.StartupEvent;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.time.Duration;
+
+@ApplicationScoped
+public class IdempotencyConfigurationValidator {
+
+ @Inject IdempotencyConfiguration configuration;
+
+ void validateOnStart(@Observes StartupEvent ignored) {
+ if (!configuration.enabled()) {
+ return;
+ }
+
+ requirePositive("polaris.idempotency.ttl-seconds", configuration.ttl());
Review Comment:
Done. Replaced IdempotencyConfigurationValidator with @DurationMin annotations directly on the IdempotencyConfiguration interface. Quarkus validates them automatically at startup via Hibernate Validator.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025644131
##########
extensions/idempotency/build.gradle.kts:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+plugins {
+ id("org.kordamp.gradle.jandex")
+ id("polaris-server")
+}
+
+dependencies {
+ implementation(project(":polaris-core"))
+ implementation(project(":polaris-api-management-model"))
+ implementation(project(":polaris-runtime-service"))
+
+ compileOnly(platform(libs.quarkus.bom))
+ compileOnly("io.quarkus:quarkus-rest-jackson")
+ compileOnly("io.quarkus:quarkus-reactive-routes")
Review Comment:
These are provided by the Quarkus application at runtime. Using implementation pulled in transitive deps that broke the license report. Added a comment explaining the rationale.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-3918213160
cc @flyrain @singhpk234 Could you please take a look when you have a moment?
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2996331585
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+ private final AtomicBoolean purgeRunning = new AtomicBoolean(false);
+ private volatile String resolvedExecutorId;
+
+ void onStart(@Observes StartupEvent event) {
Review Comment:
Would it be possible to move this class to a separate module (included into `runtime/server` but not into `runtime/service`).
The rationale is to allow downstream builds that do not opt in to support idempotency keys, to keep runtime behaviour and dependencies lean.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "singhpk234 (via GitHub)" <gi...@apache.org>.
singhpk234 commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2825564846
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import java.util.List;
+
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
Review Comment:
when we enable this how much do we degress per last benchmarks we did https://github.com/apache/polaris/pull/1517#issue-3037027635, mostly wanna because we can warning if it regresses a lot
##########
runtime/service/src/main/java/org/apache/polaris/service/catalog/iceberg/IcebergCatalogHandler.java:
##########
@@ -1345,9 +1351,25 @@ public ConfigResponse getConfig() {
PolarisEntity.of(resolvedReferenceCatalog.getEntity()).getPropertiesAsMap();
String prefix = prefixParser().catalogNameToPrefix(catalogName());
+ ImmutableMap.Builder<String, String> overrides = ImmutableMap.builder();
+ overrides.put("prefix", prefix);
+
+ // Advertise idempotency support only for Polaris-managed (internal) catalogs. For
+ // federated/external catalogs, Polaris may not enforce idempotency end-to-end.
+ CatalogEntity catalogEntity = CatalogEntity.of(resolvedReferenceCatalog.getEntity());
+ IdempotencyConfiguration idCfg = idempotencyConfiguration();
+ if (catalogEntity != null
+ && org.apache.polaris.core.admin.model.Catalog.TypeEnum.INTERNAL.equals(
Review Comment:
inline imports, can we please avoid them ?
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2873620367
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
Review Comment:
thx!
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2964168150
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStore.HeartbeatResult;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final int FINALIZE_MAX_RETRIES = 3;
+ private static final long FINALIZE_RETRY_BASE_MS = 200;
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String resourceId = rc.getUriInfo().getPath();
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. ttlGrace pads the check to tolerate clock skew
+ // between nodes. Full reconciliation/takeover is a follow-up.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ Duration staleThreshold =
+ configuration.leaseTtl().plus(configuration.ttlGrace());
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow).compareTo(staleThreshold)
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ boundedResponseSummary(response, objectMapper, configuration.responseSummaryMaxBytes());
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ for (int attempt = 1; attempt <= FINALIZE_MAX_RETRIES; attempt++) {
+ try {
+ store.finalizeRecord(
+ realmId, key, executorId(), status, null, body, headers, now);
+ return;
+ } catch (RuntimeException e) {
+ if (attempt < FINALIZE_MAX_RETRIES) {
+ LOG.debugf(
+ e,
+ "Finalize attempt %d/%d failed for key %s; retrying",
+ attempt,
+ FINALIZE_MAX_RETRIES,
+ key);
+ try {
+ Thread.sleep(FINALIZE_RETRY_BASE_MS * attempt);
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ LOG.warn(
+ "Interrupted while retrying finalize; record may remain in-progress", e);
+ return;
+ }
+ } else {
+ LOG.warnf(
+ e,
+ "Failed to finalize idempotency record after %d attempts for key %s; "
+ + "record will remain in-progress until TTL expiry",
+ FINALIZE_MAX_RETRIES,
+ key);
+ }
+ }
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatInterval().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ tid -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ HeartbeatResult hr =
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ if (hr != HeartbeatResult.UPDATED) {
+ vertx.cancelTimer(tid);
+ LOG.debugf("Stopping heartbeat for key %s: %s", key, hr);
+ }
+ } catch (RuntimeException e) {
+ warnThrottled(e, "Heartbeat failed; will retry on next interval");
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return !NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+ return false;
+ }
+
+ private static boolean shouldCancelInProgressReservation(int httpStatus) {
+ return httpStatus >= 500 || NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+
+ private static void warnThrottled(Throwable t, String message) {
+ long now = System.currentTimeMillis();
+ long last = LAST_WARN_AT_MS.get();
+ if (now - last >= WARN_THROTTLE_MS && LAST_WARN_AT_MS.compareAndSet(last, now)) {
+ LOG.warn(message, t);
+ } else {
+ LOG.debug(message, t);
+ }
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
Review Comment:
This line together with [this part](https://github.com/apache/polaris/pull/3803/changes#diff-c5572e5008b73ac1f17a56185a99d67d51a778d3d67bb5d38a69d195f693f38dR720) suggests that the implementation is designed to deliver _broken_ responses to clients. This violates the Iceberg API contracts.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2868472605
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,187 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithDefault("PT5M")
+ Duration ttlSeconds();
Review Comment:
Name changed
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-4180969838
Thanks @snazy for your review and comments! For the credential leakage comment, I have discussed with @flyrain and @singhpk234 offline, and we have decided to split it into two phases:
Phase 1 (this PR):
- Strip credential fields (AWS STS tokens, GCS tokens, ADLS SAS tokens, etc.) from the response before storing it. No plain-text credentials will be saved in the database.
- Include the X-Iceberg-Access-Delegation header in the resource ID hash so different delegation modes don't share a cache hit.
- On replay, the client gets the status and table metadata but without credentials.
Phase 2 (follow-up PR):
- Re-authorize the user and re-vend fresh credentials on replay. This fully solves the cross-principal concern — each user gets their own credentials based on their current permissions.
I'll also address all the other comments in this PR.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3028726391
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,819 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.security.MessageDigest;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStore.HeartbeatResult;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final int FINALIZE_MAX_RETRIES = 3;
+ private static final long FINALIZE_RETRY_BASE_MS = 200;
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ // Bind to path + body hash so that different payloads on the same endpoint are detected
+ // as conflicts (422) rather than silently replaying an unrelated response.
+ String bodyHash = hashRequestBody(rc);
+ String resourceId =
+ bodyHash != null ? rc.getUriInfo().getPath() + "#" + bodyHash : rc.getUriInfo().getPath();
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. ttlGrace pads the check to tolerate clock skew
+ // between nodes. Full reconciliation/takeover is a follow-up.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ Duration staleThreshold =
+ configuration.leaseTtl().plus(configuration.ttlGrace());
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow).compareTo(staleThreshold)
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ boundedResponseSummary(response, objectMapper, configuration.responseSummaryMaxBytes());
Review Comment:
> High: oversized successful responses currently disable idempotency instead of preserving a terminal replay state. In extensions/idempotency/
src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:335, when the body exceeds response-summary-max-bytes, the code
cancels the reservation and returns. That means the next retry with the same key will execute the mutation again instead of replaying a
terminal result. This directly contradicts the config contract in runtime/service/src/main/java/org/apache/polaris/service/idempotency/
IdempotencyConfiguration.java:154, which says replay should fall back to status + headers only. For mutating endpoints like create/register/
rename, this can turn a successful first call into a duplicate second execution.
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,819 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.security.MessageDigest;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStore.HeartbeatResult;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final int FINALIZE_MAX_RETRIES = 3;
+ private static final long FINALIZE_RETRY_BASE_MS = 200;
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ // Bind to path + body hash so that different payloads on the same endpoint are detected
+ // as conflicts (422) rather than silently replaying an unrelated response.
+ String bodyHash = hashRequestBody(rc);
+ String resourceId =
+ bodyHash != null ? rc.getUriInfo().getPath() + "#" + bodyHash : rc.getUriInfo().getPath();
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. ttlGrace pads the check to tolerate clock skew
+ // between nodes. Full reconciliation/takeover is a follow-up.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ Duration staleThreshold =
+ configuration.leaseTtl().plus(configuration.ttlGrace());
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow).compareTo(staleThreshold)
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
Review Comment:
> Medium: the async cancel path introduces a race where immediate retries can get 503 idempotency_in_progress instead of the real 401/403/5xx
outcome. The duplicate path waits or returns 503 for non-finalized records in extensions/idempotency/src/main/java/org/apache/polaris/service/
idempotency/IdempotencyFilter.java:238, but cancellation for 401/403/408/429/5xx is only scheduled on a worker thread in extensions/
idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:316. There is therefore a window after the first
response where a retry sees the stale in-progress row and gets an idempotency error instead of the original auth/server behavior. That is
especially problematic for unauthorized requests, where the API contract should not be altered by idempotency handling.
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -67,13 +79,17 @@ public ReserveResult reserve(
insertMap.put(ModelIdempotencyRecord.RESPONSE_SUMMARY, null);
insertMap.put(ModelIdempotencyRecord.RESPONSE_HEADERS, null);
insertMap.put(ModelIdempotencyRecord.FINALIZED_AT, null);
- insertMap.put(ModelIdempotencyRecord.CREATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.UPDATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, Timestamp.from(now));
+ insertMap.put(ModelIdempotencyRecord.CREATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
+ insertMap.put(ModelIdempotencyRecord.UPDATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
+ insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
insertMap.put(ModelIdempotencyRecord.EXECUTOR_ID, executorId);
- insertMap.put(ModelIdempotencyRecord.EXPIRES_AT, Timestamp.from(expiresAt));
+ long ttlSeconds = Duration.between(now, expiresAt).getSeconds();
Review Comment:
> Medium: the JDBC store now hardcodes a Postgres-style interval expression even though the module still advertises H2 support and the new
wiring test uses H2. persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/
RelationalJdbcIdempotencyStore.java:86 emits CURRENT_TIMESTAMP + INTERVAL '...' SECOND as a raw SQL literal, bypassing the existing database-
type abstraction in persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/DatabaseType.java:24. The added
wiring test still boots with H2 in extensions/idempotency/tests/src/test/java/org/apache/polaris/service/idempotency/
IdempotencyStoreWiringRelationalJdbcTest.java:53. Unless H2 accepts that exact interval syntax, reserve() will fail there; at minimum this is
a portability regression waiting on dialect quirks.
Is this SQL syntax really specific to PostgreSQL?
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-4032799492
I prefer to see the whole solution in one PR.
There are still some issues, many with a very high severity that have to be solved before we can continue with this PR and #3915.
* Unlimited response body size
* "Check then act" issue (InMemoryIdempotencyStore.reserve() L90)
* Non-atomic read-modify-write (InMemoryIdempotencyStore.load() L130)
* Missing database level concurrency control (RelationalJdbcIdempotencyStore.updateHeartbeat() L86)
* Potential lost update (RelationalJdbcIdempotencyStore.finalizeRecord(), whole function)
* Heartbeat race conditions in multi-instance scenarios (IdempotencyFilter.maybeStartHeartbeat(), whole function)
* Insufficient stale owner detection (IdempotencyFilter.reserveOrReplay() ~L230)
* Polling implementation can cause database overload (polling frequency 50ms - 100 duplicate requests lead to 2000 DB requests per second)
* Missing transaction boundaries in JDBC Operations (relies on auto-commit)
* Still clock skew issues - even small-ish drifts of 10s lead to premature or delayed execution
* Error handling Swallows important exceptions and doesn't propagate (e.g. IdempotencyFilter.finalizeOwned --> cancelInProgressReservation) leading to records remaining in the backend store, in turn wrong responses to duplicate requests.
* Expiry in the in-memory impl can still run into OOMs - it just needs 255 bigger requests.
* Polling is hardcoded, not configurable
* JDBC is likely missing important database indexes
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025634941
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,792 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStore.HeartbeatResult;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final int FINALIZE_MAX_RETRIES = 3;
+ private static final long FINALIZE_RETRY_BASE_MS = 200;
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
Review Comment:
Fixed. The binding now includes a SHA-256 hash of the request body in the resourceId (path#hash). Different payloads on the same endpoint will produce different hashes, causing a 422 conflict instead of silently replaying an unrelated response.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025424667
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+ private final AtomicBoolean purgeRunning = new AtomicBoolean(false);
+ private volatile String resolvedExecutorId;
+
+ void onStart(@Observes StartupEvent event) {
+ if (!configuration.enabled() || !configuration.purgeEnabled()) {
+ return;
+ }
+ Optional<String> purgeExecutorId = configuration.purgeExecutorId();
+ if (purgeExecutorId.isPresent()) {
+ String localExecutorId = executorId();
+ if (!purgeExecutorId.get().equals(localExecutorId)) {
+ LOGGER.debug(
+ "Skipping idempotency purge on executor {} (purge-executor-id={})",
+ localExecutorId,
+ purgeExecutorId.get());
+ return;
+ }
+ }
+ long intervalMs = configuration.purgeInterval().toMillis();
+ purgeTimerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ // Timer callbacks run on a Vert.x event-loop thread; offload blocking store I/O.
+ if (!purgeRunning.compareAndSet(false, true)) {
+ return;
+ }
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ purgeOnce();
+ } finally {
+ purgeRunning.set(false);
+ }
+ });
+ });
+ }
+
+ void onStop(@Observes ShutdownEvent event) {
+ Long id = purgeTimerId;
+ if (id != null) {
+ vertx.cancelTimer(id);
+ }
+ }
+
+ private void purgeOnce() {
Review Comment:
> Medium: purgeGrace is ignored for the JDBC store, so the configured grace window has no effect. extensions/idempotency/src/main/java/org/apache/polaris/
service/idempotency/IdempotencyMaintenance.java:97 computes a cutoff of now - purgeGrace and passes it to store.purgeExpired(...), but persistence/
relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:280 deletes with expires_at <
CURRENT_TIMESTAMP instead of using the before parameter. That makes the documented grace behavior in runtime/service/src/main/java/org/apache/polaris/
service/idempotency/IdempotencyConfiguration.java:203 incorrect for JDBC deployments.
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -67,13 +78,17 @@ public ReserveResult reserve(
insertMap.put(ModelIdempotencyRecord.RESPONSE_SUMMARY, null);
insertMap.put(ModelIdempotencyRecord.RESPONSE_HEADERS, null);
insertMap.put(ModelIdempotencyRecord.FINALIZED_AT, null);
- insertMap.put(ModelIdempotencyRecord.CREATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.UPDATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, Timestamp.from(now));
+ insertMap.put(ModelIdempotencyRecord.CREATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
+ insertMap.put(ModelIdempotencyRecord.UPDATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
+ insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
insertMap.put(ModelIdempotencyRecord.EXECUTOR_ID, executorId);
- insertMap.put(ModelIdempotencyRecord.EXPIRES_AT, Timestamp.from(expiresAt));
+ long ttlSeconds = Duration.between(now, expiresAt).getSeconds();
+ insertMap.put(
+ ModelIdempotencyRecord.EXPIRES_AT,
+ new SqlLiteral("CURRENT_TIMESTAMP + INTERVAL '" + ttlSeconds + "' SECOND"));
- List<Object> values = insertMap.values().stream().toList();
+ // Stream#toList returns an unmodifiable list and rejects nulls; these columns are nullable.
+ List<Object> values = new ArrayList<>(insertMap.values());
Review Comment:
> High: expired JDBC records are never reclaimable unless a purge happens, so keys can remain blocked forever with the default config. In persistence/
relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:70, reserve() does a blind
insert and treats any PK conflict as a live duplicate by returning load(...); unlike the in-memory store, it does not replace expired rows. Since purge is
disabled by default in runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:178, an expired row can sit in
the table indefinitely and make that idempotency key unusable long after TTL expiry.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025645843
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -67,13 +78,17 @@ public ReserveResult reserve(
insertMap.put(ModelIdempotencyRecord.RESPONSE_SUMMARY, null);
insertMap.put(ModelIdempotencyRecord.RESPONSE_HEADERS, null);
insertMap.put(ModelIdempotencyRecord.FINALIZED_AT, null);
- insertMap.put(ModelIdempotencyRecord.CREATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.UPDATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, Timestamp.from(now));
+ insertMap.put(ModelIdempotencyRecord.CREATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
Review Comment:
Yes, CURRENT_TIMESTAMP is standard SQL (SQL-92). It works on all our JDBC backends including Postgres and H2.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-4043472444
@snazy Thanks for your review! I have addressed all the comments (one commit for each comment) except the last one. There is already an index on `(realm_id, expires_at)` for the purge query. All other queries find rows by the primary key `(realm_id, idempotency_key)`, which is a single-row lookup, so no extra indexes are needed.
Could you please take one more look when you have time? Thanks!
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #3803: Add Iceberg REST Idempotency-Key support
URL: https://github.com/apache/polaris/pull/3803
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3028617232
##########
extensions/idempotency/build.gradle.kts:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+plugins {
+ id("org.kordamp.gradle.jandex")
+ id("polaris-server")
+}
+
+dependencies {
+ implementation(project(":polaris-core"))
+ implementation(project(":polaris-api-management-model"))
+ implementation(project(":polaris-runtime-service"))
+
+ compileOnly(platform(libs.quarkus.bom))
+ compileOnly("io.quarkus:quarkus-rest-jackson")
+ compileOnly("io.quarkus:quarkus-reactive-routes")
Review Comment:
It's a bit odd that declaring dependencies already provided by Quarkus breaks the license report :thinking: but that's ok. We can keep `compileOnly` as long as it works in our `@QuarkusTest` tests.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025429767
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,792 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStore.HeartbeatResult;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final int FINALIZE_MAX_RETRIES = 3;
+ private static final long FINALIZE_RETRY_BASE_MS = 200;
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
Review Comment:
> Medium: duplicate-key conflict detection does not bind the request payload, only the method-derived operation and request path. In extensions/idempotency/
src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:169, the stored binding is just operationType plus rc.getUriInfo().getPath(),
and the conflict check at extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:221 compares only those two
fields. Reusing the same key on the same endpoint with a different request body will replay the first response instead of returning a conflict, which is
risky for mutating Iceberg operations where the path stays the same but the body carries the actual change.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3028623144
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfigurationValidator.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.StartupEvent;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.time.Duration;
+
+@ApplicationScoped
+public class IdempotencyConfigurationValidator {
+
+ @Inject IdempotencyConfiguration configuration;
+
+ void validateOnStart(@Observes StartupEvent ignored) {
+ if (!configuration.enabled()) {
+ return;
+ }
+
+ requirePositive("polaris.idempotency.ttl-seconds", configuration.ttl());
Review Comment:
thx!
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2820301442
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStoreFactory.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.polaris.persistence.relational.jdbc.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStoreFactory;
+import org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+
+@ApplicationScoped
+@Identifier("relational-jdbc")
+public class RelationalJdbcIdempotencyStoreFactory implements IdempotencyStoreFactory {
+
+ @Inject Instance<DataSource> dataSource;
Review Comment:
I updated the idempotency store to use a dedicated idempotency datasource when configured (otherwise it falls back to the default). Added a quarkus.datasource.idempotency.* config snippet for enabling/tuning. I have also verified locally.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2833479529
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import java.util.List;
+
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /** Default TTL (seconds) for newly reserved keys. */
+ @WithDefault("300")
+ long ttlSeconds();
+
+ /**
+ * Additional grace (seconds) added to {@link #ttlSeconds()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ */
+ @WithDefault("0")
+ long ttlGraceSeconds();
Review Comment:
Using `Duration` here and other time related fields is nicer, `PT5M` is more expressive than `300`.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import java.util.List;
+
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
Review Comment:
The configuration deserves some user-facing documentation about how all the settings should be configured for both single-node and multi-node deployments and typical k8s scenarios like pod restarts.
Especially multi-node deployments _must_ define different executor-IDs. This is why `org.apache.polaris.persistence.nosql.nodeids.api.NodeManagement` exists. It's use would elminiate the need for the `executorId` configuration setting, which would be manual.
Heartbeats _must_ be enabled in multi-node deployments, as elaborated in the code review.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
Review Comment:
Not enabling heartbeats in a multi-node deployment, will let long-running requests look stale to other nodes and let those falsely error out the operation instead of waiting.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
+ final String headers =
+ headerSnapshotJson(response, configuration.responseHeaderAllowlist(), objectMapper);
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, status, null, body, headers, now);
+ } catch (RuntimeException ignored) {
+ // Best-effort: the main request already completed. If this fails, replay may be
+ // unavailable until a later retry or reconciliation.
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = Math.max(1000L, configuration.heartbeatIntervalSeconds() * 1000L);
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(
+ realmId, key, configuration.executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return httpStatus != 401 && httpStatus != 403 && httpStatus != 408 && httpStatus != 429;
+ }
+ return false;
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.getHttpStatus() == null ? 200 : existing.getHttpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ if (!applyReplayedHeaders(replay, existing.getResponseHeaders())) {
+ // if a prior finalized result can't be reproduced, return a 5xx rather
+ // than re-executing the operation.
+ return error(
+ 500,
+ "idempotency_replay_failed",
+ "Failed to replay response for this idempotency key; retry later");
+ }
+ if (existing.getResponseSummary() != null) {
+ replay.entity(existing.getResponseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ ContainerRequestContext rc, PolarisPrincipal principal) {
+ String path = rc.getUriInfo().getPath();
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
+ }
+
+ private static String normalizeResourceId(ContainerRequestContext rc, boolean scopedMode) {
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String path = rc.getUriInfo().getPath();
+ return path;
+ }
+
+ private static String responseEntityAsString(
+ ContainerResponseContext response, ObjectMapper objectMapper) {
+ Object entity = response.getEntity();
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String string) {
+ return string;
+ }
+ try {
+ return objectMapper.writeValueAsString(entity);
+ } catch (Exception e) {
+ // Best-effort fallback.
+ return entity.toString();
+ }
+ }
+
+ private boolean applyReplayedHeaders(Response.ResponseBuilder rb, String responseHeadersJson) {
+ if (responseHeadersJson == null || responseHeadersJson.isBlank()) {
+ return true;
+ }
+ try {
+ Map<String, String> m = objectMapper.readValue(responseHeadersJson, new TypeReference<>() {});
+ m.forEach(
+ (k, v) -> {
+ rb.header(k, v);
+ if (k != null && v != null && "content-type".equalsIgnoreCase(k)) {
+ // Ensure the JAX-RS response media type matches the replayed Content-Type.
+ rb.type(v);
+ }
+ });
+ return true;
+ } catch (Exception ignored) {
+ return false;
+ }
+ }
+
+ private static String headerSnapshotJson(
+ ContainerResponseContext response, List<String> allowlist, ObjectMapper objectMapper) {
+ if (allowlist == null || allowlist.isEmpty()) {
+ return null;
+ }
+ Map<String, String> out = new LinkedHashMap<>();
+ for (String name : allowlist) {
+ if (name == null || name.isBlank()) {
+ continue;
+ }
+ Object v = response.getHeaders().getFirst(name);
+ if (v != null) {
+ out.put(name, String.valueOf(v));
+ }
+ }
+ if (out.isEmpty()) {
+ return null;
+ }
+ try {
+ return objectMapper.writeValueAsString(out);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private static String truncate(String s, int maxChars) {
+ if (s == null) {
+ return null;
+ }
+ if (maxChars <= 0) {
+ return "";
+ }
Review Comment:
This silently hides a configuration issue.
Validation of configuration values like negative or zero values, also for duration, should happen early and prevent the service from starting.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import java.util.List;
+
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /** Default TTL (seconds) for newly reserved keys. */
+ @WithDefault("300")
+ long ttlSeconds();
+
+ /**
+ * Additional grace (seconds) added to {@link #ttlSeconds()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ */
+ @WithDefault("0")
+ long ttlGraceSeconds();
+
+ /** Executor identifier to store alongside reservations (e.g. pod/instance id). */
+ @WithDefault("http")
+ String executorId();
+
+ /**
+ * Maximum time to wait for an in-progress idempotency key to finalize before returning a
+ * retryable response.
+ */
+ @WithDefault("30")
+ long inProgressWaitSeconds();
+
+ /**
+ * Lease TTL (seconds) for considering an in-progress owner "active" based on {@code heartbeatAt}.
+ *
+ * <p>If a duplicate observes {@code now - heartbeatAt > leaseTtlSeconds}, the owner is treated as
+ * stale and the server should not wait indefinitely.
+ */
+ @WithDefault("25")
+ long leaseTtlSeconds();
+
+ /**
+ * Response headers that are persisted and replayed (exact names).
+ *
+ * <p>Only the first header value is stored and replayed.
+ */
+ @WithDefault("Content-Type")
+ List<String> responseHeaderAllowlist();
+
+ /** Max number of response body characters to store for replay. */
Review Comment:
What happens if the response body is bigger than this value?
The information is important for this review but also for users.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,96 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+ private final AtomicBoolean purgeRunning = new AtomicBoolean(false);
+
+ void onStart(@Observes StartupEvent event) {
+ if (!configuration.enabled() || !configuration.purgeEnabled()) {
+ return;
+ }
Review Comment:
In multi-node deployments this would lead to maintenance running on all nodes, potentially even concurrently. This leads to unnecessary contention - also think: "thundering herd."
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
+ final String headers =
+ headerSnapshotJson(response, configuration.responseHeaderAllowlist(), objectMapper);
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, status, null, body, headers, now);
+ } catch (RuntimeException ignored) {
+ // Best-effort: the main request already completed. If this fails, replay may be
+ // unavailable until a later retry or reconciliation.
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = Math.max(1000L, configuration.heartbeatIntervalSeconds() * 1000L);
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(
+ realmId, key, configuration.executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return httpStatus != 401 && httpStatus != 403 && httpStatus != 408 && httpStatus != 429;
+ }
+ return false;
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.getHttpStatus() == null ? 200 : existing.getHttpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ if (!applyReplayedHeaders(replay, existing.getResponseHeaders())) {
+ // if a prior finalized result can't be reproduced, return a 5xx rather
+ // than re-executing the operation.
+ return error(
+ 500,
+ "idempotency_replay_failed",
+ "Failed to replay response for this idempotency key; retry later");
+ }
+ if (existing.getResponseSummary() != null) {
+ replay.entity(existing.getResponseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ ContainerRequestContext rc, PolarisPrincipal principal) {
+ String path = rc.getUriInfo().getPath();
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
Review Comment:
This is likely a _blocking_ operation running on a Vert.X event loop thread, that must never block.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
+ final String headers =
+ headerSnapshotJson(response, configuration.responseHeaderAllowlist(), objectMapper);
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, status, null, body, headers, now);
Review Comment:
This should include the executor-ID IMO to prevent cross-pod races.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
+ final String headers =
+ headerSnapshotJson(response, configuration.responseHeaderAllowlist(), objectMapper);
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, status, null, body, headers, now);
+ } catch (RuntimeException ignored) {
+ // Best-effort: the main request already completed. If this fails, replay may be
+ // unavailable until a later retry or reconciliation.
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = Math.max(1000L, configuration.heartbeatIntervalSeconds() * 1000L);
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(
+ realmId, key, configuration.executorId(), clock.instant());
Review Comment:
Especially the JDBC backed implementation should be fixed to use only one `UPDATE` statement. The current implementation is racy as it can allows another pod to finalize.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
Review Comment:
This unnecessarily serialized the whole entity although the result is truncated.
Truncation can happen earlier.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,130 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import java.util.List;
+
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /** Default TTL (seconds) for newly reserved keys. */
+ @WithDefault("300")
+ long ttlSeconds();
+
+ /**
+ * Additional grace (seconds) added to {@link #ttlSeconds()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ */
+ @WithDefault("0")
+ long ttlGraceSeconds();
+
+ /** Executor identifier to store alongside reservations (e.g. pod/instance id). */
+ @WithDefault("http")
+ String executorId();
Review Comment:
Beyond the above comment, why does this even need to be explicitly provided by users?
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
Review Comment:
Truncation also happens on the number of characters, not bytes, which would be easily achievable and would be way more deterministic than the varying number of bytes per character.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
+ final String headers =
+ headerSnapshotJson(response, configuration.responseHeaderAllowlist(), objectMapper);
Review Comment:
How headers are handled by individual store implemetnations should really be up to them. But here the whole header map is always (de)serialized to/from a JSON string. Even Postgres could store the map using a native data type, so the JSON (de)serialization is just overhead.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ configuration.executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.getType() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.getExisting();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(error(500, "IdempotencyInvariantViolation", "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.getOperationType())
+ || !resourceId.equals(existing.getNormalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ // If the owner appears stale (no recent heartbeat), don't wait indefinitely. Full
+ // reconciliation/takeover is out of scope for this change; return a retryable 503.
+ Instant hb = existing.getHeartbeatAt();
+ if (hb != null
+ && Duration.between(hb, clock.instant()).getSeconds()
+ > Math.max(0L, configuration.leaseTtlSeconds())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ Instant deadline =
+ clock
+ .instant()
+ .plusSeconds(Math.max(0L, configuration.inProgressWaitSeconds()));
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, configuration.executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ truncate(responseEntityAsString(response, objectMapper), configuration.maxResponseBodyChars());
Review Comment:
Truncating the body is a correctness issue.
It leads to incomplete and broken responses that breaks clients.
Truncation is very likely to happen considering that Iceberg metadata objects can be very big.
On top, the `Content-Length` header can vary between the original and replayed response. Even the HTTP infrastructure can add it back, so the configuration option is misleading.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-3979299580
Splitting this PR into three PRs:
- [relational-jdbc change (i believe we add a new api in interface and its corresponding impl)](https://github.com/apache/polaris/pull/3915)
- core integration ( i wonder some in-meory eq can unlock us)
- E2E with service using quarkus
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2820298268
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/IdempotencyStore.java:
##########
@@ -154,6 +154,24 @@ ReserveResult reserve(
HeartbeatResult updateHeartbeat(
String realmId, String idempotencyKey, String executorId, Instant now);
+ /**
+ * Cancels (deletes) an in-progress idempotency reservation owned by {@code executorId}.
+ *
+ * <p>This is used for cases where an idempotency key was reserved but the request should not be
+ * tracked for replay (for example, 401/403/408/429 responses per the proposal). Implementations
+ * should only cancel the record if it is still in-progress (i.e., not finalized) and owned by the
+ * given executor.
+ *
+ * @param realmId logical tenant or realm identifier
+ * @param idempotencyKey application-provided idempotency key
+ * @param executorId identifier of the executor that owns the reservation
+ * @return {@code true} if a record was cancelled, {@code false} otherwise
+ */
+ default boolean cancelInProgressReservation(
+ String realmId, String idempotencyKey, String executorId) {
+ return false;
+ }
Review Comment:
I missed the 401/403/408/429 cases in the original IdempotencyStore SPI. Since we must not finalize/replay these responses for 401/403/408/429, we need an API to cancel the in‑progress reservation so keys don’t linger. This is an additive default method on the SPI (backward compatible). I can split into a follow-up PR if you prefer.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2996291490
##########
runtime/service/src/main/java/org/apache/polaris/service/config/ServiceProducers.java:
##########
@@ -217,6 +219,20 @@ public MetaStoreManagerFactory metaStoreManagerFactory(
return metaStoreManagerFactories.select(Identifier.Literal.of(config.type())).get();
}
+ @Produces
+ @ApplicationScoped
+ public IdempotencyStoreFactory idempotencyStoreFactory(
+ PersistenceConfiguration config,
+ @Any Instance<IdempotencyStoreFactory> idempotencyFactories) {
+ return idempotencyFactories.select(Identifier.Literal.of(config.type())).get();
+ }
+
+ @Produces
+ @ApplicationScoped
+ public IdempotencyStore idempotencyStore(IdempotencyStoreFactory factory) {
+ return factory.create();
Review Comment:
Sorry for late reply.
As I commented above, I do not see much value in adding a new factory interface for `IdempotencyStore` to `polaris-core`.
I see value in having uniform producer code for `IdempotencyStore` implementations in `runtime/service`, though.
So, I'd propose removing the `IdempotencyStoreFactory` from `polaris-core` and instead:
1) Annotate `RelationalJdbcIdempotencyStore` with `@Identifier("relational-jdbc")`
2) Add a new class for `InMemoryIdempotencyStore` in `runtime/service` and have its producer method annotated with `@ApplicationScoped` and `@Identifier("in-memory")`
3) this `idempotencyStore` should be able to select from `@Any Instance<IdempotencyStore` (similar to `idempotencyStoreFactory`).
My rationale is to reduce the SPI surface in `polaris-core`, while keeping the same level of configurability.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2851344754
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
Review Comment:
Thanks for your suggestion. I will keep this PR focused on the idempotency behavior, but I can follow up with a separate PR to move the filter + related idempotency service classes into a dedicated module.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2842138731
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
Review Comment:
Would it be possible to move this filter and related Idempotency service classes into a dedicated module (included into `runtime/server` as a dependency, but not into `runtime/service`)?
This is to allow downstream projects that do not wish to utilize idempotency filters to have a way to excluding the from runtime and avoid the corresponding overhead and related schema management.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3012501173
##########
runtime/service/src/test/java/org/apache/polaris/service/idempotency/IdempotencyFilterTest.java:
##########
Review Comment:
I'd like to propose having a test module for this parallel to the new `runtime/idempotency` module.
Cf. https://github.com/apache/polaris/tree/main/extensions/auth/opa/tests
##########
runtime/idempotency/build.gradle.kts:
##########
Review Comment:
This module makes sense, but I'd like to suggest keeping it under `extensions/idempotency`. The `runtime/server` module can still depend on it.
My view of the `runtime` sub-tree is that it should contain only code that is required in all Polaris deployments. While `runtime/idempotency` can be included or excluded in downstream builds, its presence under `runtime/` may make the impression that it is a required component.
WDYT?
##########
runtime/service/src/main/java/org/apache/polaris/service/config/ServiceProducers.java:
##########
@@ -214,13 +216,32 @@ public FileIOFactory fileIOFactory(
}
@Produces
- @Singleton // used in instanceof checks
+ public PolarisEventListener polarisEventListener(
+ PolarisEventListenerConfiguration config,
+ @Any Instance<PolarisEventListener> polarisEventListeners) {
+ return polarisEventListeners.select(Identifier.Literal.of(config.type())).get();
+ }
+
+ @Produces
public MetaStoreManagerFactory metaStoreManagerFactory(
PersistenceConfiguration config,
@Any Instance<MetaStoreManagerFactory> metaStoreManagerFactories) {
return metaStoreManagerFactories.select(Identifier.Literal.of(config.type())).get();
}
+ @Produces
+ @Singleton
+ public IdempotencyStore idempotencyStore(
Review Comment:
Could this be moved into the new `runtime/idempotency` module (also `PersistenceConfiguration`)?
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2876195745
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,736 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtl())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to finalize idempotency record; replay may be unavailable until a later retry or reconciliation");
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatInterval().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return !NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+ return false;
+ }
+
+ private static boolean shouldCancelInProgressReservation(int httpStatus) {
+ return httpStatus >= 500 || NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+
+ private static void warnThrottled(Throwable t, String message) {
+ long now = System.currentTimeMillis();
+ long last = LAST_WARN_AT_MS.get();
+ if (now - last >= WARN_THROTTLE_MS && LAST_WARN_AT_MS.compareAndSet(last, now)) {
+ LOG.warn(message, t);
+ } else {
+ LOG.debug(message, t);
+ }
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
+ replay.entity(existing.responseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter. If the
+ // matched resource/method isn't available, we return false (no idempotency).
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ String path, PolarisPrincipal principal) {
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to parse Iceberg REST catalog prefix for idempotency gating");
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to create resolver for idempotency internal-catalog gating");
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to resolve catalog for idempotency internal-catalog gating");
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ LOG.debugf(
+ "Resolver status %s for idempotency internal-catalog gating; treating as non-internal",
+ status.getStatus());
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
+ }
+
+ private static String normalizeResourceId(ContainerRequestContext rc) {
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String path = rc.getUriInfo().getPath();
+ return path;
+ }
+
+ private static String responseEntityAsString(
+ ContainerResponseContext response, ObjectMapper objectMapper) {
+ Object entity = response.getEntity();
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String string) {
+ return string;
+ }
+ try {
+ return objectMapper.writeValueAsString(entity);
Review Comment:
Agreed. In a follow-up I’ll switch from storing the full response body to a small, bounded response_summary, and handle streaming/unknown bodies 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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2871107974
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithName("ttl-seconds")
+ @WithDefault("PT5M")
+ Duration ttl();
+
+ /**
+ * Additional grace added to {@link #ttl()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ *
+ * <p>Examples: {@code PT0S}, {@code 10S}.
+ */
+ @WithName("ttl-grace-seconds")
+ @WithDefault("PT0S")
+ Duration ttlGrace();
+
+ /**
+ * Executor identifier to store alongside reservations (e.g. pod/instance id).
+ *
+ * <p>If unset or blank, the service derives a best-effort identifier from environment/host info
+ * (for example {@code $POD_NAME} / {@code $HOSTNAME} plus the process id).
+ *
+ * <p>In multi-node deployments, executor ids must be unique per replica.
+ */
+ Optional<String> executorId();
+
+ /**
+ * Maximum time to wait for an in-progress idempotency key to finalize before returning a
+ * retryable response.
+ */
+ @WithName("in-progress-wait-seconds")
+ @WithDefault("PT30S")
+ Duration inProgressWait();
+
+ /**
+ * Lease TTL for considering an in-progress owner "active" based on {@code heartbeatAt}.
+ *
+ * <p>If a duplicate observes {@code now - heartbeatAt > leaseTtl()}, the owner is treated as
+ * stale and the server should not wait indefinitely.
+ */
+ @WithName("lease-ttl-seconds")
+ @WithDefault("PT25S")
+ Duration leaseTtl();
+
+ /**
+ * Response headers that are persisted and replayed (exact names).
+ *
+ * <p>Only the first header value is stored and replayed.
+ */
+ @WithDefault("Content-Type")
+ List<String> responseHeaderAllowlist();
+
+ /**
+ * Enable periodic heartbeats while a request is in progress.
+ *
+ * <p>Recommended for multi-node deployments.
+ */
+ @WithDefault("false")
+ boolean heartbeatEnabled();
+
+ /**
+ * Heartbeat interval while a request is in progress.
+ *
+ * <p>Examples: {@code PT5S}, {@code 1S}.
+ *
+ * <p>In multi-node deployments, this should be shorter than {@link #leaseTtl()}.
+ */
+ @WithName("heartbeat-interval-seconds")
+ @WithDefault("PT5S")
+ Duration heartbeatInterval();
+
+ /**
+ * Enable periodic purge of expired idempotency records.
+ *
+ * <p>In multi-node deployments, enabling purge on all replicas may cause unnecessary contention.
+ */
+ @WithDefault("false")
+ boolean purgeEnabled();
+
+ /**
+ * Optional executor id that is allowed to run purge.
+ *
+ * <p>When set, only the node whose resolved {@link #executorId()} matches this value will run the
+ * purge timer. This can be used to avoid "thundering herd" behavior in multi-node deployments.
+ */
+ Optional<String> purgeExecutorId();
+
+ /**
+ * Purge interval.
+ *
+ * <p>Examples: {@code PT1M}, {@code 60S}.
+ */
+ @WithName("purge-interval-seconds")
+ @WithDefault("PT1M")
+ Duration purgeInterval();
+
+ /**
+ * Purge records expired strictly before (now - grace).
+ *
+ * <p>Allows keeping just-expired keys around a bit longer to tolerate clock skew.
+ */
+ @WithName("purge-grace-seconds")
+ @WithDefault("PT0S")
Review Comment:
The description says _"... to tolerate clock skew ..."_ but the default value (0s) does not tolerate any clock skew.
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/models/ModelIdempotencyRecord.java:
##########
@@ -42,6 +44,9 @@ public interface ModelIdempotencyRecord extends Converter<IdempotencyRecord> {
String TABLE_NAME = "idempotency_records";
+ ObjectMapper RESPONSE_HEADERS_MAPPER = new ObjectMapper();
Review Comment:
Why do we need _two_ mapper instances here and in `RelationalJdbcIdempotencyStore`, and this one exposed as a `public` constant?
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStoreFactory.java:
##########
@@ -0,0 +1,51 @@
+/*
+ * 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.polaris.persistence.relational.jdbc.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.literal.NamedLiteral;
+import jakarta.inject.Inject;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStoreFactory;
+import org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+
+@ApplicationScoped
+@Identifier("relational-jdbc")
+public class RelationalJdbcIdempotencyStoreFactory implements IdempotencyStoreFactory {
+
+ @Inject Instance<DataSource> dataSource;
+ @Inject @Any Instance<DataSource> anyDataSources;
+ @Inject RelationalJdbcConfiguration relationalJdbcConfiguration;
+
+ @Override
+ public IdempotencyStore create() {
+ try {
+ Instance<DataSource> idempotencyDs = anyDataSources.select(NamedLiteral.of("idempotency"));
+ DataSource ds = idempotencyDs.isResolvable() ? idempotencyDs.get() : dataSource.get();
Review Comment:
The mechanism here has a surprising behavior with the silent fallback to the default data source.
I'd prefer not to have a surprising behavior.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,736 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtl())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to finalize idempotency record; replay may be unavailable until a later retry or reconciliation");
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatInterval().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return !NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+ return false;
+ }
+
+ private static boolean shouldCancelInProgressReservation(int httpStatus) {
+ return httpStatus >= 500 || NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+
+ private static void warnThrottled(Throwable t, String message) {
+ long now = System.currentTimeMillis();
+ long last = LAST_WARN_AT_MS.get();
+ if (now - last >= WARN_THROTTLE_MS && LAST_WARN_AT_MS.compareAndSet(last, now)) {
+ LOG.warn(message, t);
+ } else {
+ LOG.debug(message, t);
+ }
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
+ replay.entity(existing.responseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter. If the
+ // matched resource/method isn't available, we return false (no idempotency).
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ String path, PolarisPrincipal principal) {
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to parse Iceberg REST catalog prefix for idempotency gating");
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to create resolver for idempotency internal-catalog gating");
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to resolve catalog for idempotency internal-catalog gating");
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ LOG.debugf(
+ "Resolver status %s for idempotency internal-catalog gating; treating as non-internal",
+ status.getStatus());
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
+ }
+
+ private static String normalizeResourceId(ContainerRequestContext rc) {
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String path = rc.getUriInfo().getPath();
+ return path;
+ }
+
+ private static String responseEntityAsString(
+ ContainerResponseContext response, ObjectMapper objectMapper) {
+ Object entity = response.getEntity();
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String string) {
+ return string;
+ }
+ try {
+ return objectMapper.writeValueAsString(entity);
Review Comment:
I'm quite concerned about this one and the general approach of handling the response body.
This one in particular will not work for async and streaming responses, see [this discussion](https://lists.apache.org/thread/f4rz2xdpt2jd49rjsqpc101zzlsxfgjc).
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
Review Comment:
The 2nd example here and elsewhere is an invalid duration.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithName("ttl-seconds")
+ @WithDefault("PT5M")
+ Duration ttl();
+
+ /**
+ * Additional grace added to {@link #ttl()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ *
+ * <p>Examples: {@code PT0S}, {@code 10S}.
+ */
+ @WithName("ttl-grace-seconds")
+ @WithDefault("PT0S")
+ Duration ttlGrace();
+
+ /**
+ * Executor identifier to store alongside reservations (e.g. pod/instance id).
+ *
+ * <p>If unset or blank, the service derives a best-effort identifier from environment/host info
+ * (for example {@code $POD_NAME} / {@code $HOSTNAME} plus the process id).
+ *
+ * <p>In multi-node deployments, executor ids must be unique per replica.
+ */
+ Optional<String> executorId();
+
+ /**
+ * Maximum time to wait for an in-progress idempotency key to finalize before returning a
+ * retryable response.
+ */
+ @WithName("in-progress-wait-seconds")
+ @WithDefault("PT30S")
+ Duration inProgressWait();
+
+ /**
+ * Lease TTL for considering an in-progress owner "active" based on {@code heartbeatAt}.
+ *
+ * <p>If a duplicate observes {@code now - heartbeatAt > leaseTtl()}, the owner is treated as
+ * stale and the server should not wait indefinitely.
+ */
+ @WithName("lease-ttl-seconds")
+ @WithDefault("PT25S")
+ Duration leaseTtl();
+
+ /**
+ * Response headers that are persisted and replayed (exact names).
+ *
+ * <p>Only the first header value is stored and replayed.
+ */
+ @WithDefault("Content-Type")
+ List<String> responseHeaderAllowlist();
+
+ /**
+ * Enable periodic heartbeats while a request is in progress.
+ *
+ * <p>Recommended for multi-node deployments.
+ */
+ @WithDefault("false")
+ boolean heartbeatEnabled();
+
+ /**
+ * Heartbeat interval while a request is in progress.
+ *
+ * <p>Examples: {@code PT5S}, {@code 1S}.
+ *
+ * <p>In multi-node deployments, this should be shorter than {@link #leaseTtl()}.
+ */
+ @WithName("heartbeat-interval-seconds")
+ @WithDefault("PT5S")
+ Duration heartbeatInterval();
+
+ /**
+ * Enable periodic purge of expired idempotency records.
+ *
+ * <p>In multi-node deployments, enabling purge on all replicas may cause unnecessary contention.
+ */
+ @WithDefault("false")
Review Comment:
The "in memory store" together with this default setting will eventually lead to out-of-memory situations.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithName("ttl-seconds")
+ @WithDefault("PT5M")
+ Duration ttl();
+
+ /**
+ * Additional grace added to {@link #ttl()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ *
+ * <p>Examples: {@code PT0S}, {@code 10S}.
+ */
+ @WithName("ttl-grace-seconds")
+ @WithDefault("PT0S")
Review Comment:
The description says _"... to tolerate clock skew ..."_ but the default value (0s) does not tolerate any clock skew.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfigurationValidator.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import java.time.Duration;
+
+@ApplicationScoped
+public class IdempotencyConfigurationValidator {
+
+ @Inject IdempotencyConfiguration configuration;
+
+ @PostConstruct
+ void validate() {
Review Comment:
I am not sure this will get ever called, as there is nothing that would cause this `IdempotencyConfigurationValidator` bean to be ever constructed.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,736 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtl())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to finalize idempotency record; replay may be unavailable until a later retry or reconciliation");
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatInterval().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return !NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+ return false;
+ }
+
+ private static boolean shouldCancelInProgressReservation(int httpStatus) {
+ return httpStatus >= 500 || NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+
+ private static void warnThrottled(Throwable t, String message) {
+ long now = System.currentTimeMillis();
+ long last = LAST_WARN_AT_MS.get();
+ if (now - last >= WARN_THROTTLE_MS && LAST_WARN_AT_MS.compareAndSet(last, now)) {
+ LOG.warn(message, t);
+ } else {
+ LOG.debug(message, t);
+ }
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
+ replay.entity(existing.responseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter. If the
+ // matched resource/method isn't available, we return false (no idempotency).
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ String path, PolarisPrincipal principal) {
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to parse Iceberg REST catalog prefix for idempotency gating");
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to create resolver for idempotency internal-catalog gating");
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to resolve catalog for idempotency internal-catalog gating");
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ LOG.debugf(
+ "Resolver status %s for idempotency internal-catalog gating; treating as non-internal",
+ status.getStatus());
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
+ }
+
+ private static String normalizeResourceId(ContainerRequestContext rc) {
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String path = rc.getUriInfo().getPath();
+ return path;
+ }
Review Comment:
This is only called from one call site, should be hoisted.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-4136519570
@snazy Thanks a lot for your review! Could you take one more look to see if your have further comments? If not, I will continue working on the split PR https://github.com/apache/polaris/pull/3915 (Idempotency: JDBC store implementation and SPI). Thanks!
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "singhpk234 (via GitHub)" <gi...@apache.org>.
singhpk234 commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-3924584875
Thank you for the change @huaxingao !
i wonder if we can break this ~1.9k LOC to 3 parts :
1. relational-jdbc change (i believe we add a new api in interface and its corresponding impl)
2. core integration ( i wonder some in-meory eq can unlock us)
3. E2E with service using quarkus
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2831656111
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,636 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ final IdempotencyStore.ReserveResult r;
+ try {
+ r =
+ store.reserve(
Review Comment:
Fixed — moved idempotency store calls off the event-loop (run reserve() on the worker pool; dispatch finalize/cancel/heartbeat to the worker pool too)
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.time.Clock;
+import java.time.Instant;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+
+ void onStart(@Observes StartupEvent event) {
+ if (!configuration.enabled() || !configuration.purgeEnabled()) {
+ return;
+ }
+ long intervalMs = Math.max(1000L, configuration.purgeIntervalSeconds() * 1000L);
+ purgeTimerId = vertx.setPeriodic(intervalMs, ignored -> purgeOnce());
Review Comment:
Good catch. setPeriodic runs on a Vert.x event-loop thread. I changed it so purgeOnce() runs on the worker pool instead, and I added a guard so two purges can’t run at the same time.
##########
runtime/service/src/main/java/org/apache/polaris/service/config/ServiceProducers.java:
##########
@@ -217,6 +219,20 @@ public MetaStoreManagerFactory metaStoreManagerFactory(
return metaStoreManagerFactories.select(Identifier.Literal.of(config.type())).get();
}
+ @Produces
+ @ApplicationScoped
+ public IdempotencyStoreFactory idempotencyStoreFactory(
+ PersistenceConfiguration config,
+ @Any Instance<IdempotencyStoreFactory> idempotencyFactories) {
+ return idempotencyFactories.select(Identifier.Literal.of(config.type())).get();
+ }
+
+ @Produces
+ @ApplicationScoped
+ public IdempotencyStore idempotencyStore(IdempotencyStoreFactory factory) {
+ return factory.create();
Review Comment:
I saw Polaris uses this factory + @Identifier pattern. I’m following the same approach for IdempotencyStoreFactory for consistency.can you reply in
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,636 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
Review Comment:
It probably wouldn’t work for our use case. Quarkus discovers @ServerRequestFilter at build time, but polaris.idempotency.enabled is a runtime config. So we can’t reliably “not register the filter” based on that flag.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2868425402
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,659 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
Review Comment:
created https://github.com/apache/polaris/issues/3914
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025632814
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+ private final AtomicBoolean purgeRunning = new AtomicBoolean(false);
+ private volatile String resolvedExecutorId;
+
+ void onStart(@Observes StartupEvent event) {
+ if (!configuration.enabled() || !configuration.purgeEnabled()) {
+ return;
+ }
+ Optional<String> purgeExecutorId = configuration.purgeExecutorId();
+ if (purgeExecutorId.isPresent()) {
+ String localExecutorId = executorId();
+ if (!purgeExecutorId.get().equals(localExecutorId)) {
+ LOGGER.debug(
+ "Skipping idempotency purge on executor {} (purge-executor-id={})",
+ localExecutorId,
+ purgeExecutorId.get());
+ return;
+ }
+ }
+ long intervalMs = configuration.purgeInterval().toMillis();
+ purgeTimerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ // Timer callbacks run on a Vert.x event-loop thread; offload blocking store I/O.
+ if (!purgeRunning.compareAndSet(false, true)) {
+ return;
+ }
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ purgeOnce();
+ } finally {
+ purgeRunning.set(false);
+ }
+ });
+ });
+ }
+
+ void onStop(@Observes ShutdownEvent event) {
+ Long id = purgeTimerId;
+ if (id != null) {
+ vertx.cancelTimer(id);
+ }
+ }
+
+ private void purgeOnce() {
Review Comment:
Fixed. Now the grace window from IdempotencyMaintenance is respected for JDBC deployments.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025640698
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyStoreProducer.java:
##########
@@ -0,0 +1,43 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.Produces;
+import jakarta.inject.Singleton;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.persistence.PersistenceConfiguration;
+
+@Singleton
+public class IdempotencyStoreProducer {
+
+ @Produces
+ @Singleton
+ public IdempotencyStore idempotencyStore(
+ PersistenceConfiguration config, @Any Instance<IdempotencyStore> idempotencyStores) {
+ Instance<IdempotencyStore> selected =
+ idempotencyStores.select(Identifier.Literal.of(config.type()));
Review Comment:
Added an optional polaris.idempotency.store-type config. If set, it selects the idempotency store independently from the persistence type.
##########
extensions/idempotency/tests/build.gradle.kts:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+plugins {
+ alias(libs.plugins.quarkus)
+ id("org.kordamp.gradle.jandex")
+ id("polaris-runtime")
+}
+
+dependencies {
+ implementation(platform(libs.quarkus.bom))
+ implementation("io.quarkus:quarkus-rest-jackson")
+
+ implementation(project(":polaris-extensions-idempotency"))
+ implementation(project(":polaris-runtime-service"))
+
+ testImplementation(project(":polaris-core"))
+ testImplementation(project(":polaris-relational-jdbc"))
+ testImplementation(project(":polaris-runtime-test-common"))
+
+ testImplementation("io.quarkus:quarkus-junit")
+ testImplementation("io.quarkus:quarkus-jdbc-h2")
+ testImplementation("io.rest-assured:rest-assured")
+}
+
+tasks.named("javadoc") { dependsOn("jandex") }
+
+tasks.withType<Test> {
+ if (System.getenv("AWS_REGION") == null) {
+ environment("AWS_REGION", "us-west-2")
Review Comment:
Removed.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3013688252
##########
extensions/idempotency/tests/src/test/java/org/apache/polaris/service/idempotency/IdempotencyFilterTest.java:
##########
Review Comment:
Done
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "singhpk234 (via GitHub)" <gi...@apache.org>.
singhpk234 commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2820070654
##########
polaris-core/src/main/java/org/apache/polaris/core/persistence/IdempotencyStore.java:
##########
@@ -154,6 +154,24 @@ ReserveResult reserve(
HeartbeatResult updateHeartbeat(
String realmId, String idempotencyKey, String executorId, Instant now);
+ /**
+ * Cancels (deletes) an in-progress idempotency reservation owned by {@code executorId}.
+ *
+ * <p>This is used for cases where an idempotency key was reserved but the request should not be
+ * tracked for replay (for example, 401/403/408/429 responses per the proposal). Implementations
+ * should only cancel the record if it is still in-progress (i.e., not finalized) and owned by the
+ * given executor.
+ *
+ * @param realmId logical tenant or realm identifier
+ * @param idempotencyKey application-provided idempotency key
+ * @param executorId identifier of the executor that owns the reservation
+ * @return {@code true} if a record was cancelled, {@code false} otherwise
+ */
+ default boolean cancelInProgressReservation(
+ String realmId, String idempotencyKey, String executorId) {
+ return false;
+ }
Review Comment:
Hmm this is a new interface change and technically a change in SPI should we seperate this in new pr ?
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStoreFactory.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.polaris.persistence.relational.jdbc.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStoreFactory;
+import org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+
+@ApplicationScoped
+@Identifier("relational-jdbc")
+public class RelationalJdbcIdempotencyStoreFactory implements IdempotencyStoreFactory {
+
+ @Inject Instance<DataSource> dataSource;
Review Comment:
IMHO we should not use the same datasource we use for normal flow, we can have a dedicated DS for idempotency operation
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025629799
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -67,13 +78,17 @@ public ReserveResult reserve(
insertMap.put(ModelIdempotencyRecord.RESPONSE_SUMMARY, null);
insertMap.put(ModelIdempotencyRecord.RESPONSE_HEADERS, null);
insertMap.put(ModelIdempotencyRecord.FINALIZED_AT, null);
- insertMap.put(ModelIdempotencyRecord.CREATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.UPDATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, Timestamp.from(now));
+ insertMap.put(ModelIdempotencyRecord.CREATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
+ insertMap.put(ModelIdempotencyRecord.UPDATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
+ insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
insertMap.put(ModelIdempotencyRecord.EXECUTOR_ID, executorId);
- insertMap.put(ModelIdempotencyRecord.EXPIRES_AT, Timestamp.from(expiresAt));
+ long ttlSeconds = Duration.between(now, expiresAt).getSeconds();
+ insertMap.put(
+ ModelIdempotencyRecord.EXPIRES_AT,
+ new SqlLiteral("CURRENT_TIMESTAMP + INTERVAL '" + ttlSeconds + "' SECOND"));
- List<Object> values = insertMap.values().stream().toList();
+ // Stream#toList returns an unmodifiable list and rejects nulls; these columns are nullable.
+ List<Object> values = new ArrayList<>(insertMap.values());
Review Comment:
Fixed. The JDBC reserve() now checks if the conflicting record is expired.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3025472211
##########
extensions/idempotency/tests/build.gradle.kts:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+plugins {
+ alias(libs.plugins.quarkus)
+ id("org.kordamp.gradle.jandex")
+ id("polaris-runtime")
+}
+
+dependencies {
+ implementation(platform(libs.quarkus.bom))
+ implementation("io.quarkus:quarkus-rest-jackson")
+
+ implementation(project(":polaris-extensions-idempotency"))
+ implementation(project(":polaris-runtime-service"))
+
+ testImplementation(project(":polaris-core"))
+ testImplementation(project(":polaris-relational-jdbc"))
+ testImplementation(project(":polaris-runtime-test-common"))
+
+ testImplementation("io.quarkus:quarkus-junit")
+ testImplementation("io.quarkus:quarkus-jdbc-h2")
+ testImplementation("io.rest-assured:rest-assured")
+}
+
+tasks.named("javadoc") { dependsOn("jandex") }
+
+tasks.withType<Test> {
+ if (System.getenv("AWS_REGION") == null) {
+ environment("AWS_REGION", "us-west-2")
Review Comment:
Do we use S3 in these tests?
##########
extensions/idempotency/build.gradle.kts:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+plugins {
+ id("org.kordamp.gradle.jandex")
+ id("polaris-server")
+}
+
+dependencies {
+ implementation(project(":polaris-core"))
+ implementation(project(":polaris-api-management-model"))
+ implementation(project(":polaris-runtime-service"))
+
+ compileOnly(platform(libs.quarkus.bom))
+ compileOnly("io.quarkus:quarkus-rest-jackson")
+ compileOnly("io.quarkus:quarkus-reactive-routes")
Review Comment:
`compileOnly` feels odd in this context. If we need it to build, I suppose it will be needed in runtime too, but with `compileOnly` declaration we rely on the runtime module to re-include this dependency... or did I miss something? 🤔 (some for other dependencies below).
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStore.java:
##########
@@ -67,13 +78,17 @@ public ReserveResult reserve(
insertMap.put(ModelIdempotencyRecord.RESPONSE_SUMMARY, null);
insertMap.put(ModelIdempotencyRecord.RESPONSE_HEADERS, null);
insertMap.put(ModelIdempotencyRecord.FINALIZED_AT, null);
- insertMap.put(ModelIdempotencyRecord.CREATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.UPDATED_AT, Timestamp.from(now));
- insertMap.put(ModelIdempotencyRecord.HEARTBEAT_AT, Timestamp.from(now));
+ insertMap.put(ModelIdempotencyRecord.CREATED_AT, new SqlLiteral("CURRENT_TIMESTAMP"));
Review Comment:
Is `CURRENT_TIMESTAMP` standard across all our JDBC backends?
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyStoreProducer.java:
##########
@@ -0,0 +1,43 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.Produces;
+import jakarta.inject.Singleton;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.persistence.PersistenceConfiguration;
+
+@Singleton
+public class IdempotencyStoreProducer {
+
+ @Produces
+ @Singleton
+ public IdempotencyStore idempotencyStore(
+ PersistenceConfiguration config, @Any Instance<IdempotencyStore> idempotencyStores) {
+ Instance<IdempotencyStore> selected =
+ idempotencyStores.select(Identifier.Literal.of(config.type()));
Review Comment:
Do we always have to use the same `type` value for the `IdempotencyStore` as for Persistence?
It feels a bit too restrictive to me 🤔 .... still, it is not a blocker for this PR from my POV.
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfigurationValidator.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.StartupEvent;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.time.Duration;
+
+@ApplicationScoped
+public class IdempotencyConfigurationValidator {
+
+ @Inject IdempotencyConfiguration configuration;
+
+ void validateOnStart(@Observes StartupEvent ignored) {
+ if (!configuration.enabled()) {
+ return;
+ }
+
+ requirePositive("polaris.idempotency.ttl-seconds", configuration.ttl());
Review Comment:
Can this be done via annotations on the config class? Cf. https://quarkus.io/guides/validation
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "snazy (via GitHub)" <gi...@apache.org>.
snazy commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-4187372302
I have posted a summary of the open design concerns to the [dev mailing list](https://lists.apache.org/thread/93vcv3gcn5gfbmh16rwx737j88fy055b). The short version:
- The idempotency binding does not include the caller's identity. The filter replays before resource-level authorization runs. This is a full authorization bypass.
- Phase 1 (strip credentials, [offline decided](https://github.com/apache/polaris/pull/3803#issuecomment-4180969838)) produces responses that are operationally broken in Polaris's credential-vending deployment model.
- Phase 2 (re-vend on replay, [offline decided](https://github.com/apache/polaris/pull/3803#issuecomment-4180969838)) requires reimplementing the catalog handler's authorization and credential vending logic. Incompatible with Phase 1's generic filter design.
- The operational overhead (3+ DB round-trips per mutation, write-hot table on the catalog RDBMS) has not been benchmarked.
I am not going to do further code-level reviews on this PR until these design-level concerns are resolved on the mailing list.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2868473946
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStoreFactory.java:
##########
@@ -0,0 +1,51 @@
+/*
+ * 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.polaris.persistence.relational.jdbc.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.literal.NamedLiteral;
+import jakarta.inject.Inject;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStoreFactory;
+import org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+
+@ApplicationScoped
+@Identifier("relational-jdbc")
Review Comment:
Yes, nosql will be in followups
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2876195126
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/idempotency/RelationalJdbcIdempotencyStoreFactory.java:
##########
@@ -0,0 +1,51 @@
+/*
+ * 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.polaris.persistence.relational.jdbc.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.literal.NamedLiteral;
+import jakarta.inject.Inject;
+import java.sql.SQLException;
+import javax.sql.DataSource;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStoreFactory;
+import org.apache.polaris.persistence.relational.jdbc.RelationalJdbcConfiguration;
+
+@ApplicationScoped
+@Identifier("relational-jdbc")
+public class RelationalJdbcIdempotencyStoreFactory implements IdempotencyStoreFactory {
+
+ @Inject Instance<DataSource> dataSource;
+ @Inject @Any Instance<DataSource> anyDataSources;
+ @Inject RelationalJdbcConfiguration relationalJdbcConfiguration;
+
+ @Override
+ public IdempotencyStore create() {
+ try {
+ Instance<DataSource> idempotencyDs = anyDataSources.select(NamedLiteral.of("idempotency"));
+ DataSource ds = idempotencyDs.isResolvable() ? idempotencyDs.get() : dataSource.get();
Review Comment:
Good point! I removed the silent fallback. If the idempotency datasource isn’t configured we now log that we’re using the default datasource, and if it’s misconfigured (multiple matches) we fail fast.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,736 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtl())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to finalize idempotency record; replay may be unavailable until a later retry or reconciliation");
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatInterval().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return !NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+ return false;
+ }
+
+ private static boolean shouldCancelInProgressReservation(int httpStatus) {
+ return httpStatus >= 500 || NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+
+ private static void warnThrottled(Throwable t, String message) {
+ long now = System.currentTimeMillis();
+ long last = LAST_WARN_AT_MS.get();
+ if (now - last >= WARN_THROTTLE_MS && LAST_WARN_AT_MS.compareAndSet(last, now)) {
+ LOG.warn(message, t);
+ } else {
+ LOG.debug(message, t);
+ }
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
+ replay.entity(existing.responseSummary());
+ }
+ return replay.build();
+ }
+
+ private Uni<IdempotencyRecord> waitForFinalized(String realmId, String key, Instant deadline) {
+ // Start with a small delay for low-latency replays, then exponentially back off (capped below)
+ // to avoid tight polling when the original attempt takes longer.
+ return pollUntilFinalized(realmId, key, deadline, 25L);
+ }
+
+ private Uni<IdempotencyRecord> pollUntilFinalized(
+ String realmId, String key, Instant deadline, long delayMs) {
+ return Uni.createFrom()
+ .item(() -> store.load(realmId, key))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ opt -> {
+ if (opt.isPresent() && opt.get().isFinalized()) {
+ return Uni.createFrom().item(opt.get());
+ }
+ if (!clock.instant().isBefore(deadline)) {
+ return Uni.createFrom()
+ .failure(new TimeoutException("Timed out waiting for finalize"));
+ }
+ long nextDelayMs = Math.min(500L, Math.max(25L, delayMs * 2));
+ return Uni.createFrom()
+ .nullItem()
+ .onItem()
+ .delayIt()
+ .by(Duration.ofMillis(delayMs))
+ .onItem()
+ .transformToUni(
+ ignored -> pollUntilFinalized(realmId, key, deadline, nextDelayMs));
+ });
+ }
+
+ private static boolean isMutatingMethod(String method) {
+ if (method == null) {
+ return false;
+ }
+ switch (method.toUpperCase(Locale.ROOT)) {
+ case "POST":
+ case "PUT":
+ case "PATCH":
+ case "DELETE":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isIcebergMutationEndpoint(ContainerRequestContext rc) {
+ // Best-effort: rely on the matched JAX-RS resource method rather than path heuristics so we
+ // only apply idempotency to endpoints implemented by the Iceberg REST catalog adapter. If the
+ // matched resource/method isn't available, we return false (no idempotency).
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx == null) {
+ return false;
+ }
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info == null) {
+ return false;
+ }
+ if (info.getResourceClass() != IcebergCatalogAdapter.class) {
+ return false;
+ }
+ Method m = info.getResourceMethod();
+ if (m == null) {
+ return false;
+ }
+ String name = m.getName();
+ // Mutation endpoints that accept Idempotency-Key in the Iceberg REST API.
+ return name.equals("createNamespace")
+ || name.equals("dropNamespace")
+ || name.equals("updateProperties")
+ || name.equals("createTable")
+ || name.equals("registerTable")
+ || name.equals("updateTable")
+ || name.equals("dropTable")
+ || name.equals("renameTable")
+ || name.equals("createView")
+ || name.equals("replaceView")
+ || name.equals("dropView")
+ || name.equals("renameView")
+ || name.equals("commitTransaction");
+ } catch (Throwable ignored) {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true only for Polaris-managed (INTERNAL) catalogs for Iceberg REST routes.
+ *
+ * <p>This is a best-effort guard: if we can't determine catalog type, we default to "not
+ * internal" and treat idempotency as a no-op.
+ */
+ private boolean isPolarisManagedInternalIcebergCatalogRequest(
+ String path, PolarisPrincipal principal) {
+ if (path == null || !path.startsWith("v1/")) {
+ // Non-Iceberg REST paths: leave existing behavior unchanged (scopes/mutating method gating).
+ return true;
+ }
+
+ // Expected Iceberg REST shape: v1/{prefix}/...
+ String[] parts = path.split("/", 3);
+ if (parts.length < 3) {
+ return false;
+ }
+ String prefix = parts[1];
+ if (prefix == null || prefix.isBlank()) {
+ return false;
+ }
+
+ final String catalogName;
+ try {
+ catalogName = prefixParser.prefixToCatalogName(prefix);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to parse Iceberg REST catalog prefix for idempotency gating");
+ return false;
+ }
+
+ final Resolver resolver;
+ try {
+ resolver = resolverFactory.createResolver(principal, catalogName);
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to create resolver for idempotency internal-catalog gating");
+ return false;
+ }
+
+ ResolverStatus status;
+ try {
+ status = resolver.resolveAll();
+ } catch (RuntimeException e) {
+ LOG.debugf(e, "Failed to resolve catalog for idempotency internal-catalog gating");
+ return false;
+ }
+ if (!ResolverStatus.StatusEnum.SUCCESS.equals(status.getStatus())) {
+ LOG.debugf(
+ "Resolver status %s for idempotency internal-catalog gating; treating as non-internal",
+ status.getStatus());
+ return false;
+ }
+
+ ResolvedPolarisEntity resolved = resolver.getResolvedReferenceCatalog();
+ CatalogEntity catalogEntity = resolved == null ? null : CatalogEntity.of(resolved.getEntity());
+ return catalogEntity != null
+ && Catalog.TypeEnum.INTERNAL.equals(catalogEntity.getCatalogType());
+ }
+
+ private static String normalizeResourceId(ContainerRequestContext rc) {
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String path = rc.getUriInfo().getPath();
+ return path;
+ }
Review Comment:
Fixed.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2876193747
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithName("ttl-seconds")
+ @WithDefault("PT5M")
+ Duration ttl();
+
+ /**
+ * Additional grace added to {@link #ttl()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ *
+ * <p>Examples: {@code PT0S}, {@code 10S}.
+ */
+ @WithName("ttl-grace-seconds")
+ @WithDefault("PT0S")
+ Duration ttlGrace();
+
+ /**
+ * Executor identifier to store alongside reservations (e.g. pod/instance id).
+ *
+ * <p>If unset or blank, the service derives a best-effort identifier from environment/host info
+ * (for example {@code $POD_NAME} / {@code $HOSTNAME} plus the process id).
+ *
+ * <p>In multi-node deployments, executor ids must be unique per replica.
+ */
+ Optional<String> executorId();
+
+ /**
+ * Maximum time to wait for an in-progress idempotency key to finalize before returning a
+ * retryable response.
+ */
+ @WithName("in-progress-wait-seconds")
+ @WithDefault("PT30S")
+ Duration inProgressWait();
+
+ /**
+ * Lease TTL for considering an in-progress owner "active" based on {@code heartbeatAt}.
+ *
+ * <p>If a duplicate observes {@code now - heartbeatAt > leaseTtl()}, the owner is treated as
+ * stale and the server should not wait indefinitely.
+ */
+ @WithName("lease-ttl-seconds")
+ @WithDefault("PT25S")
+ Duration leaseTtl();
+
+ /**
+ * Response headers that are persisted and replayed (exact names).
+ *
+ * <p>Only the first header value is stored and replayed.
+ */
+ @WithDefault("Content-Type")
+ List<String> responseHeaderAllowlist();
+
+ /**
+ * Enable periodic heartbeats while a request is in progress.
+ *
+ * <p>Recommended for multi-node deployments.
+ */
+ @WithDefault("false")
+ boolean heartbeatEnabled();
+
+ /**
+ * Heartbeat interval while a request is in progress.
+ *
+ * <p>Examples: {@code PT5S}, {@code 1S}.
+ *
+ * <p>In multi-node deployments, this should be shorter than {@link #leaseTtl()}.
+ */
+ @WithName("heartbeat-interval-seconds")
+ @WithDefault("PT5S")
+ Duration heartbeatInterval();
+
+ /**
+ * Enable periodic purge of expired idempotency records.
+ *
+ * <p>In multi-node deployments, enabling purge on all replicas may cause unnecessary contention.
+ */
+ @WithDefault("false")
+ boolean purgeEnabled();
+
+ /**
+ * Optional executor id that is allowed to run purge.
+ *
+ * <p>When set, only the node whose resolved {@link #executorId()} matches this value will run the
+ * purge timer. This can be used to avoid "thundering herd" behavior in multi-node deployments.
+ */
+ Optional<String> purgeExecutorId();
+
+ /**
+ * Purge interval.
+ *
+ * <p>Examples: {@code PT1M}, {@code 60S}.
+ */
+ @WithName("purge-interval-seconds")
+ @WithDefault("PT1M")
+ Duration purgeInterval();
+
+ /**
+ * Purge records expired strictly before (now - grace).
+ *
+ * <p>Allows keeping just-expired keys around a bit longer to tolerate clock skew.
+ */
+ @WithName("purge-grace-seconds")
+ @WithDefault("PT0S")
Review Comment:
Fixed
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfiguration.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.config.ConfigMapping;
+import io.smallrye.config.WithDefault;
+import io.smallrye.config.WithName;
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * Idempotency configuration.
+ *
+ * <p>Response replay persists and replays the full HTTP response entity for completed requests.
+ * Responses are not truncated, because truncation would break clients. Any practical size limits
+ * are therefore imposed by the chosen {@code IdempotencyStore} implementation / backing database.
+ * If persistence fails (for example due to store limits), replay may be unavailable for that key.
+ *
+ * <h2>Single-node vs multi-node deployments</h2>
+ *
+ * <p>In a multi-node deployment (multiple Polaris replicas), idempotency records must be shared
+ * across nodes via a durable store (for example JDBC + Postgres). Each node must use a different
+ * executor id so ownership/heartbeats can be attributed correctly.
+ *
+ * <p>Heartbeats should be enabled in multi-node deployments to prevent long-running requests from
+ * looking stale after routing changes, pod restarts, or transient pauses.
+ *
+ * <p>Purge is a best-effort background cleanup. In multi-node deployments, enabling purge on every
+ * replica can create unnecessary contention; consider running purge in only one replica or via an
+ * external scheduled job.
+ */
+@ConfigMapping(prefix = "polaris.idempotency")
+public interface IdempotencyConfiguration {
+
+ /**
+ * Allowlist of endpoint scopes where idempotency is enforced.
+ *
+ * <p>This is an optional safety/rollout control: it limits idempotency to specific endpoint
+ * prefixes and provides a stable {@link Scope#operationType()} for request binding.
+ *
+ * <p>If empty, the filter falls back to applying idempotency for Iceberg REST catalog mutating
+ * endpoints only.
+ */
+ List<Scope> scopes();
+
+ /** Enable HTTP idempotency at the request/response filter layer. */
+ @WithDefault("false")
+ boolean enabled();
+
+ /** Request header name containing the client-provided idempotency key. */
+ @WithDefault("Idempotency-Key")
+ String keyHeader();
+
+ /**
+ * Default TTL for newly reserved keys.
+ *
+ * <p>Examples: {@code PT5M}, {@code 300S}.
+ */
+ @WithName("ttl-seconds")
+ @WithDefault("PT5M")
+ Duration ttl();
+
+ /**
+ * Additional grace added to {@link #ttl()} when reserving keys.
+ *
+ * <p>This extends retention slightly to tolerate clock skew and queued retries while keeping the
+ * advertised lifetime unchanged.
+ *
+ * <p>Examples: {@code PT0S}, {@code 10S}.
+ */
+ @WithName("ttl-grace-seconds")
+ @WithDefault("PT0S")
+ Duration ttlGrace();
+
+ /**
+ * Executor identifier to store alongside reservations (e.g. pod/instance id).
+ *
+ * <p>If unset or blank, the service derives a best-effort identifier from environment/host info
+ * (for example {@code $POD_NAME} / {@code $HOSTNAME} plus the process id).
+ *
+ * <p>In multi-node deployments, executor ids must be unique per replica.
+ */
+ Optional<String> executorId();
+
+ /**
+ * Maximum time to wait for an in-progress idempotency key to finalize before returning a
+ * retryable response.
+ */
+ @WithName("in-progress-wait-seconds")
+ @WithDefault("PT30S")
+ Duration inProgressWait();
+
+ /**
+ * Lease TTL for considering an in-progress owner "active" based on {@code heartbeatAt}.
+ *
+ * <p>If a duplicate observes {@code now - heartbeatAt > leaseTtl()}, the owner is treated as
+ * stale and the server should not wait indefinitely.
+ */
+ @WithName("lease-ttl-seconds")
+ @WithDefault("PT25S")
+ Duration leaseTtl();
+
+ /**
+ * Response headers that are persisted and replayed (exact names).
+ *
+ * <p>Only the first header value is stored and replayed.
+ */
+ @WithDefault("Content-Type")
+ List<String> responseHeaderAllowlist();
+
+ /**
+ * Enable periodic heartbeats while a request is in progress.
+ *
+ * <p>Recommended for multi-node deployments.
+ */
+ @WithDefault("false")
+ boolean heartbeatEnabled();
+
+ /**
+ * Heartbeat interval while a request is in progress.
+ *
+ * <p>Examples: {@code PT5S}, {@code 1S}.
+ *
+ * <p>In multi-node deployments, this should be shorter than {@link #leaseTtl()}.
+ */
+ @WithName("heartbeat-interval-seconds")
+ @WithDefault("PT5S")
+ Duration heartbeatInterval();
+
+ /**
+ * Enable periodic purge of expired idempotency records.
+ *
+ * <p>In multi-node deployments, enabling purge on all replicas may cause unnecessary contention.
+ */
+ @WithDefault("false")
Review Comment:
I updated InMemoryIdempotencyStore to opportunistically evict expired records (and periodically purge on reserve), so it won’t grow unbounded even if purgeEnabled=false.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyConfigurationValidator.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import jakarta.annotation.PostConstruct;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import java.time.Duration;
+
+@ApplicationScoped
+public class IdempotencyConfigurationValidator {
+
+ @Inject IdempotencyConfiguration configuration;
+
+ @PostConstruct
+ void validate() {
Review Comment:
I changed it to run on Quarkus startup (StartupEvent), so the validation always executes when the app boots.
##########
persistence/relational-jdbc/src/main/java/org/apache/polaris/persistence/relational/jdbc/models/ModelIdempotencyRecord.java:
##########
@@ -42,6 +44,9 @@ public interface ModelIdempotencyRecord extends Converter<IdempotencyRecord> {
String TABLE_NAME = "idempotency_records";
+ ObjectMapper RESPONSE_HEADERS_MAPPER = new ObjectMapper();
Review Comment:
Right, we don’t need two mappers. I centralized header JSON (de)serialization into one internal helper and removed the ObjectMapper constant from ModelIdempotencyRecord.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3013687426
##########
extensions/idempotency/build.gradle.kts:
##########
Review Comment:
Sounds good. Moved to `extensions/idempotency`
##########
runtime/service/src/main/java/org/apache/polaris/service/config/ServiceProducers.java:
##########
@@ -214,13 +216,32 @@ public FileIOFactory fileIOFactory(
}
@Produces
- @Singleton // used in instanceof checks
+ public PolarisEventListener polarisEventListener(
+ PolarisEventListenerConfiguration config,
+ @Any Instance<PolarisEventListener> polarisEventListeners) {
+ return polarisEventListeners.select(Identifier.Literal.of(config.type())).get();
+ }
+
+ @Produces
public MetaStoreManagerFactory metaStoreManagerFactory(
PersistenceConfiguration config,
@Any Instance<MetaStoreManagerFactory> metaStoreManagerFactories) {
return metaStoreManagerFactories.select(Identifier.Literal.of(config.type())).get();
}
+ @Produces
+ @Singleton
+ public IdempotencyStore idempotencyStore(
Review Comment:
Done
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2831219816
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.time.Clock;
+import java.time.Instant;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+
+ void onStart(@Observes StartupEvent event) {
+ if (!configuration.enabled() || !configuration.purgeEnabled()) {
+ return;
+ }
+ long intervalMs = Math.max(1000L, configuration.purgeIntervalSeconds() * 1000L);
+ purgeTimerId = vertx.setPeriodic(intervalMs, ignored -> purgeOnce());
Review Comment:
Will this run `purgeOnce()` on a Vert.x thread (not good for blocking tasks) or on an executor thread?
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,636 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ if (principal != null && !isPolarisManagedInternalIcebergCatalogRequest(rc, principal)) {
+ // for federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt =
+ now.plusSeconds(Math.max(0L, configuration.ttlSeconds()))
+ .plusSeconds(Math.max(0L, configuration.ttlGraceSeconds()));
+
+ final IdempotencyStore.ReserveResult r;
+ try {
+ r =
+ store.reserve(
Review Comment:
It is an anti-pattern to call a potentially blocking method (I/O) from an async filter.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,636 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
Review Comment:
Would it work if we had a CDI producer method conditionally emitting a bean with `@ServerRequestFilter`? The idea is to avoid having a filter at all if `configuration.enabled()` is `false`.
##########
runtime/service/src/main/java/org/apache/polaris/service/config/ServiceProducers.java:
##########
@@ -217,6 +219,20 @@ public MetaStoreManagerFactory metaStoreManagerFactory(
return metaStoreManagerFactories.select(Identifier.Literal.of(config.type())).get();
}
+ @Produces
+ @ApplicationScoped
+ public IdempotencyStoreFactory idempotencyStoreFactory(
+ PersistenceConfiguration config,
+ @Any Instance<IdempotencyStoreFactory> idempotencyFactories) {
+ return idempotencyFactories.select(Identifier.Literal.of(config.type())).get();
+ }
+
+ @Produces
+ @ApplicationScoped
+ public IdempotencyStore idempotencyStore(IdempotencyStoreFactory factory) {
+ return factory.create();
Review Comment:
Do we really need this factory? The `create()` method does not take any parameters, so whatever is injected into the factory by CDI could also be injected into the `IdempotencyStore` implementation.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2978294718
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,777 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.IdempotencyStore.HeartbeatResult;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.logging.Logger;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+ private static final Logger LOG = Logger.getLogger(IdempotencyFilter.class);
+
+ private static final Set<Integer> NEVER_FINALIZE_STATUSES = Set.of(401, 403, 408, 429);
+
+ private static final long WARN_THROTTLE_MS = 60_000L;
+ private static final AtomicLong LAST_WARN_AT_MS = new AtomicLong(0L);
+
+ private static final int FINALIZE_MAX_RETRIES = 3;
+ private static final long FINALIZE_RETRY_BASE_MS = 200;
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ //
+ // This check is best-effort because request-to-resource matching metadata may be unavailable
+ // in some cases; if we can't confidently identify an Iceberg mutation endpoint we fail closed
+ // (treat idempotency as a no-op) to avoid false positives.
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ // Use path only to avoid accidental mismatches from query ordering/irrelevant parameters.
+ String resourceId = rc.getUriInfo().getPath();
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttl()).plus(configuration.ttlGrace());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. ttlGrace pads the check to tolerate clock skew
+ // between nodes. Full reconciliation/takeover is a follow-up.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ Duration staleThreshold =
+ configuration.leaseTtl().plus(configuration.ttlGrace());
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow).compareTo(staleThreshold)
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline = clock.instant().plus(configuration.inProgressWait());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (shouldCancelInProgressReservation(status)) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException e) {
+ warnThrottled(
+ e,
+ "Failed to cancel in-progress idempotency reservation; replay may be unavailable");
+ }
+ });
+ }
+ return;
+ }
+ final String body =
+ boundedResponseSummary(response, objectMapper, configuration.responseSummaryMaxBytes());
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ for (int attempt = 1; attempt <= FINALIZE_MAX_RETRIES; attempt++) {
+ try {
+ store.finalizeRecord(
+ realmId, key, executorId(), status, null, body, headers, now);
+ return;
+ } catch (RuntimeException e) {
+ if (attempt < FINALIZE_MAX_RETRIES) {
+ LOG.debugf(
+ e,
+ "Finalize attempt %d/%d failed for key %s; retrying",
+ attempt,
+ FINALIZE_MAX_RETRIES,
+ key);
+ try {
+ Thread.sleep(FINALIZE_RETRY_BASE_MS * attempt);
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ LOG.warn(
+ "Interrupted while retrying finalize; record may remain in-progress", e);
+ return;
+ }
+ } else {
+ LOG.warnf(
+ e,
+ "Failed to finalize idempotency record after %d attempts for key %s; "
+ + "record will remain in-progress until TTL expiry",
+ FINALIZE_MAX_RETRIES,
+ key);
+ }
+ }
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatInterval().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ tid -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ HeartbeatResult hr =
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ if (hr != HeartbeatResult.UPDATED) {
+ vertx.cancelTimer(tid);
+ LOG.debugf("Stopping heartbeat for key %s: %s", key, hr);
+ }
+ } catch (RuntimeException e) {
+ warnThrottled(e, "Heartbeat failed; will retry on next interval");
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
+ if (httpStatus == 200 || httpStatus == 201 || httpStatus == 204) {
+ return true;
+ }
+ if (httpStatus >= 400 && httpStatus < 500) {
+ return !NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+ return false;
+ }
+
+ private static boolean shouldCancelInProgressReservation(int httpStatus) {
+ return httpStatus >= 500 || NEVER_FINALIZE_STATUSES.contains(httpStatus);
+ }
+
+ private static void warnThrottled(Throwable t, String message) {
+ long now = System.currentTimeMillis();
+ long last = LAST_WARN_AT_MS.get();
+ if (now - last >= WARN_THROTTLE_MS && LAST_WARN_AT_MS.compareAndSet(last, now)) {
+ LOG.warn(message, t);
+ } else {
+ LOG.debug(message, t);
+ }
+ }
+
+ /**
+ * Normalize and validate the idempotency key.
+ *
+ * <p>Idempotency keys must be UUIDv7 in string form; normalizing to {@link UUID#toString()}
+ * avoids accidental mismatches caused by casing.
+ */
+ private static String normalizeIdempotencyKey(String rawKey) {
+ if (rawKey == null) {
+ return null;
+ }
+ String trimmed = rawKey.trim();
+ // Iceberg REST OpenAPI expects 36-char UUID strings.
+ if (trimmed.length() != 36) {
+ return null;
+ }
+ try {
+ UUID uuid = UUID.fromString(trimmed);
+ return uuid.version() == 7 ? uuid.toString() : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private Response replayResponse(IdempotencyRecord existing) {
+ Response.ResponseBuilder replay =
+ Response.status(existing.httpStatus() == null ? 200 : existing.httpStatus());
+ replay.header("X-Idempotency-Replayed", "true");
+ applyReplayedHeaders(replay, existing.responseHeaders());
+ if (existing.responseSummary() != null) {
Review Comment:
Good catch. I fixed this to cancel the reservation instead of finalizing with an empty body. This way the duplicate request executes fresh and returns a correct response, rather than replaying a broken one with no body.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r3028620771
##########
extensions/idempotency/src/main/java/org/apache/polaris/service/idempotency/IdempotencyStoreProducer.java:
##########
@@ -0,0 +1,43 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.smallrye.common.annotation.Identifier;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.Produces;
+import jakarta.inject.Singleton;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.persistence.PersistenceConfiguration;
+
+@Singleton
+public class IdempotencyStoreProducer {
+
+ @Produces
+ @Singleton
+ public IdempotencyStore idempotencyStore(
+ PersistenceConfiguration config, @Any Instance<IdempotencyStore> idempotencyStores) {
+ Instance<IdempotencyStore> selected =
+ idempotencyStores.select(Identifier.Literal.of(config.type()));
Review Comment:
thx!
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-3957353973
@snazy Thanks for the review! I’ve addressed all of your comments. Could you please take another look when you have a chance? If everything looks good, I’ll split this into smaller PRs to make it easier to review and also to address @singhpk234 's request https://github.com/apache/polaris/pull/3803/#issuecomment-3924584875
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "huaxingao (via GitHub)" <gi...@apache.org>.
huaxingao commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2868472163
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,700 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttlSeconds()).plus(configuration.ttlGraceSeconds());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtlSeconds())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline =
+ clock.instant().plus(configuration.inProgressWaitSeconds());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.cancelInProgressReservation(realmId, key, executorId());
+ } catch (RuntimeException ignored) {
+ // Best-effort.
+ }
+ });
+ }
+ return;
+ }
+ final String body = responseEntityAsString(response, objectMapper);
+ final Map<String, String> headers =
+ headerSnapshot(response, configuration.responseHeaderAllowlist());
+ Instant now = clock.instant();
+
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.finalizeRecord(realmId, key, executorId(), status, null, body, headers, now);
+ } catch (RuntimeException ignored) {
+ // Best-effort: the main request already completed. If this fails, replay may be
+ // unavailable until a later retry or reconciliation.
+ }
+ });
+ }
+
+ private void maybeStartHeartbeat(ContainerRequestContext rc, String realmId, String key) {
+ if (!configuration.heartbeatEnabled()) {
+ return;
+ }
+ long intervalMs = configuration.heartbeatIntervalSeconds().toMillis();
+ long timerId =
+ vertx.setPeriodic(
+ intervalMs,
+ ignored -> {
+ Infrastructure.getDefaultWorkerPool()
+ .execute(
+ () -> {
+ try {
+ store.updateHeartbeat(realmId, key, executorId(), clock.instant());
+ } catch (RuntimeException ignored2) {
+ // Best-effort.
+ }
+ });
+ });
+ rc.setProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID, timerId);
+ }
+
+ private String executorId() {
+ String cached = resolvedExecutorId;
+ if (cached != null) {
+ return cached;
+ }
+ String fromConfig = configuration.executorId().orElse(null);
+ if (fromConfig != null && !fromConfig.isBlank()) {
+ resolvedExecutorId = fromConfig;
+ return fromConfig;
+ }
+ String computed = defaultExecutorId();
+ resolvedExecutorId = computed;
+ return computed;
+ }
+
+ private static String defaultExecutorId() {
+ String pid = String.valueOf(ProcessHandle.current().pid());
+ String node =
+ firstNonBlank(
+ System.getenv("POD_NAME"), System.getenv("HOSTNAME"), System.getenv("NODE_NAME"));
+ if (node != null) {
+ return node + "-" + pid;
+ }
+ try {
+ return InetAddress.getLocalHost().getHostName() + "-" + pid;
+ } catch (Exception e) {
+ return "pid-" + pid;
+ }
+ }
+
+ private static String firstNonBlank(String... values) {
+ if (values == null) {
+ return null;
+ }
+ for (String v : values) {
+ if (v != null && !v.isBlank()) {
+ return v;
+ }
+ }
+ return null;
+ }
+
+ private void stopHeartbeat(ContainerRequestContext request) {
+ Object tid = request.getProperty(PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID);
+ if (tid instanceof Long l) {
+ vertx.cancelTimer(l);
+ }
+ }
+
+ private IdempotencyConfiguration.Scope matchScope(ContainerRequestContext rc) {
+ String method = rc.getMethod();
+ String path = rc.getUriInfo().getPath();
+ if (method == null || path == null) {
+ return null;
+ }
+ String normalizedPath = path.startsWith("/") ? path.substring(1) : path;
+ for (IdempotencyConfiguration.Scope s : configuration.scopes()) {
+ if (s == null) {
+ continue;
+ }
+ if (!method.equalsIgnoreCase(s.method())) {
+ continue;
+ }
+ String prefix = s.pathPrefix();
+ if (prefix == null || prefix.isBlank()) {
+ continue;
+ }
+ String normalizedPrefix = prefix.startsWith("/") ? prefix.substring(1) : prefix;
+ if (normalizedPath.startsWith(normalizedPrefix)) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static String normalizeOperationType(ContainerRequestContext rc) {
+ // Fallback for when scopes are not configured: use the matched JAX-RS resource method
+ // (stable across resource IDs), falling back to the HTTP method if unavailable.
+ try {
+ ResteasyReactiveRequestContext ctx = CurrentRequestManager.get();
+ if (ctx != null) {
+ ResteasyReactiveResourceInfo info = ctx.getResteasyReactiveResourceInfo();
+ if (info != null) {
+ Class<?> resourceClass = info.getResourceClass();
+ Method resourceMethod = info.getResourceMethod();
+ if (resourceClass != null && resourceMethod != null) {
+ return resourceClass.getName() + "#" + resourceMethod.getName();
+ }
+ }
+ }
+ } catch (Throwable ignored) {
+ // Best-effort; fall back below.
+ }
+ return rc.getMethod().toLowerCase(Locale.ROOT);
+ }
+
+ private static boolean shouldFinalize(int httpStatus) {
+ // - Finalize & replay: 200, 201, 204, and deterministic terminal 4xx
+ // - Never finalize (not stored/replayed): 401, 403, 408, 429, all 5xx
Review Comment:
Fixed.
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,700 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ *
+ * <p>Replayed responses use the full persisted response entity; responses are not truncated.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ private volatile String resolvedExecutorId;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
+ }
+
+ SecurityContext securityContext = rc.getSecurityContext();
+
+ String rawKey = rc.getHeaderString(configuration.keyHeader());
+ if (rawKey == null || rawKey.isBlank()) {
+ return Uni.createFrom().nullItem();
+ }
+ String key = normalizeIdempotencyKey(rawKey);
+ if (key == null) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 400,
+ "idempotency_key_invalid",
+ "Idempotency-Key must be a UUIDv7 string (RFC 9562)"));
+ }
+
+ boolean scopedMode = !configuration.scopes().isEmpty();
+ if (!scopedMode) {
+ // Without an explicit scope allowlist, only apply idempotency to Iceberg REST catalog
+ // mutating endpoints under /v1/{prefix}/...
+ if (!isMutatingMethod(rc.getMethod()) || !isIcebergMutationEndpoint(rc)) {
+ return Uni.createFrom().nullItem();
+ }
+ }
+
+ RealmContext realmContext = (RealmContext) rc.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ // RealmContextFilter should run before this; treat missing realm as a server error.
+ return Uni.createFrom().item(error(500, "MissingRealmContext", "Missing realm context"));
+ }
+
+ // If scopes are configured, apply idempotency only to matching endpoints and use the configured
+ // operationType for stable binding.
+ IdempotencyConfiguration.Scope scope = matchScope(rc);
+ if (scope == null && scopedMode) {
+ return Uni.createFrom().nullItem();
+ }
+
+ PolarisPrincipal principal =
+ securityContext != null && securityContext.getUserPrincipal() instanceof PolarisPrincipal p
+ ? p
+ : null;
+ final String requestPath = rc.getUriInfo().getPath();
+ Uni<Boolean> internalCatalogCheck =
+ principal == null
+ ? Uni.createFrom().item(true)
+ : Uni.createFrom()
+ .item(() -> isPolarisManagedInternalIcebergCatalogRequest(requestPath, principal))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onFailure()
+ .recoverWithItem(false);
+
+ String realmId = realmContext.getRealmIdentifier();
+ String operationType = scope == null ? normalizeOperationType(rc) : scope.operationType();
+ String resourceId = normalizeResourceId(rc, scope != null);
+
+ Instant now = clock.instant();
+ Instant expiresAt = now.plus(configuration.ttlSeconds()).plus(configuration.ttlGraceSeconds());
+
+ return internalCatalogCheck
+ .onItem()
+ .transformToUni(
+ internal -> {
+ if (!internal) {
+ // For federated/external catalogs, Polaris may not enforce idempotency end-to-end,
+ // so treat Idempotency-Key as a no-op (do not reserve/finalize/replay).
+ return Uni.createFrom().nullItem();
+ }
+ return Uni.createFrom()
+ .item(
+ () ->
+ store.reserve(
+ realmId,
+ key,
+ operationType,
+ resourceId,
+ expiresAt,
+ executorId(),
+ now))
+ .runSubscriptionOn(Infrastructure.getDefaultWorkerPool())
+ .onItem()
+ .transformToUni(
+ r -> {
+ if (r.type() == IdempotencyStore.ReserveResultType.OWNED) {
+ rc.setProperty(PROP_IDEMPOTENCY_KEY, key);
+ rc.setProperty(PROP_IDEMPOTENCY_OPERATION, operationType);
+ rc.setProperty(PROP_IDEMPOTENCY_RESOURCE, resourceId);
+ rc.setProperty(PROP_IDEMPOTENCY_OWNED, Boolean.TRUE);
+ maybeStartHeartbeat(rc, realmId, key);
+ return Uni.createFrom().nullItem();
+ }
+
+ Optional<IdempotencyRecord> existingOpt = r.existing();
+ if (existingOpt.isEmpty()) {
+ // Should not happen: DUPLICATE should always return an existing record.
+ return Uni.createFrom()
+ .item(
+ error(
+ 500,
+ "IdempotencyInvariantViolation",
+ "Missing existing record"));
+ }
+
+ IdempotencyRecord existing = existingOpt.get();
+ if (!operationType.equals(existing.operationType())
+ || !resourceId.equals(existing.normalizedResourceId())) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 422,
+ "idempotency_key_conflict",
+ "Idempotency key was already used for a different operation/resource"));
+ }
+
+ if (!existing.isFinalized()) {
+ if (configuration.heartbeatEnabled()) {
+ // If the owner appears stale (no recent heartbeat), don't wait
+ // indefinitely. Full reconciliation/takeover is out of scope for this
+ // change; return a retryable 503.
+ Instant checkNow = clock.instant();
+ Instant lastSignal = existing.heartbeatAt();
+ if (lastSignal == null) {
+ // A duplicate can arrive before the first heartbeat; fall back to
+ // updatedAt/createdAt so we don't treat fresh owners as stale.
+ lastSignal = existing.updatedAt();
+ if (lastSignal == null) {
+ lastSignal = existing.createdAt();
+ }
+ }
+ if (lastSignal == null
+ || Duration.between(lastSignal, checkNow)
+ .compareTo(configuration.leaseTtlSeconds())
+ > 0) {
+ return Uni.createFrom()
+ .item(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key may be stale; retry later"));
+ }
+ }
+ Instant deadline =
+ clock.instant().plus(configuration.inProgressWaitSeconds());
+ return waitForFinalized(realmId, key, deadline)
+ .onItem()
+ .transform(this::replayResponse)
+ .onFailure(TimeoutException.class)
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_in_progress",
+ "Operation with this idempotency key is still in progress; retry later"))
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ }
+
+ return Uni.createFrom().item(replayResponse(existing));
+ })
+ .onFailure()
+ .recoverWithItem(
+ error(
+ 503,
+ "idempotency_store_unavailable",
+ "Idempotency store unavailable; retry later"));
+ });
+ }
+
+ @ServerResponseFilter
+ public void finalizeOwned(ContainerRequestContext request, ContainerResponseContext response) {
+ if (!configuration.enabled()) {
+ return;
+ }
+ if (!Boolean.TRUE.equals(request.getProperty(PROP_IDEMPOTENCY_OWNED))) {
+ return;
+ }
+
+ stopHeartbeat(request);
+
+ RealmContext realmContext =
+ (RealmContext) request.getProperty(RealmContextFilter.REALM_CONTEXT_KEY);
+ if (realmContext == null) {
+ return;
+ }
+
+ String realmId = realmContext.getRealmIdentifier();
+ String key = (String) request.getProperty(PROP_IDEMPOTENCY_KEY);
+ if (key == null) {
+ return;
+ }
+
+ int status = response.getStatus();
+ if (!shouldFinalize(status)) {
+ // Do not finalize/replay for 401/403/408/429 or any 5xx. If we reserved this key for such a
+ // request, release the in-progress record so the key does not linger and block retries.
+ if (status == 401 || status == 403 || status == 408 || status == 429 || status >= 500) {
Review Comment:
Fixed.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2873618521
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyFilter.java:
##########
@@ -0,0 +1,636 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.smallrye.mutiny.Uni;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.SecurityContext;
+import java.lang.reflect.Method;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.TimeoutException;
+import org.apache.iceberg.rest.responses.ErrorResponse;
+import org.apache.polaris.core.admin.model.Catalog;
+import org.apache.polaris.core.auth.PolarisPrincipal;
+import org.apache.polaris.core.context.RealmContext;
+import org.apache.polaris.core.entity.CatalogEntity;
+import org.apache.polaris.core.entity.IdempotencyRecord;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.core.persistence.ResolvedPolarisEntity;
+import org.apache.polaris.core.persistence.resolver.Resolver;
+import org.apache.polaris.core.persistence.resolver.ResolverFactory;
+import org.apache.polaris.core.persistence.resolver.ResolverStatus;
+import org.apache.polaris.service.catalog.CatalogPrefixParser;
+import org.apache.polaris.service.catalog.iceberg.IcebergCatalogAdapter;
+import org.apache.polaris.service.context.RealmContextFilter;
+import org.jboss.resteasy.reactive.server.ServerRequestFilter;
+import org.jboss.resteasy.reactive.server.ServerResponseFilter;
+import org.jboss.resteasy.reactive.server.core.CurrentRequestManager;
+import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
+import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
+
+/**
+ * HTTP idempotency integration at the request/response layer.
+ *
+ * <p>For in-scope requests (see {@link IdempotencyConfiguration#scopes()}), this filter reserves an
+ * idempotency key before executing the request, and replays the previously finalized response when
+ * a duplicate key is received. For owned requests, it finalizes the response summary/headers for
+ * future replay.
+ */
+public class IdempotencyFilter {
+
+ private static final String PROP_IDEMPOTENCY_KEY = "idempotency.key";
+ private static final String PROP_IDEMPOTENCY_OPERATION = "idempotency.operation";
+ private static final String PROP_IDEMPOTENCY_RESOURCE = "idempotency.resource";
+ private static final String PROP_IDEMPOTENCY_OWNED = "idempotency.owned";
+ private static final String PROP_IDEMPOTENCY_HEARTBEAT_TIMER_ID = "idempotency.heartbeat.timerId";
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject ObjectMapper objectMapper;
+ @Inject Vertx vertx;
+ @Inject ResolverFactory resolverFactory;
+ @Inject CatalogPrefixParser prefixParser;
+
+ @ServerRequestFilter(priority = Priorities.AUTHORIZATION + 10)
+ public Uni<Response> reserveOrReplay(ContainerRequestContext rc) {
+ if (!configuration.enabled()) {
+ return Uni.createFrom().nullItem();
Review Comment:
fair point.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "dimas-b (via GitHub)" <gi...@apache.org>.
dimas-b commented on code in PR #3803:
URL: https://github.com/apache/polaris/pull/3803#discussion_r2996353223
##########
runtime/service/src/main/java/org/apache/polaris/service/idempotency/IdempotencyMaintenance.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.polaris.service.idempotency;
+
+import io.quarkus.runtime.ShutdownEvent;
+import io.quarkus.runtime.StartupEvent;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
+import io.vertx.core.Vertx;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import java.net.InetAddress;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.polaris.core.persistence.IdempotencyStore;
+import org.apache.polaris.service.context.RealmContextConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Background maintenance for idempotency (purge of expired keys). */
+@ApplicationScoped
+public class IdempotencyMaintenance {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(IdempotencyMaintenance.class);
+
+ @Inject IdempotencyConfiguration configuration;
+ @Inject RealmContextConfiguration realmContextConfiguration;
+ @Inject IdempotencyStore store;
+ @Inject Clock clock;
+ @Inject Vertx vertx;
+
+ private volatile Long purgeTimerId;
+ private final AtomicBoolean purgeRunning = new AtomicBoolean(false);
+ private volatile String resolvedExecutorId;
+
+ void onStart(@Observes StartupEvent event) {
Review Comment:
Essentially, most of the new Idempotency classes under `runtime/service` probably belong in a dedicated module.
Essentially these classes provide an implementation and supporting tools for the Idempotency SPI, so it should be possible to swap them for a different impl. in a downstream project.
However, currently, this particular class is bundles within `runtime/service`, so it is not easy to exclude it if/when another Idempotency implementation is meant to be used.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add Iceberg REST Idempotency-Key support [polaris]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #3803:
URL: https://github.com/apache/polaris/pull/3803#issuecomment-4414220913
This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
--
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: issues-unsubscribe@polaris.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org