laserninja commented on code in PR #14972: URL: https://github.com/apache/gravitino/pull/14972#discussion_r4594635473
########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java: ########## @@ -0,0 +1,227 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.idempotency; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.time.Clock; +import java.time.Duration; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import javax.annotation.Nullable; +import org.apache.gravitino.iceberg.common.IcebergConfig; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore; +import org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper; +import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO; +import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.gravitino.storage.relational.utils.ExceptionUtils; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Durable idempotency records shared by replicas using the same Gravitino relational entity store. + * Requires an initialized entity store, as provided in auxiliary mode. The database schema must be + * upgraded before this store is enabled. + * + * <p>Reservations commit independently of catalog transactions. Claim tokens fence stale finalize + * and release calls, but cannot undo catalog side effects or make the catalog mutation and response + * persistence atomic. Expired keys can be reserved again without waiting for background cleanup. Review Comment: Addressed the operational-constraint option in 54f1e9840. The service guide, store Javadoc, and design document now explicitly require the reuse window to exceed the maximum reservation-to-response-persistence duration plus maximum clock skew and a safety margin, including lock waits, backend retries, serialization, and JVM pauses. They also state that an HTTP timeout does not necessarily stop a catalog mutation, and that deployments without enforceable bounds cannot rely on at-most-once execution. Removed the old assumption that mutations are always sub-second. There is still no heartbeat/renewal in this SPI; supporting unbounded work needs a separate renewal and catalog-side fencing design. Claim-fenced release continues to protect a replacement owner. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java: ########## @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.idempotency.mapper.provider.base; + +import static org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper.TABLE_NAME; + +import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO; +import org.apache.ibatis.annotations.Param; + +/** SQL statements shared by the MySQL and H2 entity stores. */ +public class IcebergIdempotencyKeyBaseSQLProvider { + /** + * Returns the reservation INSERT. + * + * @param po reservation to persist + * @return SQL statement + */ + public String insert(@Param("po") IcebergIdempotencyKeyPO po) { + return "INSERT INTO " + + TABLE_NAME + + " (idempotency_key, operation_binding, claim, audit_info, created_at, expires_at)" + + " VALUES (#{po.idempotencyKey}, #{po.operationBinding}, #{po.claim}, #{po.auditInfo}," + + " #{po.createdAt}, #{po.expiresAt})"; + } + + /** + * Returns an atomic replacement of an expired reservation or response. + * + * @param po reservation to persist + * @return SQL statement + */ + public String replaceExpired(@Param("po") IcebergIdempotencyKeyPO po) { + return "UPDATE " + + TABLE_NAME + + " SET operation_binding = #{po.operationBinding}, claim = #{po.claim}," + + " http_status = NULL, response_summary = NULL, audit_info = #{po.auditInfo}," + + " created_at = #{po.createdAt}, expires_at = #{po.expiresAt}" + + " WHERE idempotency_key = #{po.idempotencyKey} AND expires_at <= #{po.createdAt}"; + } + + /** + * Returns only a finalized, unexpired response. + * + * @param idempotencyKey canonical UUIDv7 key + * @param nowMs current time in unix epoch milliseconds + * @return SQL statement + */ + public String selectRecord( + @Param("idempotencyKey") String idempotencyKey, @Param("nowMs") long nowMs) { + return "SELECT idempotency_key AS idempotencyKey, operation_binding AS operationBinding," + + " claim, http_status AS httpStatus, response_summary AS responseSummary," + + " audit_info AS auditInfo, created_at AS createdAt, expires_at AS expiresAt FROM " + + TABLE_NAME + + " WHERE idempotency_key = #{idempotencyKey}" + + " AND http_status IS NOT NULL AND expires_at > #{nowMs}"; + } + + /** + * Returns a finalization guarded by the reservation's claim and expiry. + * + * @param idempotencyKey canonical UUIDv7 key + * @param claim reservation fencing token + * @param httpStatus response status + * @param responseSummary serialized response body, or null for an empty body + * @param nowMs current time in unix epoch milliseconds + * @return SQL statement + */ + public String finalizeRecord( + @Param("idempotencyKey") String idempotencyKey, + @Param("claim") long claim, + @Param("httpStatus") int httpStatus, + @Param("responseSummary") String responseSummary, + @Param("nowMs") long nowMs) { + return "UPDATE " + + TABLE_NAME + + " SET http_status = #{httpStatus}, response_summary = #{responseSummary}" + + " WHERE idempotency_key = #{idempotencyKey} AND claim = #{claim}" + + " AND http_status IS NULL AND expires_at > #{nowMs}"; + } + + /** + * Returns a release guarded by the reservation's claim. Finalized responses are retained. + * + * @param idempotencyKey canonical UUIDv7 key + * @param claim reservation fencing token + * @return SQL statement + */ + public String deleteReservation( + @Param("idempotencyKey") String idempotencyKey, @Param("claim") long claim) { + return "DELETE FROM " + + TABLE_NAME + + " WHERE idempotency_key = #{idempotencyKey} AND claim = #{claim} AND http_status IS NULL"; Review Comment: Fixed at the manager boundary in 54f1e9840. Once the action returns a terminal response, the manager no longer releases its reservation if serialization, finalize, or read-back fails or finalize is a no-op. It preserves the original mutation response and leaves any reservation until expiry, so immediate retries cannot re-execute. Retryable/auth responses and thrown action exceptions retain their existing release behavior. HTTP fault-injection cases reproduce the previous re-execution/500 behavior and now verify retention, successful-response preservation, and replay after a lost finalize commit acknowledgement. Unit coverage also checks serialization and read-back failures. SQL claim fencing is unchanged. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java: ########## @@ -0,0 +1,227 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.idempotency; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.time.Clock; +import java.time.Duration; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import javax.annotation.Nullable; +import org.apache.gravitino.iceberg.common.IcebergConfig; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore; +import org.apache.gravitino.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper; +import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO; +import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.gravitino.storage.relational.utils.ExceptionUtils; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Durable idempotency records shared by replicas using the same Gravitino relational entity store. + * Requires an initialized entity store, as provided in auxiliary mode. The database schema must be + * upgraded before this store is enabled. + * + * <p>Reservations commit independently of catalog transactions. Claim tokens fence stale finalize + * and release calls, but cannot undo catalog side effects or make the catalog mutation and response + * persistence atomic. Expired keys can be reserved again without waiting for background cleanup. + * Replicas must synchronize system clocks: a fast clock can reclaim a key another replica still + * considers live. There is no clock-skew grace period. + * + * <p>Share one store per service instance across requests. Each store owns a cleanup scheduler that + * is stopped by {@link #close()}; the relational entity store owns the shared connection pool. + */ +public class JdbcIdempotencyStore implements IdempotencyStore { + private static final Logger LOG = LoggerFactory.getLogger(JdbcIdempotencyStore.class); + @VisibleForTesting static final int PURGE_BATCH_SIZE = 1000; + @VisibleForTesting static final int MAX_PURGE_BATCHES = 100; + + private final Clock clock; + private SqlSessionFactory sessionFactory; + private ScheduledExecutorService purgeScheduler; + + /** Creates a store using the system UTC clock. */ + public JdbcIdempotencyStore() { + this(Clock.systemUTC()); + } + + @VisibleForTesting + JdbcIdempotencyStore(Clock clock) { + this.clock = clock; + } + + @Override + public void initialize(Map<String, String> properties) { + Preconditions.checkState( + sessionFactory == null, "JDBC idempotency store is already initialized"); + Duration interval = + Duration.parse( + new IcebergConfig(properties).get(IcebergConfig.ICEBERG_IDEMPOTENCY_CLEANUP_INTERVAL)); + long intervalMs = interval.toMillis(); + Preconditions.checkArgument( + intervalMs > 0, "Idempotency cleanup interval must be at least 1ms"); + SqlSessionFactory factory; + try { + factory = SqlSessionFactoryHelper.getInstance().getSqlSessionFactory(); + } catch (IllegalStateException e) { + throw new IllegalStateException( + "JDBC idempotency storage requires an initialized Gravitino relational entity store " + + "(auxiliary mode); it is not available in the standalone Iceberg REST server", + e); + } + // Core cannot discover mappers in the auxiliary service's class loader during its startup. + Configuration configuration = factory.getConfiguration(); + synchronized (configuration) { + if (!configuration.hasMapper(IcebergIdempotencyKeyMapper.class)) { + configuration.addMapper(IcebergIdempotencyKeyMapper.class); + } + } + // Fail startup, rather than the first mutation, when the database has not been upgraded. + try (SqlSession session = factory.openSession()) { + session + .getMapper(IcebergIdempotencyKeyMapper.class) + .selectRecord("00000000-0000-7000-8000-000000000000", clock.millis()); + session.commit(); + } + sessionFactory = factory; + purgeScheduler = + Executors.newSingleThreadScheduledExecutor( + runnable -> { + Thread thread = new Thread(runnable, "iceberg-idempotency-purge"); + thread.setDaemon(true); + return thread; + }); + purgeScheduler.scheduleWithFixedDelay( + this::purgeExpiredRecords, intervalMs, intervalMs, TimeUnit.MILLISECONDS); + } + + @Override + public ReserveResult reserve( + String idempotencyKey, String operationBinding, long claim, long expiresAtMs) { + String key = IdempotencyKeys.canonicalize(idempotencyKey); + Preconditions.checkArgument(operationBinding != null, "operationBinding should not be null"); + IcebergIdempotencyKeyPO po = + IcebergIdempotencyKeyPO.reserved(key, operationBinding, claim, clock.millis(), expiresAtMs); + for (int attempt = 0; attempt < 2; attempt++) { + try { + execute(mapper -> mapper.insert(po)); + return ReserveResult.RESERVED; + } catch (RuntimeException e) { + if (!ExceptionUtils.isDuplicateKey(e)) { + throw e; Review Comment: Added explicit pre-execution error handling in 54f1e9840. Reservation and replay-lookup failures now return ServiceUnavailableException/503 with Retry-After and a message that this attempt did not execute the mutation. The manager does not release a possibly committed reservation or run the action after the error. HTTP tests cover failure before reservation and a lost reservation commit acknowledgement; both verify the namespace was never created, and the latter remains protected by a subsequent 409. The operations guide explains same-key retries within the window and catalog-state reconciliation outside it or after an uncertain mutation failure. The JDBC store still propagates non-duplicate SQL errors to this boundary. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
