fix(lambda): bound a destination cycle that re-enters through SNS or EventBridge (#4279)

The 16-hop bound only advanced when a destination named a Lambda function, so a
cycle closed through an SNS topic or an EventBridge bus restarted at zero on every
lap and ran forever. The chain position now rides the calling thread, which both
services already deliver their Lambda targets on, and the asynchronous invoke drops
the event once the chain is exhausted instead of running it.

Closes #4267

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-23 23:11:06 -04:00
1 parent 4de043cf88
commit fc81cdedd9
6 files changed
+227 -69

No files matched your search

@@ -23,16 +23,17 @@ import org.mockito.quality.Strictness;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -189,18 +190,10 @@ class AsyncInvokeDestinationRouterTest {
verify(lambdaService).invokeArnFromDestination(eq(COLLECTOR_ARN), any(), eq(4));
}
@Test
void lambdaDestinationAtTheChainLimit_stopsRatherThanInvokingAgain() {
configure(COLLECTOR_ARN, null);
router.route(fn, request(), success("{\"rate\":3.5}"), 16);
verify(lambdaService, never()).invokeArnFromDestination(anyString(), any(), anyInt());
}
@Test
void nonLambdaDestinationAtTheChainLimit_isStillDelivered() {
// The bound exists to stop a chain re-entering Lambda; a queue is the end of one.
// The bound exists to stop a chain re-entering Lambda; a queue is the end of one, and AWS
// lets the message through and stops the invocation it would cause instead.
configure(QUEUE_ARN, null);
router.route(fn, request(), success("{\"rate\":3.5}"), 16);
@@ -209,6 +202,64 @@ class AsyncInvokeDestinationRouterTest {
anyString(), eq(0), eq("us-east-1"));
}
@Test
void snsDestination_publishesOneHopFurtherAlongTheChain() {
// SnsService invokes a Lambda subscriber on the publishing thread, so the depth it reads
// there is what stops a topic that fans straight back into the function.
configure(TOPIC_ARN, null);
AtomicInteger depthWhilePublishing = new AtomicInteger(-1);
doAnswer(invocation -> {
depthWhilePublishing.set(LambdaInvocationChain.currentDepth());
return null;
}).when(snsService).publish(anyString(), any(), anyString(), anyString(), anyString());
router.route(fn, request(), success("{\"rate\":3.5}"), 3);
assertEquals(4, depthWhilePublishing.get());
assertEquals(0, LambdaInvocationChain.currentDepth(), "the thread must be left as it was found");
}
@Test
void eventBridgeDestination_putsTheEventOneHopFurtherAlongTheChain() {
configure(BUS_ARN, null);
AtomicInteger depthWhilePutting = new AtomicInteger(-1);
when(eventBridgeService.putEvents(any(), any(), any())).thenAnswer(invocation -> {
depthWhilePutting.set(LambdaInvocationChain.currentDepth());
return new EventBridgeService.PutEventsResult(0, List.of());
});
router.route(fn, request(), success("{\"rate\":3.5}"), 3);
assertEquals(4, depthWhilePutting.get());
assertEquals(0, LambdaInvocationChain.currentDepth(), "the thread must be left as it was found");
}
@Test
void snsDestinationFanningBackIntoTheFunction_stopsAtTheChainBound() {
// The reported cycle: the function's OnSuccess is a topic the function itself subscribes
// to. The stand-in below re-enters where SnsService would, on the publishing thread, and
// refuses the invocation on the same rule LambdaExecutorService applies. Before the depth
// travelled through SNS every hop started a fresh chain and this never came back.
configure(TOPIC_ARN, null);
AtomicInteger invocations = new AtomicInteger();
doAnswer(invocation -> {
int depth = LambdaInvocationChain.currentDepth();
if (LambdaInvocationChain.exhausted(depth)) {
return null;
}
invocations.incrementAndGet();
router.route(fn, request(), success("{\"rate\":3.5}"), depth);
return null;
}).when(snsService).publish(anyString(), any(), anyString(), anyString(), anyString());
router.route(fn, request(), success("{\"rate\":3.5}"), 0);
assertEquals(LambdaInvocationChain.MAX_DEPTH - 1, invocations.get(),
"the originating invocation plus these re-entrant ones is the bound");
verify(snsService, times(LambdaInvocationChain.MAX_DEPTH))
.publish(anyString(), any(), anyString(), anyString(), anyString());
}
@Test
void handlerError_routesToTheFailureDestinationWithTheErrorPayload() {
configure(BUS_ARN, BUS_ARN);
@@ -30,6 +30,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -55,6 +56,40 @@ class LambdaExecutorServiceTest {
when(concurrencyLimiter.acquire(any())).thenReturn(() -> {});
}
@Test
void asyncInvocationPastTheChainBound_isDroppedWithoutRunningTheFunction() {
// AWS stops the next invocation in a chain of requests once the same originating event has
// caused about this many, which is what keeps a destination cycle from running forever.
InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.Event,
LambdaInvocationChain.MAX_DEPTH);
assertEquals(202, result.getStatusCode());
assertNotNull(result.getRequestId());
verify(concurrencyLimiter, never()).acquire(any());
verify(warmPool, never()).acquire(any());
}
@Test
void asyncInvocationShortOfTheChainBound_stillRuns() {
executor.invoke(fn, "{}".getBytes(), InvocationType.Event, LambdaInvocationChain.MAX_DEPTH - 1);
verify(warmPool, timeout(5000)).acquire(fn);
}
@Test
void syncInvocationPastTheChainBound_isNotAffected() {
// Only the asynchronous path can be re-entered by a destination chain, and refusing a
// RequestResponse invoke would need an error shape AWS does not define here.
RuntimeApiServer rtas = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("cid-bound", "test-fn", rtas, ContainerState.WARM);
when(warmPool.acquire(any())).thenReturn(handle);
when(rtas.enqueue(any())).thenReturn(new CompletableFuture<>());
executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, LambdaInvocationChain.MAX_DEPTH);
verify(warmPool).acquire(fn);
}
@Test
void timeoutInvocation_destroysHandle_doesNotRelease() {
RuntimeApiServer rtas = mock(RuntimeApiServer.class);