lasdf1234 commented on code in PR #14972: URL: https://github.com/apache/gravitino/pull/14972#discussion_r4583045472
########## 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()); Review Comment: **[Medium] Clock skew across replicas** Expiry / reclaim / load / finalize all evaluate deadlines with each JVM’s `Clock` (`clock.millis()`). A fast-clock replica can purge or `replaceExpired` a row that a slow-clock replica still treats as live, which breaks shared-store replay vs re-execution semantics. Docs already say to synchronize clocks — worth elevating in ops/runbooks because this is safety-critical for multi-replica idempotency, not just 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())); + 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)); + } Review Comment: **[Medium] Silent no-op when 0 rows affected** `finalizeRecord` / `release` always commit and ignore the UPDATE/DELETE row count. Wrong claim, expiry, or a lost reservation therefore fail silently (acceptable for the SPI if the HTTP layer never treats this as success). Suggestion: optionally debug-log when the mapper returns 0, and add JDBC parity tests for the release→re-reserve paths covered in `TestInMemoryIdempotencyStore`: - `testStaleFinalizeAfterReReservationIsIgnored` - `testStaleReleaseAfterReReservationIsIgnored` - `testDifferentBindingStillReturnsDuplicateWithoutReplacingOriginal` Expiry reclaim fencing is already covered by `testExpiredReservationIsReclaimedAndOldOwnerIsFenced`; the gap is specifically after `release` + re-reserve. ########## 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: **[Low] Purge throughput cap** `MAX_PURGE_BATCHES * PURGE_BATCH_SIZE` ≈ 100k rows per `purgeExpired` call. Backlog beyond that only delays cleanup (disk bloat), not correctness — reserve/load/finalize still enforce expiry in SQL. Fine as-is; just calling out the operational bound. ########## 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); Review Comment: **[Low] One purge scheduler per store instance** Each successful `initialize()` starts a dedicated `ScheduledExecutorService`. Tests construct multiple stores → multiple purge threads; if production ever creates more than one live instance you get redundant purges and extra lock churn. Consider documenting singleton usage, or sharing a process-wide scheduler / guarding “already scheduled”. ########## 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: **[Low] Partial `initialize()` leaves the instance stuck** `sessionFactory` is assigned before the schema probe (`selectRecord(...)`). If that probe fails, `sessionFactory != null` so a later retry on the same instance hits “already initialized”. `IdempotencyStoreFactory` discards/closes the instance on failure, so production is fine; just awkward for tests / hot reload. Could assign `sessionFactory` only after the probe succeeds, or reset it in the failure path. ########## 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: **[Medium] JDBC test gap vs in-memory suite** This covers stale finalize/release after *expiry reclaim*. Please also port the in-memory cases for stale finalize/release after `release` + re-reserve, and different `operation_binding` still returning `DUPLICATE` without replacing the original (`TestInMemoryIdempotencyStore`). Those are the highest-value non-blocking follow-ups before the HTTP integration PR relies on this store. ########## iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java: ########## @@ -33,7 +33,11 @@ public class IdempotencyStoreFactory { * fully-qualified class name for them. */ private static final ImmutableMap<String, String> STORE_CLASS_NAMES = - ImmutableMap.of("in-memory", InMemoryIdempotencyStore.class.getCanonicalName()); + ImmutableMap.of( + "in-memory", + InMemoryIdempotencyStore.class.getCanonicalName(), + "jdbc", + "org.apache.gravitino.iceberg.service.idempotency.JdbcIdempotencyStore"); Review Comment: **[Info] Module coupling via FQN** `jdbc` resolves to `JdbcIdempotencyStore` in `iceberg-rest-server` by fully-qualified name from `iceberg-common`. That is fine for auxiliary mode, but ClassNotFound will surface only at create-time if the REST server jar is missing from the classpath — worth keeping explicit in docs (already mostly covered). ########## 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}"; + } Review Comment: Claim + `http_status IS NULL` + `expires_at > now` fencing looks correct and matches the SPI. Same pattern on `deleteReservation` (claim + unfinalized only). No code change requested — noting this as intentional so HTTP integration must not assume finalize/release always mutated a row. ########## scripts/mysql/schema-2.0.0-mysql.sql: ########## @@ -816,3 +816,16 @@ CREATE TABLE IF NOT EXISTS `domain_rel` ( KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`), KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain parent relation'; + +CREATE TABLE IF NOT EXISTS `iceberg_idempotency_key_meta` ( + `idempotency_key` VARCHAR(36) NOT NULL COMMENT 'client-provided UUIDv7 idempotency key', + `operation_binding` TEXT NOT NULL COMMENT 'request identity, e.g. POST /v1/{prefix}/namespaces/{ns}/tables', + `claim` BIGINT NOT NULL COMMENT 'reservation fencing token', + `http_status` INT(10) UNSIGNED DEFAULT NULL COMMENT 'HTTP status of finalized response, NULL while reserved', + `response_summary` MEDIUMTEXT DEFAULT NULL COMMENT 'serialized response body (JSON) for replay', + `audit_info` MEDIUMTEXT NOT NULL COMMENT 'idempotency record audit info', + `created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record created at (unix epoch millis)', + `expires_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'record expires at (unix epoch millis)', + PRIMARY KEY (`idempotency_key`), + KEY `idx_iik_expires` (`expires_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'Iceberg REST idempotency key records'; Review Comment: **[Low] Schema CI coverage** Table + `claim` + `idx_iik_expires` look correct (and the design-doc MySQL snippet is slightly stale: missing `claim`, `TEXT` binding, `ON CONFLICT` wording). Optional follow-up: assert `iceberg_idempotency_key_meta` in `TestSQLScripts` so a future schema drift fails CI. Same for H2/PG scripts. ########## docs/iceberg-rest-service.md: ########## @@ -178,6 +178,41 @@ The settings below tune the background workers and are optional. | `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No | | `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No | +### JDBC Idempotency Storage + +The `jdbc` idempotency store persists request reservations and response bodies in Gravitino's +relational entity store. Replicas connected to the same database share records, and finalized +responses survive Iceberg REST service restarts. This supplies the storage backend for +[Idempotency-Key endpoint integration](https://github.com/apache/gravitino/pull/12474); the storage +backend alone does not enable HTTP request replay. + +Use this backend in auxiliary mode, with an initialized relational entity store. Standalone Iceberg +REST servers cannot use it. It reuses Gravitino's connection pool and supports H2, MySQL, and +PostgreSQL. For multiple replicas, use the same shared MySQL or PostgreSQL database; separate local +H2 databases do not provide cross-replica deduplication. + +| Configuration item | Description | Default value | Required | +|--------------------|-------------|---------------|----------| +| `gravitino.iceberg-rest.idempotency-store-type` | Select `jdbc` for durable storage, `in-memory` for node-local storage, or a custom implementation class. | `in-memory` | No | +| `gravitino.iceberg-rest.idempotency-cleanup-interval` | Time between bounded JDBC cleanup passes, as an ISO-8601 duration of at least one millisecond. | `PT5M` | No | + +Initialize a new database with the 2.0.0 schema or apply the 1.3.0-to-2.0.0 upgrade before selecting +`jdbc`. An existing development 2.0.0 database created before this table was added must also apply +the `iceberg_idempotency_key_meta` table and its expiry index from the matching database's schema +script. Store initialization fails if the table is missing. The new table is additive and does not +modify catalog metadata. + +Reservations are atomic across replicas. A claim token prevents an old request from finalizing or +releasing a newer reservation. Expiry is enforced on reads, finalization, and reservation attempts; +reusing an expired key does not depend on the cleanup schedule. Each cleanup pass deletes at most +100 batches of 1,000 expired rows, and transient failures are retried on the next pass. Synchronize +replica clocks because reuse-window deadlines are evaluated using each server's UTC clock. + +Durable storage does not make catalog mutations and response persistence one transaction. A crash +or response-persistence failure after the catalog mutation can still allow re-execution after the +reservation is released or expires. Claim fencing protects idempotency records, not external catalog +side effects. A request running beyond its reuse window can overlap a retry. Review Comment: Good that clock sync, non-atomic catalog+response, and TTL overlap are documented here. The clock-skew point is the one I would treat as ops-critical for multi-replica `jdbc` deployments (see inline note on `JdbcIdempotencyStore`’s `Clock`). -- 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]
