Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/advanced/logging.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ Replay (after wait):
[INFO] Continuing after wait ✓ Logged (new code path)
```

The context leaves replay mode when the first operation that completed while the execution was
suspended (a `wait`, or a callback `get()`) is consumed. The SDK relies on the invocation's
`UpdatedOperationIds` for this. After an invocation that saved some operations and then failed or
timed out, the retry can list those operations as updated, so logs written after them can appear
again. Logs are not guaranteed to be emitted exactly once across failed invocations.

To log during replay (e.g., for debugging):

```java
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.lambda.durable;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import software.amazon.lambda.durable.model.ExecutionStatus;
import software.amazon.lambda.durable.testing.LocalDurableTestRunner;

/** The context must leave replay mode once the first operation that completed during suspension is consumed. */
class ReplayModeAfterSuspensionTest {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex AI review · Finding arf_v1_cusqr2xcutrqallsrwjbwtztqe

[P2] Approach: include the required unit regression coverage

AGENTS.md's Testing Requirements and CONTRIBUTING.md's pull-request requirement 3 require related unit tests, with integration tests added for cross-component behavior. This PR supplies only integration tests and explicitly reports “Unit Tests: No.” The shared replay transition therefore lacks the required isolated regression coverage. Under rule 9, return to the design phase described in rule 8 and revise the validation plan to include unit regressions alongside these integration scenarios.

To suppress repeats, reply /ai verdict deferred, /ai verdict false-positive, or /ai verdict out-of-scope on the first nonblank line. Add rationale on later lines. A new /ai verdict accepted allows future repeats again.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#859 also asks for coverage of child contexts and parallel branches. All tests here use only the top-level context. Can you add those?

🤖 AI-assisted comment


@Test
void waitCompletedDuringSuspension_codeAfterWaitIsNotReplay() {
var replayStates = new ArrayList<Boolean>();
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
ctx.step("before", String.class, s -> "a");
ctx.wait("pause", Duration.ofSeconds(1));
replayStates.add(ctx.isReplaying());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests check isReplaying(), but the bug in #859 is about lost log lines. Could one test also check what reaches the logger?

🤖 AI-assisted comment

return "done";
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
replayStates.clear();
runner.advanceTime();
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of(false), replayStates);
}

@Test
void callbackCompletedDuringSuspension_codeAfterGetIsNotReplay() {
var replayStates = new ArrayList<Boolean>();
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
var cb = ctx.createCallback("approval", String.class);
var value = cb.get();
replayStates.add(ctx.isReplaying());
return value;
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
replayStates.clear();
runner.completeCallback(runner.getCallbackId("approval"), "\"ok\"");
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of(false), replayStates);
}

@Test
void waitAsyncThenStep_intermediateStepStaysReplay() {
var states = new ArrayList<String>();
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
var w = ctx.waitAsync("pause", Duration.ofSeconds(1));
ctx.step("middle", String.class, s -> "m");
states.add("middle=" + ctx.isReplaying());
w.get();
states.add("after=" + ctx.isReplaying());
return "done";
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
states.clear();
runner.advanceTime();
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of("middle=true", "after=false"), states);
}

@Test
void waitFinishedInOlderInvocation_staysReplay() {
var states = new ArrayList<String>();
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
ctx.wait("w1", Duration.ofSeconds(1));
states.add("afterW1=" + ctx.isReplaying());
ctx.wait("w2", Duration.ofSeconds(1));
states.add("afterW2=" + ctx.isReplaying());
return "done";
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
runner.advanceTime();
assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
states.clear();
runner.advanceTime();
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of("afterW1=true", "afterW2=false"), states);
}

@Test
void logsAfterWait_reachTheLogger_andReplayedLogsDoNot() {
var messages = new ArrayList<String>();
var delegate = recordingLogger(messages);
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
var logger = ctx.getLogger(delegate);
logger.info("before wait");
ctx.wait("pause", Duration.ofSeconds(1));
logger.info("after wait");
return "done";
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
assertEquals(List.of("before wait"), messages);
runner.advanceTime();
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of("before wait", "after wait"), messages);
}

@Test
void childContextWaitCompletedDuringSuspension_childLogsReachTheLogger() {
var messages = new ArrayList<String>();
var delegate = recordingLogger(messages);
var runner = LocalDurableTestRunner.create(
String.class,
(input, ctx) -> ctx.runInChildContext("child", String.class, child -> {
var logger = child.getLogger(delegate);
logger.info("child before wait");
child.wait("pause", Duration.ofSeconds(1));
logger.info("child after wait");
return "done";
}));

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
runner.advanceTime();
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of("child before wait", "child after wait"), messages);
}

