fix(lambda): honor MaximumRetryAttempts and DestinationConfig.OnFailure for DynamoDB Streams ESM (#3263) (#3428)

* fix(lambda): honor MaximumRetryAttempts and DestinationConfig.OnFailure for DynamoDB Streams ESM (#3263)

* test(lambda): pin the OnFailure payload's arrival timestamps to epoch seconds

Seeds a known approximateCreationDateTime and asserts the exact
approximateArrivalOfFirstRecord/LastRecord timestamps, using a value
46+ years away from its millis interpretation so a seconds/millis mix-up
cannot accidentally pass. The prior tests only asserted the fields were
present, which stayed green even with the epoch-millis bug fixed in the
previous commit's Instant.ofEpochSecond conversion.

* fix(lambda): track retries and trigger OnFailure when batch does not clear under ReportBatchItemFailures

* fix(lambda): carry retry count across partial batch failures in DynamoDB Streams ESM
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-13 16:02:17 -04:00
1 parent 2290247802
commit 1af3b56683
6 files changed
+633 -30

No files matched your search

@@ -1,6 +1,11 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
@@ -10,16 +15,16 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.vertx.core.Vertx;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -45,9 +50,13 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
private final EsmStore esmStore;
private final ObjectMapper objectMapper;
private final PipesFilterMatcher filterMatcher;
private final SqsService sqsService;
private final SnsService snsService;
private final String baseUrl;
private final long pollIntervalMs;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Integer> retryCounts = new ConcurrentHashMap<>();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "dynamodb-streams-esm-poller");
t.setDaemon(true);
@@ -61,7 +70,9 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
EsmStore esmStore,
ObjectMapper objectMapper,
EmulatorConfig config,
PipesFilterMatcher filterMatcher) {
PipesFilterMatcher filterMatcher,
SqsService sqsService,
SnsService snsService) {
this.vertx = vertx;
this.streamService = streamService;
this.executorService = executorService;
@@ -69,7 +80,10 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
this.esmStore = esmStore;
this.objectMapper = objectMapper;
this.pollIntervalMs = config.services().lambda().pollIntervalMs();
this.baseUrl = config.effectiveBaseUrl();
this.filterMatcher = filterMatcher;
this.sqsService = sqsService;
this.snsService = snsService;
}
public void startPersistedPollers() {
@@ -118,6 +132,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
timerIds.values().forEach(vertx::cancelTimer);
timerIds.clear();
activePolls.clear();
retryCounts.clear();
}
public void startPolling(EventSourceMapping esm) {
@@ -142,8 +157,10 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
vertx.cancelTimer(timerId);
LOG.debugv("Stopped DynamoDB Streams polling for ESM {0}", uuid);
}
retryCounts.keySet().removeIf(k -> k.startsWith(uuid + ":"));
}
void pollAndInvoke(EventSourceMapping esm) {
if (activePolls.putIfAbsent(esm.getUuid(), Boolean.TRUE) != null) {
return;
@@ -161,6 +178,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
String shardId = DynamoDbStreamService.SHARD_ID;
String lastSeq = esm.getShardSequenceNumbers().get(shardId);
boolean checkpointTrimmed = false;
DynamoDbStreamService.GetRecordsResult result;
try {
String iterator = lastSeq == null
@@ -171,6 +189,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
if (!TRIMMED_DATA_ACCESS_EXCEPTION.equals(e.getErrorCode())) {
throw e;
}
checkpointTrimmed = true;
// The checkpoint fell outside the retained window, so the cursor it names can
// never succeed again. Retrying it wedges the ESM permanently: every later
// write reaches the stream and none is ever delivered. Resume from the oldest
@@ -226,15 +245,64 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
throw e;
}
if (invokeResult.getFunctionError() == null) {
String checkpoint = successfulInvocationCheckpoint(
esm, invokeResult, lastSeq, records, matched);
if (checkpoint != null && !checkpoint.equals(lastSeq)) {
advanceCheckpoint(esm, shardId, checkpoint);
String checkpointSeq = (lastSeq == null || checkpointTrimmed) ? "TRIM_HORIZON" : lastSeq;
String batchKey = esm.getUuid() + ":" + shardId + ":" + checkpointSeq;
CheckpointOutcome outcome = invokeResult.getFunctionError() == null
? successfulInvocationCheckpoint(esm, invokeResult, lastSeq, records, matched)
: new CheckpointOutcome(null, 0);
if (outcome.lowestFailedIndex() == records.size()) {
retryCounts.remove(batchKey);
advanceCheckpoint(esm, shardId, outcome.checkpoint());
} else if (outcome.lowestFailedIndex() > 0) {
retryCounts.remove(batchKey);
String nextCheckpoint = outcome.checkpoint();
String nextBatchKey = esm.getUuid() + ":" + shardId + ":" + nextCheckpoint;
Integer maxRetries = esm.getMaximumRetryAttempts();
int currentRetries = retryCounts.merge(nextBatchKey, 1, Integer::sum);
if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
LOG.warnv("DynamoDB Streams ESM {0}: maximum retry attempts ({1}) exhausted for batch ending at {2}",
esm.getUuid(), maxRetries, newestFetchedSeq);
Set<String> deliveredSeqs = new HashSet<>();
for (DynamoDbStreamRecord rec : matched) {
deliveredSeqs.add(rec.getSequenceNumber());
}
List<DynamoDbStreamRecord> failedRecords = new ArrayList<>();
for (int i = outcome.lowestFailedIndex(); i < records.size(); i++) {
DynamoDbStreamRecord rec = records.get(i);
if (deliveredSeqs.contains(rec.getSequenceNumber())) {
failedRecords.add(rec);
}
}
if (failedRecords.isEmpty()) {
failedRecords = records.subList(outcome.lowestFailedIndex(), records.size());
}
sendToOnFailureDestination(esm, shardId, failedRecords, invokeResult, currentRetries);
retryCounts.remove(nextBatchKey);
advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else {
LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [batchItemFailures], retry {1}, records will be retried",
esm.getUuid(), currentRetries);
advanceCheckpoint(esm, shardId, nextCheckpoint);
}
} else {
LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [{1}], records will be retried",
esm.getUuid(), invokeResult.getFunctionError());
Integer maxRetries = esm.getMaximumRetryAttempts();
int currentRetries = retryCounts.merge(batchKey, 1, Integer::sum);
if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
LOG.warnv("DynamoDB Streams ESM {0}: maximum retry attempts ({1}) exhausted for batch ending at {2}",
esm.getUuid(), maxRetries, newestFetchedSeq);
sendToOnFailureDestination(esm, shardId, matched, invokeResult, currentRetries);
retryCounts.remove(batchKey);
advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else {
String error = invokeResult.getFunctionError() != null
? invokeResult.getFunctionError()
: "batchItemFailures";
LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [{1}], retry {2}, records will be retried",
esm.getUuid(), error, currentRetries);
}
}
} catch (Exception e) {
LOG.warnv("DynamoDB Streams ESM {0} poll error: {1}", esm.getUuid(), e.getMessage());
@@ -244,29 +312,32 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
});
}
private record CheckpointOutcome(String checkpoint, int lowestFailedIndex) {}
/**
* Returns the last record that can be consumed after a successful invocation. Floci stores the
* last consumed sequence and resumes with {@code AFTER_SEQUENCE_NUMBER}, so a partial failure
* checkpoints the record immediately before AWS's lowest reported failed sequence.
*/
private String successfulInvocationCheckpoint(EventSourceMapping esm, InvokeResult invokeResult,
String previousCheckpoint,
List<DynamoDbStreamRecord> fetched,
List<DynamoDbStreamRecord> delivered) {
private CheckpointOutcome successfulInvocationCheckpoint(EventSourceMapping esm, InvokeResult invokeResult,
String previousCheckpoint,
List<DynamoDbStreamRecord> fetched,
List<DynamoDbStreamRecord> delivered) {
String newestFetchedSeq = fetched.get(fetched.size() - 1).getSequenceNumber();
byte[] payload = invokeResult.getPayload();
if (!esm.isReportBatchItemFailures() || payload == null || payload.length == 0) {
return newestFetchedSeq;
return new CheckpointOutcome(newestFetchedSeq, fetched.size());
}
try {
JsonNode response = objectMapper.readTree(payload);
JsonNode failures = response.get("batchItemFailures");
if (failures == null || failures.isNull()) {
return newestFetchedSeq;
return new CheckpointOutcome(newestFetchedSeq, fetched.size());
}
if (!failures.isArray()) {
return retryWholeBatch(esm, previousCheckpoint, "batchItemFailures is not an array");
return new CheckpointOutcome(
retryWholeBatch(esm, previousCheckpoint, "batchItemFailures is not an array"), 0);
}
Map<String, Integer> fetchedIndexes = new HashMap<>();
@@ -282,27 +353,30 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
for (JsonNode item : failures) {
JsonNode identifier = item.get("itemIdentifier");
if (identifier == null || identifier.isNull() || identifier.asText().isEmpty()) {
return retryWholeBatch(esm, previousCheckpoint,
"entry has a missing, null or empty itemIdentifier");
return new CheckpointOutcome(
retryWholeBatch(esm, previousCheckpoint,
"entry has a missing, null or empty itemIdentifier"), 0);
}
String sequenceNumber = identifier.asText();
Integer index = fetchedIndexes.get(sequenceNumber);
if (index == null || !deliveredSequences.contains(sequenceNumber)) {
return retryWholeBatch(esm, previousCheckpoint,
"itemIdentifier " + sequenceNumber + " is not in the delivered batch");
return new CheckpointOutcome(
retryWholeBatch(esm, previousCheckpoint,
"itemIdentifier " + sequenceNumber + " is not in the delivered batch"), 0);
}
lowestFailedIndex = Math.min(lowestFailedIndex, index);
}
if (lowestFailedIndex == fetched.size()) {
return newestFetchedSeq;
return new CheckpointOutcome(newestFetchedSeq, fetched.size());
}
return lowestFailedIndex == 0
String checkpoint = lowestFailedIndex == 0
? previousCheckpoint
: fetched.get(lowestFailedIndex - 1).getSequenceNumber();
return new CheckpointOutcome(checkpoint, lowestFailedIndex);
} catch (Exception e) {
return retryWholeBatch(esm, previousCheckpoint,
"response is not valid JSON: " + e.getMessage());
return new CheckpointOutcome(
retryWholeBatch(esm, previousCheckpoint, "response is not valid JSON: " + e.getMessage()), 0);
}
}
@@ -313,6 +387,86 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
return previousCheckpoint;
}
private void sendToOnFailureDestination(EventSourceMapping esm, String shardId,
List<DynamoDbStreamRecord> records,
InvokeResult invokeResult,
int invokeCount) {
if (esm.getDestinationConfig() == null || esm.getDestinationConfig().getOnFailure() == null) {
return;
}
String destinationArn = esm.getDestinationConfig().getOnFailure().getDestination();
if (destinationArn == null || destinationArn.isBlank()) {
return;
}
try {
String payload = buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount);
String region = AwsArnUtils.regionOrDefault(destinationArn, esm.getRegion());
if (destinationArn.contains(":sqs:")) {
String queueUrl = AwsArnUtils.arnToQueueUrl(destinationArn, baseUrl);
sqsService.sendMessage(queueUrl, payload, 0, region);
LOG.infov("DynamoDB Streams ESM {0}: sent failed batch to SQS DLQ {1}", esm.getUuid(), destinationArn);
} else if (destinationArn.contains(":sns:")) {
snsService.publish(destinationArn, null, payload, "ESM OnFailure", region);
LOG.infov("DynamoDB Streams ESM {0}: sent failed batch to SNS DLQ {1}", esm.getUuid(), destinationArn);
} else {
LOG.warnv("DynamoDB Streams ESM {0}: unsupported OnFailure destination ARN {1}",
esm.getUuid(), destinationArn);
}
} catch (Exception e) {
LOG.errorv("DynamoDB Streams ESM {0}: failed to send to OnFailure destination {1}: {2}",
esm.getUuid(), destinationArn, e.getMessage());
}
}
private String buildOnFailurePayload(EventSourceMapping esm, String shardId,
List<DynamoDbStreamRecord> records,
InvokeResult invokeResult,
int invokeCount) {
try {
ObjectNode root = objectMapper.createObjectNode();
root.put("version", "1.0");
root.put("timestamp", DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
ObjectNode requestContext = root.putObject("requestContext");
requestContext.put("requestId", invokeResult.getRequestId() != null ? invokeResult.getRequestId() : "");
requestContext.put("functionArn", esm.getFunctionArn() != null ? esm.getFunctionArn() : "");
requestContext.put("condition", "RetryAttemptsExhausted");
requestContext.put("approximateInvokeCount", invokeCount);
ObjectNode responseContext = root.putObject("responseContext");
responseContext.put("statusCode", invokeResult.getStatusCode() != 0 ? invokeResult.getStatusCode() : 200);
responseContext.put("executedVersion", invokeResult.getExecutedVersion() != null ? invokeResult.getExecutedVersion() : "$LATEST");
if (invokeResult.getFunctionError() != null) {
responseContext.put("functionError", invokeResult.getFunctionError());
}
ObjectNode batchInfo = root.putObject("DDBStreamBatchInfo");
batchInfo.put("shardId", shardId);
String startSeq = records.isEmpty() ? "" : records.get(0).getSequenceNumber();
String endSeq = records.isEmpty() ? "" : records.get(records.size() - 1).getSequenceNumber();
batchInfo.put("startSequenceNumber", startSeq);
batchInfo.put("endSequenceNumber", endSeq);
if (!records.isEmpty()) {
long firstArrival = records.get(0).getApproximateCreationDateTime();
long lastArrival = records.get(records.size() - 1).getApproximateCreationDateTime();
batchInfo.put("approximateArrivalOfFirstRecord",
DateTimeFormatter.ISO_INSTANT.format(Instant.ofEpochSecond(firstArrival)));
batchInfo.put("approximateArrivalOfLastRecord",
DateTimeFormatter.ISO_INSTANT.format(Instant.ofEpochSecond(lastArrival)));
}
batchInfo.put("batchSize", records.size());
batchInfo.put("streamArn", esm.getEventSourceArn());
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
LOG.warnv("Failed to serialize OnFailure payload: {0}", e.getMessage());
return "{}";
}
}
private String buildDynamoDbEvent(List<DynamoDbStreamRecord> records, EventSourceMapping esm) {
try {
ObjectNode root = objectMapper.createObjectNode();
@@ -369,6 +369,10 @@ public class LambdaController {
node.put("BisectBatchOnFunctionError", esm.getBisectBatchOnFunctionError());
}
if (esm.getMaximumRetryAttempts() != null) {
node.put("MaximumRetryAttempts", esm.getMaximumRetryAttempts());
}
if (esm.getDestinationConfig() != null && esm.getDestinationConfig().getOnFailure() != null) {
ObjectNode destinationConfig = node.putObject("DestinationConfig");
ObjectNode onFailure = destinationConfig.putObject("OnFailure");
@@ -1319,6 +1319,8 @@ public class LambdaService implements ResourceProvider {
? b
: null;
Integer maximumRetryAttempts = parseMaximumRetryAttempts(request);
EventSourceMapping.DestinationConfig destinationConfig = parseDestinationConfig(request);
EventSourceMapping.FilterCriteria filterCriteria = parseFilterCriteria(request, objectMapper);
@@ -1344,6 +1346,7 @@ public class LambdaService implements ResourceProvider {
esm.setScalingConfig(scalingConfig);
esm.setFunctionResponseTypes(functionResponseTypes);
esm.setBisectBatchOnFunctionError(bisectBatchOnFunctionError);
esm.setMaximumRetryAttempts(maximumRetryAttempts);
esm.setDestinationConfig(destinationConfig);
esm.setFilterCriteria(filterCriteria);
esm.setStartingPosition(startingPosition.position());
@@ -1727,6 +1730,28 @@ public class LambdaService implements ResourceProvider {
return (int) value;
}
private Integer parseMaximumRetryAttempts(Map<String, Object> request) {
Object raw = request.get("MaximumRetryAttempts");
if (raw == null) {
return null;
}
if (!(raw instanceof Number)) {
throw new AwsException("InvalidParameterValueException",
"MaximumRetryAttempts must be a numeric value", 400);
}
double d = ((Number) raw).doubleValue();
if (Double.isNaN(d) || Double.isInfinite(d) || d != Math.floor(d)) {
throw new AwsException("InvalidParameterValueException",
"MaximumRetryAttempts must be an integer", 400);
}
long value = ((Number) raw).longValue();
if (value < -1 || value > 10000) {
throw new AwsException("InvalidParameterValueException",
"MaximumRetryAttempts must be between -1 and 10000 (got " + value + ")", 400);
}
return (int) value;
}
private void startPollingHelper(EventSourceMapping esm) {
if (esm.getEventSourceArn() == null) {
return;
@@ -1798,6 +1823,10 @@ public class LambdaService implements ResourceProvider {
esm.setBisectBatchOnFunctionError(raw instanceof Boolean b ? b : null);
}
if (request.containsKey("MaximumRetryAttempts")) {
esm.setMaximumRetryAttempts(parseMaximumRetryAttempts(request));
}
if (request.containsKey("DestinationConfig")) {
esm.setDestinationConfig(parseDestinationConfig(request));
}
@@ -31,6 +31,7 @@ public class EventSourceMapping {
private Map<String, String> shardSequenceNumbers = new HashMap<>();
private ScalingConfig scalingConfig;
private Boolean bisectBatchOnFunctionError;
private Integer maximumRetryAttempts;
private DestinationConfig destinationConfig;
private FilterCriteria filterCriteria;
private Map<String, Object> selfManagedEventSource;
@@ -118,6 +119,14 @@ public class EventSourceMapping {
this.bisectBatchOnFunctionError = bisectBatchOnFunctionError;
}
public Integer getMaximumRetryAttempts() {
return maximumRetryAttempts;
}
public void setMaximumRetryAttempts(Integer maximumRetryAttempts) {
this.maximumRetryAttempts = maximumRetryAttempts;
}
public DestinationConfig getDestinationConfig() {
return destinationConfig;
}