laserninja commented on code in PR #14972: URL: https://github.com/apache/gravitino/pull/14972#discussion_r4577119970
########## 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: Fixed in 69d67e299. After an unsuccessful expired-row replacement, reserve now retries INSERT once. If purge or release freed the key, the retry claims it; if another caller won, the duplicate-key result leaves that reservation untouched. Non-duplicate SQL failures still propagate and each transaction is closed before the next attempt. The regression test pauses after the real duplicate INSERT, purges from another store, and resumes: it failed before the fix (expected RESERVED, got DUPLICATE) and now passes on H2, MySQL, and PostgreSQL. ########## 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: Kept the single-statement MySQL/H2 DELETE and documented the distinction in 69d67e299. Its expiry condition is already a target-row predicate; PostgreSQL needs the additional outer predicate because its batch subquery selects candidate keys separately. Added a database-lock test that holds a renewed reservation uncommitted, observes the purge blocked in the database, commits the renewal, then verifies zero rows were deleted and the renewed claim can finalize/replay. This passed on all three backends. H2 explicitly rechecks the condition after locking a changed row ([source](https://github.com/h2database/h2database/blob/version-2.2.224/h2/src/main/org/h2/command/dml/Delete.java#L54-L66)); MySQL DML uses current rows rather than the consistent-read snapshot ([manual](https://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html)). ########## 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: Added three deterministic concurrency cases in 69d67e299: purge between the duplicate INSERT and expired-row replacement; a peer claiming the purged key before the retry; and purge waiting on a renewal that commits a future deadline. The first two coordinate real database operations with latches, and the third observes an actual database lock wait. All three pass on H2, MySQL, and PostgreSQL. The complete REST server suite also passed: 767 tests, with formatting and Javadoc checks successful. -- 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]