@Test
void parallelBranchWaitCompletedDuringSuspension_branchLogsReachTheLogger() {
var messages = new ArrayList<String>();
var delegate = recordingLogger(messages);
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
var futures = new ArrayList<DurableFuture<String>>();
var parallel = ctx.parallel("par");
try (parallel) {
futures.add(parallel.branch("branch-a", String.class, branch -> {
var logger = branch.getLogger(delegate);
logger.info("branch before wait");
branch.wait("pause", Duration.ofSeconds(1));
logger.info("branch after wait");
return "A";
}));
}
parallel.get();
return futures.get(0).get();
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
runner.advanceTime();
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of("branch before wait", "branch after wait"), messages);
}

@Test
void childAwaitingParentCallback_resumesChildAndParentLogging() {
var messages = new ArrayList<String>();
var delegate = recordingLogger(messages);
var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
var callback = ctx.createCallback("approval", String.class);
var result = ctx.runInChildContext("child", String.class, child -> {
child.step("before", String.class, s -> "done");
var logger = child.getLogger(delegate);
logger.info("child before callback");
var value = callback.get();
logger.info("child after callback");
return value;
});
ctx.getLogger(delegate).info("parent after child");
return result;
});

assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
assertEquals(List.of("child before callback"), messages);
runner.completeCallback(runner.getCallbackId("approval"), "\"ok\"");
assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
assertEquals(List.of("child before callback", "child after callback", "parent after child"), messages);
}

