Skip to content

fix: leave replay mode once an operation completed during suspension is consumed - #895

Open
pcbeingused333 wants to merge 4 commits into
aws:mainfrom
pcbeingused333:fix/c4495-logger-replay-after-wait
Open

pcbeingused333 wants to merge 4 commits into
aws:mainfrom
pcbeingused333:fix/c4495-logger-replay-after-wait

Conversation

@pcbeingused333

@pcbeingused333 pcbeingused333 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Refs #859 (partial: covers operations that completed while the execution was suspended; operations that complete during the resumed invocation are not covered yet, see review)

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

Issue Link, if available

#859

Description

DurableLogger drops the handler's logs written after a wait or a callback get() that completed while the execution was suspended: the context stays in replay mode for the rest of the invocation, so shouldSuppress returns true for new code.

Demo/Screenshots

N/A

Design

  • Design note (rule 3): not needed (bug fix, no public API change).
  • Simpler options considered (rule 2): flipping the mode in execute() when a replayed operation is in updatedOperationIds is the same size, but it is wrong for waitAsync → step → get(): the intermediate step is still a replay and its logs must stay suppressed (covered by waitAsyncThenStep_intermediateStepStaysReplay). Changing ExecutionManager's global mode was rejected because DurableExecutor and the plugin hooks read it.
  • Root cause (rule 5): DurableContextImpl.isReplaying only becomes false when an operation with no checkpoint starts (BaseDurableOperation.execute()). An operation that completed during suspension is replayed as terminal, so if it is the last checkpointed operation of the context, the context never leaves replay mode.
  • Net change in source lines and in public API members: +5 source lines (plus a 3-line comment) in BaseDurableOperation.waitForOperationCompletion(); no public API change.

Assumptions

  • updatedOperationIds in the invocation input lists the operations that changed since the previous successful invocation (documented in DurableExecutionInput). Consequence: after a failed invocation, logs from the retried section can be emitted again. Behavior against the real service: unverified (tests use LocalDurableTestRunner, which fills updatedOperationIds).

Decisions not covered by the issue or the design note

  • Replay mode is left when the completed operation's result is consumed (get()), not when the operation is replayed, so code between an async start and its get() keeps the replay behavior.

Checklist

  • I have filled out every section of the PR template
  • I have thoroughly tested this change: the new regression tests and the full sdk + sdk-integration-tests suite were run by the AI tool (see Testing)
  • Every new branch has a test that fails without it (rule 4)
  • For a bug fix: the description or commit order shows the regression test failing before the fix and passing after it (rule 5)
  • Every edited test expectation is listed in the description, with the reason (rule 5): no existing test expectation was edited.

Testing

Unit Tests

No.

Integration Tests

Yes, ReplayModeAfterSuspensionTest (sdk-integration-tests, LocalDurableTestRunner, 7 tests): code after a wait that completed during suspension is not a replay; same after callback.get(); waitAsync → step → get() keeps the step in replay and leaves it afterwards; a wait that finished in an older invocation stays a replay; logs written after the wait reach the delegate logger and replayed ones do not; same inside a child context and a parallel branch. On main all 7 fail (for example expected: <[false]> but was: <[true]>; expected: <[middle=true, after=false]> but was: <[middle=true, after=true]>); with the fix they pass, and the full sdk + sdk-integration-tests suite passes.

Examples

Not applicable.

This change was prepared with the assistance of an AI tool (Claude Code); the submitter has not manually reviewed or run it.

…is consumed

DurableLogger suppresses logs while the context is replaying, but the context
only left replay mode when starting an operation with no checkpoint. If the
last checkpointed operation (wait/callback) completed while suspended, the
context stayed in replay and dropped the handler's new logs after it.

