fix(lambda): end the invocation when a checkpoint closes a durable execution (#5299)

* fix(lambda): end the invocation at the checkpoint that closes a durable execution

On AWS a checkpoint that closes the execution also ends the invocation.
The history shows InvocationCompleted before ExecutionSucceeded or
ExecutionFailed. A chained invoke started in that batch comes between
them. What the handler returns after that checkpoint is ignored.

The invocation now runs under a request id that Floci picks, so
InvocationCompleted names the same request the function saw.

* fix(lambda): answer a closing durable checkpoint with no operations

AWS answers the checkpoint that closes the execution with an empty
Operations list and no token, even when the batch changed other
operations.

* fix(lambda): fail an unreachable chained invoke before the invocation ends

When a chained invoke target cannot be invoked, AWS logs
ChainedInvokeStarted at its place in the batch and ChainedInvokeFailed
after the batch, before InvocationCompleted. This also holds in a batch
that closes the execution, where Floci logged no ChainedInvokeFailed.
A target that can be invoked still starts after the batch, and after
InvocationCompleted when the batch closes the execution.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-08 14:34:34 -04:00
1 parent 6fc957a3b4
commit ebd364e23e
10 files changed
+155 -66

No files matched your search

@@ -146,6 +146,10 @@ public class LambdaExecutorService implements Resettable {
return invoke(fn, payload, type, 0);
}
public InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, String requestId) {
return invoke(fn, payload, type, 0, null, null, requestId);
}
/**
* Invokes {@code fn}, carrying the number of invocations that the same originating event has
* already caused. A direct invoke starts at zero; each destination delivery adds one, whether
@@ -167,8 +171,11 @@ public class LambdaExecutorService implements Resettable {
InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
String invokedQualifier, String clientContext) {
String requestId = UUID.randomUUID().toString();
return invoke(fn, payload, type, chainDepth, invokedQualifier, clientContext, UUID.randomUUID().toString());
}
private InvokeResult invoke(LambdaFunction fn, byte[] payload, InvocationType type, int chainDepth,
String invokedQualifier, String clientContext, String requestId) {
if (type == InvocationType.DryRun) {
return new InvokeResult(204, null, new byte[0], null, requestId);
}
@@ -20,6 +20,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Pattern;
/**
@@ -37,18 +38,31 @@ final class DurableCheckpointApplier {
private DurableCheckpointApplier() {
}
/** {@code chainedInvokes} names the CHAINED_INVOKE operations this batch started, for the service to run. */
record Outcome(boolean closed, List<String> chainedInvokes) {
/**
* A non-null {@code closingStatus} means the batch closed the execution, which the service then
* closes. {@code chainedInvokes} names the CHAINED_INVOKE operations this batch started, for the
* service to run. {@code unreachableChainedInvokes} holds those whose target cannot be invoked,
* with the error that fails them, in batch order.
*/
record Outcome(DurableExecutionStatus closingStatus, String closingResult, DurableErrorObject closingError,
List<String> chainedInvokes, Map<String, AwsException> unreachableChainedInvokes) {
boolean closed() {
return closingStatus != null;
}
}
static Outcome apply(DurableExecution execution, List<DurableOperationUpdate> updates, long now) {
/** {@code unreachableTarget} gives the error for a chained target that cannot be invoked, or null. */
static Outcome apply(DurableExecution execution, List<DurableOperationUpdate> updates, long now,
Function<String, AwsException> unreachableTarget) {
validateBatch(updates);
Draft draft = new Draft(execution, now);
Draft draft = new Draft(execution, now, unreachableTarget);
for (DurableOperationUpdate update : updates) {
draft.apply(update);
}
draft.commit();
return new Outcome(draft.closingStatus != null, List.copyOf(draft.chainedInvokes));
return new Outcome(draft.closingStatus, draft.closingResult, draft.closingError,
List.copyOf(draft.chainedInvokes), draft.unreachableChainedInvokes);
}
/** Completes waits, step retries and callback timeouts whose time has come. The sweeper and every checkpoint call it. */
@@ -157,17 +171,20 @@ final class DurableCheckpointApplier {
private final DurableExecution execution;
private final long now;
private final Function<String, AwsException> unreachableTarget;
private final LinkedHashMap<String, DurableOperation> operations = new LinkedHashMap<>();
private final List<Consumer<DurableExecution>> events = new ArrayList<>();
private final List<String> chainedInvokes = new ArrayList<>();
private final LinkedHashMap<String, AwsException> unreachableChainedInvokes = new LinkedHashMap<>();
private long changeSequence;
private DurableExecutionStatus closingStatus;
private String closingResult;
private DurableErrorObject closingError;
Draft(DurableExecution execution, long now) {
Draft(DurableExecution execution, long now, Function<String, AwsException> unreachableTarget) {
this.execution = execution;
this.now = now;
this.unreachableTarget = unreachableTarget;
this.changeSequence = execution.getChangeSequence();
for (Map.Entry<String, DurableOperation> entry : execution.getOperations().entrySet()) {
operations.put(entry.getKey(), entry.getValue().copy());
@@ -218,17 +235,6 @@ final class DurableCheckpointApplier {
for (Consumer<DurableExecution> event : events) {
event.accept(execution);
}
if (closingStatus != null) {
execution.setStatus(closingStatus);
execution.setResult(closingResult);
execution.setError(closingError);
execution.setEndTimestamp(now);
if (closingStatus == DurableExecutionStatus.SUCCEEDED) {
DurableHistory.executionSucceeded(execution, now);
} else {
DurableHistory.executionEnded(execution, "ExecutionFailed", now);
}
}
}
private void applyExecution(DurableOperationUpdate update) {
@@ -245,12 +251,6 @@ final class DurableCheckpointApplier {
closingStatus = succeeded ? DurableExecutionStatus.SUCCEEDED : DurableExecutionStatus.FAILED;
closingResult = succeeded ? update.payload() : null;
closingError = succeeded ? null : update.error();
DurableOperation operation = operations.get(execution.getExecutionId());
if (operation != null) {
operation.setStatus(succeeded ? DurableOperationStatus.SUCCEEDED : DurableOperationStatus.FAILED);
operation.setEndTimestamp(now);
touch(operation);
}
}
private void applyContext(DurableOperationUpdate update, DurableOperation existing) {
@@ -393,7 +393,19 @@ final class DurableCheckpointApplier {
operation.setChainedFunctionName(update.chainedFunctionName());
operation.setChainedTenantId(update.chainedTenantId());
operation.setInputPayload(update.payload());
chainedInvokes.add(update.id());
AwsException unreachable = unreachableTarget.apply(update.chainedFunctionName());
if (unreachable == null) {
chainedInvokes.add(update.id());
return;
}
// AWS logs the start of a target it cannot invoke in batch order, naming only the function.
Map<String, Object> details = new LinkedHashMap<>();
details.put("FunctionName", update.chainedFunctionName());
if (update.chainedTenantId() != null) {
details.put("TenantId", update.chainedTenantId());
}
event(operation, "ChainedInvokeStarted", details);
unreachableChainedInvokes.put(update.id(), unreachable);
}
/** A name that does not parse is left to the target lookup, which fails the operation. */
@@ -35,6 +35,7 @@ import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -122,7 +123,10 @@ public class DurableExecutionService implements Resettable {
Long startedBefore, boolean reverseOrder, Integer maxItems, String marker) {
}
/** The token is null when the batch closed the execution. The SDK reads that as "completed". */
/**
* The token is null and the operations are empty when the batch closed the execution. The SDK
* reads that as "completed".
*/
public record CheckpointResult(String checkpointToken, List<DurableOperation> newExecutionState) {
}
@@ -247,11 +251,25 @@ public class DurableExecutionService implements Resettable {
}
DurableExecution execution = loadWithCurrentToken(arn, checkpointToken);
long now = clock.millis();
DurableCheckpointApplier.Outcome outcome = DurableCheckpointApplier.apply(execution, updates, now);
Map<String, ResolvedDurableTarget> targets = new HashMap<>();
DurableCheckpointApplier.Outcome outcome = DurableCheckpointApplier.apply(execution, updates, now,
functionName -> unreachableTarget(execution, functionName, targets));
for (Map.Entry<String, AwsException> unreachable : outcome.unreachableChainedInvokes().entrySet()) {
completeChainedInvoke(execution, execution.getOperations().get(unreachable.getKey()),
ChainedOutcome.failed(unreachable.getValue()), now, effects);
}
if (outcome.closed()) {
// AWS ends the invocation here and ignores what the handler returns after it.
DurableHistory.invocationCompleted(execution, execution.getCurrentInvocationStartedAt(), now,
execution.getCurrentInvocationId(), null);
execution.setCurrentInvocationId(null);
}
// AWS runs a target started in the batch that closes the execution, and ignores its result.
List<DurableExecution> children = new ArrayList<>();
for (String operationId : outcome.chainedInvokes()) {
startChainedInvoke(execution, execution.getOperations().get(operationId), now, children, effects);
DurableOperation operation = execution.getOperations().get(operationId);
startChainedInvoke(execution, operation, targets.get(operation.getChainedFunctionName()), now,
children, effects);
}
if (!outcome.closed()) {
DurableCheckpointApplier.fireDueTimers(execution, now);
@@ -259,7 +277,8 @@ public class DurableExecutionService implements Resettable {
List<DurableOperation> changed = unseenOperations(execution);
String nextToken = null;
if (outcome.closed()) {
closeBookkeeping(execution, now, effects);
close(execution, outcome.closingStatus(), outcome.closingResult(), outcome.closingError(), now,
effects);
} else {
execution.setCheckpointSequence(execution.getCheckpointSequence() + 1);
nextToken = DurableTokens.checkpointToken(execution.getExecutionArn(),
@@ -274,7 +293,7 @@ public class DurableExecutionService implements Resettable {
for (DurableExecution child : children) {
save(child);
}
result = new CheckpointResult(nextToken, changed);
result = new CheckpointResult(nextToken, outcome.closed() ? List.of() : changed);
}
runEffects(effects);
return result;
@@ -537,6 +556,7 @@ public class DurableExecutionService implements Resettable {
return;
}
startedAt = clock.millis();
execution.setCurrentInvocationStartedAt(startedAt);
String token = DurableTokens.checkpointToken(execution.getExecutionArn(), invocationId,
execution.getCheckpointSequence());
List<String> updatedOperationIds = unseenOperations(execution).stream().map(DurableOperation::getId).toList();
@@ -558,7 +578,7 @@ public class DurableExecutionService implements Resettable {
result = new DurableInvocationResult(null, null, "ResourceNotFoundException");
} else {
try {
result = invoker.invoke(target, payload);
result = invoker.invoke(target, payload, invocationId);
} catch (AwsException e) {
result = new DurableInvocationResult(null, DurableWire.functionErrorPayload(
DurableErrorObject.of(e.getMessage(), e.getErrorCode())),
@@ -719,13 +739,17 @@ public class DurableExecutionService implements Resettable {
root.setEndTimestamp(now);
root.setChangeSequence(execution.nextChangeSequence());
}
switch (status) {
closeEvent(execution, now);
closeBookkeeping(execution, now, effects);
}
private static void closeEvent(DurableExecution execution, long now) {
switch (execution.getStatus()) {
case SUCCEEDED -> DurableHistory.executionSucceeded(execution, now);
case TIMED_OUT -> DurableHistory.executionTimedOut(execution, now);
case STOPPED -> DurableHistory.executionEnded(execution, "ExecutionStopped", now);
default -> DurableHistory.executionEnded(execution, "ExecutionFailed", now);
}
closeBookkeeping(execution, now, effects);
}
/** What every close shares, whether the applier or the service decided it. */
@@ -765,25 +789,25 @@ public class DurableExecutionService implements Resettable {
effects.add(() -> finishChainedInvoke(parent.accountId(), parent.storeKey(), operationId, childArn, outcome));
}
/**
* Resolves the target of a CHAINED_INVOKE this checkpoint started. A target that cannot be
* invoked fails the operation at once, and ChainedInvokeStarted then names only the function.
*/
private void startChainedInvoke(DurableExecution execution, DurableOperation operation, long now,
List<DurableExecution> children, List<Runnable> effects) {
/** Null when the target can be invoked. The resolved target is kept in {@code targets} for the start. */
private AwsException unreachableTarget(DurableExecution execution, String functionName,
Map<String, ResolvedDurableTarget> targets) {
try {
targets.put(functionName, resolveChainedTarget(execution, functionName));
return null;
} catch (AwsException e) {
return e;
}
}
private void startChainedInvoke(DurableExecution execution, DurableOperation operation,
ResolvedDurableTarget target, long now, List<DurableExecution> children,
List<Runnable> effects) {
Map<String, Object> details = new LinkedHashMap<>();
details.put("FunctionName", operation.getChainedFunctionName());
if (operation.getChainedTenantId() != null) {
details.put("TenantId", operation.getChainedTenantId());
}
ResolvedDurableTarget target;
try {
target = resolveChainedTarget(execution, operation.getChainedFunctionName());
} catch (AwsException e) {
DurableHistory.operationEvent(execution, operation, "ChainedInvokeStarted", now, details);
completeChainedInvoke(execution, operation, ChainedOutcome.failed(e), now, effects);
return;
}
details.put("Input", DurableHistory.payloadWrapper(operation.getInputPayload()));
details.put("ExecutedVersion", target.version());
if (target.durable()) {
@@ -854,7 +878,7 @@ public class DurableExecutionService implements Resettable {
private ChainedOutcome invokePlainFunction(ResolvedDurableTarget target, byte[] payload) {
DurableInvocationResult result;
try {
result = invoker.invoke(target, payload);
result = invoker.invoke(target, payload, UUID.randomUUID().toString());
} catch (AwsException e) {
return ChainedOutcome.failed(e);
} catch (RuntimeException e) {
@@ -10,7 +10,7 @@ public interface DurableFunctionInvoker {
/** The function a durable execution runs on, or an AwsException when the name does not resolve. */
ResolvedDurableTarget resolve(String accountId, String region, String functionName, String qualifier);
DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload);
DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId);
record ResolvedDurableTarget(String accountId,
String region,
@@ -38,11 +38,11 @@ public class LambdaDurableFunctionInvoker implements DurableFunctionInvoker {
* {@code $LATEST} execution resumes on whatever code $LATEST holds now, as on AWS.
*/
@Override
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload) {
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId) {
LambdaFunction fn = targetResolver.resolveInvokeTargetForAccount(target.accountId(), target.region(),
target.functionName(), target.version());
InvokeResult result = RequestScopes.callAs(target.accountId(),
() -> executorService.invoke(fn, payload, InvocationType.RequestResponse));
() -> executorService.invoke(fn, payload, InvocationType.RequestResponse, requestId));
return new DurableInvocationResult(result.getRequestId(), result.getPayload(), result.getFunctionError());
}
}
@@ -48,6 +48,7 @@ public class DurableExecution {
private long seenSequence;
private long checkpointSequence;
private String currentInvocationId;
private Long currentInvocationStartedAt;
private boolean reinvokeRequested;
private int consecutiveInvocationFailures;
private Long nextInvocationAttemptAt;
@@ -189,6 +190,11 @@ public class DurableExecution {
public String getCurrentInvocationId() { return currentInvocationId; }
public void setCurrentInvocationId(String currentInvocationId) { this.currentInvocationId = currentInvocationId; }
public Long getCurrentInvocationStartedAt() { return currentInvocationStartedAt; }
public void setCurrentInvocationStartedAt(Long currentInvocationStartedAt) {
this.currentInvocationStartedAt = currentInvocationStartedAt;
}
public boolean isReinvokeRequested() { return reinvokeRequested; }
public void setReinvokeRequested(boolean reinvokeRequested) { this.reinvokeRequested = reinvokeRequested; }