Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(lambda): split a failed Kinesis batch with BisectBatchOnFunctionError (#6523)

Niels Kootstrad1b9baeb4a27
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 4451916972..79f583f2bf 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -1143,7 +1143,7 @@ Connect Lambda to SQS, Kinesis, or DynamoDB Streams. Self-managed Apache Kafka e
For DynamoDB Streams mappings, Floci retries failed batches with exponential backoff, honors `MaximumRetryAttempts` and `MaximumRecordAgeInSeconds`, and sends discarded batches to configured SQS, SNS, or S3 `DestinationConfig.OnFailure` destinations. With `BisectBatchOnFunctionError`, a batch that fails with a function error is split in half and retried, narrowing it down to the failing record, which then follows the normal retry and record age rules. Splits do not count as retry attempts, and only function errors split: throttles do not, and a partial batch response retries from the reported record. If the OnFailure destination refuses a discarded batch, Floci logs the failure, drops the batch and advances past it.
-For Kinesis mappings, a function error leaves the shard checkpoint in place and the same batch is retried with exponential backoff. With `FunctionResponseTypes: ["ReportBatchItemFailures"]`, a partial batch response moves the checkpoint up to the lowest reported record and retries from there, and a malformed response retries the whole batch. Each of these retries counts toward `MaximumRetryAttempts`; when a partial batch response moves the checkpoint forward, the attempts count again from the new checkpoint, as they do for DynamoDB Streams. When the attempts run out, or a failed batch is older than `MaximumRecordAgeInSeconds`, Floci discards the batch: it sends one invocation record with a `KinesisBatchInfo` block to the SQS, SNS, or S3 `DestinationConfig.OnFailure` destination, if one is set, moves the checkpoint past the batch and goes on with the next records of the shard. If the destination refuses the record, Floci logs the failure and discards the batch all the same. With the defaults (`-1` or unset) a failing batch is retried until it succeeds. A throttle leaves the checkpoint in place, without a backoff and without using an attempt, until the batch is older than `MaximumRecordAgeInSeconds`: then it is discarded the same way, with an `approximateInvokeCount` of the invocations that ran. The record age is checked only when an invoke fails or is throttled, so records are not dropped before their first invoke. `BisectBatchOnFunctionError` is stored and returned but not applied to Kinesis mappings: a failing batch is retried whole. `FunctionResponseTypes` can be set or cleared on an existing mapping with `UpdateEventSourceMapping`.
+For Kinesis mappings, a function error leaves the shard checkpoint in place and the same batch is retried with exponential backoff. With `FunctionResponseTypes: ["ReportBatchItemFailures"]`, a partial batch response moves the checkpoint up to the lowest reported record and retries from there, and a malformed response retries the whole batch. Each of these retries counts toward `MaximumRetryAttempts`; when a partial batch response moves the checkpoint forward, the attempts count again from the new checkpoint, as they do for DynamoDB Streams. When the attempts run out, or a failed batch is older than `MaximumRecordAgeInSeconds`, Floci discards the batch: it sends one invocation record with a `KinesisBatchInfo` block to the SQS, SNS, or S3 `DestinationConfig.OnFailure` destination, if one is set, moves the checkpoint past the batch and goes on with the next records of the shard. If the destination refuses the record, Floci logs the failure and discards the batch all the same. With the defaults (`-1` or unset) a failing batch is retried until it succeeds. A throttle leaves the checkpoint in place, without a backoff and without using an attempt, until the batch is older than `MaximumRecordAgeInSeconds`: then it is discarded the same way, with an `approximateInvokeCount` of the invocations that ran. The record age is checked only when an invoke fails or is throttled, so records are not dropped before their first invoke. With `BisectBatchOnFunctionError`, a batch that fails with a function error is split in half and retried, as for DynamoDB Streams, narrowing it down to the failing record, which then follows the normal retry and record age rules. Splits do not count as retry attempts, and a batch already older than `MaximumRecordAgeInSeconds` is discarded rather than split. `FunctionResponseTypes` can be set or cleared on an existing mapping with `UpdateEventSourceMapping`.
For both stream sources, the first retry waits twice `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` (2 seconds by default), and each later retry waits twice as long as the one before, up to 60 seconds.
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
index 4f198f2b1c..0be761b529 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/DynamoDbStreamsEventSourcePoller.java
@@ -279,7 +279,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
DynamoDbStreamReader.RecordsPage page;
try {
page = streamReader.readAfter(stream, shardId, lastSeq,
- Math.min(bisectLimit(esm, persistedKey), esm.getBatchSize()));
+ Math.min(StreamBatchFailures.bisectLimit(esm, bisectLimits, persistedKey), esm.getBatchSize()));
} catch (AwsException e) {
if (!TRIMMED_DATA_ACCESS_EXCEPTION.equals(e.getErrorCode())) {
throw e;
@@ -296,7 +296,8 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
+ "trim horizon; records between were dropped from the stream",
esm.getUuid(), lastSeq);
page = streamReader.readAfter(stream, shardId, null, Math.min(esm.getBatchSize(),
- bisectLimit(esm, StreamBatchFailures.batchStateKey(esm.getUuid(), shardId, null))));
+ StreamBatchFailures.bisectLimit(esm, bisectLimits,
+ StreamBatchFailures.batchStateKey(esm.getUuid(), shardId, null))));
}
List<DynamoDbStreamReader.Record> records = page.records();
@@ -420,13 +421,12 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
clearBatchState(batchKey);
dispose(esm, shardId, persistedKey, new PendingFailure(matched, invokeResult,
currentRetries, StreamBatchFailures.MAXIMUM_RECORD_AGE_EXCEEDED, newestFetchedSeq));
- } else if (invokeResult.getFunctionError() != null
- && Boolean.TRUE.equals(esm.getBisectBatchOnFunctionError()) && matched.size() > 1) {
+ } else if (StreamBatchFailures.splitsOnFunctionError(esm, invokeResult, matched.size())) {
// ponytail: the halved limit is keyed by checkpoint, so once a good half advances the
// rest is refetched at full batch size and split again. One window converges on the
// poison record in O(log n) invocations, a busy stream in O(log^2 n) worst case;
// carrying the right half's end sequence forward would match AWS exactly.
- int limit = (records.size() + 1) / 2;
+ int limit = StreamBatchFailures.splitBatchSize(records.size());
bisectLimits.put(batchKey, limit);
LOG.infov("DynamoDB Streams ESM {0}: function error on {1} record(s), bisecting to {2}",
esm.getUuid(), records.size(), limit);
@@ -471,12 +471,6 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
bisectLimits.remove(key);
}
- private int bisectLimit(EventSourceMapping esm, String key) {
- return Boolean.TRUE.equals(esm.getBisectBatchOnFunctionError())
- ? bisectLimits.getOrDefault(key, Integer.MAX_VALUE)
- : Integer.MAX_VALUE;
- }
-
private static String finishedShardKey(String uuid, String shardId) {
return uuid + ":" + shardId;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java
index 8e444d702d..ffe290d78f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePoller.java
@@ -60,6 +60,8 @@ public class KinesisEventSourcePoller implements Resettable {
/** Keyed by {@link StreamBatchFailures#batchStateKey}. */
private final ConcurrentHashMap<String, Integer> retryCounts = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Long> retryNotBefore = new ConcurrentHashMap<>();
+ /** The batch size a split batch is refetched at, keyed like {@link #retryCounts}. */
+ private final ConcurrentHashMap<String, Integer> bisectLimits = new ConcurrentHashMap<>();
/** Set during a reset and after shutdown: a failed invoke then counts for nothing. */
private volatile boolean quiesced;
/** Mappings stopped since their last start; a delete stops the mapping before the store forgets it. */
@@ -136,6 +138,7 @@ public class KinesisEventSourcePoller implements Resettable {
activePolls.clear();
retryCounts.clear();
retryNotBefore.clear();
+ bisectLimits.clear();
stopped.clear();
}
@@ -161,6 +164,7 @@ public class KinesisEventSourcePoller implements Resettable {
}
retryCounts.keySet().removeIf(k -> k.startsWith(uuid + ":"));
retryNotBefore.keySet().removeIf(k -> k.startsWith(uuid + ":"));
+ bisectLimits.keySet().removeIf(k -> k.startsWith(uuid + ":"));
}
/** Drops the stop tombstone once the store has forgotten the mapping, which stillActive then sees. */
@@ -208,7 +212,8 @@ public class KinesisEventSourcePoller implements Resettable {
}
Map<String, Object> result = kinesisService.getRecordsForAccount(
- esm.getAccountId(), iterator, esm.getBatchSize(), esm.getRegion());
+ esm.getAccountId(), iterator, Math.min(esm.getBatchSize(), StreamBatchFailures.bisectLimit(esm, bisectLimits, batchKey)),
+ esm.getRegion());
List<KinesisRecord> records = (List<KinesisRecord>) result.get("Records");
if (records.isEmpty()) {
@@ -290,6 +295,11 @@ public class KinesisEventSourcePoller implements Resettable {
// function is not retried at once.
long now = clock.getAsLong();
List<KinesisRecord> failed = failedRecords(records, matched, outcome.lowestFailedIndex());
+ if (StreamBatchFailures.splitsOnFunctionError(esm, invokeResult, failed.size())
+ && !StreamBatchFailures.maximumRecordAgeExceeded(esm, failed.get(0).getApproximateArrivalTimestamp(), now)) {
+ bisect(esm, shardId, retryKey, records.size());
+ return;
+ }
int invokeCount = retryCounts.getOrDefault(retryKey, 0) + 1;
Optional<String> discardCondition = discardCondition(esm, failed, invokeCount, now);
if (discardCondition.isPresent()) {
@@ -334,6 +344,21 @@ public class KinesisEventSourcePoller implements Resettable {
records, shardId, backoffMs);
}
+ /**
+ * Refetches the failed batch at half its size, unless stopPolling, a reset or shutdown came first. The
+ * limit is keyed by checkpoint, so once the first half succeeds the rest is fetched at the full batch
+ * size and split again if it fails.
+ */
+ private synchronized void bisect(EventSourceMapping esm, String shardId, String retryKey, int fetched) {
+ if (!stillActive(esm)) {
+ return;
+ }
+ int limit = StreamBatchFailures.splitBatchSize(fetched);
+ bisectLimits.put(retryKey, limit);
+ LOG.infov("Kinesis ESM {0}: function error on {1} record(s) of shard {2}, bisecting to {3}",
+ esm.getUuid(), fetched, shardId, limit);
+ }
+
private record CheckpointOutcome(String checkpoint, int lowestFailedIndex) {}
long retryBackoffMs(int retries) {
@@ -384,6 +409,7 @@ public class KinesisEventSourcePoller implements Resettable {
private void clearBatchState(String key) {
retryCounts.remove(key);
retryNotBefore.remove(key);
+ bisectLimits.remove(key);
}
private String buildKinesisEvent(List<KinesisRecord> records, EventSourceMapping esm, String shardId) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailures.java b/src/main/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailures.java
index 2f08e4b7f9..0dc852c678 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailures.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailures.java
@@ -89,6 +89,27 @@ public class StreamBatchFailures {
return maximum != null && maximum > 0 && nowMillis - oldestArrival.toEpochMilli() >= maximum * 1_000L;
}
+ /**
+ * With {@code BisectBatchOnFunctionError}, a batch that failed with a function error is split while
+ * it holds more than one record. Splitting does not consume the retry quota.
+ */
+ static boolean splitsOnFunctionError(EventSourceMapping esm, InvokeResult invokeResult, int records) {
+ return invokeResult.getFunctionError() != null
+ && Boolean.TRUE.equals(esm.getBisectBatchOnFunctionError()) && records > 1;
+ }
+
+ /** A split batch is refetched at its first half, rounded up. */
+ static int splitBatchSize(int fetched) {
+ return (fetched + 1) / 2;
+ }
+
+ /** The most records to fetch after the checkpoint {@code key}: its split size, while bisecting. */
+ static int bisectLimit(EventSourceMapping esm, Map<String, Integer> splitSizes, String key) {
+ return Boolean.TRUE.equals(esm.getBisectBatchOnFunctionError())
+ ? splitSizes.getOrDefault(key, Integer.MAX_VALUE)
+ : Integer.MAX_VALUE;
+ }
+
/** The retry state of a failing batch is keyed by the checkpoint it is read after. */
static String batchStateKey(String esmUuid, String shardId, String checkpoint) {
return esmUuid + ":" + shardId + ":" + (checkpoint == null ? "TRIM_HORIZON" : checkpoint);
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java
index 606b726762..2eeda9f07e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/KinesisEventSourcePollerTest.java
@@ -705,6 +705,64 @@ class KinesisEventSourcePollerTest {
assertEquals(2, record.at("/requestContext/approximateInvokeCount").asInt());
}
+ /**
+ * "BisectBatchOnFunctionError, which splits a failed batch into two smaller batches, isolating bad records
+ * [...] Splitting batches doesn't consume the retry quota." With no retries left, only the bad record is
+ * discarded; the records around it are delivered.
+ */
+ @Test
+ void bisectingSplitsAFailedBatchUntilOnlyTheBadRecordIsDiscarded() throws Exception {
+ stubShard("s1", "s2", "s3", "s4");
+ List<byte[]> events = failInvocationsContaining("s3");
+ EventSourceMapping esm = esmWithOnFailure(0, QUEUE_ARN);
+ esm.setBisectBatchOnFunctionError(true);
+
+ for (int poll = 0; poll < 5; poll++) {
+ pollOnce(esm);
+ }
+
+ assertEquals(List.of(List.of("s1", "s2", "s3", "s4"), List.of("s1", "s2"), List.of("s3", "s4"),
+ List.of("s3"), List.of("s4")), invokedSequences(events));
+ assertEquals("s4", checkpoint(esm));
+ ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
+ verify(sqsService, times(1)).sendMessage(eq(QUEUE_URL), body.capture(), eq(0), eq(REGION));
+ JsonNode record = MAPPER.readTree(body.getValue());
+ assertEquals("RetryAttemptsExhausted", record.at("/requestContext/condition").asText());
+ assertEquals(1, record.at("/requestContext/approximateInvokeCount").asInt());
+ assertBatchInfo(record, "s3", "s3", "2026-10-20T12:07:28.012Z", "2026-10-20T12:07:28.012Z", 1);
+ }
+
+ @Test
+ void aFailedBatchIsNotSplitWithoutBisectBatchOnFunctionError() throws Exception {
+ stubShard("s1", "s2", "s3", "s4");
+ List<byte[]> events = failInvocationsContaining("s3");
+ EventSourceMapping esm = esmWithOnFailure(0, QUEUE_ARN);
+
+ pollOnce(esm);
+
+ assertEquals(List.of(List.of("s1", "s2", "s3", "s4")), invokedSequences(events));
+ assertEquals("s4", checkpoint(esm), "the whole batch is discarded");
+ }
+
+ @Test
+ void aBatchOlderThanMaximumRecordAgeIsDiscardedRatherThanSplit() throws Exception {
+ stubShard("s1", "s2");
+ List<byte[]> events = failInvocationsContaining("s2");
+ EventSourceMapping esm = esmWithOnFailure(null, QUEUE_ARN);
+ esm.setBisectBatchOnFunctionError(true);
+ esm.setMaximumRecordAgeInSeconds(60);
+ clock.set(FIRST_ARRIVAL.plusSeconds(61).toEpochMilli());
+
+ pollOnce(esm);
+
+ assertEquals(1, events.size());
+ assertEquals("s2", checkpoint(esm));
+ ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
+ verify(sqsService, times(1)).sendMessage(eq(QUEUE_URL), body.capture(), eq(0), eq(REGION));
+ assertEquals("MaximumRecordAgeExceeded",
+ MAPPER.readTree(body.getValue()).at("/requestContext/condition").asText());
+ }
+
@Test
void failedBatchIsNotRetriedBeforeItsDoublingBackoffElapses() throws Exception {
stubShard("s1");
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailuresTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailuresTest.java
index f4db37e5bd..828a122701 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailuresTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/StreamBatchFailuresTest.java
@@ -103,6 +103,36 @@ class StreamBatchFailuresTest {
assertTrue(StreamBatchFailures.maximumRecordAgeExceeded(esm(null, 60), arrival, aMinute));
}
+ @Test
+ void onlyAFunctionErrorOnMoreThanOneRecordSplitsAndOnlyWhenBisecting() {
+ EventSourceMapping bisecting = esm(null, null);
+ bisecting.setBisectBatchOnFunctionError(true);
+ InvokeResult functionError = new InvokeResult(200, "Unhandled", new byte[0], null, "req-1");
+
+ assertTrue(StreamBatchFailures.splitsOnFunctionError(bisecting, functionError, 2));
+ assertFalse(StreamBatchFailures.splitsOnFunctionError(bisecting, functionError, 1), "a single record");
+ assertFalse(StreamBatchFailures.splitsOnFunctionError(bisecting, new InvokeResult(), 2), "batchItemFailures");
+ assertFalse(StreamBatchFailures.splitsOnFunctionError(esm(null, null), functionError, 2), "unset");
+ }
+
+ @Test
+ void aSplitBatchIsRefetchedAtItsFirstHalfRoundedUp() {
+ assertEquals(2, StreamBatchFailures.splitBatchSize(4));
+ assertEquals(3, StreamBatchFailures.splitBatchSize(5));
+ assertEquals(1, StreamBatchFailures.splitBatchSize(2));
+ }
+
+ @Test
+ void theSplitSizeLimitsTheFetchOnlyWhileBisecting() {
+ Map<String, Integer> splitSizes = Map.of("esm-1:shard:42", 3);
+ EventSourceMapping bisecting = esm(null, null);
+ bisecting.setBisectBatchOnFunctionError(true);
+
+ assertEquals(3, StreamBatchFailures.bisectLimit(bisecting, splitSizes, "esm-1:shard:42"));
+ assertEquals(Integer.MAX_VALUE, StreamBatchFailures.bisectLimit(bisecting, splitSizes, "esm-1:shard:43"));
+ assertEquals(Integer.MAX_VALUE, StreamBatchFailures.bisectLimit(esm(null, null), splitSizes, "esm-1:shard:42"));
+ }
+
@Test
void sqsRecordFillsDefaultsWritesTheTimestampInMillisecondsAndDoesNotBuildTheEvent() throws Exception {
EventSourceMapping esm = esm(0, null);