private static Logger recordingLogger(List<String> messages) {
return (Logger) Proxy.newProxyInstance(
Logger.class.getClassLoader(), new Class<?>[] {Logger.class}, (proxy, method, args) -> {
var name = method.getName();
if (name.equals("info") && args != null && args.length > 0) {
messages.add((String) args[0]);
return null;
}
if (name.startsWith("is") && name.endsWith("Enabled")) {
return true;
}
if (name.equals("getName")) {
return "recording";
}
if (name.equals("hashCode")) {
return System.identityHashCode(proxy);
}
if (name.equals("equals")) {
return proxy == args[0];
}
return method.getReturnType() == boolean.class ? Boolean.FALSE : null;
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import software.amazon.awssdk.services.lambda.model.OperationType;
import software.amazon.awssdk.services.lambda.model.OperationUpdate;
import software.amazon.lambda.durable.DurableFuture;
import software.amazon.lambda.durable.context.BaseContext;
import software.amazon.lambda.durable.context.DurableContextImpl;
import software.amazon.lambda.durable.exception.DurableOperationException;
import software.amazon.lambda.durable.exception.IllegalDurableOperationException;
Expand Down Expand Up @@ -261,6 +262,12 @@ protected Operation waitForOperationCompletion() {
throw terminateExecutionWithIllegalDurableOperationException(
String.format("%s operation not found: %s", getType(), getOperationId()));
}
// The consuming context can differ from the operation's owner when a future crosses contexts.
if (replayCompletedOperation.get()
&& executionManager.isOperationUpdatedSinceLastInvocation(getOperationId())
&& BaseContext.getCurrentContext() instanceof DurableContextImpl consumer) {
consumer.setExecutionMode();
}
return op;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import software.amazon.lambda.durable.DurableContext;
import software.amazon.lambda.durable.TypeToken;
import software.amazon.lambda.durable.config.RunInChildContextConfig;
import software.amazon.lambda.durable.context.BaseContext;
import software.amazon.lambda.durable.context.DurableContextImpl;
import software.amazon.lambda.durable.exception.CallbackFailedException;
import software.amazon.lambda.durable.exception.CallbackSubmitterException;
Expand Down Expand Up @@ -52,6 +53,7 @@ public class ChildContextOperation<T> extends SerializableDurableOperation<T> {
private static final int LARGE_RESULT_THRESHOLD = 256 * 1024;

private final Function<DurableContext, T> function;
private DurableContextImpl executedChildContext;
private final AtomicBoolean replayChildren = new AtomicBoolean(false);
private final AtomicReference<DeserializedOperationResult<T>> cachedOperationResult = new AtomicReference<>(null);

Expand Down Expand Up @@ -132,6 +134,7 @@ private void executeChildContext() {
// we notify the parent BEFORE closing the child context. This ensures the parent
// can trigger the next queued branch while the current child context is still valid.
var childContext = getContext().createChildContext(contextId, getName(), isVirtual);
executedChildContext = childContext;
DurableContextImpl.setCurrentContext(childContext);
try (var ignored = DurableLogger.attachContext()) {
try {
Expand Down Expand Up @@ -227,6 +230,13 @@ private void handleChildContextFailure(Throwable exception) {
@Override
public T get() {
var op = waitForOperationCompletion();
// Only a newly executed result advances its consumer. Reconstructing an older result is replay.
if (executedChildContext != null
&& !replayChildren.get()
&& !executedChildContext.isReplaying()
&& BaseContext.getCurrentContext() instanceof DurableContextImpl consumer) {
consumer.setExecutionMode();
}
if (cachedOperationResult.get() != null) {
// we have a result, just return it directly
return cachedOperationResult.get().get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.time.Duration;
Expand All @@ -12,11 +14,14 @@
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.lambda.model.*;
import software.amazon.lambda.durable.DurableConfig;
import software.amazon.lambda.durable.TestUtils;
import software.amazon.lambda.durable.TypeToken;
import software.amazon.lambda.durable.config.CallbackConfig;
import software.amazon.lambda.durable.context.BaseContext;
import software.amazon.lambda.durable.context.DurableContextImpl;
import software.amazon.lambda.durable.exception.CallbackFailedException;
import software.amazon.lambda.durable.exception.CallbackTimeoutException;
Expand Down Expand Up @@ -83,6 +88,11 @@ public <T> T deserialize(String data, TypeToken<T> typeToken) {
}

private ExecutionManager createExecutionManager(List<Operation> initialOperations) {
return createExecutionManager(initialOperations, List.of());
}

private ExecutionManager createExecutionManager(
List<Operation> initialOperations, List<String> updatedOperationIds) {
var client = TestUtils.createMockClient();
var operations = new ArrayList<Operation>();
operations.add(Operation.builder()
Expand All @@ -94,7 +104,7 @@ private ExecutionManager createExecutionManager(List<Operation> initialOperation
var initialState =
CheckpointUpdatedExecutionState.builder().operations(operations).build();
var executionManager = new ExecutionManager(
new DurableExecutionInput(EXECUTION_ARN, "test-token", initialState),
new DurableExecutionInput(EXECUTION_ARN, "test-token", initialState, updatedOperationIds),
DurableConfig.builder().withDurableExecutionClient(client).build(),
null);
executionManager.setCurrentThreadContext(new ThreadContext("Root", ThreadType.CONTEXT));
Expand Down Expand Up @@ -191,6 +201,46 @@ void getReturnsDeserializedResultWhenSucceeded() {
assertEquals("approved", result);
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
void replayedCallbackChangesOnlyConsumerModeWhenUpdated(boolean updatedSinceLastInvocation) {
var existingCallback = Operation.builder()
.id(OPERATION_ID)
.name(OPERATION_NAME)
.type(OperationType.CALLBACK)
.subType(OperationSubType.CALLBACK.getValue())
.status(OperationStatus.SUCCEEDED)
.callbackDetails(CallbackDetails.builder()
.callbackId("callback-id")
.result("\"approved\"")
.build())
.build();
var executionManager = createExecutionManager(
List.of(existingCallback), updatedSinceLastInvocation ? List.of(OPERATION_ID) : List.of());
when(durableContext.getExecutionManager()).thenReturn(executionManager);
when(durableContext.isReplaying()).thenReturn(true);
var consumer = mock(DurableContextImpl.class);
var operation = new CallbackOperation<>(
OPERATION_IDENTIFIER,
TypeToken.get(String.class),
CallbackConfig.builder().serDes(new JacksonSerDes()).build(),
durableContext);
operation.execute();

DurableContextImpl.setCurrentContext(consumer);
try {
assertEquals("approved", operation.get());
verify(durableContext, never()).setExecutionMode();
if (updatedSinceLastInvocation) {
verify(consumer).setExecutionMode();
} else {
verify(consumer, never()).setExecutionMode();
}
} finally {
BaseContext.CONTEXT.remove();
}
}

@Test
void getThrowsCallbackExceptionWhenFailed() {
var existingCallback = Operation.builder()
Expand Down
Loading