Fixes aws#859

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pcbeingused333
pcbeingused333 requested a review from a team November 19, 2026 04:19
@pcbeingused333
pcbeingused333 deployed to ai-pr-review-runtime November 19, 2026 04:19 — with GitHub Actions Active
Comment on lines +268 to +270
&& durableContext.isReplaying()
&& executionManager.isOperationUpdatedSinceLastInvocation(getOperationId())) {
durableContext.setExecutionMode();

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_vh7pvlq3cnto2tiea4ujgg62dy

[P2] Keep replay transitions local to the consuming context

durableContext identifies the operation's creator, but ExecutionManager.waitForOperationCompletion() permits another context to await its future. When a replaying child consumes a parent-owned callback completed during suspension, this switches the parent's flag while leaving the child's flag unchanged. The parent can emit duplicate logs while still replaying, and fresh child logs remain suppressed, violating ADR-004's per-context replay isolation. Apply the transition to the context consuming the future and add a cross-context suspension regression asserting both contexts' replay states.

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.

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.

// invocation. Once its result is consumed, the code that follows is no longer a replay, so leave
// replay mode and stop suppressing the handler's logs.
if (replayCompletedOperation.get()
&& durableContext.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.

Codex AI review · Finding arf_v1_y2jsi7yzsi6fvzulsfofhh76yn

[P3] Approach: justify each retained condition under rule 4

Rule 4 requires an assertion-sensitive test for every new condition. Removing durableContext.isReplaying() cannot change the resulting state: setExecutionMode() only assigns false, including when the context already holds false. The guard therefore adds a condition without observable behavior that needs it. Under rule 9, return to the design phase described in rule 8 and simplify the transition around conditions with demonstrable behavioral requirements.

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.

@github-actions

Copy link
Copy Markdown
Contributor

Codex AI review

Three findings: replay isolation and Rule 4 issues at sdk/src/main/java/software/amazon/lambda/durable/operation/BaseDurableOperation.java:268, and missing required unit coverage at sdk-integration-tests/src/test/java/software/amazon/lambda/durable/ReplayModeAfterSuspensionTest.java:15.

Static review only; tests were not executed. Real-service updatedOperationIds behavior remains unverified.

Reviewed commit 520263cf1cbb5a2fb4183c7da684c03042fb6374. Workflow run

@zhongkechen

zhongkechen commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for picking up #859, and for the clear write-up. The root-cause notes and the before/after test evidence made this easy to review. I confirmed locally that the three new tests fail on main and pass with this change, so the direct wait and callback.get() cases are fixed.

While trying a few neighbouring patterns, I found some cases where the handler's logs are still dropped after resume. So I don't think this fully closes #859 yet.

What seems to be going on. The new transition fires only when the consumed operation was already terminal at the start of the invocation, that is, it completed while the execution was suspended. Some operations are still in flight when the invocation starts and complete during it. They don't set replayCompletedOperation, so the context stays in replay mode after them, and DurableLogger keeps suppressing the new code that follows.

Cases I reproduced at 520263cf with LocalDurableTestRunner. Each test records isReplaying() right after the operation on the resumed invocation. It gets true where false is expected:

Scenario Result on resume
ctx.waitForCallback(...). Its WAIT_FOR_CALLBACK child context is STARTED at invocation start. Root still replaying
ctx.runInChildContext(...) whose body waits Root still replaying after the child returns
ctx.map(...) whose branch waits Root still replaying after map returns
A step that failed and suspended for its retry delay, then succeeds on resume Root still replaying after the step
Default (virtual) ctx.withRetry(...) whose body waits Root still replaying after it
A child context awaiting a parent-created callback (cb.get() inside the child) Child still replaying after get(). The parent's flag is changed instead.

I expect the same mechanism to apply to these, though I haven't run them separately:

  • parallel branches that wait
  • waitForCondition completing after a polling delay
  • waits, callbacks and invokes that are STARTED at invocation start and complete through polling during the invocation

waitForCallback is the main callback API, and #859's acceptance criteria call out child contexts and concurrent branches. It would be great to cover these before this lands as "Fixes #859".

A possible way forward. The root cause in the description covers one class of operations: terminal at start and listed in updatedOperationIds. It doesn't cover the general cause, which is that a context leaves replay mode only when a new operation starts. It may be worth stepping back to the design phase, as CONTRIBUTING rules 8 and 9 suggest. You could restate when a context should leave replay mode, so that one rule:

  • covers results that became available while the execution was suspended;
  • covers results that become available during this invocation;
  • is applied to the context that consumes the result.

Regression tests for the cases above that check what DurableLogger actually emits, not only isReplaying(), would help lock this in. I've attached the repro below in case it's a useful starting point.

Thanks again for working on this!

Repro: sdk-integration-tests/.../InFlightReplayModeTest.java (6 tests, all fail at 520263cf with expected: <[false]> but was: <[true]>)
package software.amazon.lambda.durable;

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

import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import software.amazon.lambda.durable.config.StepConfig;
import software.amazon.lambda.durable.config.WithRetryConfig;
import software.amazon.lambda.durable.model.ExecutionStatus;
import software.amazon.lambda.durable.retry.RetryStrategies;
import software.amazon.lambda.durable.testing.LocalDurableTestRunner;

/** Code after an operation that completes during the resumed invocation is new and must not be a replay. */
class InFlightReplayModeTest {
    private final List<Boolean> states = new CopyOnWriteArrayList<>();

    private void resumeAfterTimer(LocalDurableTestRunner<String, String> runner) {
        assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
        states.clear();
        runner.advanceTime();
        assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
    }

    @Test
    void waitForCallback() {
        var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
            var v = ctx.waitForCallback("approval", String.class, (id, sc) -> {});
            states.add(ctx.isReplaying());
            return v;
        });
        assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
        states.clear();
        runner.completeCallback(runner.getCallbackId("approval-callback"), "\"ok\"");
        assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
        assertEquals(List.of(false), states);
    }

    @Test
    void childContextThatWaits() {
        var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
            ctx.runInChildContext("child", String.class, child -> {
                child.wait("pause", Duration.ofSeconds(1));
                return "c";
            });
            states.add(ctx.isReplaying());
            return "done";
        });
        resumeAfterTimer(runner);
        assertEquals(List.of(false), states);
    }

    @Test
    void mapBranchThatWaits() {
        var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
            ctx.map("m", List.of("a"), String.class, (item, index, c) -> {
                c.wait("pause", Duration.ofSeconds(1));
                return item;
            });
            states.add(ctx.isReplaying());
            return "done";
        });
        resumeAfterTimer(runner);
        assertEquals(List.of(false), states);
    }

    @Test
    void stepRetriedAfterSuspension() {
        var attempts = new AtomicInteger();
        var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
            ctx.step(
                    "flaky",
                    String.class,
                    sc -> {
                        if (attempts.incrementAndGet() == 1) throw new RuntimeException("boom");
                        return "ok";
                    },
                    StepConfig.builder()
                            .retryStrategy(RetryStrategies.fixedDelay(3, Duration.ofSeconds(1)))
                            .build());
            states.add(ctx.isReplaying());
            return "done";
        });
        resumeAfterTimer(runner);
        assertEquals(List.of(false), states);
    }

    @Test
    void defaultWithRetryThatWaits() {
        var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
            ctx.withRetry(
                    "retry",
                    (attempt, c) -> {
                        c.wait("pause", Duration.ofSeconds(1));
                        return "x";
                    },
                    WithRetryConfig.builder()
                            .retryStrategy(RetryStrategies.fixedDelay(2, Duration.ofSeconds(1)))
                            .build());
            states.add(ctx.isReplaying());
            return "done";
        });
        resumeAfterTimer(runner);
        assertEquals(List.of(false), states);
    }

    @Test
    void childAwaitingParentCallback() {
        var runner = LocalDurableTestRunner.create(String.class, (input, ctx) -> {
            var cb = ctx.createCallback("approval", String.class);
            return ctx.runInChildContext("child", String.class, child -> {
                child.step("childStep", String.class, s -> "s");
                var v = cb.get();
                states.add(child.isReplaying());
                return v;
            });
        });
        assertEquals(ExecutionStatus.PENDING, runner.run("x").getStatus());
        states.clear();
        runner.completeCallback(runner.getCallbackId("approval"), "\"ok\"");
        assertEquals(ExecutionStatus.SUCCEEDED, runner.run("x").getStatus());
        assertEquals(List.of(false), states);
    }
}

