laserninja commented on code in PR #14972: URL: https://github.com/apache/gravitino/pull/14972#discussion_r4594421968
########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java: ########## @@ -0,0 +1,207 @@ +/* + * 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); + 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; + } + } + // The failed insert has rolled back before this update, including on PostgreSQL. + // Separate transactions also avoid upgrading duplicate-insert locks on MySQL. + if (attempt == 0 && execute(mapper -> mapper.replaceExpired(po)) > 0) { + return ReserveResult.RESERVED; + } + // Purge or release may have removed the row before replacement. Retry INSERT once to + // claim a now-free key or observe another owner's reservation without overwriting it. + } + return ReserveResult.DUPLICATE; + } + + @Override + public Optional<IdempotencyRecord> load(String idempotencyKey) { + String key = IdempotencyKeys.canonicalize(idempotencyKey); + return Optional.ofNullable(execute(mapper -> mapper.selectRecord(key, clock.millis()))) + .map(IcebergIdempotencyKeyPO::toIdempotencyRecord); + } + + @Override + public void finalizeRecord( + String idempotencyKey, long claim, int httpStatus, @Nullable String responseSummary) { + String key = IdempotencyKeys.canonicalize(idempotencyKey); + execute( + mapper -> mapper.finalizeRecord(key, claim, httpStatus, responseSummary, clock.millis())); + } + + @Override + public void release(String idempotencyKey, long claim) { + String key = IdempotencyKeys.canonicalize(idempotencyKey); + execute(mapper -> mapper.deleteReservation(key, claim)); + } + + @Override + public int purgeExpired(long beforeMs) { + int purged = 0; + for (int batch = 0; batch < MAX_PURGE_BATCHES; batch++) { + int deleted = execute(mapper -> mapper.deleteExpiredBatch(beforeMs, PURGE_BATCH_SIZE)); + purged += deleted; + if (deleted < PURGE_BATCH_SIZE) { + break; + } + } + return purged; Review Comment: Documented the 100,000-row per-pass cap and backlog behavior explicitly in 8aa3d9080. The operations guide now recommends monitoring expired-row backlog/storage growth and adjusting the interval with database load and lock waits in mind. The bounded cleanup behavior is unchanged, and expiry remains enforced on access regardless of cleanup lag. ########## iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/JdbcIdempotencyStore.java: ########## @@ -0,0 +1,207 @@ +/* + * 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())); Review Comment: Fixed in 8aa3d9080 by keeping the session factory local until the schema probe succeeds. Extended the real-database missing-schema test to restore the table and retry initialize on the same instance, then reserve/finalize/replay successfully. It reproduced the "already initialized" failure before the fix and now passes on H2, MySQL, and PostgreSQL. Reinitializing a successfully initialized store is still rejected. ########## iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/idempotency/TestJdbcIdempotencyStore.java: ########## @@ -0,0 +1,666 @@ +/* + * 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 static org.awaitility.Awaitility.await; + +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.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +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.iceberg.service.idempotency.mapper.IcebergIdempotencyKeyMapper; +import org.apache.gravitino.iceberg.service.idempotency.po.IcebergIdempotencyKeyPO; +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.executor.Executor; +import org.apache.ibatis.jdbc.ScriptRunner; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.plugin.Interceptor; +import org.apache.ibatis.plugin.Intercepts; +import org.apache.ibatis.plugin.Invocation; +import org.apache.ibatis.plugin.Signature; +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)); + + Assertions.assertEquals(ReserveResult.RESERVED, store.reserve(KEY, BINDING, 1, FAR_FUTURE_MS)); + Assertions.assertEquals( + ReserveResult.DUPLICATE, + store.reserve(OTHER_KEY, BINDING, 1, FAR_FUTURE_MS), + "an unexpired record must survive the purge"); + } + + @TestTemplate + void testPurgeTaskRemovesOnlyExpiredRecords() throws Exception { + store.reserve(KEY, BINDING, 1, now.get()); + store.reserve(OTHER_KEY, BINDING, 1, FAR_FUTURE_MS); + store.finalizeRecord(OTHER_KEY, 1, 200, "{}"); + store.purgeExpiredRecords(); + Assertions.assertEquals(1, rowCount()); + Assertions.assertTrue(store.load(OTHER_KEY).isPresent()); + } + + @TestTemplate + void testPurgeExpiredDeletesMoreThanOneBatch() { + long now = this.now.get(); + int records = JdbcIdempotencyStore.PURGE_BATCH_SIZE + 5; + for (int i = 0; i < records; i++) { + store.reserve(newKey(), BINDING, 1, now - 1); + } + store.reserve(OTHER_KEY, BINDING, 1, FAR_FUTURE_MS); + + Assertions.assertEquals(records, store.purgeExpired(now)); + Assertions.assertEquals( + ReserveResult.DUPLICATE, store.reserve(OTHER_KEY, BINDING, 1, FAR_FUTURE_MS)); + } + + @TestTemplate + void testReplaySurvivesStoreRestartAndIsVisibleToPeer() throws Exception { + store.reserve(KEY, BINDING, -7, FAR_FUTURE_MS); + Assertions.assertEquals(ReserveResult.DUPLICATE, peer.reserve(KEY, BINDING, 2, FAR_FUTURE_MS)); + Assertions.assertTrue(peer.load(KEY).isEmpty()); + String response = "{\"metadata\":\"" + "x".repeat(100_000) + "\"}"; + store.finalizeRecord(KEY, -7, 200, response); + IdempotencyRecord original = peer.load(KEY).orElseThrow(); + Assertions.assertEquals(-7, original.claim()); + store.close(); + try (IdempotencyStore restarted = + IdempotencyStoreFactory.create( + new IcebergConfig(ImmutableMap.of("idempotency-store-type", "jdbc")))) { + Assertions.assertEquals(original, restarted.load(KEY).orElseThrow()); + Assertions.assertEquals(response, restarted.load(KEY).orElseThrow().responseSummary()); + } + // Closing the store must not close the entity store's connection pool. + Assertions.assertEquals(original, peer.load(KEY).orElseThrow()); + } + + @TestTemplate + void testExpiredReservationIsReclaimedAndOldOwnerIsFenced() { + store.reserve(KEY, BINDING, 1, now.get() + 1); + now.incrementAndGet(); + Assertions.assertEquals( + ReserveResult.RESERVED, peer.reserve(KEY, "new binding", 2, FAR_FUTURE_MS)); + store.finalizeRecord(KEY, 1, 500, "stale"); + store.release(KEY, 1); + Assertions.assertEquals(ReserveResult.DUPLICATE, store.reserve(KEY, BINDING, 3, FAR_FUTURE_MS)); + Assertions.assertTrue(peer.load(KEY).isEmpty()); + peer.finalizeRecord(KEY, 2, 201, "new"); + IdempotencyRecord record = store.load(KEY).orElseThrow(); + Assertions.assertEquals(2, record.claim()); + Assertions.assertEquals("new binding", record.operationBinding()); + Assertions.assertEquals("new", record.responseSummary()); + } Review Comment: Added testStaleFinalizeAfterReReservationIsIgnored, testStaleReleaseAfterReReservationIsIgnored, and testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal in 8aa3d9080. The tests verify that the new owner retains the key and can finalize, and that the original binding/claim/response survive a conflicting binding. All 28 JDBC behavior tests pass on H2, MySQL, and PostgreSQL; the full REST server suite passes with 770 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
