diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftDataOperationsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftDataOperationsTest.java
index 6e35a3d2e1..52635353c1 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftDataOperationsTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftDataOperationsTest.java
@@ -13,6 +13,7 @@ import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.model.CreateClusterRequest;
import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest;
import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient;
+import software.amazon.awssdk.services.redshiftdata.model.BatchExecuteStatementRequest;
import software.amazon.awssdk.services.redshiftdata.model.DescribeStatementRequest;
import software.amazon.awssdk.services.redshiftdata.model.DescribeStatementResponse;
import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementRequest;
@@ -74,6 +75,37 @@ class RedshiftDataOperationsTest {
}
}
+ @Test
+ @DisplayName("explicit client token retries an INSERT without inserting twice")
+ void executeStatementClientTokenRetry() throws Exception {
+ run("CREATE TABLE compat_idempotent_single (id int)");
+ ExecuteStatementRequest request = ExecuteStatementRequest.builder()
+ .clusterIdentifier(clusterId).database(DATABASE).dbUser(USERNAME)
+ .clientToken(TestFixtures.uniqueName("single-token"))
+ .sql("INSERT INTO compat_idempotent_single VALUES (1)").build();
+ String first = data.executeStatement(request).id();
+ awaitFinished(first);
+ assertThat(data.executeStatement(request).id()).isEqualTo(first);
+ String count = run("SELECT COUNT(*) FROM compat_idempotent_single");
+ assertThat(data.getStatementResult(r -> r.id(count)).records().get(0).get(0).longValue()).isEqualTo(1L);
+ }
+
+ @Test
+ @DisplayName("explicit client token retries a batch without repeating its mutations")
+ void batchExecuteStatementClientTokenRetry() throws Exception {
+ run("CREATE TABLE compat_idempotent_batch (id int)");
+ BatchExecuteStatementRequest request = BatchExecuteStatementRequest.builder()
+ .clusterIdentifier(clusterId).database(DATABASE).dbUser(USERNAME)
+ .clientToken(TestFixtures.uniqueName("batch-token"))
+ .sqls("INSERT INTO compat_idempotent_batch VALUES (1)",
+ "INSERT INTO compat_idempotent_batch VALUES (2)").build();
+ String first = data.batchExecuteStatement(request).id();
+ awaitFinished(first);
+ assertThat(data.batchExecuteStatement(request).id()).isEqualTo(first);
+ String count = run("SELECT COUNT(*) FROM compat_idempotent_batch");
+ assertThat(data.getStatementResult(r -> r.id(count)).records().get(0).get(0).longValue()).isEqualTo(2L);
+ }
+
@Test
@DisplayName("execute, describe, and get-statement-result round trip")
void executeDescribeGetResult() throws Exception {
diff --git a/docs/services/redshift-data.md b/docs/services/redshift-data.md
index f57935cc94..0ff6337ba9 100644
--- a/docs/services/redshift-data.md
+++ b/docs/services/redshift-data.md
@@ -58,6 +58,48 @@ A statement run against a workgroup reports `WorkgroupName` and omits `ClusterId
- **`ExecuteSql` and `BatchExecuteSql`** (the deprecated pre-2020 operations) return `ValidationException`.
- **Type mapping.** JDBC `BOOLEAN` and `BIT` map to `booleanValue`; integer types to `longValue`; floating-point types to `doubleValue`; `NUMERIC` and `DECIMAL` to `stringValue` (as AWS does); binary types to `blobValue`; everything else, including dates, timestamps, and uuid, to `stringValue`. A SQL `NULL` maps to `isNull`. A result column of type `line`, `json`, or `jsonb` fails the statement with the Redshift error text.
+## Client token retries
+
+`ExecuteStatement` and `BatchExecuteStatement` accept an optional `ClientToken`, a case-sensitive
+string of 1 to 64 characters. Repeating an admitted request with the same token returns the
+original statement `Id` and `CreatedAt` without running SQL or publishing its terminal event
+again. This applies while the statement is queued or running and after it finishes, fails or is
+cancelled. Omit the token, or use a new one, to submit independent work. AWS SDKs normally generate
+the token automatically and keep it for their retries.
+
+Tokens expire 8 hours after first admission. Retries do not extend this deadline. Validation,
+reported storage errors and queue-admission failures do not consume the token. An SQL execution failure after
+admission does consume it. `WaitTimeSeconds` on a retry can wait for the original execution without
+submitting another one.
+
+Request validation and database-target resolution run before admission coordination. Only requests
+sharing an account, region, execute operation and token share an admission lock; tokenless requests
+use no token lock. The executor reserves queue capacity before writing admission state, so a full
+queue cannot create a receipt that reappears after restart. Workers run SQL only after admission
+writes succeed. Reset still signals cancellation if clearing either storage backend reports an
+error. Expired receipts are removed in one atomic batch per sweep, with concurrently replaced
+receipts retained.
+
+Receipts use the configured storage mode. Persistent, hybrid and WAL modes retain them across a
+normal restart; memory mode loses them. Interrupted statements keep the existing recovery behavior:
+they become `FAILED`, and SQL is never replayed automatically. This does not provide a distributed
+transaction between PostgreSQL and Floci storage or an exactly-once guarantee after a host crash.
+Persistent and WAL modes use atomic admission writes that report write failures before enqueueing
+SQL. Hybrid mode retains its write-behind behavior: disk flush failures are logged while the live
+in-memory state remains available.
+The token deadline is independent of result retention: if a configured result TTL shorter than
+8 hours removes the statement, its receipt still returns the original admission response until
+the token expires, without restoring results.
+
+Floci scopes tokens by account, region and execute operation. It validates the request and resolves
+the database target before looking up a receipt, including on retries. Within that scope, reusing
+a token with changed SQL, parameters or event settings replays the original operation; it does not
+change that operation. The precise AWS behavior for changed payloads, different IAM principals,
+cross-operation reuse and responses after result eviction has not been verified against a live
+AWS cluster. These are explicit Floci policies. See the
+[AWS Data API guide](https://docs.aws.amazon.com/redshift/latest/mgmt/data-api.html) for the documented
+8-hour token window and SDK retry behavior.
+
## Statement status events
[Redshift Data API status events](https://docs.aws.amazon.com/redshift/latest/mgmt/data-api-monitoring-events.html)
diff --git a/pom.xml b/pom.xml
index 2ad1956285..ccca191e64 100644
--- a/pom.xml
+++ b/pom.xml
@@ -417,6 +417,12 @@
${aws.sdk.version}
test
+
+ software.amazon.awssdk
+ redshiftdata
+ ${aws.sdk.version}
+ test
+
software.amazon.awssdk
url-connection-client
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
index e9c0cd54f7..4f877ccddf 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
@@ -438,6 +438,17 @@ public class AccountAwareStorageBackend implements StorageBackend
delegate.delete(accountId + "/" + key);
}
+ @Override
+ public void deleteAllAtomically(Set keys) {
+ deleteAllAtomicallyForAccounts(Map.of(prefix(), keys));
+ }
+
+ public void deleteAllAtomicallyForAccounts(Map> keysByAccount) {
+ Set rawKeys = new LinkedHashSet<>();
+ keysByAccount.forEach((account, keys) -> keys.forEach(key -> rawKeys.add(account + "/" + key)));
+ delegate.deleteAllAtomically(rawKeys);
+ }
+
// --- Entry writes, for map-valued stores whose backend persists one entry at a time ---
/** Whether the backend persists one map entry at a time; the entry methods require it. */
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/HybridStorage.java b/src/main/java/io/github/hectorvent/floci/core/storage/HybridStorage.java
index ff1675c686..5245097e8c 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/HybridStorage.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/HybridStorage.java
@@ -72,6 +72,17 @@ public class HybridStorage implements StorageBackend {
dirty.set(true);
}
+ @Override
+ public synchronized void deleteAllAtomically(Set keys) {
+ if (keys.isEmpty()) {
+ return;
+ }
+ ConcurrentHashMap candidate = new ConcurrentHashMap<>(store);
+ candidate.keySet().removeAll(Set.copyOf(keys));
+ store = candidate;
+ dirty.set(true);
+ }
+
@Override
public List scan(Predicate keyFilter) {
return store.entrySet().stream()
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/InMemoryStorage.java b/src/main/java/io/github/hectorvent/floci/core/storage/InMemoryStorage.java
index 630e9ee6d4..d645202b74 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/InMemoryStorage.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/InMemoryStorage.java
@@ -38,6 +38,16 @@ public class InMemoryStorage implements StorageBackend {
store.remove(key);
}
+ @Override
+ public synchronized void deleteAllAtomically(Set keys) {
+ if (keys.isEmpty()) {
+ return;
+ }
+ ConcurrentHashMap candidate = new ConcurrentHashMap<>(store);
+ candidate.keySet().removeAll(Set.copyOf(keys));
+ store = candidate;
+ }
+
@Override
public List scan(Predicate keyFilter) {
List result = new ArrayList<>();
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java b/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java
index 8df755766e..a23160a19d 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/PersistentStorage.java
@@ -85,6 +85,21 @@ public class PersistentStorage implements StorageBackend {
persistToDisk();
}
+ @Override
+ public synchronized void deleteAllAtomically(Set keys) {
+ if (keys.isEmpty()) {
+ return;
+ }
+ ConcurrentHashMap candidate = new ConcurrentHashMap<>(store);
+ candidate.keySet().removeAll(Set.copyOf(keys));
+ try {
+ StorageFiles.writeAtomically(filePath, tempFile -> objectMapper.writeValue(tempFile.toFile(), candidate));
+ } catch (IOException exception) {
+ throw new UncheckedIOException("Failed to commit atomic deletions to " + filePath, exception);
+ }
+ store = candidate;
+ }
+
@Override
public List scan(Predicate keyFilter) {
return store.entrySet().stream()
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/StorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/StorageBackend.java
index c7ba2ab5d8..02c9ceb9fb 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/StorageBackend.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/StorageBackend.java
@@ -39,6 +39,11 @@ public interface StorageBackend {
void delete(K key);
+ /** Remove keys as one storage commit, with the same durability guarantees as atomic puts. */
+ default void deleteAllAtomically(Set keys) {
+ throw new UnsupportedOperationException("Atomic deletions are not supported by this backend");
+ }
+
/**
* Return a new mutable list of values whose keys pass the filter. Callers may sort,
* filter, or otherwise mutate the returned list without affecting the underlying store.
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/WalStorage.java b/src/main/java/io/github/hectorvent/floci/core/storage/WalStorage.java
index 54b295452b..abd1ec7e50 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/WalStorage.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/WalStorage.java
@@ -43,6 +43,7 @@ import java.util.stream.Collectors;
* PUT: [0x01] [4-byte key length] [key bytes] [4-byte value length] [value bytes]
* DELETE: [0x02] [4-byte key length] [key bytes]
* BATCH: [0x03] [4-byte map length] [CBOR map bytes]
+ * DELETE_BATCH: [0x04] [4-byte array length] [CBOR key array bytes]
*
* Key and value bytes are serialized via Jackson CBOR (compact binary format).
* Snapshot files use indented JSON for debuggability.
@@ -54,6 +55,7 @@ public class WalStorage implements StorageBackend {
static final byte OP_PUT = 0x01;
static final byte OP_DELETE = 0x02;
static final byte OP_BATCH = 0x03;
+ static final byte OP_DELETE_BATCH = 0x04;
private volatile ConcurrentHashMap store = new ConcurrentHashMap<>();
private final Path snapshotPath;
@@ -130,6 +132,25 @@ public class WalStorage implements StorageBackend {
} catch (IOException exception) {
throw new UncheckedIOException("Failed to encode atomic WAL batch", exception);
}
+ commitBatch(OP_BATCH, payload, replacements, Set.of());
+ }
+
+ @Override
+ public void deleteAllAtomically(Set keys) {
+ Set deletions = Set.copyOf(keys);
+ if (deletions.isEmpty()) {
+ return;
+ }
+ byte[] payload;
+ try {
+ payload = walMapper.writeValueAsBytes(deletions);
+ } catch (IOException exception) {
+ throw new UncheckedIOException("Failed to encode atomic WAL deletions", exception);
+ }
+ commitBatch(OP_DELETE_BATCH, payload, Map.of(), deletions);
+ }
+
+ private void commitBatch(byte operation, byte[] payload, Map replacements, Set deletions) {
compactionLock.writeLock().lock();
try {
if (walWriter == null) {
@@ -137,13 +158,14 @@ public class WalStorage implements StorageBackend {
}
ConcurrentHashMap candidate = new ConcurrentHashMap<>(store);
candidate.putAll(replacements);
+ candidate.keySet().removeAll(deletions);
walWriter.flush();
FileChannel channel = FileChannel.open(walPath, StandardOpenOption.WRITE);
try {
long offset = channel.size();
channel.position(offset);
ByteBuffer record = ByteBuffer.allocate(1 + Integer.BYTES + payload.length);
- record.put(OP_BATCH).putInt(payload.length).put(payload).flip();
+ record.put(operation).putInt(payload.length).put(payload).flip();
try {
while (record.hasRemaining()) {
channel.write(record);
@@ -417,6 +439,14 @@ public class WalStorage implements StorageBackend {
break;
}
store.putAll(batch);
+ } else if (op == OP_DELETE_BATCH) {
+ List keys = walMapper.readValue(keyBytes, walMapper.getTypeFactory().constructCollectionType(
+ List.class, walMapper.constructType(typeReference.getType()).getKeyType()));
+ if (keys == null || keys.stream().anyMatch(key -> key == null)) {
+ LOG.warnv("Invalid WAL deletion batch at offset {0} in {1}, stopping replay", consumed, walPath);
+ break;
+ }
+ keys.forEach(store::remove);
} else if (op == OP_PUT) {
byte[] valueBytes = readFrame(in, fileSize - consumed - recordLength);
if (valueBytes == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataExecutor.java b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataExecutor.java
index c3fbcd49b2..f323e94aef 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataExecutor.java
@@ -14,12 +14,15 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
+import java.util.function.Supplier;
@ApplicationScoped
class RedshiftDataExecutor implements AutoCloseable {
@@ -65,8 +68,9 @@ class RedshiftDataExecutor implements AutoCloseable {
}
/**
- * Admits a statement. {@code admit} runs under the reset read lock, so a reset cannot slip
- * between persisting the statement and registering its execution. {@code onFailure} runs when
+ * Reserves queue capacity before {@code admit} writes any state. The worker waits for admission
+ * to succeed. {@code admit} runs under the reset read lock, so reset cannot split admission.
+ * {@code onFailure} runs when
* the worker dies with an unexpected exception, so the statement can still reach a terminal state.
*/
RedshiftDataExecution submit(String account, String region, String id, Runnable admit,
@@ -79,7 +83,25 @@ class RedshiftDataExecutor implements AutoCloseable {
}
String key = account + ":" + id;
RedshiftDataExecution execution = new RedshiftDataExecution(generation);
+ CountDownLatch ready = new CountDownLatch(1);
+ AtomicBoolean admitted = new AtomicBoolean();
+ AtomicBoolean claimed = new AtomicBoolean();
Runnable task = () -> {
+ if (closed && ready.getCount() != 0) {
+ return;
+ }
+ try {
+ ready.await();
+ } catch (InterruptedException expected) {
+ // The admitting thread completes a pending reservation after shutdown interrupts its worker.
+ Thread.currentThread().interrupt();
+ if (ready.getCount() != 0) {
+ return;
+ }
+ }
+ if (!admitted.get() || !claimed.compareAndSet(false, true)) {
+ return;
+ }
try {
RequestScopes.runAs(account, region, () -> work.accept(execution));
} catch (RuntimeException failure) {
@@ -93,7 +115,6 @@ class RedshiftDataExecutor implements AutoCloseable {
}
};
execution.task(task);
- admit.run();
synchronized (this) {
executions.put(key, execution);
}
@@ -105,12 +126,45 @@ class RedshiftDataExecutor implements AutoCloseable {
}
throw new AwsException("ActiveStatementsExceededException", "Too many active statements", 400);
}
+ try {
+ admit.run();
+ admitted.set(true);
+ } catch (RuntimeException | Error failure) {
+ workers.remove(task);
+ synchronized (this) {
+ executions.remove(key, execution);
+ }
+ execution.completed();
+ throw failure;
+ } finally {
+ boolean finishAfterShutdown;
+ synchronized (this) {
+ finishAfterShutdown = closed && admitted.get();
+ if (finishAfterShutdown) {
+ execution.requestCancellation();
+ }
+ ready.countDown();
+ }
+ if (finishAfterShutdown) {
+ Thread.startVirtualThread(task);
+ }
+ }
return execution;
} finally {
resetLock.readLock().unlock();
}
}
+ /** Keeps receipt lookup, admission and rejected-admission cleanup in one reset generation. */
+ T admitting(Supplier admission) {
+ resetLock.readLock().lock();
+ try {
+ return admission.get();
+ } finally {
+ resetLock.readLock().unlock();
+ }
+ }
+
private static void recover(RedshiftDataExecution execution, RuntimeException failure,
BiConsumer onFailure,
String id, String account, String region) {
@@ -121,6 +175,10 @@ class RedshiftDataExecutor implements AutoCloseable {
}
}
+ synchronized RedshiftDataExecution execution(String account, String id) {
+ return executions.get(account + ":" + id);
+ }
+
boolean cancel(String account, String id) {
RedshiftDataExecution execution;
synchronized (this) {
@@ -173,12 +231,12 @@ class RedshiftDataExecutor implements AutoCloseable {
}
void clear(Runnable clearStorage) {
- List active;
+ List active = new ArrayList<>();
resetLock.writeLock().lock();
try {
generation++;
synchronized (this) {
- active = new ArrayList<>(executions.values());
+ active.addAll(executions.values());
executions.clear();
}
for (RedshiftDataExecution execution : active) {
@@ -187,13 +245,13 @@ class RedshiftDataExecutor implements AutoCloseable {
clearStorage.run();
} finally {
resetLock.writeLock().unlock();
- }
- for (RedshiftDataExecution execution : active) {
- if (execution.requestCancellation()) {
- Thread.startVirtualThread(execution::signalCancellation);
- }
- if (workers.remove(execution.task())) {
- execution.completed();
+ for (RedshiftDataExecution execution : active) {
+ if (execution.requestCancellation()) {
+ Thread.startVirtualThread(execution::signalCancellation);
+ }
+ if (workers.remove(execution.task())) {
+ execution.completed();
+ }
}
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataIdempotencyStore.java b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataIdempotencyStore.java
new file mode 100644
index 0000000000..ec8a92a1c6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftDataIdempotencyStore.java
@@ -0,0 +1,149 @@
+package io.github.hectorvent.floci.services.redshiftdata;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+@ApplicationScoped
+class RedshiftDataIdempotencyStore {
+ private static final Duration TOKEN_TTL = Duration.ofHours(8);
+
+ private final AccountAwareStorageBackend receipts;
+ private final Clock clock;
+ private final ReentrantReadWriteLock mutations = new ReentrantReadWriteLock();
+
+ @Inject
+ RedshiftDataIdempotencyStore(StorageFactory factory) {
+ this(factory.create("redshift-data", "idempotency.json", new TypeReference