AI-assisted comment.

Comment on lines +267 to +269
if (replayCompletedOperation.get()
&& durableContext.isReplaying()
&& executionManager.isOperationUpdatedSinceLastInvocation(getOperationId())) {

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.

Nit: could you add a test with an old wait?

The isOperationUpdatedSinceLastInvocation check keeps an operation that finished in an older invocation in replay mode. waitAsyncThenStep_intermediateStepStaysReplay already covers this check through the middle step. Waits and callbacks run the same lines today, so they should behave the same way.

A test with an old wait would stop a later change from breaking this for waits only, for example if the mode switch moves into WaitOperation. It needs three invocations, so w1 is old by the last one:

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);

🤖 AI-assisted comment

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

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.

#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

Comment on lines +264 to +266
// An operation that completed while the execution was suspended is the first new event of this
// invocation. Once its result is consumed, the code that follows is no longer a replay, so leave
// replay mode and stop suppressing the handler's logs.

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.

This check can show logs twice after a failed invocation. The local runner can't show this case.

The service fills UpdatedOperationIds with every operation whose sequence number is newer than the last successful invocation. So if an invocation saves some steps and then fails or times out, the retry lists those steps as updated. If the first invocation never succeeded, the retry lists every operation.

Steps also go through waitForOperationCompletion() (StepOperation line 214). So on the retry, the first replayed step from the failed run leaves replay mode. Every log after it is written again, even though that code already ran and logged in the failed run.

