lasdf1234 commented on code in PR #14972: URL: https://github.com/apache/gravitino/pull/14972#discussion_r4576851063
########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java: ########## @@ -0,0 +1,201 @@ +/* + * 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. + */ +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"); + try { + sessionFactory = 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 = sessionFactory.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. + execute(mapper -> mapper.selectRecord("00000000-0000-7000-8000-000000000000", clock.millis())); + 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); + try { + execute(mapper -> mapper.insert(po)); + return ReserveResult.RESERVED; + } catch (RuntimeException e) { + if (!ExceptionUtils.isDuplicateKey(e)) { + throw e; + } + } + // The failed insert has rolled back before this conditional update, including on PostgreSQL. + // Keeping these transactions separate also avoids upgrading duplicate-insert locks on MySQL. + int replaced = execute(mapper -> mapper.replaceExpired(po)); + return replaced > 0 ? ReserveResult.RESERVED : ReserveResult.DUPLICATE; Review Comment: **Medium — `DUPLICATE` can be returned when the key is actually free** `reserve()` does insert-then-`replaceExpired` across two transactions. If an expired row is removed by `purgeExpired` after the duplicate-key `INSERT` but before `replaceExpired`, `replaced == 0` and callers get `DUPLICATE` even though no row remains. With the planned HTTP mapping (`DUPLICATE` + empty `load` → 409 in-flight), that becomes a **spurious 409** until the client retries (a later `INSERT` would succeed). At-most-once is not broken by itself, but the signal is wrong under heavy purge. **Suggestion:** if `replaceExpired` returns 0, retry `INSERT` once (or loop); only return `DUPLICATE` when a second insert still hits a duplicate key and replace still fails. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/mapper/provider/base/IcebergIdempotencyKeyBaseSQLProvider.java: ########## @@ -0,0 +1,123 @@ +/* + * 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"; + } + + /** + * Returns an indexed, bounded deletion including the exact expiry cutoff. + * + * @param beforeMs inclusive expiry cutoff in unix epoch milliseconds + * @param batchSize maximum number of rows to delete + * @return SQL statement + */ + public String deleteExpiredBatch( + @Param("beforeMs") long beforeMs, @Param("batchSize") int batchSize) { + return "DELETE FROM " + TABLE_NAME + " WHERE expires_at <= #{beforeMs} LIMIT #{batchSize}"; Review Comment: **Low — MySQL/H2 purge lacks PostgreSQL’s outer `expires_at` re-check** PostgreSQL `deleteExpiredBatch` wraps the batch in `WHERE expires_at <= ? AND idempotency_key IN (…)` so a concurrent `replaceExpired` that extends TTL is less likely to delete a freshly reclaimed row. This base provider is a single `DELETE … WHERE expires_at <= ? LIMIT ?`. InnoDB often re-evaluates predicates at lock time, but parity with PG is not guaranteed. Worth aligning the SQL (or documenting why MySQL/H2 are safe without the outer check). ########## iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.java: ########## @@ -0,0 +1,465 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.gravitino.iceberg.service.idempotency; + +import com.google.common.collect.ImmutableMap; +import java.io.StringReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.util.Locale; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.gravitino.GravitinoEnv; +import org.apache.gravitino.iceberg.common.IcebergConfig; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult; +import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory; +import org.apache.gravitino.storage.relational.TestJDBCBackend; +import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper; +import org.apache.gravitino.storage.relational.utils.SessionUtils; +import org.apache.ibatis.jdbc.ScriptRunner; +import org.apache.ibatis.session.SqlSession; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.mockito.Mockito; + +/** + * Shared {@link JdbcIdempotencyStore} test logic exercised against the same relational backend + * matrix as core metadata service tests. {@link TestJDBCBackend} initializes H2 by default, adds + * MySQL and PostgreSQL when {@code dockerTest=true}, and empties backend tables before each + * invocation. + */ +public class TestJdbcIdempotencyStore extends TestJDBCBackend { + + private static final String KEY = "017f22e2-79b0-7cc3-98c4-dc0c0c07398f"; + private static final String OTHER_KEY = "017f22e2-79b0-7cc3-98c4-dc0c0c073990"; + private static final String BINDING = "POST v1/cat1/namespaces/ns1/tables"; + private static final long FAR_FUTURE_MS = Long.MAX_VALUE; + + private final AtomicLong now = new AtomicLong(); + private JdbcIdempotencyStore store; + private JdbcIdempotencyStore peer; + + // TestJDBCBackend's BackendTestExtension overwrites GravitinoEnv's singleton "config" and + // "idGenerator" fields with a backend-only Mockito mock and never restores them. Because the + // whole iceberg-rest-server module runs in one JVM, that mock would leak into later test classes + // (e.g. credential vending), where MetadataAuthzHelper.enableAuthorization() unboxes the + // unstubbed config.get(ENABLE_AUTHORIZATION) -> null and NPEs. Snapshot the pre-test fields and + // restore them after this class so it leaves GravitinoEnv exactly as it found it. + private Object originalConfig; + private Object originalIdGenerator; + + /** Saves the process-wide environment before the backend test fixture replaces it. */ + @BeforeAll + public void snapshotGravitinoEnv() throws IllegalAccessException { + originalConfig = FieldUtils.readField(GravitinoEnv.getInstance(), "config", true); + originalIdGenerator = FieldUtils.readField(GravitinoEnv.getInstance(), "idGenerator", true); + } + + /** Restores the environment so other REST server tests retain their original configuration. */ + @AfterAll + public void restoreGravitinoEnv() throws IllegalAccessException { + FieldUtils.writeField(GravitinoEnv.getInstance(), "config", originalConfig, true); + FieldUtils.writeField(GravitinoEnv.getInstance(), "idGenerator", originalIdGenerator, true); + } + + /** Creates two store instances sharing the test database and a controllable clock. */ + @BeforeEach + public void prepareIdempotencyStore() { + now.set(1_000_000L); + Clock clock = Mockito.mock(Clock.class); + Mockito.when(clock.millis()).thenAnswer(invocation -> now.get()); + store = new JdbcIdempotencyStore(clock); + peer = new JdbcIdempotencyStore(clock); + // A long interval keeps the background task out of the way: every test below drives the purge + // itself, so a concurrent scheduled run would only make assertions racy. + store.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H")); + peer.initialize(ImmutableMap.of("idempotency-cleanup-interval", "PT1H")); + } + + /** Stops the stores' cleanup tasks without closing the fixture's connection pool. */ + @AfterEach + public void closeIdempotencyStore() { + store.close(); + peer.close(); + } + + @TestTemplate + void testReserveClaimsKeyOnlyOnce() { + Assertions.assertEquals(ReserveResult.RESERVED, store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS)); + Assertions.assertEquals(ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS)); + Assertions.assertEquals( + ReserveResult.RESERVED, store.reserve(OTHER_KEY, BINDING, 1, FAR_FUTURE_MS)); + } + + @TestTemplate + void testConcurrentReserveOnOneKeyHasExactlyOneWinner() throws InterruptedException { + int threads = 16; + ExecutorService executor = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(threads); + AtomicInteger reserved = new AtomicInteger(); + AtomicInteger failed = new AtomicInteger(); + + try { + for (int i = 0; i < threads; i++) { + long claim = i + 1L; + JdbcIdempotencyStore contender = i % 2 == 0 ? store : peer; + executor.submit( + () -> { + try { + start.await(); + if (contender.reserve(KEY, BINDING, claim, FAR_FUTURE_MS) + == ReserveResult.RESERVED) { + reserved.incrementAndGet(); + } + } catch (Exception e) { + // A duplicate-key error rather than a zero-row insert would break the contract as + // surely as two winners would, so count it instead of letting it vanish. + failed.incrementAndGet(); + } finally { + done.countDown(); + } + }); + } + start.countDown(); + Assertions.assertTrue(done.await(60, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + + Assertions.assertEquals(0, failed.get(), "reserve should never raise on a lost race"); + Assertions.assertEquals(1, reserved.get(), "exactly one caller should claim the key"); + } + + @TestTemplate + void testLoadReturnsEmptyUntilFinalized() { + store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS); + Assertions.assertEquals(Optional.empty(), store.load(KEY)); + + store.finalizeRecord(KEY, 1, 200, "{\"a\":1}"); + + IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new); + Assertions.assertTrue(record.isFinalized()); + Assertions.assertEquals(KEY, record.idempotencyKey()); + Assertions.assertEquals(BINDING, record.operationBinding()); + Assertions.assertEquals(200, record.httpStatus().intValue()); + Assertions.assertEquals("{\"a\":1}", record.responseSummary()); + Assertions.assertEquals(FAR_FUTURE_MS, record.expiresAtMs()); + } + + @TestTemplate + void testFinalizeWithoutBodyIsReplayable() { + store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS); + store.finalizeRecord(KEY, 1, 204, null); + + IdempotencyRecord record = store.load(KEY).orElseThrow(AssertionError::new); + Assertions.assertEquals(204, record.httpStatus().intValue()); + Assertions.assertNull(record.responseSummary()); + } + + @TestTemplate + void testFinalizeDoesNotResurrectPurgedRecord() { + store.finalizeRecord(KEY, 1, 200, "{}"); + Assertions.assertEquals(Optional.empty(), store.load(KEY)); + } + + @TestTemplate + void testReleaseFreesReservationButKeepsFinalizedResponse() { + store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS); + store.release(KEY, 1); + Assertions.assertEquals(ReserveResult.RESERVED, store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS)); + + store.finalizeRecord(KEY, 1, 201, "{\"b\":2}"); + store.release(KEY, 1); + Assertions.assertTrue(store.load(KEY).isPresent(), "a finalized response survives a release"); + } + + @TestTemplate + void testPurgeExpiredRemovesOnlyExpiredRecords() { + long now = this.now.get(); + store.reserve(KEY, BINDING, 1, now - 1); + store.reserve(OTHER_KEY, BINDING, 1, FAR_FUTURE_MS); + + Assertions.assertEquals(1, store.purgeExpired(now)); Review Comment: **Low — missing purge ∩ `reserve` concurrency coverage** Existing tests cover purge, reclaim, and multi-thread `reserve`, but not **the same expired key** under concurrent `purgeExpired` + `reserve`. A focused stress/race test here would lock in the `replaceExpired == 0` → retry-insert behavior suggested on `JdbcIdempotencyStore.reserve`. -- 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]
