feat(lambda): pass the X-Ray trace header through durable chained invokes (#8189)

* feat(lambda): pass the X-Ray trace header through durable chained invokes

* fix(lambda): give a PassThrough invocation a new Parent for an unsampled header without one
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-13 08:30:31 -04:00
1 parent 7d7c87338f
commit ede4ebf6b0
12 files changed
+306 -38

No files matched your search

+7 -3
View File
@@ -255,7 +255,12 @@ Stopping the parent leaves the child running, as on AWS.
Each durable execution gets an X-Ray trace header. It is built from the `X-Amzn-Trace-Id` header of
Invoke when the request carries one. `GetDurableExecution` returns it as `TraceHeader`. Every
invocation of the execution gets the same `Root` in `_X_AMZN_TRACE_ID`. A `PassThrough` function
gets the `Parent` of the execution. An `Active` function gets a new `Parent` on each invocation.
gets the `Parent` of the execution. When the header has none, the function gets only the `Root` if
`Sampled=1`, and a new `Parent` on each invocation if `Sampled=0`. An `Active` function gets a new
`Parent` on each invocation.
A durable execution started by a chained invoke takes its header from
`ChainedInvokeOptions.XAmznTraceId`, or from the calling execution when that is absent. A plain
function invoked this way gets the same header.
`GetDurableExecutionHistory` leaves payloads out unless `IncludeExecutionData=true` is sent. The
API reference names `true` as the default, but AWS answers this way.
@@ -276,8 +281,7 @@ Not emulated yet:
- Payload encryption. `KMSKeyArn` is stored and returned only.
- EventBridge status-change events and a dead-letter queue or destinations for durable
executions.
- The `Lineage` field AWS adds to the trace header, and trace header propagation through chained
invokes.
- The `Lineage` field AWS adds to the trace header.
- The per-execution limits of 3,000 operations and 100 MB of persisted payload.
## Code signing configuration pagination
@@ -395,6 +395,7 @@ final class DurableCheckpointApplier {
DurableOperation operation = create(update);
operation.setChainedFunctionName(update.chainedFunctionName());
operation.setChainedTenantId(update.chainedTenantId());
operation.setChainedTraceHeader(update.chainedTraceHeader());
operation.setInputPayload(update.payload());
AwsException unreachable = unreachableTarget.apply(update.chainedFunctionName());
if (unreachable == null) {
@@ -691,11 +691,12 @@ public class DurableExecutionService implements Resettable {
// ──────────────────────────── state changes ────────────────────────────
private DurableExecution newExecution(StartRequest request, ResolvedDurableTarget target, String name, long now) {
return newExecution(request, target, name, UUID.randomUUID().toString(), now);
return newExecution(request, target, name, UUID.randomUUID().toString(),
DurableTraceHeader.forExecution(request.traceHeader(), target.activeTracing(), now / 1000), now);
}
private DurableExecution newExecution(StartRequest request, ResolvedDurableTarget target, String name,
String executionId, long now) {
String executionId, String traceHeader, long now) {
DurableExecution execution = new DurableExecution();
execution.setExecutionId(executionId);
execution.setName(name);
@@ -706,8 +707,7 @@ public class DurableExecutionService implements Resettable {
execution.setVersion(target.version());
execution.setExecutionArn(target.functionArn() + "/durable-execution/" + name + "/" + executionId);
execution.setStartTimestamp(now);
execution.setTraceHeader(DurableTraceHeader.forExecution(request.traceHeader(), target.activeTracing(),
now / 1000));
execution.setTraceHeader(traceHeader);
execution.setInputPayload(request.inputPayload());
execution.setExecutionTimeoutSeconds(target.executionTimeoutSeconds());
execution.setRetentionPeriodInDays(target.retentionPeriodInDays());
@@ -856,13 +856,20 @@ public class DurableExecutionService implements Resettable {
List<Runnable> effects) {
StartRequest request = new StartRequest(target.accountId(), target.region(), target.functionName(),
target.version(), name, operation.getInputPayload(), false, null);
DurableExecution child = newExecution(request, target, name, executionId, now);
DurableExecution child = newExecution(request, target, name, executionId,
chainedTraceHeader(parent, operation, target), now);
child.setParentExecutionArn(parent.getExecutionArn());
child.setParentOperationId(operation.getId());
trigger(child, effects);
return child;
}
private static String chainedTraceHeader(DurableExecution parent, DurableOperation operation,
ResolvedDurableTarget target) {
return DurableTraceHeader.forChainedChild(operation.getChainedTraceHeader(), parent.getTraceHeader(),
target.activeTracing());
}
private Runnable plainChainedInvoke(DurableExecution parent, DurableOperation operation,
ResolvedDurableTarget target) {
String accountId = parent.getAccountId();
@@ -871,19 +878,21 @@ public class DurableExecutionService implements Resettable {
// A plain target gets {} when the update has no Payload. A durable child starts with no input.
byte[] payload = (operation.getInputPayload() != null ? operation.getInputPayload() : "{}")
.getBytes(StandardCharsets.UTF_8);
String traceId = DurableTraceHeader.forInvocation(chainedTraceHeader(parent, operation, target),
target.activeTracing());
long launchGeneration = generation.get();
return () -> launchExecutor.execute(() -> {
ChainedOutcome outcome = invokePlainFunction(target, payload);
ChainedOutcome outcome = invokePlainFunction(target, payload, traceId);
if (launchGeneration == generation.get()) {
finishChainedInvoke(accountId, key, operationId, null, outcome);
}
});
}
private ChainedOutcome invokePlainFunction(ResolvedDurableTarget target, byte[] payload) {
private ChainedOutcome invokePlainFunction(ResolvedDurableTarget target, byte[] payload, String traceId) {
DurableInvocationResult result;
try {
result = invoker.invoke(target, payload, UUID.randomUUID().toString(), null);
result = invoker.invoke(target, payload, UUID.randomUUID().toString(), traceId);
} catch (AwsException e) {
return ChainedOutcome.failed(e);
} catch (RuntimeException e) {
@@ -37,6 +37,22 @@ final class DurableTraceHeader {
return format(root, parent, sampled);
}
/**
* Unlike Invoke, the Parent sent is kept as is, and an Active target gets none when none was sent.
*/
static String forChainedChild(String requested, String callerHeader, boolean activeTracing) {
Fields fields = parse(requested);
if (fields.root() == null) {
return callerHeader;
}
String sampled = fields.sampled() != null ? fields.sampled() : activeTracing ? "1" : "0";
String parent = fields.parent();
if (parent == null && !activeTracing && fields.sampled() == null) {
parent = XRayTraceIds.segmentId();
}
return format(fields.root(), parent, sampled);
}
static String forInvocation(String executionHeader, boolean activeTracing) {
if (executionHeader == null) {
return null;
@@ -48,6 +64,9 @@ final class DurableTraceHeader {
if (fields.parent() != null) {
return executionHeader;
}
if ("0".equals(fields.sampled())) {
return format(fields.root(), XRayTraceIds.segmentId(), "0");
}
return "Root=" + fields.root();
}
@@ -287,7 +287,8 @@ public final class DurableWire {
integer(callbackOptions, "HeartbeatTimeoutSeconds", path + "callbackOptions", 0,
MAX_CALLBACK_TIMEOUT_SECONDS),
chainedInvokeOptions == null ? null : string(chainedInvokeOptions, "FunctionName"),
chainedInvokeOptions == null ? null : string(chainedInvokeOptions, "TenantId"));
chainedInvokeOptions == null ? null : string(chainedInvokeOptions, "TenantId"),
chainedInvokeOptions == null ? null : string(chainedInvokeOptions, "XAmznTraceId"));
}
private static <E extends Enum<E>> E enumMember(Map<?, ?> map, String member, Class<E> type) {
@@ -37,6 +37,7 @@ public class DurableOperation {
/** The FunctionName of a chained invoke, as the function sent it. */
private String chainedFunctionName;
private String chainedTenantId;
private String chainedTraceHeader;
/** Set when a chained invoke runs a durable function. Unset, the function runs as a plain invocation. */
private String childExecutionArn;
/** Position in the execution's change log. The handler is only shown operations newer than it has seen. */
@@ -68,6 +69,7 @@ public class DurableOperation {
copy.heartbeatDeadline = heartbeatDeadline;
copy.chainedFunctionName = chainedFunctionName;
copy.chainedTenantId = chainedTenantId;
copy.chainedTraceHeader = chainedTraceHeader;
copy.childExecutionArn = childExecutionArn;
copy.changeSequence = changeSequence;
return copy;
@@ -138,6 +140,9 @@ public class DurableOperation {
public String getChainedTenantId() { return chainedTenantId; }
public void setChainedTenantId(String chainedTenantId) { this.chainedTenantId = chainedTenantId; }
public String getChainedTraceHeader() { return chainedTraceHeader; }
public void setChainedTraceHeader(String chainedTraceHeader) { this.chainedTraceHeader = chainedTraceHeader; }
public String getChildExecutionArn() { return childExecutionArn; }
public void setChildExecutionArn(String childExecutionArn) { this.childExecutionArn = childExecutionArn; }
@@ -18,5 +18,6 @@ public record DurableOperationUpdate(String id,
Integer callbackTimeoutSeconds,
Integer callbackHeartbeatTimeoutSeconds,
String chainedFunctionName,
String chainedTenantId) {
String chainedTenantId,
String chainedTraceHeader) {
}
@@ -35,10 +35,10 @@ class DurableCheckpointApplierTest {
void anExecutionCloseCarriesOnlyItsOwnResultKind() {
DurableErrorObject error = DurableErrorObject.of("m", "T");
assertRejected(List.of(new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
DurableOperationAction.SUCCEED, "\"p\"", error, null, null, null, null, null, null, null)),
DurableOperationAction.SUCCEED, "\"p\"", error, null, null, null, null, null, null, null, null)),
"Cannot provide an Error for SUCCEED action.");
assertRejected(List.of(new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
DurableOperationAction.FAIL, "\"p\"", error, null, null, null, null, null, null, null)),
DurableOperationAction.FAIL, "\"p\"", error, null, null, null, null, null, null, null, null)),
"Cannot provide a Payload for FAIL action.");
}
@@ -46,7 +46,7 @@ class DurableCheckpointApplierTest {
void anExecutionErrorHasTheSameSizeLimitAsAnOperationError() {
DurableErrorObject large = DurableErrorObject.of("x".repeat(DurableCheckpointApplier.MAX_ERROR_BYTES), "T");
assertRejected(List.of(new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
DurableOperationAction.FAIL, null, large, null, null, null, null, null, null, null)),
DurableOperationAction.FAIL, null, large, null, null, null, null, null, null, null, null)),
"Error object size must be less than 32768 bytes.");
}
@@ -79,7 +79,7 @@ class DurableCheckpointApplierTest {
assertEquals("Invalid current STEP state to start.", reject(execution, List.of(stepStart("s1", null))));
assertEquals("Cannot provide an Error for SUCCEED action.", reject(execution, List.of(
new DurableOperationUpdate("s1", null, null, DurableOperationType.STEP, null,
DurableOperationAction.SUCCEED, null, DurableErrorObject.of("x", "y"), null, null, null, null, null, null, null))));
DurableOperationAction.SUCCEED, null, DurableErrorObject.of("x", "y"), null, null, null, null, null, null, null, null))));
assertEquals("Invalid StepOptions for the given action.", reject(execution, List.of(
update("s1", null, DurableOperationType.STEP, DurableOperationAction.RETRY, null))));
DurableCheckpointApplier.apply(execution, List.of(update("s1", null, DurableOperationType.STEP,
@@ -191,7 +191,7 @@ class DurableCheckpointApplierTest {
update("s1", null, DurableOperationType.STEP, DurableOperationAction.SUCCEED, null),
update("s2", null, DurableOperationType.STEP, DurableOperationAction.FAIL, null),
new DurableOperationUpdate("s3", null, null, DurableOperationType.STEP, null,
DurableOperationAction.RETRY, null, null, 1, null, null, null, null, null, null),
DurableOperationAction.RETRY, null, null, 1, null, null, null, null, null, null, null),
update("c1", null, DurableOperationType.CONTEXT, DurableOperationAction.SUCCEED, null),
update("c2", null, DurableOperationType.CONTEXT, DurableOperationAction.FAIL, null)), NOW, REACHABLE);
@@ -258,12 +258,12 @@ class DurableCheckpointApplierTest {
private static DurableOperationUpdate waitStart(String id) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.WAIT, null, DurableOperationAction.START,
null, null, null, 5, null, null, null, null, null);
null, null, null, 5, null, null, null, null, null, null);
}
private static DurableOperationUpdate callbackStart(String id, int timeoutSeconds, int heartbeatSeconds) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.CALLBACK, "Callback",
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds, null, null);
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds, null, null, null);
}
private static DurableOperationUpdate chainedStart(String id, String payload) {
@@ -272,7 +272,7 @@ class DurableCheckpointApplierTest {
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.CHAINED_INVOKE, "ChainedInvoke",
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null);
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null, null);
}
private static DurableOperationUpdate executionSucceed() {
@@ -282,6 +282,6 @@ class DurableCheckpointApplierTest {
private static DurableOperationUpdate update(String id, String parentId, DurableOperationType type,
DurableOperationAction action, String payload) {
return new DurableOperationUpdate(id, parentId, null, type, null, action, payload, null, null, null, null, null,
null, null, null);
null, null, null, null);
}
}
@@ -145,7 +145,7 @@ class DurableExecutionServicePersistenceTest {
before.script((service, event) -> {
service.checkpoint(arn(event), token(event), null, List.of(new DurableOperationUpdate("i1", null, null,
DurableOperationType.CHAINED_INVOKE, "ChainedInvoke", DurableOperationAction.START, "{\"n\":1}",
null, null, null, null, null, null, "plain-fn", null)));
null, null, null, null, null, null, "plain-fn", null, null)));
return "{\"Status\":\"PENDING\"}";
});
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
@@ -180,7 +180,7 @@ class DurableExecutionServicePersistenceTest {
before.script((service, event) -> {
service.checkpoint(arn(event), token(event), null, List.of(new DurableOperationUpdate("i1", null, null,
DurableOperationType.CHAINED_INVOKE, "ChainedInvoke", DurableOperationAction.START, null,
null, null, null, null, null, null, "child-fn:1", null)));
null, null, null, null, null, null, "child-fn:1", null, null)));
return "{\"Status\":\"PENDING\"}";
});
String executionArn = first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}",
@@ -264,7 +264,7 @@ class DurableExecutionServicePersistenceTest {
service.checkpoint(arn(event), token(event), null, List.of(chainedStart("i1", "plain-fn", "{\"n\":1}"),
new DurableOperationUpdate("result", null, null, DurableOperationType.EXECUTION, null,
DurableOperationAction.SUCCEED, "\"closed\"", null, null, null, null, null, null, null,
null)));
null, null)));
return "{\"Status\":\"SUCCEEDED\",\"Result\":\"\"}";
});
first.start(new StartRequest(ACCOUNT, "us-east-1", "durable-fn", "1", "exec-1", "{}", false, null));
@@ -298,7 +298,7 @@ class DurableExecutionServicePersistenceTest {
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.CHAINED_INVOKE, "ChainedInvoke",
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null);
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null, null);
}
private DurableExecutionService newService(StorageFactory storage, ScriptedInvoker invoker) {
@@ -314,12 +314,12 @@ class DurableExecutionServicePersistenceTest {
private static DurableOperationUpdate update(String id, DurableOperationType type, DurableOperationAction action,
String payload, Integer waitSeconds) {
return new DurableOperationUpdate(id, null, null, type, null, action, payload, null, null, waitSeconds, null, null, null, null, null);
return new DurableOperationUpdate(id, null, null, type, null, action, payload, null, null, waitSeconds, null, null, null, null, null, null);
}
private static DurableOperationUpdate callbackStart(String id, int timeoutSeconds) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.CALLBACK, "Callback",
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, null, null, null);
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, null, null, null, null);
}
private static String arn(JsonNode event) {
@@ -29,6 +29,7 @@ import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -736,6 +737,82 @@ class DurableExecutionServiceTest {
assertTrue(eventTypes(execution).contains("ChainedInvokeSucceeded"));
}
@Test
void aDurableChainedChildTakesTheRequestedTraceHeaderAndPassesItToItsInvocation() {
String header = "Root=1-6af70000-0000000000000000000000e1;Parent=00000000000000e1;Sampled=1";
invoker.childScript("child-fn", event -> succeeded("\"c\""));
invoker.script(event -> {
checkpoint(event, token(event), List.of(chainedStart("i1", "child-fn:1", null, header)));
return pending();
});
invoker.script(event -> succeeded("\"done\""));
DurableExecution parent = service.get(startWithTraceHeader("exec-1",
"Root=1-6af70000-0000000000000000000000aa;Parent=00000000000000a1;Sampled=1").getExecutionArn());
DurableExecution child = service.get(parent.getOperations().get("i1").getChildExecutionArn());
assertEquals(header, child.getTraceHeader());
assertEquals(List.of(header), invoker.otherTraceIds.get("child-fn"));
}
@Test
void aDurableChainedChildWithoutARequestedTraceHeaderTakesTheParentHeader() {
String parentHeader = "Root=1-6af70000-0000000000000000000000aa;Parent=00000000000000a1;Sampled=1";
invoker.childScript("child-fn", event -> succeeded("\"c\""));
invoker.script(event -> {
checkpoint(event, token(event), List.of(chainedStart("i1", "child-fn:1", null)));
return pending();
});
invoker.script(event -> succeeded("\"done\""));
DurableExecution parent = service.get(startWithTraceHeader("exec-1", parentHeader).getExecutionArn());
DurableExecution child = service.get(parent.getOperations().get("i1").getChildExecutionArn());
assertEquals(parentHeader, child.getTraceHeader());
assertEquals(List.of(parentHeader), invoker.otherTraceIds.get("child-fn"));
}
@Test
void aPlainChainedTargetGetsTheRequestedTraceHeader() {
String header = "Root=1-6af70000-0000000000000000000000e1;Parent=00000000000000e1;Sampled=1";
invoker.plainFunctions.put("plain-fn", event -> handlerResponse("{}"));
invoker.plainFunctions.put("active-fn", event -> handlerResponse("{}"));
invoker.activeFunctions.add("active-fn");
invoker.script(event -> {
checkpoint(event, token(event), List.of(chainedStart("p", "plain-fn", null, header),
chainedStart("a", "active-fn", null, header)));
return pending();
});
invoker.script(event -> succeeded("\"done\""));
start("exec-1", "{}", false);
assertEquals(List.of(header), invoker.otherTraceIds.get("plain-fn"));
assertEquals(1, invoker.otherTraceIds.get("active-fn").size());
assertTrue(invoker.otherTraceIds.get("active-fn").get(0)
.matches("Root=1-6af70000-0000000000000000000000e1;Parent=(?!00000000000000e1)[0-9a-f]{16};Sampled=1"));
}
@Test
void aPlainPassThroughTargetGetsANewParentOnlyForAnUnsampledHeaderWithoutOne() {
invoker.plainFunctions.put("sampled-fn", event -> handlerResponse("{}"));
invoker.plainFunctions.put("unsampled-fn", event -> handlerResponse("{}"));
invoker.script(event -> {
checkpoint(event, token(event), List.of(
chainedStart("s", "sampled-fn", null, "Root=1-6af70000-0000000000000000000000a1;Sampled=1"),
chainedStart("u", "unsampled-fn", null, "Root=1-6af70000-0000000000000000000000a2;Sampled=0")));
return pending();
});
invoker.script(event -> succeeded("\"done\""));
start("exec-1", "{}", false);
assertEquals(List.of("Root=1-6af70000-0000000000000000000000a1"), invoker.otherTraceIds.get("sampled-fn"));
assertEquals(1, invoker.otherTraceIds.get("unsampled-fn").size());
assertTrue(invoker.otherTraceIds.get("unsampled-fn").get(0)
.matches("Root=1-6af70000-0000000000000000000000a2;Parent=[0-9a-f]{16};Sampled=0"));
}
@Test
void aChainedInvokeOfAPlainFunctionFailsWithItsErrorOrAnOversizedOutput() {
invoker.plainFunctions.put("raising-fn",
@@ -924,8 +1001,14 @@ class DurableExecutionServiceTest {
}
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload) {
return chainedStart(id, functionName, payload, null);
}
private static DurableOperationUpdate chainedStart(String id, String functionName, String payload,
String traceHeader) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.CHAINED_INVOKE, "ChainedInvoke",
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null);
DurableOperationAction.START, payload, null, null, null, null, null, null, functionName, null,
traceHeader);
}
private static void assertCallbackClosed(Executable call) {
@@ -977,27 +1060,27 @@ class DurableExecutionServiceTest {
private static DurableOperationUpdate step(String id, DurableOperationAction action, String payload,
DurableErrorObject error) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.STEP, "Step", action, payload, error,
null, null, null, null, null, null, null);
null, null, null, null, null, null, null, null);
}
private static DurableOperationUpdate stepRetry(String id, int delaySeconds, DurableErrorObject error) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.STEP, "Step",
DurableOperationAction.RETRY, null, error, delaySeconds, null, null, null, null, null, null);
DurableOperationAction.RETRY, null, error, delaySeconds, null, null, null, null, null, null, null);
}
private static DurableOperationUpdate callbackStart(String id, int timeoutSeconds, int heartbeatSeconds) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.CALLBACK, "Callback",
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds, null, null);
DurableOperationAction.START, null, null, null, null, null, timeoutSeconds, heartbeatSeconds, null, null, null);
}
private static DurableOperationUpdate waitStart(String id, int seconds) {
return new DurableOperationUpdate(id, null, null, DurableOperationType.WAIT, "Wait",
DurableOperationAction.START, null, null, null, seconds, null, null, null, null, null);
DurableOperationAction.START, null, null, null, seconds, null, null, null, null, null, null);
}
private static DurableOperationUpdate executionSucceed(String payload) {
return new DurableOperationUpdate("execution-result", null, null, DurableOperationType.EXECUTION, null,
DurableOperationAction.SUCCEED, payload, null, null, null, null, null, null, null, null);
DurableOperationAction.SUCCEED, payload, null, null, null, null, null, null, null, null, null);
}
private static DurableFunctionInvoker.DurableInvocationResult succeeded(String result) {
@@ -1032,7 +1115,11 @@ class DurableExecutionServiceTest {
String functionName = FUNCTION;
int retentionPeriodInDays = 7;
boolean activeTracing;
/** Functions that trace Active, plain or durable, whatever activeTracing says. */
final Set<String> activeFunctions = new HashSet<>();
final List<String> traceIds = new ArrayList<>();
/** The trace id each invocation of a function other than the one under test received. */
final Map<String, List<String>> otherTraceIds = new HashMap<>();
void script(Function<JsonNode, DurableInvocationResult> script) {
scripts.add(script);
@@ -1047,7 +1134,8 @@ class DurableExecutionServiceTest {
String version = qualifier == null ? "$LATEST" : qualifier;
if (plainFunctions.containsKey(functionName)) {
return new ResolvedDurableTarget(accountId, region, functionName,
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName, version, false, 0, 0, false);
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName, version, false, 0, 0,
activeFunctions.contains(functionName));
}
String name = FUNCTION.equals(functionName) ? this.functionName : functionName;
if (!name.equals(this.functionName) && !childScripts.containsKey(name)) {
@@ -1057,7 +1145,7 @@ class DurableExecutionServiceTest {
return new ResolvedDurableTarget(accountId, region, name,
"arn:aws:lambda:us-east-1:000000000000:function:" + name + ":" + durableVersion, durableVersion,
true, name.equals(this.functionName) ? executionTimeoutSeconds : childExecutionTimeoutSeconds,
retentionPeriodInDays, activeTracing);
retentionPeriodInDays, activeTracing || activeFunctions.contains(name));
}
@Override
@@ -1069,6 +1157,9 @@ class DurableExecutionServiceTest {
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (!FUNCTION.equals(target.functionName())) {
otherTraceIds.computeIfAbsent(target.functionName(), ignored -> new ArrayList<>()).add(traceId);
}
if (!target.durable()) {
return plainFunctions.get(target.functionName()).apply(event);
}
@@ -14,6 +14,7 @@ class DurableTraceHeaderTest {
private static final long NOW = 0x6af80000L;
private static final String NEW_ROOT = "1-6af80000-[0-9a-f]{24}";
private static final String NEW_ID = "[0-9a-f]{16}";
private static final String CALLER = "Root=1-6af6281a-10d34ccb165fe4201aea66dd;Parent=4800428e122b3d8d;Sampled=0";
private static String execution(String received, boolean active) {
return DurableTraceHeader.forExecution(received, active, NOW);
@@ -144,8 +145,20 @@ class DurableTraceHeaderTest {
}
@Test
void passThroughInvocationWithoutAParentGetsTheRootOnly() {
assertEquals("Root=" + ROOT, DurableTraceHeader.forInvocation("Root=" + ROOT + ";Sampled=0", false));
void passThroughInvocationOfASampledHeaderWithoutAParentGetsTheRootOnly() {
assertEquals("Root=" + ROOT, DurableTraceHeader.forInvocation("Root=" + ROOT + ";Sampled=1", false));
}
@Test
void passThroughInvocationsOfAnUnsampledHeaderWithoutAParentGetANewParentEach() {
String stored = "Root=" + ROOT + ";Sampled=0";
String first = DurableTraceHeader.forInvocation(stored, false);
String second = DurableTraceHeader.forInvocation(stored, false);
assertTrue(first.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
assertTrue(second.matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
assertNotEquals(first, second);
}
@Test
@@ -153,4 +166,80 @@ class DurableTraceHeaderTest {
assertNull(DurableTraceHeader.forInvocation(null, true));
assertNull(DurableTraceHeader.forInvocation(null, false));
}
private static String chained(String requested, boolean active) {
return DurableTraceHeader.forChainedChild(requested, CALLER, active);
}
@Test
void chainedFullHeaderIsKeptOnPassThrough() {
String header = "Root=" + ROOT + ";Parent=00000000000000aa;Sampled=1";
assertEquals(header, chained(header, false));
}
@Test
void chainedFullUnsampledHeaderIsKeptOnActive() {
String header = "Root=" + ROOT + ";Parent=00000000000000cc;Sampled=0";
assertEquals(header, chained(header, true));
}
@Test
void chainedFullSampledHeaderKeepsItsParentOnActive() {
String header = "Root=" + ROOT + ";Parent=00000000000000e1;Sampled=1";
assertEquals(header, chained(header, true));
}
@Test
void chainedRootOnlyOnPassThroughGetsANewParentAndUnsampled() {
assertTrue(chained("Root=" + ROOT, false).matches("Root=" + ROOT + ";Parent=" + NEW_ID + ";Sampled=0"));
}
@Test
void chainedRootOnlyOnActiveGetsSampledWithoutAParent() {
assertEquals("Root=" + ROOT + ";Sampled=1", chained("Root=" + ROOT, true));
}
@Test
void chainedRootAndSampledOnPassThroughGetsNoParent() {
assertEquals("Root=" + ROOT + ";Sampled=1", chained("Root=" + ROOT + ";Sampled=1", false));
}
@Test
void chainedRootAndParentOnPassThroughGetsUnsampled() {
assertEquals("Root=" + ROOT + ";Parent=00000000000000e4;Sampled=0",
chained("Root=" + ROOT + ";Parent=00000000000000e4", false));
}
@Test
void chainedRootAndUnsampledOnActiveGetsNoParent() {
assertEquals("Root=" + ROOT + ";Sampled=0", chained("Root=" + ROOT + ";Sampled=0", true));
}
@Test
void chainedRootAndParentOnActiveGetsSampled() {
assertEquals("Root=" + ROOT + ";Parent=00000000000000e6;Sampled=1",
chained("Root=" + ROOT + ";Parent=00000000000000e6", true));
}
@Test
void chainedUnknownSampledOnActiveBecomesSampled() {
assertEquals("Root=" + ROOT + ";Parent=00000000000000e7;Sampled=1",
chained("Root=" + ROOT + ";Parent=00000000000000e7;Sampled=?", true));
}
@Test
void chainedWithoutAUsableRequestTakesTheCallerHeaderAsIs() {
for (boolean active : new boolean[] {false, true}) {
assertEquals(CALLER, chained(null, active));
assertEquals(CALLER, chained("", active));
assertEquals(CALLER, chained("garbage", active));
assertEquals(CALLER, chained("Parent=00000000000000e7;Sampled=1", active));
}
}
@Test
void chainedCallerHeaderWithoutAParentPassesVerbatim() {
String caller = "Root=" + ROOT + ";Sampled=1";
assertEquals(caller, DurableTraceHeader.forChainedChild(null, caller, false));
}
}
@@ -27,6 +27,7 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -90,6 +91,53 @@ class LambdaDurableProtocolIntegrationTest {
assertEquals(200, invoke.get(30, TimeUnit.SECONDS).statusCode());
}
@Test
void aChainedInvokeTraceHeaderReachesTheChildInvocationAndExecution() throws Exception {
String traceHeader = "Root=1-6af70000-0000000000000000000000e1;Parent=00000000000000e1;Sampled=1";
Response accepted = given()
.header("X-Amz-Invocation-Type", "Event")
.header("X-Amz-Durable-Execution-Name", "chained-trace-1")
.body("{}")
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations");
String arn = accepted.getHeader("X-Amz-Durable-Execution-Arn");
Invocation parent = invoker.awaitInvocation(Duration.ofSeconds(30));
JsonNode event = MAPPER.readTree(parent.payload());
given()
.urlEncodingEnabled(false)
.contentType("application/json")
.body("""
{
"CheckpointToken": "%s",
"Updates": [{"Id": "i1", "Name": "child", "Type": "CHAINED_INVOKE", "SubType": "ChainedInvoke",
"Action": "START", "ChainedInvokeOptions": {"FunctionName": "%s:$LATEST",
"XAmznTraceId": "%s"}}]
}
""".formatted(event.get("CheckpointToken").asText(), FUNCTION, traceHeader))
.when()
.post(DURABLE + "/durable-executions/" + arn + "/checkpoint")
.then()
.statusCode(200);
parent.response().complete(handlerResponse("{\"Status\": \"PENDING\"}"));
Invocation child = invoker.awaitInvocation(Duration.ofSeconds(30));
String childArn = MAPPER.readTree(child.payload()).get("DurableExecutionArn").asText();
assertNotEquals(arn, childArn);
assertEquals(traceHeader, child.traceId());
given()
.urlEncodingEnabled(false)
.when()
.get(DURABLE + "/durable-executions/" + childArn)
.then()
.statusCode(200)
.body("TraceHeader.XAmznTraceId", equalTo(traceHeader));
child.response().complete(handlerResponse("{\"Status\": \"SUCCEEDED\", \"Result\": \"{}\"}"));
Invocation resumed = invoker.awaitInvocation(Duration.ofSeconds(30));
assertEquals(arn, MAPPER.readTree(resumed.payload()).get("DurableExecutionArn").asText());
resumed.response().complete(handlerResponse("{\"Status\": \"SUCCEEDED\", \"Result\": \"{}\"}"));
}
@Test
void aSynchronousInvokeReturnsTheResultOfACheckpointedExecution() throws Exception {
CompletableFuture<Response> invoke = CompletableFuture.supplyAsync(() -> given()