#859 says it does not need exactly-once logs across retries, so this may be fine. Could you:

  1. Say in the PR description and in docs/advanced/logging.md that logs can repeat after a failed invocation.
  2. Check it once against the real service, for example with CloudDurableTestRunner. LocalDurableTestRunner doesn't model a failed invocation followed by a retry, and the PR description lists this as unverified.

🤖 AI-assisted comment

…r suspension

Document that logs can repeat after a failed invocation.
@pcbeingused333

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. Pushed a1d05b7 on top of the PR:

  • Old wait: waitFinishedInOlderInvocation_staysReplay (your three-invocation example; expects afterW1=true, afterW2=false).
  • Logger output: logsAfterWait_reachTheLogger_andReplayedLogsDoNot records what reaches the delegate logger via ctx.getLogger(delegate).
  • Child and parallel: childContextWaitCompletedDuringSuspension_childLogsReachTheLogger and parallelBranchWaitCompletedDuringSuspension_branchLogsReachTheLogger (a wait inside the child/branch; both assert the logs written after the wait reach the logger). All 7 tests in the class fail without the source change and pass with it.
  • docs/advanced/logging.md now says logs can repeat after a failed invocation (relies on UpdatedOperationIds). The PR description's Assumptions already lists this as unverified against the real service; I have not run it against CloudDurableTestRunner, so that part is still open.

On @zhongkechen's comment: agreed that this does not close #859, so the description now says Refs #859 instead of Fixes. The in-flight cases (waitForCallback, runInChildContext/map whose body waits, a retried step, withRetry, a child awaiting a parent callback) need a different exit rule: leave replay mode in the context that consumes a result once that result was not already terminal in the checkpoint replayed at invocation start, whether it arrived during suspension or during this invocation. Would you prefer that rule in this PR, with your InFlightReplayModeTest cases added and asserting on logger output, or this PR kept to the suspended case and the general rule written up in #859 first?

Disclosure: this reply and the commit were prepared with an AI coding assistant.

This branch was successfully deployed

1 active (outdated) deployment
ai-pr-review-runtime — 520263cf Deployed Nov 19, 2026 by pcbeingused333 via notify / Generate notification summary #362
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants