diff --git a/.autover/autover.json b/.autover/autover.json
index 670e0ba97..f9e21dcdd 100644
--- a/.autover/autover.json
+++ b/.autover/autover.json
@@ -54,6 +54,10 @@
"Libraries/src/Amazon.Lambda.DurableExecution.Analyzers/Amazon.Lambda.DurableExecution.Analyzers.csproj"
]
},
+ {
+ "Name": "Amazon.Lambda.DurableExecution.OpenTelemetry",
+ "Path": "Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Amazon.Lambda.DurableExecution.OpenTelemetry.csproj"
+ },
{
"Name": "Amazon.Lambda.DurableExecution.Testing",
"Path": "Libraries/src/Amazon.Lambda.DurableExecution.Testing/Amazon.Lambda.DurableExecution.Testing.csproj"
diff --git a/.autover/changes/7c2d4e19-5a3b-4f6e-8b0d-1e9f2a3b4c5d.json b/.autover/changes/7c2d4e19-5a3b-4f6e-8b0d-1e9f2a3b4c5d.json
new file mode 100644
index 000000000..fd8cd4a79
--- /dev/null
+++ b/.autover/changes/7c2d4e19-5a3b-4f6e-8b0d-1e9f2a3b4c5d.json
@@ -0,0 +1,11 @@
+{
+ "Projects": [
+ {
+ "Name": "Amazon.Lambda.DurableExecution.OpenTelemetry",
+ "Type": "Minor",
+ "ChangelogMessages": [
+ "Initial preview of OpenTelemetry tracing for Amazon.Lambda.DurableExecution. The Invocation view emits Workflow, Invocation, operation and attempt spans through System.Diagnostics.ActivitySource, with no OpenTelemetry package dependency. ContextExtractors.W3C anchors the execution on a W3C traceparent instead of an X-Ray header."
+ ]
+ }
+ ]
+}
diff --git a/Libraries/Amazon.Lambda.DurableExecution.slnf b/Libraries/Amazon.Lambda.DurableExecution.slnf
index 645c64888..4e3d405b7 100644
--- a/Libraries/Amazon.Lambda.DurableExecution.slnf
+++ b/Libraries/Amazon.Lambda.DurableExecution.slnf
@@ -8,8 +8,10 @@
"src\\Amazon.Lambda.TestUtilities\\Amazon.Lambda.TestUtilities.csproj",
"src\\Amazon.Lambda.DurableExecution\\Amazon.Lambda.DurableExecution.csproj",
"src\\Amazon.Lambda.DurableExecution.Testing\\Amazon.Lambda.DurableExecution.Testing.csproj",
+ "src\\Amazon.Lambda.DurableExecution.OpenTelemetry\\Amazon.Lambda.DurableExecution.OpenTelemetry.csproj",
"test\\Amazon.Lambda.DurableExecution.Tests\\Amazon.Lambda.DurableExecution.Tests.csproj",
"test\\Amazon.Lambda.DurableExecution.Testing.Tests\\Amazon.Lambda.DurableExecution.Testing.Tests.csproj",
+ "test\\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests\\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj",
"test\\Amazon.Lambda.DurableExecution.IntegrationTests\\Amazon.Lambda.DurableExecution.IntegrationTests.csproj",
"test\\Amazon.Lambda.DurableExecution.AotPublishTest\\Amazon.Lambda.DurableExecution.AotPublishTest.csproj"
]
diff --git a/Libraries/Libraries.sln b/Libraries/Libraries.sln
index 0d4118486..60577aa9c 100644
--- a/Libraries/Libraries.sln
+++ b/Libraries/Libraries.sln
@@ -181,6 +181,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.OCI.Builder.Tests", "te
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.OCI.Builder.IntegrationTests", "test\AWS.OCI.Builder.IntegrationTests\AWS.OCI.Builder.IntegrationTests.csproj", "{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Amazon.Lambda.DurableExecution.OpenTelemetry", "src\Amazon.Lambda.DurableExecution.OpenTelemetry\Amazon.Lambda.DurableExecution.OpenTelemetry.csproj", "{F7163946-2476-45F1-B56F-8B9340B1533A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Amazon.Lambda.DurableExecution.OpenTelemetry.Tests", "test\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj", "{9336B275-FC95-4590-8D57-D1FB6BAA7A33}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -1151,6 +1155,30 @@ Global
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}.Release|x64.Build.0 = Release|Any CPU
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}.Release|x86.ActiveCfg = Release|Any CPU
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}.Release|x86.Build.0 = Release|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x64.Build.0 = Debug|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x86.Build.0 = Debug|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x64.ActiveCfg = Release|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x64.Build.0 = Release|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x86.ActiveCfg = Release|Any CPU
+ {F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x86.Build.0 = Release|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x64.Build.0 = Debug|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x86.Build.0 = Debug|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|Any CPU.Build.0 = Release|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x64.ActiveCfg = Release|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x64.Build.0 = Release|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x86.ActiveCfg = Release|Any CPU
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -1240,6 +1268,8 @@ Global
{BB37A746-2351-9685-2D1F-1571F8F23E06} = {AAB54E74-20B1-42ED-BC3D-CE9F7BC7FD12}
{7636C459-D2A3-30DB-4964-CAF22E6BA256} = {1DE4EE60-45BA-4EF7-BE00-B9EB861E4C69}
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9} = {1DE4EE60-45BA-4EF7-BE00-B9EB861E4C69}
+ {F7163946-2476-45F1-B56F-8B9340B1533A} = {AAB54E74-20B1-42ED-BC3D-CE9F7BC7FD12}
+ {9336B275-FC95-4590-8D57-D1FB6BAA7A33} = {1DE4EE60-45BA-4EF7-BE00-B9EB861E4C69}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {503678A4-B8D1-4486-8915-405A3E9CF0EB}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Amazon.Lambda.DurableExecution.OpenTelemetry.csproj b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Amazon.Lambda.DurableExecution.OpenTelemetry.csproj
new file mode 100644
index 000000000..f8cac8a2f
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Amazon.Lambda.DurableExecution.OpenTelemetry.csproj
@@ -0,0 +1,36 @@
+
+
+
+
+
+ $(DefaultPackageTargets)
+ OpenTelemetry tracing for Amazon.Lambda.DurableExecution. Emits Workflow, Invocation, operation and attempt spans through System.Diagnostics.ActivitySource.
+ Amazon.Lambda.DurableExecution.OpenTelemetry
+ 0.1.0
+ Amazon.Lambda.DurableExecution.OpenTelemetry
+ Amazon.Lambda.DurableExecution.OpenTelemetry
+ AWS;Amazon;Lambda;Durable;Workflow;OpenTelemetry;Tracing
+ true
+ true
+ enable
+ enable
+ true
+ IL2026,IL2067,IL2075,IL3050
+
+
+
+
+ <_Parameter1>Amazon.Lambda.DurableExecution.OpenTelemetry.Tests, PublicKey="0024000004800000940000000602000000240000525341310004000001000100db5f59f098d27276c7833875a6263a3cc74ab17ba9a9df0b52aedbe7252745db7274d5271fd79c1f08f668ecfa8eaab5626fa76adc811d3c8fc55859b0d09d3bc0a84eecd0ba891f2b8a2fc55141cdcc37c2053d53491e650a479967c3622762977900eddbf1252ed08a2413f00a28f3a0752a81203f03ccb7f684db373518b4"
+
+
+
+
+
+
+
+
+
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/ContextExtractors.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/ContextExtractors.cs
new file mode 100644
index 000000000..5f6ac8a42
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/ContextExtractors.cs
@@ -0,0 +1,102 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+/// Finds the trace context of a durable execution.
+public static class ContextExtractors
+{
+ ///
+ /// Reads . The durable service keeps the X-Ray Root the same for
+ /// every invocation of an execution, so its trace id anchors the whole execution.
+ ///
+ public static ExtractedContext? XRay(InvocationInfo info) => ParseXRayHeader(info.XRayTraceId);
+
+ ///
+ /// Reads , the W3C traceparent the invoke carried on
+ /// clientContext.w3c. Use it when the caller propagates W3C context instead of an X-Ray header. Like any
+ /// extractor it must return the same context on every invocation of an execution, or the execution splits
+ /// across traces.
+ ///
+ public static ExtractedContext? W3C(InvocationInfo info) => ParseTraceParent(info.TraceParent);
+
+ ///
+ /// Parses a W3C traceparent: version-traceid-parentid-flags, lowercase hex. A zero trace id or
+ /// parent id, a ff version, or a malformed field returns null. Version 00 has exactly four
+ /// fields; a later version may add more after them. The sampled flag is the low bit of the flags.
+ ///
+ internal static ExtractedContext? ParseTraceParent(string? traceParent)
+ {
+ if (string.IsNullOrWhiteSpace(traceParent))
+ return null;
+
+ var parts = traceParent.Trim().Split('-');
+ if (parts.Length < 4)
+ return null;
+
+ var (version, traceId, parentId, flags) = (parts[0], parts[1], parts[2], parts[3]);
+ if (version.Length != 2 || !DeterministicIds.IsLowerHex(version) || version == "ff" || (version == "00" && parts.Length != 4))
+ return null;
+ if (!DeterministicIds.IsValidTraceId(traceId) || !DeterministicIds.IsValidSpanId(parentId))
+ return null;
+ if (flags.Length != 2 || !DeterministicIds.IsLowerHex(flags))
+ return null;
+
+ return new ExtractedContext
+ {
+ TraceId = traceId,
+ ParentSpanId = parentId,
+ Sampling = (Convert.ToInt32(flags, 16) & 1) != 0 ? UpstreamSampling.Sampled : UpstreamSampling.NotSampled,
+ };
+ }
+
+ ///
+ /// Parses an X-Amzn-Trace-Id header. Root, Parent and Sampled are read independently;
+ /// an all-zero or malformed Root or Parent is ignored. Returns null without a valid Root.
+ ///
+ internal static ExtractedContext? ParseXRayHeader(string? header)
+ {
+ if (string.IsNullOrWhiteSpace(header))
+ return null;
+
+ string? root = null, parent = null, sampled = null;
+ foreach (var part in header.Split(';'))
+ {
+ var eq = part.IndexOf('=');
+ if (eq <= 0)
+ continue;
+
+ var key = part[..eq].Trim();
+ var value = part[(eq + 1)..].Trim();
+ switch (key)
+ {
+ case "Root": root = value; break;
+ case "Parent": parent = value; break;
+ case "Sampled": sampled = value; break;
+ }
+ }
+
+ if (root == null)
+ return null;
+
+ var rootValue = root.StartsWith("1-", StringComparison.Ordinal) ? root[2..] : root;
+ var traceId = rootValue.Replace("-", string.Empty).ToLowerInvariant();
+ if (!DeterministicIds.IsValidTraceId(traceId))
+ return null;
+
+ var parentSpanId = parent?.ToLowerInvariant();
+ return new ExtractedContext
+ {
+ TraceId = traceId,
+ ParentSpanId = parentSpanId != null && DeterministicIds.IsValidSpanId(parentSpanId) ? parentSpanId : null,
+ Sampling = sampled switch
+ {
+ "1" => UpstreamSampling.Sampled,
+ "0" => UpstreamSampling.NotSampled,
+ _ => UpstreamSampling.Undecided,
+ },
+ };
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ActivityIdOverride.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ActivityIdOverride.cs
new file mode 100644
index 000000000..1d9f2e175
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ActivityIdOverride.cs
@@ -0,0 +1,76 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// Gives an a span id of our choosing.
+///
+///
+/// The public API cannot do this: SpanId is read-only, and a parent context or SetParentId
+/// only chooses the parent. A durable execution needs it, because spans in one invocation must name spans that
+/// another invocation exports (the Workflow span, the first segment of an operation), and nothing is stored
+/// between invocations.
+/// This writes the private _spanId and _id fields through ,
+/// which is generated at compile time and is safe for trimming and Native AOT. The fields are not a contract. If
+/// a runtime renames them the first call throws, the override switches itself off, and spans get random ids:
+/// parenting inside one invocation still works, references across invocations do not. A test fails when the
+/// fields are missing, so a new runtime is noticed.
+/// Listeners notified when the activity starts have already seen the random id. Export and child spans see
+/// the one set here.
+///
+internal static class ActivityIdOverride
+{
+ private static volatile bool _disabled;
+
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_spanId")]
+ private static extern ref string? SpanIdField(Activity activity);
+
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_id")]
+ private static extern ref string? IdField(Activity activity);
+
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_parentSpanId")]
+ private static extern ref string? ParentSpanIdField(Activity activity);
+
+ [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_parentId")]
+ private static extern ref string? ParentIdField(Activity activity);
+
+ /// True once an override failed. Spans then have random ids.
+ internal static bool IsDisabled => _disabled;
+
+ /// Switches the override back on. For tests.
+ internal static void Reset() => _disabled = false;
+
+ ///
+ /// Sets the span id of a started activity, and optionally removes its parent so it exports as a root.
+ /// Returns false, and leaves the activity unchanged, when the override is unavailable.
+ ///
+ internal static bool TrySet(Activity? activity, string spanId, bool asRoot = false)
+ {
+ if (activity == null || _disabled)
+ return false;
+
+ try
+ {
+ var traceId = activity.TraceId.ToHexString();
+ var flags = (activity.ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0 ? "01" : "00";
+
+ SpanIdField(activity) = spanId;
+ IdField(activity) = $"00-{traceId}-{spanId}-{flags}";
+ if (asRoot)
+ {
+ ParentSpanIdField(activity) = null;
+ ParentIdField(activity) = null;
+ }
+ return true;
+ }
+ catch (Exception ex) when (ex is MissingFieldException or MissingMemberException or NullReferenceException)
+ {
+ _disabled = true;
+ return false;
+ }
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/DeterministicIds.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/DeterministicIds.cs
new file mode 100644
index 000000000..ea2b12cad
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/DeterministicIds.cs
@@ -0,0 +1,60 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// Trace and span ids that every invocation of an execution derives the same way. A span exported by one
+/// invocation can then be the parent of, or be linked from, a span exported by another, with nothing stored
+/// between them. The derivations match the JavaScript, Python and Java SDKs, so a trace that crosses SDKs stays
+/// consistent.
+///
+internal static class DeterministicIds
+{
+ private const string ZeroSpanId = "0000000000000000";
+ private const string ZeroTraceId = "00000000000000000000000000000000";
+
+ internal static bool IsValidTraceId(string? value) =>
+ value is { Length: 32 } && value != ZeroTraceId && IsLowerHex(value);
+
+ internal static bool IsValidSpanId(string? value) =>
+ value is { Length: 16 } && value != ZeroSpanId && IsLowerHex(value);
+
+ internal static bool IsLowerHex(string value)
+ {
+ foreach (var c in value)
+ {
+ if (!(c is >= '0' and <= '9' || c is >= 'a' and <= 'f'))
+ return false;
+ }
+ return true;
+ }
+
+ private static string Sha256Hex(string value, int length) =>
+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))).ToLowerInvariant()[..length];
+
+ /// The trace id of an execution that has no propagated trace: SHA-256 of the ARN and start time.
+ internal static string TraceIdFromArn(string executionArn, DateTimeOffset? executionStart)
+ {
+ var identity = executionStart is { } start
+ ? $"{executionArn}:{start.UtcDateTime:yyyy-MM-ddTHH:mm:ss.fffZ}"
+ : executionArn;
+ return Sha256Hex(identity, 32);
+ }
+
+ /// The id of the first span of an operation, scoped to the execution.
+ internal static string SpanIdFromOperationId(string operationId, string executionArn) =>
+ Sha256Hex(executionArn + ":" + operationId, 16);
+
+ /// The id of the Workflow span.
+ internal static string WorkflowSpanId(string executionArn) => NonZero(Sha256Hex("workflow:" + executionArn, 16));
+
+ /// The id of the synthetic root that anchors an execution with no propagated parent.
+ internal static string ExecutionRootSpanId(string executionArn) =>
+ NonZero(Sha256Hex("execution-root:" + executionArn, 16));
+
+ private static string NonZero(string spanId) => spanId == ZeroSpanId ? "0000000000000001" : spanId;
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ExecutionOtelPlugin.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ExecutionOtelPlugin.cs
new file mode 100644
index 000000000..c941cc5e1
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ExecutionOtelPlugin.cs
@@ -0,0 +1,435 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// The Execution view: operations are children of the Workflow span, whichever invocation runs them.
+///
+///
+///
+/// Execution ancestor (remote parent or synthetic root)
+/// +-- Workflow exported once, by the invocation that finishes the execution
+/// | +-- operation exported once, by the invocation where it finishes; links Invocation
+/// | +-- attempt exported by the invocation that ran it; links Invocation
+/// +-- Invocation one per Lambda invocation
+///
+/// An operation has one span, with an id derived from the execution ARN and the operation id. While it is open its
+/// identity is only a context: nothing is exported, so nothing is left unended when an invocation suspends. The span
+/// is created and ended together when the operation finishes, from the start and end times the service recorded.
+/// Attempts are real spans in the invocation that runs them, parented on the operation's derived id. The Workflow
+/// span is deferred the same way, to the invocation that finishes the execution.
+///
+internal sealed class ExecutionOtelPlugin : OtelPluginBase
+{
+ /// What was seen when an operation started, kept until it finishes.
+ private sealed class OperationStart
+ {
+ internal string? Name;
+ internal string? SubType;
+ internal string? ParentId;
+ internal DateTimeOffset Start;
+ }
+
+ // Operations that started and have not finished, by id. Their span does not exist yet.
+ private readonly Dictionary _operationContexts = new(StringComparer.Ordinal);
+ private readonly Dictionary _operationStarts = new(StringComparer.Ordinal);
+ private readonly Dictionary _attemptSpans = new(StringComparer.Ordinal);
+
+ // Child contexts exported in this invocation. A completion whose parent is one of them keeps that parent.
+ private readonly HashSet _recordedContextIds = new(StringComparer.Ordinal);
+
+ private IReadOnlyDictionary _endOperations = new Dictionary();
+ private DateTimeOffset? _latestObserved;
+
+ internal ExecutionOtelPlugin(ActivitySource source, OtelPluginOptions options, InvocationInfo info)
+ : base(source, options, info)
+ {
+ }
+
+ // ── Time ────────────────────────────────────────────────────────────────
+
+ ///
+ /// The invocation clock, never earlier than a time already seen. The service's timestamps are authoritative, so
+ /// a local clock that reads a little behind them must not put a span before something it enclosed.
+ ///
+ private DateTimeOffset LogicalNow() => Observe(Clock.Now);
+
+ private DateTimeOffset Observe(DateTimeOffset time)
+ {
+ if (_latestObserved == null || time > _latestObserved)
+ _latestObserved = time;
+ return time;
+ }
+
+ private static DateTimeOffset Earliest(DateTimeOffset? a, DateTimeOffset b) => a is { } x && x <= b ? x : b;
+
+ // ── Operations ──────────────────────────────────────────────────────────
+
+ public override void OnOperationStart(OperationInfo info)
+ {
+ if (!Enabled || Finalized)
+ return;
+
+ lock (Gate)
+ {
+ _operationContexts[info.Id] = OperationContext(info.Id);
+
+ _operationStarts.TryGetValue(info.Id, out var existing);
+ var start = Earliest(existing?.Start, info.StartTimestamp ?? LogicalNow());
+ var parentId = info.ParentId ?? existing?.ParentId;
+ _operationStarts[info.Id] = new OperationStart
+ {
+ Name = info.Name ?? existing?.Name,
+ SubType = info.SubType ?? existing?.SubType,
+ ParentId = parentId,
+ Start = start,
+ };
+ ObserveAncestorStart(parentId, start);
+ }
+ }
+
+ public override void OnOperationEnd(OperationEndInfo info)
+ {
+ if (!Enabled)
+ return;
+
+ lock (Gate)
+ FinishOperation(info);
+ }
+
+ private void FinishOperation(OperationEndInfo info)
+ {
+ // Callbacks, waits and invokes inside a child context that finished while suspended end with their parent.
+ if (info.Type == OperationTypes.Context && !info.IsReplay)
+ {
+ foreach (var child in Externals.Pending.Where(c => c.ParentId == info.Id))
+ FinishOperation(ToEndInfo(child));
+ }
+
+ _operationStarts.Remove(info.Id, out var started);
+ _operationContexts.Remove(info.Id);
+
+ if (Externals.ShouldSkip(info))
+ return;
+
+ // An operation exports once, in the invocation where it finishes. Reaching it again by replay is not that
+ // invocation. A wait, invoke or callback completion this invocation learned about is the exception.
+ if (info.IsReplay && !ExternalCompletions.IsExternal(info))
+ return;
+
+ var name = info.Name ?? started?.Name;
+ var subType = info.SubType ?? started?.SubType;
+ var parentId = info.ParentId ?? started?.ParentId;
+
+ var tags = OperationTags(info);
+ if (name != null && info.Name == null)
+ tags.Add(new("durable.operation.name", name));
+ if (subType != null && info.SubType == null)
+ tags.Add(new("durable.operation.subtype", subType));
+ if (info.Status != null)
+ tags.Add(new("durable.operation.status", info.Status));
+ if ((info.Type == OperationTypes.Step || subType == OperationSubTypes.WaitForCondition) && info.Attempt != null)
+ tags.Add(new("durable.attempt.number", info.Attempt.Value));
+
+ // The earliest start seen, whether the service's or the local one, so the operation encloses its children.
+ // With no start at all the local clock stands in, but never later than the service's end.
+ DateTimeOffset start;
+ if (started != null || info.StartTimestamp != null)
+ {
+ start = Earliest(started?.Start, info.StartTimestamp ?? started!.Start);
+ if (info.StartTimestamp is { } serviceStart && serviceStart < start)
+ start = serviceStart;
+ }
+ else
+ {
+ var now = LogicalNow();
+ start = info.EndTimestamp is { } serviceEnd && serviceEnd < now ? serviceEnd : now;
+ }
+ ObserveAncestorStart(parentId, start);
+ Observe(start);
+
+ var span = Start(name ?? info.Type, ParentContextFor(parentId), tags, InvocationLinks(), start);
+ if (span != null)
+ {
+ ActivityIdOverride.TrySet(span, DeterministicIds.SpanIdFromOperationId(info.Id, ExecutionArn));
+
+ var end = info.EndTimestamp ?? LogicalNow();
+ if (end < start)
+ end = start;
+ Observe(end);
+
+ SetOperationStatus(span, info);
+ RecordError(span, info.Error, info.Exception, end);
+ if (info.Type == OperationTypes.Context && span.IsAllDataRequested)
+ _recordedContextIds.Add(info.Id);
+ End(span, end);
+ }
+
+ Externals.MarkExported(info);
+ }
+
+ ///
+ /// The parent of an operation or attempt span: the parent operation's derived identity, or the Workflow's for a
+ /// top-level operation. The parent need not be open or even reached in this invocation.
+ ///
+ private ActivityContext ParentContextFor(string? parentOperationId)
+ {
+ if (parentOperationId == null)
+ return WorkflowContext;
+
+ return _operationContexts.TryGetValue(parentOperationId, out var open)
+ ? open
+ : OperationContext(parentOperationId);
+ }
+
+ ///
+ /// A child that started earlier than its parent's recorded start moves that start earlier, up the chain of
+ /// parents that are still open, so a parent exported when it finishes encloses everything it contains.
+ ///
+ private void ObserveAncestorStart(string? parentId, DateTimeOffset start)
+ {
+ var visited = new HashSet(StringComparer.Ordinal);
+ while (parentId != null && visited.Add(parentId))
+ {
+ if (!_operationStarts.TryGetValue(parentId, out var parent) || !_operationContexts.ContainsKey(parentId))
+ return;
+
+ start = Earliest(parent.Start, start);
+ parent.Start = start;
+ parentId = parent.ParentId;
+ }
+ }
+
+ private List? InvocationLinks() =>
+ InvocationSpan != null ? new List { new(InvocationSpan.Context) } : null;
+
+ // ── Attempts ────────────────────────────────────────────────────────────
+
+ public override void OnAttemptStart(AttemptInfo info)
+ {
+ if (!Enabled || Finalized)
+ return;
+
+ var attempt = info.Attempt ?? 1;
+ var tags = OperationTags(info);
+ tags.Add(new("durable.attempt.number", attempt));
+
+ lock (Gate)
+ {
+ var start = info.StartTimestamp ?? LogicalNow();
+ _operationStarts.TryGetValue(info.Id, out var operation);
+ var parentId = info.ParentId ?? operation?.ParentId;
+ var earliest = Earliest(operation?.Start, start);
+ _operationStarts[info.Id] = new OperationStart
+ {
+ Name = operation?.Name, SubType = operation?.SubType, ParentId = parentId, Start = earliest,
+ };
+ ObserveAncestorStart(parentId, earliest);
+
+ var span = Start(
+ $"{info.Name ?? info.Type} attempt {attempt}", ParentContextFor(info.Id), tags, InvocationLinks(), Observe(start));
+ if (span != null)
+ _attemptSpans[AttemptKey(info.Id, attempt)] = span;
+ }
+ }
+
+ public override void OnAttemptEnd(AttemptEndInfo info)
+ {
+ if (!Enabled)
+ return;
+
+ var attempt = info.Attempt ?? 1;
+ lock (Gate)
+ {
+ if (!_attemptSpans.Remove(AttemptKey(info.Id, attempt), out var span))
+ return;
+
+ var end = Observe(info.EndTimestamp ?? LogicalNow());
+ span.SetTag("durable.attempt.outcome", info.Outcome.ToString().ToUpperInvariant());
+ if (info.Outcome == AttemptOutcome.Failed)
+ {
+ span.SetStatus(ActivityStatusCode.Error, info.Exception?.Message ?? "Attempt failed");
+ RecordError(span, null, info.Exception, end);
+ }
+ else
+ {
+ span.SetStatus(ActivityStatusCode.Ok);
+ }
+ End(span, end);
+ }
+ }
+
+ public override void OnOperationChange(OperationChangeInfo info)
+ {
+ if (!Enabled)
+ return;
+
+ lock (Gate)
+ {
+ _endOperations = info.Operations;
+ Externals.Observe(info.UpdatedOperations, info.Operations);
+ }
+ }
+
+ // ── Invocation end ──────────────────────────────────────────────────────
+
+ protected override void BeforeInvocationEnds(InvocationEndInfo info)
+ {
+ lock (Gate)
+ {
+ _endOperations = info.Operations;
+ DrainCompletions(info, final: false);
+ }
+ }
+
+ /// The invocation ends no earlier than any boundary it observed, so it encloses the spans it exported.
+ protected override DateTimeOffset InvocationEndTime()
+ {
+ lock (Gate)
+ {
+ var now = LogicalNow();
+ return _latestObserved is { } latest && latest > now ? latest : now;
+ }
+ }
+
+ protected override void AfterInvocationEnds(InvocationEndInfo info, DateTimeOffset end)
+ {
+ lock (Gate)
+ {
+ // Completions that waited for an open parent are exported now, whether or not the parent finished.
+ DrainCompletions(info, final: true);
+
+ // An open operation exports nothing: it is exported by the invocation where it finishes. Attempts are
+ // real spans and end here.
+ foreach (var span in _attemptSpans.Values)
+ End(span, end);
+ _attemptSpans.Clear();
+ }
+ }
+
+ ///
+ /// Exports the waits, invokes and callbacks that completed while the execution was suspended and that the
+ /// workflow did not reach. One whose parent is a child context that is still open waits for that context unless
+ /// this is the last drain.
+ ///
+ private void DrainCompletions(InvocationEndInfo info, bool final)
+ {
+ var terminal = info.Status is InvocationEndStatus.Succeeded or InvocationEndStatus.Failed;
+ foreach (var operation in Externals.Pending)
+ {
+ var openParent = HasOpenUnrecordedParent(operation);
+ if (openParent && !final)
+ continue;
+
+ var recordedParent = operation.ParentId != null && _recordedContextIds.Contains(operation.ParentId);
+ var parentId = !recordedParent && ((terminal && openParent) || HasAbandonedParent(operation.ParentId))
+ ? null
+ : operation.ParentId;
+
+ var end = ToEndInfo(operation);
+ FinishOperation(new OperationEndInfo
+ {
+ Id = end.Id, Name = end.Name, Type = end.Type, SubType = end.SubType, ParentId = parentId,
+ Status = end.Status, StartTimestamp = end.StartTimestamp, EndTimestamp = end.EndTimestamp,
+ Attempt = end.Attempt, IsReplay = false,
+ });
+ }
+ }
+
+ private bool HasOpenUnrecordedParent(OperationInfo operation) =>
+ operation.ParentId != null
+ && _operationContexts.ContainsKey(operation.ParentId)
+ && !_recordedContextIds.Contains(operation.ParentId);
+
+ ///
+ /// True when the parent is a child context that never finished (it is still started or waiting) inside an
+ /// ancestor that did, so nothing will ever export it and the completion is attached to the Workflow instead.
+ ///
+ private bool HasAbandonedParent(string? parentId)
+ {
+ if (parentId == null || !_endOperations.TryGetValue(parentId, out var parent)
+ || parent.Type != OperationTypes.Context
+ || parent.Status is not (OperationStatuses.Started or OperationStatuses.Ready or OperationStatuses.Pending))
+ return false;
+
+ var visited = new HashSet(StringComparer.Ordinal) { parent.Id };
+ var ancestorId = parent.ParentId;
+ while (ancestorId != null && visited.Add(ancestorId))
+ {
+ if (!_endOperations.TryGetValue(ancestorId, out var ancestor) || ancestor.Type != OperationTypes.Context)
+ return false;
+ if (ExternalCompletions.IsFinished(ancestor.Status))
+ return true;
+ ancestorId = ancestor.ParentId;
+ }
+ return false;
+ }
+
+ // ── User code ───────────────────────────────────────────────────────────
+
+ ///
+ /// Makes the Workflow, the child context or the attempt the current while user code runs,
+ /// then restores the caller's. The Workflow and child contexts have no span yet, so a stand-in carrying their
+ /// derived identity is current: spans the application starts inside parent onto the span exported later.
+ ///
+ public override async Task WrapAsync(UserCodeInfo info, Func next)
+ {
+ Activity? current = null;
+ if (Enabled)
+ {
+ lock (Gate)
+ {
+ current = info.Kind switch
+ {
+ UserCodeKind.Invocation => StandIn(WorkflowContext),
+ UserCodeKind.ChildContext => info.Operation != null ? StandIn(ParentContextFor(info.Operation.Id)) : null,
+ UserCodeKind.Attempt => info.Operation != null && _attemptSpans.TryGetValue(AttemptKey(info.Operation.Id, info.Operation.Attempt ?? 1), out var a) ? a : null,
+ _ => null,
+ };
+ }
+ }
+
+ if (current == null)
+ {
+ await next().ConfigureAwait(false);
+ return;
+ }
+
+ var previous = Activity.Current;
+ Activity.Current = current;
+ try
+ {
+ await next().ConfigureAwait(false);
+ }
+ finally
+ {
+ Activity.Current = previous;
+ }
+ }
+
+ ///
+ /// An activity that carries a span identity and is never exported. It is not created by an
+ /// , so no listener sees it.
+ ///
+ private static Activity? StandIn(ActivityContext identity)
+ {
+ var previous = Activity.Current;
+ try
+ {
+ var standIn = new Activity("durable-context");
+ standIn.SetIdFormat(ActivityIdFormat.W3C);
+ standIn.SetParentId(identity.TraceId, identity.SpanId, identity.TraceFlags);
+ standIn.Start();
+ ActivityIdOverride.TrySet(standIn, identity.SpanId.ToHexString());
+ return standIn;
+ }
+ finally
+ {
+ Activity.Current = previous;
+ }
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ExternalCompletions.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ExternalCompletions.cs
new file mode 100644
index 000000000..6bbff8db3
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/ExternalCompletions.cs
@@ -0,0 +1,79 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// Tracks waits, chained invokes and callbacks that finished outside the invocation, while the execution was
+/// suspended. They have no span of their own in the invocation that notices, so the plugin exports one segment
+/// for each, once, in the invocation that observes the completion.
+///
+internal sealed class ExternalCompletions
+{
+ private readonly Dictionary _pending = new(StringComparer.Ordinal);
+ private readonly HashSet _exported = new(StringComparer.Ordinal);
+
+ internal static bool IsExternal(OperationInfo info) =>
+ info.Type is OperationTypes.Wait or OperationTypes.ChainedInvoke or OperationTypes.Callback;
+
+ internal static bool IsFinished(string? status) =>
+ status is OperationStatuses.Succeeded or OperationStatuses.Failed or OperationStatuses.TimedOut
+ or OperationStatuses.Stopped or OperationStatuses.Cancelled;
+
+ /// Operations still waiting to be exported, in the order they were observed.
+ internal IReadOnlyList Pending => _pending.Values.ToList();
+
+ internal bool IsPending(string id) => _pending.ContainsKey(id);
+
+ internal void Observe(
+ IReadOnlyDictionary updates, IReadOnlyDictionary operations)
+ {
+ foreach (var info in updates.Values)
+ {
+ if (!IsExternal(info) || !IsFinished(info.Status) || _exported.Contains(info.Id))
+ continue;
+
+ // A callback of WaitForCallback has no name of its own. Name it after its parent so it can be found.
+ var completion = info;
+ if (info.Type == OperationTypes.Callback && info.Name == null && info.ParentId != null
+ && operations.TryGetValue(info.ParentId, out var parent)
+ && parent.Type == OperationTypes.Context && parent.SubType == OperationSubTypes.WaitForCallback
+ && parent.Name != null)
+ {
+ completion = new OperationInfo
+ {
+ Id = info.Id, Name = parent.Name + "-callback", Type = info.Type, SubType = info.SubType,
+ ParentId = info.ParentId, Status = info.Status, StartTimestamp = info.StartTimestamp,
+ EndTimestamp = info.EndTimestamp, Attempt = info.Attempt, IsReplay = info.IsReplay,
+ };
+ }
+ _pending[info.Id] = completion;
+ }
+ }
+
+ ///
+ /// True when an end report must not produce a span: the operation was exported already, or it is a replay of
+ /// one whose completion this invocation has not seen.
+ ///
+ internal bool ShouldSkip(OperationInfo info) =>
+ IsExternal(info) && (_exported.Contains(info.Id) || (info.IsReplay && !_pending.ContainsKey(info.Id)));
+
+ internal void MarkExported(OperationInfo info)
+ {
+ if (!IsExternal(info))
+ return;
+
+ _exported.Add(info.Id);
+ _pending.Remove(info.Id);
+ }
+
+ internal OperationInfo? Get(string id) => _pending.TryGetValue(id, out var info) ? info : null;
+
+ internal void Clear()
+ {
+ _pending.Clear();
+ _exported.Clear();
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/InvocationClock.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/InvocationClock.cs
new file mode 100644
index 000000000..af32f8ad8
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/InvocationClock.cs
@@ -0,0 +1,19 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// The time of an invocation: the wall clock read once at the start, advanced by the monotonic clock. Spans of one
+/// invocation then never overlap or collapse because the wall clock was adjusted while it ran, and they still line
+/// up with spans the application creates, which read the wall clock.
+///
+internal sealed class InvocationClock
+{
+ private readonly DateTimeOffset _wallStart = DateTimeOffset.UtcNow;
+ private readonly long _monotonicStart = Stopwatch.GetTimestamp();
+
+ internal DateTimeOffset Now => _wallStart + Stopwatch.GetElapsedTime(_monotonicStart);
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/InvocationOtelPlugin.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/InvocationOtelPlugin.cs
new file mode 100644
index 000000000..7673112b7
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/InvocationOtelPlugin.cs
@@ -0,0 +1,253 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// The Invocation view: operations are children of the Invocation that runs them.
+///
+///
+///
+/// Execution ancestor (remote parent or synthetic root)
+/// +-- Workflow exported once, by the invocation that finishes the execution
+/// +-- Invocation one per Lambda invocation
+/// +-- operation links Workflow
+/// +-- attempt links Workflow
+///
+/// Spans are timed on the invocation's own clock. The first segment of an operation has an id derived from the
+/// execution ARN and the operation id. An unfinished operation that a later invocation reaches again is exported as a
+/// new span that links that first segment, because nothing is stored between invocations. A finished operation that
+/// is only replayed is not exported again.
+///
+internal sealed class InvocationOtelPlugin : OtelPluginBase
+{
+ // Open spans by operation id, and open attempt spans by "operationId:attempt".
+ private readonly Dictionary _operationSpans = new(StringComparer.Ordinal);
+ private readonly Dictionary _attemptSpans = new(StringComparer.Ordinal);
+
+ internal InvocationOtelPlugin(ActivitySource source, OtelPluginOptions options, InvocationInfo info)
+ : base(source, options, info)
+ {
+ }
+
+ // ── Operations ──────────────────────────────────────────────────────────
+
+ public override void OnOperationStart(OperationInfo info)
+ {
+ if (!Enabled || Finalized)
+ return;
+
+ lock (Gate)
+ {
+ if (info.IsReplay && _operationSpans.ContainsKey(info.Id))
+ return;
+
+ var tags = OperationTags(info);
+ tags.Add(new("durable.operation.status", "STARTED"));
+
+ Activity? span = null;
+ if (!info.IsReplay)
+ {
+ // The first segment of the operation. Its id is derived, so later invocations can link it.
+ span = Start(info.Name ?? info.Type, ParentContext(info.ParentId), tags, WorkflowLinks(), Clock.Now);
+ ActivityIdOverride.TrySet(span, DeterministicIds.SpanIdFromOperationId(info.Id, ExecutionArn));
+ }
+ else if (info.Type is OperationTypes.Context or OperationTypes.Step && !IsFinished(info.Status))
+ {
+ // An operation an earlier invocation started and did not finish (a retried step, a context that
+ // suspended). The original span is not stored anywhere, so this is a new span that links the Workflow
+ // and the first segment. One that already finished is only replayed and is not exported again.
+ span = Start(info.Name ?? info.Type, ParentContext(info.ParentId), tags, ReplayLinks(info.Id), Clock.Now);
+ }
+
+ if (span != null)
+ _operationSpans[info.Id] = span;
+ }
+ }
+
+ public override void OnOperationEnd(OperationEndInfo info)
+ {
+ if (!Enabled)
+ return;
+
+ lock (Gate)
+ FinishOperation(info);
+ }
+
+ private void FinishOperation(OperationEndInfo info)
+ {
+ // Callbacks, waits and invokes inside a child context that finished while suspended end with their parent.
+ if (info.Type == OperationTypes.Context && !info.IsReplay)
+ {
+ foreach (var child in Externals.Pending.Where(c => c.ParentId == info.Id))
+ FinishOperation(ToEndInfo(child));
+ }
+
+ if (Externals.ShouldSkip(info))
+ return;
+
+ if (_operationSpans.Remove(info.Id, out var span))
+ {
+ if (info.Status != null)
+ span.SetTag("durable.operation.status", info.Status);
+ if (IsAttemptOperation(info) && info.Attempt != null)
+ span.SetTag("durable.attempt.number", info.Attempt.Value);
+
+ SetOperationStatus(span, info);
+ RecordError(span, info.Error, info.Exception, Clock.Now);
+ End(span);
+ }
+ else if (!info.IsReplay || Externals.IsPending(info.Id))
+ {
+ // The operation finished in an invocation that did not start it (a callback completed from outside, a
+ // wait that elapsed): export the segment this invocation saw.
+ var tags = OperationTags(info);
+ if (info.Status != null)
+ tags.Add(new("durable.operation.status", info.Status));
+ if (IsAttemptOperation(info) && info.Attempt != null)
+ tags.Add(new("durable.attempt.number", info.Attempt.Value));
+
+ var now = Clock.Now;
+ var continuation = Start(info.Name ?? info.Type, ParentContext(info.ParentId), tags, ReplayLinks(info.Id), now);
+ if (continuation != null)
+ {
+ SetOperationStatus(continuation, info);
+ RecordError(continuation, info.Error, info.Exception, now);
+ End(continuation, now);
+ }
+ }
+
+ Externals.MarkExported(info);
+ }
+
+ // ── Attempts ────────────────────────────────────────────────────────────
+
+ public override void OnAttemptStart(AttemptInfo info)
+ {
+ if (!Enabled || Finalized)
+ return;
+
+ var attempt = info.Attempt ?? 1;
+ var tags = OperationTags(info);
+ tags.Add(new("durable.attempt.number", attempt));
+
+ lock (Gate)
+ {
+ var parent = _operationSpans.TryGetValue(info.Id, out var op) ? op.Context : ParentContext(null);
+ var span = Start($"{info.Name ?? info.Type} attempt {attempt}", parent, tags, WorkflowLinks(), Clock.Now);
+ if (span != null)
+ _attemptSpans[AttemptKey(info.Id, attempt)] = span;
+ }
+ }
+
+ public override void OnAttemptEnd(AttemptEndInfo info)
+ {
+ if (!Enabled)
+ return;
+
+ var attempt = info.Attempt ?? 1;
+ lock (Gate)
+ {
+ if (!_attemptSpans.Remove(AttemptKey(info.Id, attempt), out var span))
+ return;
+
+ span.SetTag("durable.attempt.outcome", info.Outcome.ToString().ToUpperInvariant());
+ var now = Clock.Now;
+ if (info.Outcome == AttemptOutcome.Failed)
+ {
+ span.SetStatus(ActivityStatusCode.Error, info.Exception?.Message ?? "Attempt failed");
+ RecordError(span, null, info.Exception, now);
+ }
+ else
+ {
+ span.SetStatus(ActivityStatusCode.Ok);
+ }
+ End(span, now);
+ }
+ }
+
+ // ── Invocation end ──────────────────────────────────────────────────────
+
+ protected override void BeforeInvocationEnds(InvocationEndInfo info)
+ {
+ // Waits, invokes and callbacks that finished while suspended and that the workflow did not reach.
+ lock (Gate)
+ {
+ foreach (var pending in Externals.Pending)
+ FinishOperation(ToEndInfo(pending));
+ }
+ }
+
+ protected override void AfterInvocationEnds(InvocationEndInfo info, DateTimeOffset end)
+ {
+ lock (Gate)
+ {
+ foreach (var span in _attemptSpans.Values)
+ End(span, end);
+ _attemptSpans.Clear();
+
+ // Operations still open (a wait, a retry that suspended) keep the STARTED status they were created with.
+ foreach (var span in _operationSpans.Values)
+ End(span, end);
+ _operationSpans.Clear();
+ }
+ }
+
+ // ── User code ───────────────────────────────────────────────────────────
+
+ /// Makes the right span the current while user code runs, then restores it.
+ public override async Task WrapAsync(UserCodeInfo info, Func next)
+ {
+ Activity? span = null;
+ if (Enabled)
+ {
+ lock (Gate)
+ {
+ span = info.Kind switch
+ {
+ UserCodeKind.Invocation => InvocationSpan,
+ UserCodeKind.ChildContext => info.Operation != null && _operationSpans.TryGetValue(info.Operation.Id, out var c) ? c : null,
+ UserCodeKind.Attempt => info.Operation != null && _attemptSpans.TryGetValue(AttemptKey(info.Operation.Id, info.Operation.Attempt ?? 1), out var a) ? a : null,
+ _ => null,
+ };
+ }
+ }
+
+ if (span == null)
+ {
+ await next().ConfigureAwait(false);
+ return;
+ }
+
+ var previous = Activity.Current;
+ Activity.Current = span;
+ try
+ {
+ await next().ConfigureAwait(false);
+ }
+ finally
+ {
+ Activity.Current = previous;
+ }
+ }
+
+ // ── Helpers ─────────────────────────────────────────────────────────────
+
+ private ActivityContext ParentContext(string? parentOperationId) =>
+ parentOperationId != null && _operationSpans.TryGetValue(parentOperationId, out var parent)
+ ? parent.Context
+ : InvocationSpan?.Context ?? Ancestor;
+
+ private static bool IsFinished(string? status)
+ => status is OperationStatuses.Succeeded or OperationStatuses.Failed or OperationStatuses.Cancelled
+ or OperationStatuses.Stopped or OperationStatuses.TimedOut;
+
+ private List ReplayLinks(string operationId) => new()
+ {
+ new ActivityLink(OperationContext(operationId)),
+ new ActivityLink(WorkflowContext),
+ };
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/OtelPluginBase.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/OtelPluginBase.cs
new file mode 100644
index 000000000..705659f2f
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/OtelPluginBase.cs
@@ -0,0 +1,419 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+///
+/// What both views share: finding the execution's trace, the Invocation span, the Workflow span and synthetic root,
+/// sampling, trace propagation, log correlation and the flush. A view decides how operations and attempts become
+/// spans.
+///
+///
+/// Every invocation of an execution joins one trace, anchored at the execution ancestor found when it starts: the
+/// propagated remote parent when there is one, otherwise a synthetic root whose id comes from the execution ARN.
+/// The Workflow span, the synthetic root and the first segment of each operation have ids derived from the ARN, so a
+/// span exported by one invocation can name one exported by another.
+///
+internal abstract class OtelPluginBase : IDurableInstrumentationPlugin
+{
+ private readonly ActivitySource _source;
+ private bool _syntheticRootExported;
+ private DateTimeOffset _invocationStart;
+
+ protected readonly OtelPluginOptions Options;
+ protected readonly string ExecutionArn;
+ protected readonly DateTimeOffset? ReportedExecutionStart;
+ protected readonly InvocationClock Clock = new();
+ protected readonly object Gate = new();
+ protected readonly ExternalCompletions Externals = new();
+
+ protected bool Enabled;
+ protected bool Finalized;
+ protected Activity? InvocationSpan;
+
+ protected string TraceId = string.Empty;
+ private ActivityTraceId _traceId;
+ private ActivitySpanId _ancestorSpanId;
+
+ /// The invocation's sampling decision. Spans are only started when it is recorded.
+ protected ActivityTraceFlags Flags;
+ protected ActivityContext Ancestor;
+ protected bool AncestorIsRemote;
+ protected ActivityContext WorkflowContext;
+
+ protected OtelPluginBase(ActivitySource source, OtelPluginOptions options, InvocationInfo info)
+ {
+ _source = source;
+ Options = options;
+ ExecutionArn = info.ExecutionArn;
+ ReportedExecutionStart = info.ExecutionStartTimestamp;
+ }
+
+ private void SetSampled(bool sampled)
+ {
+ Flags = sampled ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None;
+ Ancestor = new ActivityContext(_traceId, _ancestorSpanId, Flags, isRemote: AncestorIsRemote);
+ WorkflowContext = new ActivityContext(
+ _traceId, ActivitySpanId.CreateFromString(DeterministicIds.WorkflowSpanId(ExecutionArn)), Flags);
+ }
+
+ /// What the Workflow span and the synthetic root are backdated to.
+ private DateTimeOffset WorkflowStart => ReportedExecutionStart ?? _invocationStart;
+
+ // ── Invocation ──────────────────────────────────────────────────────────
+
+ public void OnInvocationStart(InvocationInfo info)
+ {
+ // Nothing to trace when nobody listens. Spans are not created and every later hook returns early.
+ if (!_source.HasListeners())
+ return;
+
+ try
+ {
+ Initialize(info);
+ }
+ catch
+ {
+ Enabled = false;
+ End(InvocationSpan);
+ InvocationSpan = null;
+ throw;
+ }
+ }
+
+ private void Initialize(InvocationInfo info)
+ {
+ _invocationStart = Clock.Now;
+
+ var extracted = (Options.ContextExtractor ?? ContextExtractors.XRay)(info);
+ var hasTraceId = extracted != null && DeterministicIds.IsValidTraceId(extracted.TraceId);
+ TraceId = hasTraceId
+ ? extracted!.TraceId
+ : DeterministicIds.TraceIdFromArn(ExecutionArn, ReportedExecutionStart);
+
+ // One sampling decision covers every span of the invocation, as in the other SDKs. An upstream decision is
+ // authoritative. Without one, the application's sampler decides for the Invocation span and the rest follow
+ // it. A span the plugin does not start cannot be exported by a sampler that ignores its parent.
+ var sampling = hasTraceId ? extracted!.Sampling : UpstreamSampling.Undecided;
+
+ _traceId = ActivityTraceId.CreateFromString(TraceId);
+ if (hasTraceId && DeterministicIds.IsValidSpanId(extracted!.ParentSpanId))
+ {
+ _ancestorSpanId = ActivitySpanId.CreateFromString(extracted.ParentSpanId);
+ AncestorIsRemote = true;
+ }
+ else
+ {
+ _ancestorSpanId = ActivitySpanId.CreateFromString(DeterministicIds.ExecutionRootSpanId(ExecutionArn));
+ AncestorIsRemote = false;
+ }
+ SetSampled(sampling != UpstreamSampling.NotSampled);
+ var traceId = _traceId;
+
+ // The Invocation span joins an ambient span of the same trace (the Lambda or ADOT handler span) so the
+ // trace shows the Lambda call. Otherwise it hangs off the execution ancestor.
+ var ambient = Activity.Current;
+ var parent = AncestorIsRemote && ambient != null && ambient.TraceId == traceId
+ && (ambient.ActivityTraceFlags & ActivityTraceFlags.Recorded) == (Flags & ActivityTraceFlags.Recorded)
+ ? ambient.Context
+ : Ancestor;
+
+ InvocationSpan = Start("Invocation", parent, new List>
+ {
+ new("durable.execution.arn", ExecutionArn),
+ new("durable.invocation.first", info.IsFirstInvocation),
+ }, links: null, _invocationStart);
+
+ if (sampling == UpstreamSampling.Undecided && InvocationSpan is not { Recorded: true })
+ {
+ // The application's sampler dropped the invocation, so the rest of it is dropped too. Propagation and
+ // the stand-in contexts then carry the unsampled flag.
+ InvocationSpan = null;
+ SetSampled(false);
+ }
+
+ if (ReportedExecutionStart != null)
+ ExportSyntheticRoot(ReportedExecutionStart.Value);
+
+ Enabled = true;
+ lock (Gate)
+ Externals.Observe(info.UpdatedOperations, info.Operations);
+ }
+
+ /// Lets a view export or release what it holds before the invocation span ends.
+ protected virtual void BeforeInvocationEnds(InvocationEndInfo info) { }
+
+ /// When the invocation span ends. A view can push it later than the clock, to enclose what it observed.
+ protected virtual DateTimeOffset InvocationEndTime() => Clock.Now;
+
+ /// Called after the invocation span, the Workflow span and the synthetic root were ended.
+ protected virtual void AfterInvocationEnds(InvocationEndInfo info, DateTimeOffset end) { }
+
+ public async Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken cancellationToken)
+ {
+ if (!Enabled)
+ return;
+
+ BeforeInvocationEnds(info);
+ var end = InvocationEndTime();
+
+ if (InvocationSpan != null)
+ {
+ InvocationSpan.SetTag("durable.invocation.status", info.Status.ToString().ToUpperInvariant());
+ switch (info.Status)
+ {
+ case InvocationEndStatus.Failed:
+ InvocationSpan.SetStatus(ActivityStatusCode.Error, info.Error?.ErrorMessage ?? info.Exception?.Message ?? "Execution failed");
+ break;
+ case InvocationEndStatus.Succeeded:
+ case InvocationEndStatus.Pending:
+ InvocationSpan.SetStatus(ActivityStatusCode.Ok);
+ break;
+ // Retrying: the invocation will be retried, so its status stays unset.
+ }
+ End(InvocationSpan, end);
+ }
+
+ if ((Flags & ActivityTraceFlags.Recorded) != 0
+ && info.Status is InvocationEndStatus.Succeeded or InvocationEndStatus.Failed)
+ {
+ ExportWorkflow(info, end);
+ ExportSyntheticRoot(ReportedExecutionStart ?? end);
+ }
+
+ AfterInvocationEnds(info, end);
+
+ Enabled = false;
+ Finalized = true;
+ lock (Gate)
+ Externals.Clear();
+
+ await FlushAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ private void ExportWorkflow(InvocationEndInfo info, DateTimeOffset end)
+ {
+ var workflow = Start(Options.WorkflowSpanName, Ancestor, new List>
+ {
+ new("durable.execution.arn", ExecutionArn),
+ }, links: null, WorkflowStart);
+ if (workflow == null)
+ return;
+
+ ActivityIdOverride.TrySet(workflow, WorkflowContext.SpanId.ToHexString());
+ workflow.SetTag("durable.execution.status", info.Status.ToString().ToUpperInvariant());
+ if (info.Status == InvocationEndStatus.Failed)
+ workflow.SetStatus(ActivityStatusCode.Error, info.Error?.ErrorMessage ?? "Execution failed");
+ else
+ workflow.SetStatus(ActivityStatusCode.Ok);
+ End(workflow, end);
+ }
+
+ ///
+ /// With no propagated parent the execution hangs off a synthetic root. It is exported, once per invocation,
+ /// with the same id each time, so the trace has a root even when an earlier invocation's copy was lost.
+ /// Consumers deduplicate on the span id.
+ ///
+ private void ExportSyntheticRoot(DateTimeOffset at)
+ {
+ if (AncestorIsRemote || _syntheticRootExported || (Flags & ActivityTraceFlags.Recorded) == 0)
+ return;
+
+ // Started under a made-up parent so the sampler sees the execution's trace and flags, then made a root.
+ var fakeParent = new ActivityContext(Ancestor.TraceId, ActivitySpanId.CreateRandom(), Flags);
+ var root = Start("DurableExecutionRoot", fakeParent, new List>
+ {
+ new("durable.execution.synthetic_root", true),
+ new("durable.execution.arn", ExecutionArn),
+ }, links: null, at);
+ if (root == null)
+ return;
+
+ ActivityIdOverride.TrySet(root, Ancestor.SpanId.ToHexString(), asRoot: true);
+ _syntheticRootExported = true;
+ End(root, at);
+ }
+
+ private async Task FlushAsync(CancellationToken cancellationToken)
+ {
+ var flush = Options.FlushAsync;
+ if (flush == null)
+ return;
+
+ try
+ {
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ cts.CancelAfter(Options.FlushTimeout);
+ await flush(Options.FlushTimeout, cts.Token).ConfigureAwait(false);
+ }
+ catch
+ {
+ // A failing flush must not fail the invocation. The spans stay queued in the application's provider.
+ }
+ }
+
+ // ── Hooks a view implements ─────────────────────────────────────────────
+
+ public abstract void OnOperationStart(OperationInfo info);
+ public abstract void OnOperationEnd(OperationEndInfo info);
+ public abstract void OnAttemptStart(AttemptInfo info);
+ public abstract void OnAttemptEnd(AttemptEndInfo info);
+ public abstract Task WrapAsync(UserCodeInfo info, Func next);
+
+ public virtual void OnOperationChange(OperationChangeInfo info)
+ {
+ if (!Enabled)
+ return;
+
+ lock (Gate)
+ Externals.Observe(info.UpdatedOperations, info.Operations);
+ }
+
+ // ── Propagation and logging ─────────────────────────────────────────────
+
+ ///
+ /// The header the invoked function continues the trace from: this execution's trace, with the calling
+ /// operation's span as the parent. No span is created here.
+ ///
+ public string? ProvidePropagationMetadata(PropagationInput input)
+ {
+ if (!Enabled || Finalized || input.ExecutionArn != ExecutionArn)
+ return null;
+
+ var spanId = DeterministicIds.SpanIdFromOperationId(input.OperationId, ExecutionArn);
+ var sampled = (Flags & ActivityTraceFlags.Recorded) != 0 ? "1" : "0";
+ return $"Root=1-{TraceId[..8]}-{TraceId[8..]};Parent={spanId};Sampled={sampled}";
+ }
+
+ public IReadOnlyDictionary? GetLogScope()
+ {
+ if (!Enabled || !Options.EnrichLogger)
+ return null;
+
+ var current = Activity.Current;
+ if (current == null)
+ return null;
+
+ return new Dictionary(3)
+ {
+ ["otelTraceId"] = current.TraceId.ToHexString(),
+ ["otelSpanId"] = current.SpanId.ToHexString(),
+ ["otelTraceSampled"] = (current.ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0,
+ };
+ }
+
+ // ── Helpers ─────────────────────────────────────────────────────────────
+
+ protected List> OperationTags(OperationInfo info)
+ {
+ var tags = new List>(7)
+ {
+ new("durable.execution.arn", ExecutionArn),
+ new("durable.operation.id", info.Id),
+ new("durable.operation.type", info.Type),
+ };
+ if (info.Name != null)
+ tags.Add(new("durable.operation.name", info.Name));
+ if (info.SubType != null)
+ tags.Add(new("durable.operation.subtype", info.SubType));
+ return tags;
+ }
+
+ protected static bool IsAttemptOperation(OperationInfo info) =>
+ info.Type == OperationTypes.Step || info.SubType == OperationSubTypes.WaitForCondition;
+
+ protected static string AttemptKey(string operationId, int attempt) => $"{operationId}:{attempt}";
+
+ protected static OperationEndInfo ToEndInfo(OperationInfo info) => new()
+ {
+ Id = info.Id, Name = info.Name, Type = info.Type, SubType = info.SubType, ParentId = info.ParentId,
+ Status = info.Status, StartTimestamp = info.StartTimestamp, EndTimestamp = info.EndTimestamp,
+ Attempt = info.Attempt, IsReplay = false,
+ };
+
+ /// The context of an operation's first segment, which every invocation derives the same way.
+ protected ActivityContext OperationContext(string operationId) => new(
+ Ancestor.TraceId,
+ ActivitySpanId.CreateFromString(DeterministicIds.SpanIdFromOperationId(operationId, ExecutionArn)),
+ Flags);
+
+ protected List WorkflowLinks() => new() { new ActivityLink(WorkflowContext) };
+
+ protected static void SetOperationStatus(Activity span, OperationInfo info)
+ {
+ var hasError = info is OperationEndInfo { Error: not null } or OperationEndInfo { Exception: not null };
+ if (hasError || info.Status is OperationStatuses.Failed or OperationStatuses.TimedOut or OperationStatuses.Stopped)
+ {
+ var message = (info as OperationEndInfo)?.Error?.ErrorMessage
+ ?? (info as OperationEndInfo)?.Exception?.Message
+ ?? info.Status;
+ span.SetStatus(ActivityStatusCode.Error, message);
+ }
+ else if (info.Status == OperationStatuses.Succeeded)
+ {
+ span.SetStatus(ActivityStatusCode.Ok);
+ }
+ }
+
+ /// Starts a span without leaving it as of the calling context.
+ protected Activity? Start(
+ string name, ActivityContext parent, IEnumerable> tags,
+ IEnumerable? links, DateTimeOffset start)
+ {
+ if ((Flags & ActivityTraceFlags.Recorded) == 0)
+ return null;
+
+ var previous = Activity.Current;
+ try
+ {
+ return _source.StartActivity(name, ActivityKind.Internal, parent, tags, links, start);
+ }
+ finally
+ {
+ Activity.Current = previous;
+ }
+ }
+
+ protected void End(Activity? span, DateTimeOffset? at = null)
+ {
+ if (span == null)
+ return;
+
+ var previous = Activity.Current;
+ try
+ {
+ span.SetEndTime((at ?? Clock.Now).UtcDateTime);
+ span.Stop();
+ }
+ finally
+ {
+ Activity.Current = previous;
+ }
+ }
+
+ ///
+ /// Adds the standard exception event. A stored error type is used as is, including one raised by a
+ /// function in another language. The event is only recorded when there are error details.
+ ///
+ protected static void RecordError(Activity span, ErrorObject? error, Exception? exception, DateTimeOffset at)
+ {
+ if (error == null && exception == null)
+ return;
+
+ var tags = new ActivityTagsCollection
+ {
+ ["exception.type"] = error?.ErrorType ?? exception?.GetType().FullName ?? "Error",
+ };
+ var message = error?.ErrorMessage ?? exception?.Message;
+ if (message != null)
+ tags["exception.message"] = message;
+ var stack = error?.StackTrace != null ? string.Join("\n", error.StackTrace) : exception?.StackTrace;
+ if (stack != null)
+ tags["exception.stacktrace"] = stack;
+
+ span.AddEvent(new ActivityEvent("exception", at, tags));
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/OtelPluginFactory.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/OtelPluginFactory.cs
new file mode 100644
index 000000000..31cb452a7
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Internal/OtelPluginFactory.cs
@@ -0,0 +1,31 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+/// Creates one plugin per invocation, in the chosen view, all sharing one activity source.
+internal sealed class OtelPluginFactory : IDurableInstrumentationPluginFactory
+{
+ private readonly OtelView _view;
+ private readonly OtelPluginOptions _options;
+ private readonly ActivitySource _source;
+
+ internal OtelPluginFactory(OtelView view, OtelPluginOptions options)
+ {
+ _view = view;
+ _options = options;
+ _source = new ActivitySource(options.InstrumentationName);
+ }
+
+ public string? ExclusiveGroup => OtelPlugin.ViewExclusiveGroup;
+
+ public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => _view switch
+ {
+ OtelView.Invocation => new InvocationOtelPlugin(_source, _options, info),
+ OtelView.Execution => new ExecutionOtelPlugin(_source, _options, info),
+ _ => throw new InvalidOperationException($"Unknown view '{_view}'."),
+ };
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/OtelPlugin.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/OtelPlugin.cs
new file mode 100644
index 000000000..f13e24f79
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/OtelPlugin.cs
@@ -0,0 +1,60 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+/// Where operation spans are parented.
+public enum OtelView
+{
+ /// Workflow -> operation -> attempt. Operations and attempts link the Invocation span.
+ Execution,
+
+ /// Invocation -> operation -> attempt. Operations and attempts link the Workflow span.
+ Invocation,
+}
+
+/// Creates the OpenTelemetry tracing plugin for durable executions.
+public static class OtelPlugin
+{
+ ///
+ /// The default name. Add it to the application's tracer provider
+ /// (AddSource) so the spans are exported.
+ ///
+ public const string ActivitySourceName = "Amazon.Lambda.DurableExecution";
+
+ /// The of both views.
+ internal const string ViewExclusiveGroup = "durable-opentelemetry-view";
+
+ ///
+ /// Creates a plugin factory. Register exactly one, in or with
+ /// .
+ ///
+ /// Where operation spans are parented.
+ /// Optional settings.
+ public static IDurableInstrumentationPluginFactory CreateFactory(
+ OtelView view = OtelView.Execution, OtelPluginOptions? options = null)
+ {
+ if (view is not (OtelView.Execution or OtelView.Invocation))
+ throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown view.");
+
+ return new OtelPluginFactory(view, options ?? new OtelPluginOptions());
+ }
+}
+
+/// Registration helpers for .
+public static class DurableExecutionOptionsExtensions
+{
+ /// Adds the OpenTelemetry tracing plugin. Returns so calls can be chained.
+ /// The options to add the plugin to.
+ /// Where operation spans are parented.
+ /// Optional settings.
+ public static DurableExecutionOptions AddOpenTelemetry(
+ this DurableExecutionOptions options, OtelView view = OtelView.Execution, OtelPluginOptions? pluginOptions = null)
+ {
+ ArgumentNullException.ThrowIfNull(options);
+ options.Plugins.Add(OtelPlugin.CreateFactory(view, pluginOptions));
+ return options;
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/OtelPluginOptions.cs b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/OtelPluginOptions.cs
new file mode 100644
index 000000000..6ac860629
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/OtelPluginOptions.cs
@@ -0,0 +1,66 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using Amazon.Lambda.DurableExecution.Instrumentation;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+/// Settings for the OpenTelemetry tracing plugin.
+public sealed class OtelPluginOptions
+{
+ /// The name of the the spans come from.
+ public string InstrumentationName { get; init; } = OtelPlugin.ActivitySourceName;
+
+ /// The name of the Workflow span.
+ public string WorkflowSpanName { get; init; } = "Workflow";
+
+ ///
+ /// Adds otelTraceId, otelSpanId and otelTraceSampled to the logging scope of durable log
+ /// entries written while a span is current.
+ ///
+ public bool EnrichLogger { get; init; } = true;
+
+ ///
+ /// Called at the end of every invocation so the application can export spans before Lambda freezes the
+ /// environment, for example by calling TracerProvider.ForceFlush. The plugin does not reference the
+ /// OpenTelemetry SDK and cannot flush by itself. The token is cancelled when or the
+ /// invocation's remaining time runs out.
+ ///
+ public Func? FlushAsync { get; init; }
+
+ /// The longest may take. Default: one second.
+ public TimeSpan FlushTimeout { get; init; } = TimeSpan.FromSeconds(1);
+
+ ///
+ /// Finds the trace context of the durable execution. Default: , which reads
+ /// . A custom extractor must return the execution's own context: one
+ /// that changes between invocations of the same execution splits it across traces.
+ ///
+ public Func? ContextExtractor { get; init; }
+}
+
+/// The upstream sampling decision carried by a trace header.
+public enum UpstreamSampling
+{
+ /// No decision was made upstream. The application's sampler decides.
+ Undecided,
+
+ /// Upstream decided to sample.
+ Sampled,
+
+ /// Upstream decided not to sample.
+ NotSampled,
+}
+
+/// A trace context found by a .
+public sealed class ExtractedContext
+{
+ /// The 32 lowercase hex characters of the trace id.
+ public required string TraceId { get; init; }
+
+ /// The 16 lowercase hex characters of the remote parent span, if the header carried one.
+ public string? ParentSpanId { get; init; }
+
+ /// The upstream sampling decision.
+ public UpstreamSampling Sampling { get; init; }
+}
diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md
new file mode 100644
index 000000000..450355c64
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/README.md
@@ -0,0 +1,116 @@
+# Amazon.Lambda.DurableExecution.OpenTelemetry
+
+OpenTelemetry tracing for [Amazon.Lambda.DurableExecution](../Amazon.Lambda.DurableExecution/README.md). It is a plugin for the SDK's [instrumentation plugin API](../Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md).
+
+**Preview.**
+
+The plugin emits spans through `System.Diagnostics.ActivitySource`, so the package has no OpenTelemetry NuGet dependency. The OpenTelemetry SDK, the ADOT layer and `OpenTelemetry.Instrumentation.AWSLambda` listen to it once you add the source name.
+
+## Quick start
+
+```csharp
+using Amazon.Lambda.DurableExecution.OpenTelemetry;
+
+static readonly TracerProvider Tracer = Sdk.CreateTracerProviderBuilder()
+ .AddSource(OtelPlugin.ActivitySourceName) // "Amazon.Lambda.DurableExecution"
+ .AddOtlpExporter()
+ .Build();
+
+static readonly DurableExecutionOptions Options = new DurableExecutionOptions()
+ .AddOpenTelemetry(OtelView.Execution, new OtelPluginOptions
+ {
+ // The plugin cannot flush by itself. Export before Lambda freezes the environment.
+ FlushAsync = (timeout, _) => { Tracer.ForceFlush((int)timeout.TotalMilliseconds); return Task.CompletedTask; },
+ });
+
+public Task Handler(DurableExecutionInvocationInput input, ILambdaContext context)
+ => DurableFunction.WrapAsync(Workflow, input, context, Options);
+```
+
+Create the options once and reuse them. Register exactly one OpenTelemetry view: two factories fail with `PluginLoadException` before the workflow runs.
+
+With the ADOT Lambda layer, activate it with `AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrument` and omit your own provider; the layer listens for the source.
+
+## Choosing a view
+
+Register one view. Both emit the same Workflow, Invocation, operation and attempt spans in one trace per execution; they differ in where operations are parented.
+
+| View | Hierarchy | Operations link | Use it to see |
+|---|---|---|---|
+| `Execution` (default) | `Workflow -> operation -> attempt` | Invocation | what the workflow did, start to finish |
+| `Invocation` | `Invocation -> operation -> attempt` | Workflow | what each Lambda invocation did |
+
+```text
+Execution view Invocation view
+
+Execution ancestor Execution ancestor
++-- Workflow +-- Workflow
+| +-- operation (links Invocation) +-- Invocation
+| +-- attempt +-- operation (links Workflow)
++-- Invocation +-- attempt
+```
+
+### What both views share
+
+- **The ancestor** is the complete `Root` and `Parent` of the X-Ray header the service propagates (`ILambdaContext.TraceId`). Without a parent the plugin exports a synthetic `DurableExecutionRoot` span whose id comes from the execution ARN, once per invocation with the same id. Consumers deduplicate on span id. An ambient span of the same trace (the ADOT handler span) is used as the Invocation's parent instead.
+- **Derived ids.** The Workflow span, the synthetic root and every operation's span (its first segment, in the Invocation view) have ids derived from the execution ARN, so a span exported by one invocation can name one exported by another. They match the JavaScript, Python and Java SDKs.
+- **Workflow** is exported once, by the invocation that finishes the execution.
+
+### Invocation view
+
+- Spans use the invocation's own clock: the wall clock read at the start, advanced by the monotonic clock.
+- An operation that is still running when the invocation suspends is ended with `durable.operation.status=STARTED`. A step or child context that a later invocation reaches again before it finished (a retried step, a suspended context) is a new span that links the Workflow and the operation's first segment. One that already finished is only replayed and is not exported again. A wait, invoke or callback that finished while the execution was suspended is exported once, in the invocation that sees it. A wait that is only replayed is not exported again.
+
+### Execution view
+
+- **One span per operation**, exported when the operation finishes, by the invocation where that happens. While it is open only its identity exists, so nothing is left unended when an invocation suspends. Reaching a finished operation again by replay exports nothing.
+- **Times come from the service.** The span starts at the earliest start seen (the service's, or the local clock if the service has none) and ends at the service's end time. A parent starts no later than its earliest child, and an end before the start is raised to the start. The Invocation span ends no earlier than any boundary it observed.
+- **Attempts** are exported by the invocation that ran them, parented on the operation's derived id before the operation's own span exists. A retried step therefore has one operation span and one attempt span per attempt, each linking the invocation that ran it. The service resets a step's start time when it schedules a retry, and a later invocation cannot see an earlier attempt, so the operation span of a retried step can start after its first attempts (observed on a deployed function).
+- **Application spans** started inside the workflow, a child context or a step are parented on the Workflow, the child context or the attempt. The first two have no span yet, so a stand-in activity that carries their derived id is current. It is not created by an `ActivitySource`, so no listener sees or exports it.
+
+## Attributes and status
+
+All spans are `SpanKind.Internal`.
+
+| Span | Attributes |
+|---|---|
+| Workflow (`WorkflowSpanName`, default `Workflow`) | `durable.execution.arn`, `durable.execution.status` |
+| Invocation | `durable.execution.arn`, `durable.invocation.first`, `durable.invocation.status` (`SUCCEEDED`, `FAILED`, `PENDING`, `RETRYING`) |
+| Operation (named by the operation name, or its type) | `durable.execution.arn`, `durable.operation.id`, `.type`, `.name`, `.subtype`, `.status`; `durable.attempt.number` on steps and wait-for-condition |
+| Attempt (` attempt `) | the operation identity, `durable.attempt.number`, `durable.attempt.outcome` |
+
+Status: Workflow `Ok`/`Error`. Invocation `Ok` for succeeded and pending, `Error` for failed, unset for retrying. An operation is `Error` when it failed, timed out or was stopped, even with no error details, and `Ok` when it succeeded. An `exception` event is added only when error details exist, with a stored error type used as is.
+
+## Sampling
+
+Each invocation makes one sampling decision for all of its spans, as the other SDKs do. An upstream decision in the header (`Sampled=1` or `0`) is authoritative. Without one, your sampler decides for the Invocation span and the invocation's other spans follow it. When the decision is not to sample, the plugin starts no spans, so even a sampler that ignores the parent (`AlwaysOn`) exports nothing, and a chained invoke carries `Sampled=0`. The plugin cannot make your sampler keep a span it drops, so a custom sampler that drops some spans by name can still leave gaps; `ParentBased`, `AlwaysOn` and `TraceIdRatioBased` cannot.
+
+## Chained invokes
+
+The plugin supplies the `X-Amzn-Trace-Id` the SDK sends with a chained invoke: this execution's trace, with the calling operation's span as the parent and the upstream sampling decision. The invoked function continues the trace.
+
+## Log correlation
+
+`EnrichLogger` (default on) adds `otelTraceId`, `otelSpanId` and `otelTraceSampled` to the logging scope of durable log entries written while a span is current. The names avoid the `traceId` field the Lambda runtime already writes in JSON logs.
+
+## Options
+
+| Option | Default | |
+|---|---|---|
+| `InstrumentationName` | `Amazon.Lambda.DurableExecution` | The `ActivitySource` name. |
+| `WorkflowSpanName` | `Workflow` | |
+| `EnrichLogger` | `true` | |
+| `FlushAsync` | none | Called at the end of every invocation, after its spans ended. |
+| `FlushTimeout` | 1 second | Passed to `FlushAsync`; its token is cancelled after this time or when the invocation's time runs out. |
+| `ContextExtractor` | `ContextExtractors.XRay` | Finds the execution's trace context. It must return the execution's own context: one that changes between invocations splits the execution across traces. |
+
+To anchor the execution on a W3C `traceparent` the invoke carried on `clientContext.w3c` (`ILambdaContext.W3C`), set `ContextExtractor = ContextExtractors.W3C`. It returns the trace id, parent span id and sampled flag, and nothing when the header is missing or malformed.
+
+## Span ids and `Activity`
+
+`Activity` has no public way to choose its own span id. The plugin sets the private `_spanId` and `_id` fields through `[UnsafeAccessor]`, only for the spans whose ids other invocations must reproduce. It is generated at compile time and works under trimming and Native AOT. The fields are not a contract: if a runtime changes them the override switches itself off and spans get random ids. Parenting inside one invocation still works; references across invocations (the Workflow span, the link from a replayed step to its first segment) then dangle. A test fails when the fields are missing. Listeners notified when a span starts see the random id; export and child spans see the derived one.
+
+## Not yet available
+
+- Loading the plugin from an environment variable or a Lambda layer without code.
+- `[DurableExecution(Tracing = ...)]` for Amazon.Lambda.Annotations.
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Amazon.Lambda.DurableExecution.AotPublishTest.csproj b/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Amazon.Lambda.DurableExecution.AotPublishTest.csproj
index ec4d0ffd0..27eaa3a68 100644
--- a/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Amazon.Lambda.DurableExecution.AotPublishTest.csproj
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Amazon.Lambda.DurableExecution.AotPublishTest.csproj
@@ -17,6 +17,7 @@
+
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Program.cs b/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Program.cs
index 10d9dd3ca..98d0e96ae 100644
--- a/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Program.cs
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.AotPublishTest/Program.cs
@@ -4,6 +4,7 @@
using System.Text.Json.Serialization;
using Amazon.Lambda.Core;
using Amazon.Lambda.DurableExecution;
+using Amazon.Lambda.DurableExecution.OpenTelemetry;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
@@ -28,9 +29,14 @@ await LambdaBootstrapBuilder
.RunAsync();
}
+ // The tracing plugin goes through the same publish check: its span id override, trace context parsing and
+ // ActivitySource use must not need reflection.
+ private static readonly DurableExecutionOptions Options = new DurableExecutionOptions()
+ .AddOpenTelemetry(OtelView.Invocation);
+
public static Task HandlerAsync(
DurableExecutionInvocationInput input, ILambdaContext context) =>
- DurableFunction.WrapAsync(WorkflowAsync, input, context);
+ DurableFunction.WrapAsync(WorkflowAsync, input, context, Options);
private static async Task WorkflowAsync(OrderEvent input, IDurableContext context)
{
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj
new file mode 100644
index 000000000..c5c38885c
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj
@@ -0,0 +1,39 @@
+
+
+
+
+
+ $(DefaultPackageTargets)
+ Amazon.Lambda.DurableExecution.OpenTelemetry.Tests
+ Amazon.Lambda.DurableExecution.OpenTelemetry.Tests
+ true
+ ..\..\..\buildtools\public.snk
+ true
+ enable
+ enable
+ $(NoWarn);CS1591
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/BuildingBlockTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/BuildingBlockTests.cs
new file mode 100644
index 000000000..27d2e6685
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/BuildingBlockTests.cs
@@ -0,0 +1,208 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Xunit;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry.Tests;
+
+public class ContextExtractorTests
+{
+ [Fact]
+ public void XRayHeader_WithRootParentAndSampled_IsParsed()
+ {
+ var context = ContextExtractors.ParseXRayHeader(
+ "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1;Lineage=1:1888001e:0");
+
+ Assert.Equal("5759e988bd862e3fe1be46a994272793", context!.TraceId);
+ Assert.Equal("53995c3f42cd8ad8", context.ParentSpanId);
+ Assert.Equal(UpstreamSampling.Sampled, context.Sampling);
+ }
+
+ [Theory]
+ [InlineData("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=0", UpstreamSampling.NotSampled)]
+ [InlineData("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8", UpstreamSampling.Undecided)]
+ [InlineData("Root=1-5759e988-bd862e3fe1be46a994272793;Sampled=?", UpstreamSampling.Undecided)]
+ public void Sampling_IsReadIndependentlyOfTheParent(string header, UpstreamSampling expected) =>
+ Assert.Equal(expected, ContextExtractors.ParseXRayHeader(header)!.Sampling);
+
+ [Theory]
+ [InlineData("Root=1-5759e988-bd862e3fe1be46a994272793;Sampled=1")]
+ [InlineData("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=0000000000000000;Sampled=1")]
+ [InlineData("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=short;Sampled=1")]
+ public void MissingOrInvalidParent_LeavesTheTraceIdUsable(string header)
+ {
+ var context = ContextExtractors.ParseXRayHeader(header)!;
+
+ Assert.Equal("5759e988bd862e3fe1be46a994272793", context.TraceId);
+ Assert.Null(context.ParentSpanId);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("Parent=53995c3f42cd8ad8;Sampled=1")]
+ [InlineData("Root=1-00000000-000000000000000000000000;Parent=53995c3f42cd8ad8")]
+ [InlineData("Root=1-xyz;Parent=53995c3f42cd8ad8")]
+ public void WithoutAValidRoot_NothingIsExtracted(string? header) =>
+ Assert.Null(ContextExtractors.ParseXRayHeader(header));
+}
+
+public class TraceParentExtractorTests
+{
+ private const string Valid = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
+
+ [Fact]
+ public void TraceParent_IsParsed()
+ {
+ var context = ContextExtractors.ParseTraceParent(Valid)!;
+
+ Assert.Equal("4bf92f3577b34da6a3ce929d0e0e4736", context.TraceId);
+ Assert.Equal("00f067aa0ba902b7", context.ParentSpanId);
+ Assert.Equal(UpstreamSampling.Sampled, context.Sampling);
+ }
+
+ [Theory]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00", UpstreamSampling.NotSampled)]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-03", UpstreamSampling.Sampled)]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-02", UpstreamSampling.NotSampled)]
+ public void Sampling_IsTheLowBitOfTheFlags(string traceParent, UpstreamSampling expected) =>
+ Assert.Equal(expected, ContextExtractors.ParseTraceParent(traceParent)!.Sampling);
+
+ [Fact]
+ public void ALaterVersion_MayAddFields() =>
+ Assert.NotNull(ContextExtractors.ParseTraceParent("01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-extra"));
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7")]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-extra")]
+ [InlineData("ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")]
+ [InlineData("00-00000000000000000000000000000000-00f067aa0ba902b7-01")]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01")]
+ [InlineData("00-4BF92F3577B34DA6A3CE929D0E0E4736-00f067aa0ba902b7-01")]
+ [InlineData("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-1")]
+ [InlineData("0-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")]
+ public void Malformed_ExtractsNothing(string? traceParent) =>
+ Assert.Null(ContextExtractors.ParseTraceParent(traceParent));
+
+ [Fact]
+ public void W3C_ReadsTheInvocationsTraceParent() =>
+ Assert.Equal(
+ "4bf92f3577b34da6a3ce929d0e0e4736",
+ ContextExtractors.W3C(new Instrumentation.InvocationInfo { ExecutionArn = "arn", TraceParent = Valid })!.TraceId);
+}
+
+public class DeterministicIdTests
+{
+ private const string Arn = "arn:aws:lambda:us-east-1:123456789012:execution:test-fn:test-execution";
+
+ // Expected values were computed with SHA-256 over the same strings the JavaScript, Python and Java SDKs hash,
+ // so a trace that crosses SDKs agrees on these ids.
+ [Fact]
+ public void Ids_MatchTheOtherSdks()
+ {
+ Assert.Equal("90dc7e18c6d7080f", DeterministicIds.WorkflowSpanId(Arn));
+ Assert.Equal("3dd8b3833680e6c9", DeterministicIds.ExecutionRootSpanId(Arn));
+ Assert.Equal("83b376fa00e63e69", DeterministicIds.SpanIdFromOperationId("abc", Arn));
+ Assert.Equal("471df46191ffb07efe6435d179443e16", DeterministicIds.TraceIdFromArn(Arn, null));
+ Assert.Equal(
+ "80dc8381b6cc28ec62f41397071bd59a",
+ DeterministicIds.TraceIdFromArn(Arn, new DateTimeOffset(2026, 11, 17, 4, 30, 42, 814, TimeSpan.Zero)));
+ }
+
+ [Fact]
+ public void Ids_AreScopedToTheExecution()
+ {
+ Assert.NotEqual(
+ DeterministicIds.SpanIdFromOperationId("abc", Arn),
+ DeterministicIds.SpanIdFromOperationId("abc", Arn + "-other"));
+ Assert.NotEqual(DeterministicIds.WorkflowSpanId(Arn), DeterministicIds.ExecutionRootSpanId(Arn));
+ }
+
+ [Fact]
+ public void Validation_RejectsZeroAndMalformedIds()
+ {
+ Assert.False(DeterministicIds.IsValidSpanId("0000000000000000"));
+ Assert.False(DeterministicIds.IsValidSpanId("ABCDEF0123456789"));
+ Assert.False(DeterministicIds.IsValidTraceId(new string('0', 32)));
+ Assert.True(DeterministicIds.IsValidTraceId("5759e988bd862e3fe1be46a994272793"));
+ }
+}
+
+public class ActivityIdOverrideTests
+{
+ private static ActivitySource NewSource(out ActivityListener listener, out string name)
+ {
+ name = "override-" + Guid.NewGuid().ToString("N");
+ var captured = name;
+ listener = new ActivityListener
+ {
+ ShouldListenTo = s => s.Name == captured,
+ Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded,
+ };
+ ActivitySource.AddActivityListener(listener);
+ return new ActivitySource(name);
+ }
+
+ private static readonly ActivityContext Parent = new(
+ ActivityTraceId.CreateFromString("5759e988bd862e3fe1be46a994272793"),
+ ActivitySpanId.CreateFromString("53995c3f42cd8ad8"), ActivityTraceFlags.Recorded, isRemote: true);
+
+ // This test is the early warning for a runtime that renames the private fields the override writes. If it
+ // fails on a new runtime, spans lose their derived ids and references across invocations break.
+ [Fact]
+ public void TheActivityFieldsTheOverrideWritesExist()
+ {
+ ActivityIdOverride.Reset();
+ using var source = NewSource(out var listener, out _);
+ using var _l = listener;
+ using var activity = source.StartActivity("x", ActivityKind.Internal, Parent)!;
+
+ Assert.True(ActivityIdOverride.TrySet(activity, "00f067aa0ba902b7"));
+ Assert.False(ActivityIdOverride.IsDisabled);
+ }
+
+ [Fact]
+ public void SpanId_IdAndChildrenSeeTheOverriddenId()
+ {
+ ActivityIdOverride.Reset();
+ using var source = NewSource(out var listener, out _);
+ using var _l = listener;
+ using var activity = source.StartActivity("x", ActivityKind.Internal, Parent)!;
+
+ ActivityIdOverride.TrySet(activity, "00f067aa0ba902b7");
+ using var child = source.StartActivity("child", ActivityKind.Internal, activity.Context)!;
+
+ Assert.Equal("00f067aa0ba902b7", activity.SpanId.ToHexString());
+ Assert.Contains("00f067aa0ba902b7", activity.Id);
+ Assert.Equal("00f067aa0ba902b7", activity.Context.SpanId.ToHexString());
+ Assert.Equal(activity.SpanId, child.ParentSpanId);
+ Assert.Equal("53995c3f42cd8ad8", activity.ParentSpanId.ToHexString());
+ }
+
+ [Fact]
+ public void AsRoot_RemovesTheParent()
+ {
+ ActivityIdOverride.Reset();
+ using var source = NewSource(out var listener, out _);
+ using var _l = listener;
+ using var activity = source.StartActivity("root", ActivityKind.Internal, Parent)!;
+
+ ActivityIdOverride.TrySet(activity, "00f067aa0ba902b7", asRoot: true);
+
+ Assert.Equal(default, activity.ParentSpanId);
+ Assert.Null(activity.ParentId);
+ Assert.Equal("5759e988bd862e3fe1be46a994272793", activity.TraceId.ToHexString());
+ }
+
+ [Fact]
+ public void WithoutAnActivity_NothingHappens()
+ {
+ ActivityIdOverride.Reset();
+
+ Assert.False(ActivityIdOverride.TrySet(null, "00f067aa0ba902b7"));
+ Assert.False(ActivityIdOverride.IsDisabled);
+ }
+}
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/ExecutionViewTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/ExecutionViewTests.cs
new file mode 100644
index 000000000..9d3fb4bce
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/ExecutionViewTests.cs
@@ -0,0 +1,434 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+using Amazon.Lambda.DurableExecution.Testing;
+using Xunit;
+using static Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.SpanCollector;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry.Tests;
+
+/// The Execution view: operations are children of the Workflow span and export once, when they finish.
+public class ExecutionViewTests
+{
+ private const string Arn = "arn:aws:lambda:us-east-1:123456789012:execution:test-fn:test-execution";
+
+ private static async Task> Run(
+ SpanCollector spans, Func> workflow, Func? extractor = null)
+ {
+ var options = spans.ExecutionOptions(spans.Options(extractor ?? RemoteParent()), OtelView.Execution);
+ await using var runner = new DurableTestRunner((_, ctx) => workflow(ctx), Runner(options));
+ return await runner.RunAsync("in");
+ }
+
+ private static string Id(string spanOperationId) => DeterministicIds.SpanIdFromOperationId(spanOperationId, Arn);
+
+ [Fact]
+ public async Task SingleStep_OperationsAreChildrenOfTheWorkflow_AndLinkTheInvocation()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"));
+
+ result.EnsureSucceeded();
+ var workflow = spans.Single("Workflow");
+ var invocation = spans.Single("Invocation");
+ var charge = spans.Single("charge");
+ var attempt = spans.Single("charge attempt 1");
+
+ Assert.All(spans.Spans, s => Assert.Equal(RemoteTraceId, s.TraceId.ToHexString()));
+ Assert.Equal(RemoteParentSpanId, workflow.ParentSpanId.ToHexString());
+ Assert.Equal(RemoteParentSpanId, invocation.ParentSpanId.ToHexString());
+ Assert.Equal(workflow.SpanId, charge.ParentSpanId);
+ Assert.Equal(charge.SpanId, attempt.ParentSpanId);
+
+ Assert.Equal(DeterministicIds.WorkflowSpanId(Arn), workflow.SpanId.ToHexString());
+ Assert.Equal(Id(Tag(charge, "durable.operation.id")), charge.SpanId.ToHexString());
+
+ // The Invocation is not a parent here. Operations and attempts link it.
+ Assert.Equal(invocation.SpanId, Assert.Single(charge.Links).Context.SpanId);
+ Assert.Equal(invocation.SpanId, Assert.Single(attempt.Links).Context.SpanId);
+ Assert.Empty(workflow.Links);
+ Assert.Empty(invocation.Links);
+
+ Assert.Equal("SUCCEEDED", Tag(charge, "durable.operation.status"));
+ Assert.Equal("1", Tag(charge, "durable.attempt.number"));
+ Assert.Equal(ActivityStatusCode.Ok, charge.Status);
+ Assert.Equal("SUCCEEDED", Tag(attempt, "durable.attempt.outcome"));
+ }
+
+ [Fact]
+ public async Task OperationSpansEncloseTheirAttemptsAndChildren()
+ {
+ using var spans = new SpanCollector();
+
+ await Run(spans, ctx => ctx.RunInChildContextAsync(
+ async (child, _) => await child.StepAsync(async (_, _) => { await Task.Delay(5); return "x"; }, name: "inner"), name: "outer"));
+
+ var outer = spans.Single("outer");
+ var inner = spans.Single("inner");
+ var attempt = spans.Single("inner attempt 1");
+ Assert.Equal(spans.Single("Workflow").SpanId, outer.ParentSpanId);
+ Assert.Equal(outer.SpanId, inner.ParentSpanId);
+ Assert.Equal(inner.SpanId, attempt.ParentSpanId);
+ Assert.True(outer.StartTimeUtc <= inner.StartTimeUtc);
+ Assert.True(inner.StartTimeUtc <= attempt.StartTimeUtc);
+ Assert.True(attempt.StartTimeUtc + attempt.Duration <= inner.StartTimeUtc + inner.Duration + TimeSpan.FromMilliseconds(1));
+ Assert.True(inner.StartTimeUtc + inner.Duration <= outer.StartTimeUtc + outer.Duration + TimeSpan.FromMilliseconds(1));
+ }
+
+ [Fact]
+ public async Task ExecutionSpanningInvocations_ExportsEachOperationOnce_InTheInvocationWhereItFinished()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, async ctx =>
+ {
+ await ctx.StepAsync((_, _) => Task.FromResult("a"), name: "first");
+ await ctx.WaitAsync(TimeSpan.FromSeconds(5), name: "pause");
+ await ctx.StepAsync((_, _) => Task.FromResult("b"), name: "second");
+ return "done";
+ });
+
+ result.EnsureSucceeded();
+ Assert.Equal(2, result.InvocationCount);
+ var invocations = spans.All("Invocation").OrderBy(s => s.StartTimeUtc).ToList();
+
+ // Replaying "first" in invocation 2 exports nothing.
+ var first = Assert.Single(spans.All("first"));
+ var second = Assert.Single(spans.All("second"));
+ Assert.Equal(invocations[0].SpanId, Assert.Single(first.Links).Context.SpanId);
+ Assert.Equal(invocations[1].SpanId, Assert.Single(second.Links).Context.SpanId);
+ Assert.Single(spans.All("Workflow"));
+ Assert.All(new[] { first, second }, s => Assert.Equal(spans.Single("Workflow").SpanId, s.ParentSpanId));
+ Assert.Equal(spans.Spans.Count, spans.Spans.Select(s => s.SpanId).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task RetriedStep_HasOneOperationSpan_AndAnAttemptSpanForEachAttempt()
+ {
+ using var spans = new SpanCollector();
+ var attempts = 0;
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) =>
+ {
+ if (++attempts < 3) throw new InvalidOperationException("transient");
+ return Task.FromResult("ok");
+ }, name: "flaky", config: new StepConfig
+ {
+ RetryStrategy = RetryStrategy.FromDelegate((_, attempt) => RetryDecision.RetryAfter(TimeSpan.FromSeconds(1))),
+ }));
+
+ result.EnsureSucceeded();
+ Assert.Equal(3, result.InvocationCount);
+
+ // One span for the step, exported by the invocation that finished it. Its attempts were exported by the
+ // invocations that ran them, parented on the step's derived id before the step span existed.
+ var step = Assert.Single(spans.All("flaky"));
+ var attemptSpans = Enumerable.Range(1, 3).Select(n => spans.Single($"flaky attempt {n}")).ToList();
+ Assert.All(attemptSpans, a => Assert.Equal(step.SpanId, a.ParentSpanId));
+ Assert.Equal(new[] { "FAILED", "FAILED", "SUCCEEDED" }, attemptSpans.Select(a => Tag(a, "durable.attempt.outcome")).ToArray());
+ Assert.Equal("3", Tag(step, "durable.attempt.number"));
+
+ // Each attempt links the invocation that ran it. The step links the one that finished it.
+ var invocations = spans.All("Invocation").OrderBy(s => s.StartTimeUtc).Select(s => s.SpanId).ToList();
+ Assert.Equal(invocations, attemptSpans.Select(a => a.Links.Single().Context.SpanId).ToList());
+ Assert.Equal(invocations[2], step.Links.Single().Context.SpanId);
+ }
+
+ [Fact]
+ public async Task FailedStep_RecordsTheErrorOnTheOperationSpan()
+ {
+ using var spans = new SpanCollector();
+
+ await Run(spans, async ctx =>
+ {
+ try { await ctx.StepAsync((_, _) => throw new InvalidOperationException("card declined"), name: "charge"); }
+ catch (StepException) { }
+ return "handled";
+ });
+
+ var charge = spans.Single("charge");
+ Assert.Equal(ActivityStatusCode.Error, charge.Status);
+ var exception = Assert.Single(charge.Events, e => e.Name == "exception");
+ Assert.Equal("card declined", exception.Tags.Single(t => t.Key == "exception.message").Value);
+ Assert.Equal(ActivityStatusCode.Error, spans.Single("charge attempt 1").Status);
+ }
+
+ [Fact]
+ public async Task WithoutAPropagatedParent_TheWorkflowHangsOffTheSyntheticRoot()
+ {
+ using var spans = new SpanCollector();
+
+ await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"), _ => null);
+
+ var root = spans.Single("DurableExecutionRoot");
+ Assert.Equal(default, root.ParentSpanId);
+ Assert.Equal(root.SpanId, spans.Single("Workflow").ParentSpanId);
+ Assert.Equal(spans.Single("Workflow").SpanId, spans.Single("charge").ParentSpanId);
+ }
+
+ [Fact]
+ public async Task UpstreamNotSampled_ExportsNothing()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"),
+ RemoteParent(UpstreamSampling.NotSampled));
+
+ result.EnsureSucceeded();
+ Assert.Empty(spans.Spans);
+ }
+
+ [Fact]
+ public async Task UserCode_RunsUnderTheWorkflowChildContextAndAttempt_AndSpansItStartsParentOntoThem()
+ {
+ using var spans = new SpanCollector();
+ using var source = new ActivitySource(spans.SourceName);
+ string? workflowSeen = null, childSeen = null, stepSeen = null, userInChildParent = null, userInWorkflowParent = null;
+
+ await Run(spans, async ctx =>
+ {
+ workflowSeen = Activity.Current?.SpanId.ToHexString();
+ using (var user = source.StartActivity("user in workflow")) userInWorkflowParent = user?.ParentSpanId.ToHexString();
+ await ctx.RunInChildContextAsync(async (child, _) =>
+ {
+ childSeen = Activity.Current?.SpanId.ToHexString();
+ using (var user = source.StartActivity("user in child")) userInChildParent = user?.ParentSpanId.ToHexString();
+ await child.StepAsync((_, _) => { stepSeen = Activity.Current?.OperationName; return Task.FromResult("x"); }, name: "inner");
+ return 1;
+ }, name: "outer");
+ return "done";
+ });
+
+ Assert.Equal(DeterministicIds.WorkflowSpanId(Arn), workflowSeen);
+ Assert.Equal(workflowSeen, userInWorkflowParent);
+ var outer = spans.Single("outer");
+ Assert.Equal(outer.SpanId.ToHexString(), childSeen);
+ Assert.Equal(outer.SpanId.ToHexString(), userInChildParent);
+ Assert.Equal("inner attempt 1", stepSeen);
+ Assert.Null(Activity.Current);
+
+ // The stand-ins carry identity only. They are never exported, and the user's spans are.
+ Assert.DoesNotContain(spans.Spans, s => s.OperationName == "durable-context");
+ Assert.Equal(workflowSeen, spans.Single("user in workflow").ParentSpanId.ToHexString());
+ }
+
+ [Fact]
+ public async Task TwoOtelFactories_AreStillRejected()
+ {
+ using var spans = new SpanCollector();
+ var options = new DurableExecutionOptions();
+ options.AddOpenTelemetry(OtelView.Execution, spans.Options());
+ options.AddOpenTelemetry(OtelView.Invocation, spans.Options());
+ await using var runner = new DurableTestRunner((_, _) => Task.FromResult("x"), Runner(options));
+
+ await Assert.ThrowsAsync(() => runner.RunAsync("in"));
+ }
+}
+
+/// Calls the Execution view's hooks directly, for timing and ordering the in-memory service cannot produce.
+public class ExecutionViewHookTests
+{
+ private const string Arn = "arn:aws:lambda:us-east-1:123456789012:execution:direct";
+ private static readonly DateTimeOffset T0 = new(2026, 11, 17, 4, 30, 0, TimeSpan.Zero);
+
+ private static OperationInfo Op(
+ string id, string type, string status, string? name = null, string? parent = null, string? subType = null,
+ bool replay = false, DateTimeOffset? start = null, DateTimeOffset? end = null) => new()
+ {
+ Id = id, Type = type, Status = status, Name = name, ParentId = parent, SubType = subType, IsReplay = replay,
+ StartTimestamp = start, EndTimestamp = end,
+ };
+
+ private static OperationEndInfo End(OperationInfo op, bool replay = false) => new()
+ {
+ Id = op.Id, Type = op.Type, Name = op.Name, ParentId = op.ParentId, SubType = op.SubType, Status = op.Status,
+ StartTimestamp = op.StartTimestamp, EndTimestamp = op.EndTimestamp, Attempt = op.Attempt, IsReplay = replay,
+ };
+
+ private static InvocationInfo Info(params OperationInfo[] updated) => new()
+ {
+ ExecutionArn = Arn,
+ UpdatedOperations = updated.ToDictionary(o => o.Id),
+ Operations = updated.ToDictionary(o => o.Id),
+ };
+
+ private static IDurableInstrumentationPlugin Start(SpanCollector spans, InvocationInfo info)
+ {
+ var plugin = OtelPlugin.CreateFactory(OtelView.Execution, spans.Options(RemoteParent())).CreatePlugin(info)!;
+ plugin.OnInvocationStart(info);
+ return plugin;
+ }
+
+ private static Task Finish(
+ IDurableInstrumentationPlugin plugin, InvocationEndStatus status = InvocationEndStatus.Pending,
+ params OperationInfo[] operations) =>
+ plugin.OnInvocationEndAsync(new InvocationEndInfo
+ {
+ ExecutionArn = Arn, Status = status, Operations = operations.ToDictionary(o => o.Id),
+ }, CancellationToken.None);
+
+ [Fact]
+ public async Task OperationSpan_UsesTheServicesStartAndEnd()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var step = Op("step-1", OperationTypes.Step, OperationStatuses.Succeeded, "charge", start: T0, end: T0.AddSeconds(10));
+
+ plugin.OnOperationStart(Op("step-1", OperationTypes.Step, OperationStatuses.Started, "charge"));
+ plugin.OnOperationEnd(End(step));
+ await Finish(plugin);
+
+ var charge = spans.Single("charge");
+ Assert.Equal(T0, new DateTimeOffset(charge.StartTimeUtc, TimeSpan.Zero));
+ Assert.Equal(TimeSpan.FromSeconds(10), charge.Duration);
+ }
+
+ [Fact]
+ public async Task EndBeforeStart_IsRaisedToTheStart()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var step = Op("step-1", OperationTypes.Step, OperationStatuses.Succeeded, "charge", start: T0, end: T0.AddSeconds(-3));
+
+ plugin.OnOperationStart(step);
+ plugin.OnOperationEnd(End(step));
+ await Finish(plugin);
+
+ // Activity reports a span with no length as one tick.
+ Assert.InRange(spans.Single("charge").Duration, TimeSpan.Zero, TimeSpan.FromTicks(1));
+ }
+
+ [Fact]
+ public async Task ParentStartMovesEarlier_WhenAChildStartedBeforeIt()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var parent = Op("ctx-1", OperationTypes.Context, OperationStatuses.Succeeded, "outer", start: T0.AddSeconds(5), end: T0.AddSeconds(20));
+ var child = Op("step-1", OperationTypes.Step, OperationStatuses.Succeeded, "inner", parent: "ctx-1", start: T0, end: T0.AddSeconds(10));
+
+ plugin.OnOperationStart(Op("ctx-1", OperationTypes.Context, OperationStatuses.Started, "outer", start: T0.AddSeconds(5)));
+ plugin.OnOperationStart(Op("step-1", OperationTypes.Step, OperationStatuses.Started, "inner", parent: "ctx-1", start: T0));
+ plugin.OnOperationEnd(End(child));
+ plugin.OnOperationEnd(End(parent));
+ await Finish(plugin);
+
+ var outer = spans.Single("outer");
+ Assert.Equal(T0, new DateTimeOffset(outer.StartTimeUtc, TimeSpan.Zero));
+ Assert.Equal(outer.SpanId, spans.Single("inner").ParentSpanId);
+ }
+
+ [Fact]
+ public async Task OperationStillOpenWhenTheInvocationSuspends_ExportsNothing_ButItsAttemptsEnd()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ plugin.OnOperationStart(Op("wait-1", OperationTypes.Wait, OperationStatuses.Started, "pause"));
+ plugin.OnOperationStart(Op("step-1", OperationTypes.Step, OperationStatuses.Started, "retrying"));
+ plugin.OnAttemptStart(new AttemptInfo { Id = "step-1", Type = OperationTypes.Step, Name = "retrying", Attempt = 1 });
+
+ await Finish(plugin);
+
+ Assert.Empty(spans.All("pause"));
+ Assert.Empty(spans.All("retrying"));
+ Assert.Single(spans.All("retrying attempt 1"));
+ Assert.Equal("PENDING", Tag(spans.Single("Invocation"), "durable.invocation.status"));
+ Assert.Empty(spans.All("Workflow"));
+ }
+
+ [Fact]
+ public async Task ReplayedStep_ExportsNothing()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var step = Op("step-1", OperationTypes.Step, OperationStatuses.Succeeded, "charge", replay: true, start: T0, end: T0.AddSeconds(1));
+
+ plugin.OnOperationStart(step);
+ plugin.OnOperationEnd(End(step, replay: true));
+ await Finish(plugin);
+
+ Assert.Empty(spans.All("charge"));
+ }
+
+ [Fact]
+ public async Task WaitThatElapsedWhileSuspended_IsExportedOnce_WithTheServicesTimes()
+ {
+ using var spans = new SpanCollector();
+ var wait = Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause", start: T0, end: T0.AddSeconds(30));
+ var plugin = Start(spans, Info(wait));
+
+ plugin.OnOperationStart(Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause", replay: true, start: T0));
+ plugin.OnOperationEnd(End(wait, replay: true));
+ plugin.OnOperationEnd(End(wait, replay: false));
+ await Finish(plugin);
+
+ var pause = Assert.Single(spans.All("pause"));
+ Assert.Equal(TimeSpan.FromSeconds(30), pause.Duration);
+ Assert.Equal(DeterministicIds.WorkflowSpanId(Arn), pause.ParentSpanId.ToHexString());
+ Assert.Equal(spans.Single("Invocation").SpanId, Assert.Single(pause.Links).Context.SpanId);
+ }
+
+ [Fact]
+ public async Task CompletionTheWorkflowDidNotReach_IsExportedWhenTheInvocationEnds()
+ {
+ using var spans = new SpanCollector();
+ var callback = Op("cb-1", OperationTypes.Callback, OperationStatuses.Failed, "approval", start: T0, end: T0.AddSeconds(2));
+ var plugin = Start(spans, Info(callback));
+
+ await Finish(plugin);
+
+ var span = Assert.Single(spans.All("approval"));
+ Assert.Equal(ActivityStatusCode.Error, span.Status);
+ Assert.Equal(TimeSpan.FromSeconds(2), span.Duration);
+ }
+
+ [Fact]
+ public async Task CompletionWhoseParentContextNeverFinished_ButAnAncestorDid_AttachesToTheWorkflow()
+ {
+ using var spans = new SpanCollector();
+ var callback = Op("cb-1", OperationTypes.Callback, OperationStatuses.Succeeded, "approval", parent: "ctx-1", start: T0, end: T0.AddSeconds(2));
+ var plugin = Start(spans, Info(callback));
+ var abandoned = Op("ctx-1", OperationTypes.Context, OperationStatuses.Started, "inner", parent: "ctx-0");
+ var finishedAncestor = Op("ctx-0", OperationTypes.Context, OperationStatuses.Succeeded, "outer");
+
+ await Finish(plugin, InvocationEndStatus.Succeeded, abandoned, finishedAncestor);
+
+ var approval = spans.Single("approval");
+ Assert.Equal(spans.Single("Workflow").SpanId, approval.ParentSpanId);
+ }
+
+ [Fact]
+ public async Task InvocationSpan_EndsNoEarlierThanTheLatestBoundaryItObserved()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var future = DateTimeOffset.UtcNow.AddMinutes(10);
+ var step = Op("step-1", OperationTypes.Step, OperationStatuses.Succeeded, "charge", start: future.AddSeconds(-1), end: future);
+
+ plugin.OnOperationStart(step);
+ plugin.OnOperationEnd(End(step));
+ await Finish(plugin);
+
+ var invocation = spans.Single("Invocation");
+ Assert.True(invocation.StartTimeUtc + invocation.Duration >= future.UtcDateTime - TimeSpan.FromMilliseconds(1));
+ }
+
+ [Fact]
+ public async Task PropagationHeader_NamesTheOperationsDerivedSpan()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+
+ var header = plugin.ProvidePropagationMetadata(new PropagationInput
+ {
+ ExecutionArn = Arn, OperationId = "invoke-1", TargetFunctionName = "other",
+ });
+
+ Assert.Equal(
+ $"Root=1-5759e988-bd862e3fe1be46a994272793;Parent={DeterministicIds.SpanIdFromOperationId("invoke-1", Arn)};Sampled=1",
+ header);
+ await Finish(plugin);
+ }
+}
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/InvocationTraceTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/InvocationTraceTests.cs
new file mode 100644
index 000000000..0a379afda
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/InvocationTraceTests.cs
@@ -0,0 +1,410 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+using Amazon.Lambda.DurableExecution.Testing;
+using Xunit;
+using static Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.SpanCollector;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry.Tests;
+
+/// The spans of the Invocation view, produced by running workflows on the in-memory test service.
+public class InvocationTraceTests
+{
+ private const string Arn = "arn:aws:lambda:us-east-1:123456789012:execution:test-fn:test-execution";
+
+ private static async Task> Run(
+ SpanCollector spans, Func> workflow, Func? extractor = null)
+ {
+ var options = spans.ExecutionOptions(spans.Options(extractor));
+ await using var runner = new DurableTestRunner((_, ctx) => workflow(ctx), Runner(options));
+ return await runner.RunAsync("in");
+ }
+
+ [Fact]
+ public async Task SingleStep_EmitsWorkflowInvocationOperationAndAttempt_OnTheUpstreamTrace()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"), RemoteParent());
+
+ result.EnsureSucceeded();
+ var workflow = spans.Single("Workflow");
+ var invocation = spans.Single("Invocation");
+ var charge = spans.Single("charge");
+ var attempt = spans.Single("charge attempt 1");
+
+ Assert.All(spans.Spans, s => Assert.Equal(RemoteTraceId, s.TraceId.ToHexString()));
+ Assert.All(spans.Spans, s => Assert.Equal(ActivityKind.Internal, s.Kind));
+
+ // Workflow and Invocation join the upstream span. Operations nest under the Invocation.
+ Assert.Equal(RemoteParentSpanId, workflow.ParentSpanId.ToHexString());
+ Assert.Equal(RemoteParentSpanId, invocation.ParentSpanId.ToHexString());
+ Assert.Equal(invocation.SpanId, charge.ParentSpanId);
+ Assert.Equal(charge.SpanId, attempt.ParentSpanId);
+ Assert.Empty(spans.All("DurableExecutionRoot"));
+
+ // Ids that other invocations must be able to name.
+ Assert.Equal(DeterministicIds.WorkflowSpanId(Arn), workflow.SpanId.ToHexString());
+ Assert.Equal(DeterministicIds.SpanIdFromOperationId(Tag(charge, "durable.operation.id"), Arn), charge.SpanId.ToHexString());
+
+ // Operations and attempts link the Workflow span.
+ Assert.Equal(workflow.SpanId, Assert.Single(charge.Links).Context.SpanId);
+ Assert.Equal(workflow.SpanId, Assert.Single(attempt.Links).Context.SpanId);
+ Assert.Empty(invocation.Links);
+ Assert.Empty(workflow.Links);
+ }
+
+ [Fact]
+ public async Task Attributes_StatusAndTiming_AreSet()
+ {
+ using var spans = new SpanCollector();
+
+ await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"), RemoteParent());
+
+ var workflow = spans.Single("Workflow");
+ Assert.Equal("SUCCEEDED", Tag(workflow, "durable.execution.status"));
+ Assert.Equal(Arn, Tag(workflow, "durable.execution.arn"));
+ Assert.Equal(ActivityStatusCode.Ok, workflow.Status);
+
+ var invocation = spans.Single("Invocation");
+ Assert.Equal("True", Tag(invocation, "durable.invocation.first"));
+ Assert.Equal("SUCCEEDED", Tag(invocation, "durable.invocation.status"));
+ Assert.Equal(ActivityStatusCode.Ok, invocation.Status);
+
+ var charge = spans.Single("charge");
+ Assert.Equal("STEP", Tag(charge, "durable.operation.type"));
+ Assert.Equal("Step", Tag(charge, "durable.operation.subtype"));
+ Assert.Equal("charge", Tag(charge, "durable.operation.name"));
+ Assert.Equal("SUCCEEDED", Tag(charge, "durable.operation.status"));
+ Assert.Equal("1", Tag(charge, "durable.attempt.number"));
+ Assert.Equal(ActivityStatusCode.Ok, charge.Status);
+
+ var attempt = spans.Single("charge attempt 1");
+ Assert.Equal("SUCCEEDED", Tag(attempt, "durable.attempt.outcome"));
+ Assert.False(HasTag(attempt, "durable.operation.status"));
+
+ // The operation sits inside the invocation, and the attempt inside the operation.
+ Assert.True(charge.StartTimeUtc >= invocation.StartTimeUtc);
+ Assert.True(charge.StartTimeUtc + charge.Duration <= invocation.StartTimeUtc + invocation.Duration);
+ Assert.True(attempt.StartTimeUtc >= charge.StartTimeUtc);
+ Assert.True(attempt.StartTimeUtc + attempt.Duration <= charge.StartTimeUtc + charge.Duration);
+ }
+
+ [Fact]
+ public async Task WithoutAPropagatedParent_AnArnDerivedRootAnchorsTheTrace()
+ {
+ using var spans = new SpanCollector();
+
+ await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"));
+
+ var root = spans.Single("DurableExecutionRoot");
+ Assert.Equal(default, root.ParentSpanId);
+ Assert.Equal(DeterministicIds.ExecutionRootSpanId(Arn), root.SpanId.ToHexString());
+ Assert.Equal("True", Tag(root, "durable.execution.synthetic_root"));
+
+ Assert.Equal(root.SpanId, spans.Single("Workflow").ParentSpanId);
+ Assert.Equal(root.SpanId, spans.Single("Invocation").ParentSpanId);
+ Assert.All(spans.Spans, s => Assert.Equal(root.TraceId, s.TraceId));
+ Assert.True(DeterministicIds.IsValidTraceId(root.TraceId.ToHexString()));
+ }
+
+ [Fact]
+ public async Task FailedStep_RecordsTheErrorOnTheOperationAndAttempt()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, async ctx =>
+ {
+ try { await ctx.StepAsync((_, _) => throw new InvalidOperationException("card declined"), name: "charge"); }
+ catch (StepException) { }
+ return "handled";
+ }, RemoteParent());
+
+ result.EnsureSucceeded();
+ var charge = spans.Single("charge");
+ Assert.Equal(ActivityStatusCode.Error, charge.Status);
+ Assert.Equal("FAILED", Tag(charge, "durable.operation.status"));
+ var exception = Assert.Single(charge.Events, e => e.Name == "exception");
+ Assert.Equal("card declined", exception.Tags.Single(t => t.Key == "exception.message").Value);
+ Assert.Equal("System.InvalidOperationException", exception.Tags.Single(t => t.Key == "exception.type").Value);
+
+ var attempt = spans.Single("charge attempt 1");
+ Assert.Equal(ActivityStatusCode.Error, attempt.Status);
+ Assert.Equal("FAILED", Tag(attempt, "durable.attempt.outcome"));
+ Assert.Contains(attempt.Events, e => e.Name == "exception");
+
+ // The workflow handled the failure, so the execution and invocation still succeeded.
+ Assert.Equal(ActivityStatusCode.Ok, spans.Single("Workflow").Status);
+ }
+
+ [Fact]
+ public async Task FailedWorkflow_MarksInvocationAndWorkflowAsErrors()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, _ => throw new InvalidOperationException("workflow broke"), RemoteParent());
+
+ Assert.NotEqual(InvocationStatus.Succeeded, result.Status);
+ var invocation = spans.Single("Invocation");
+ Assert.Equal("FAILED", Tag(invocation, "durable.invocation.status"));
+ Assert.Equal(ActivityStatusCode.Error, invocation.Status);
+ var workflow = spans.Single("Workflow");
+ Assert.Equal("FAILED", Tag(workflow, "durable.execution.status"));
+ Assert.Equal(ActivityStatusCode.Error, workflow.Status);
+ // Failures of the workflow itself set the status without an exception event.
+ Assert.DoesNotContain(workflow.Events, e => e.Name == "exception");
+ }
+
+ [Fact]
+ public async Task ChildContextAndParallel_NestUnderTheirParents()
+ {
+ using var spans = new SpanCollector();
+
+ await Run(spans, async ctx =>
+ {
+ await ctx.RunInChildContextAsync(async (child, _) => await child.StepAsync((_, _) => Task.FromResult("x"), name: "inner"), name: "outer");
+ await ctx.ParallelAsync(new Func>[]
+ {
+ async (c, _) => await c.StepAsync((_, _) => Task.FromResult("a"), name: "branch-a"),
+ }, name: "fan");
+ return "done";
+ }, RemoteParent());
+
+ var outer = spans.Single("outer");
+ Assert.Equal(spans.Single("Invocation").SpanId, outer.ParentSpanId);
+ Assert.Equal(outer.SpanId, spans.Single("inner").ParentSpanId);
+ Assert.Equal("CONTEXT", Tag(outer, "durable.operation.type"));
+
+ var fan = spans.Single("fan");
+ Assert.Equal("Parallel", Tag(fan, "durable.operation.subtype"));
+ var branch = spans.Spans.Single(x => Tag(x, "durable.operation.subtype") == "ParallelBranch");
+ Assert.Equal(fan.SpanId, branch.ParentSpanId);
+ Assert.Equal(branch.SpanId, spans.Single("branch-a").ParentSpanId);
+ }
+
+ [Fact]
+ public async Task ExecutionSpanningInvocations_ShareOneTrace_AndFinishedStepsAreNotExportedAgain()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, async ctx =>
+ {
+ await ctx.StepAsync((_, _) => Task.FromResult("a"), name: "first");
+ await ctx.WaitAsync(TimeSpan.FromSeconds(5), name: "pause");
+ await ctx.StepAsync((_, _) => Task.FromResult("b"), name: "second");
+ return "done";
+ }, RemoteParent());
+
+ result.EnsureSucceeded();
+ Assert.Equal(2, result.InvocationCount);
+ Assert.All(spans.Spans, s => Assert.Equal(RemoteTraceId, s.TraceId.ToHexString()));
+
+ var invocations = spans.All("Invocation").OrderBy(s => s.StartTimeUtc).ToList();
+ Assert.Equal(2, invocations.Count);
+ Assert.Equal("PENDING", Tag(invocations[0], "durable.invocation.status"));
+ Assert.Equal("SUCCEEDED", Tag(invocations[1], "durable.invocation.status"));
+ Assert.Equal("True", Tag(invocations[0], "durable.invocation.first"));
+ Assert.Equal("False", Tag(invocations[1], "durable.invocation.first"));
+
+ // Only the invocation that finishes the execution exports the Workflow span.
+ Assert.Single(spans.All("Workflow"));
+
+ // "first" finished in invocation 1. Invocation 2 only replays it, so it is exported once.
+ var first = Assert.Single(spans.All("first"));
+ Assert.Equal(invocations[0].SpanId, first.ParentSpanId);
+
+ // The wait started in invocation 1. Invocation 2 reaches it again, but a wait that is only replayed is not
+ // exported a second time.
+ var pause = Assert.Single(spans.All("pause"));
+ Assert.Equal(invocations[0].SpanId, pause.ParentSpanId);
+ }
+
+ [Fact]
+ public async Task RetriedStep_NeverReusesASpanIdAcrossInvocations()
+ {
+ using var spans = new SpanCollector();
+ var attempts = 0;
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) =>
+ {
+ if (++attempts < 3) throw new InvalidOperationException("transient");
+ return Task.FromResult("ok");
+ }, name: "flaky", config: new StepConfig
+ {
+ RetryStrategy = RetryStrategy.FromDelegate((_, attempt) => RetryDecision.RetryAfter(TimeSpan.FromSeconds(1))),
+ }), RemoteParent());
+
+ result.EnsureSucceeded();
+ Assert.Equal(3, result.InvocationCount);
+ // Every span in the trace has its own id, including the segments of the retried step.
+ Assert.Equal(spans.Spans.Count, spans.Spans.Select(s => s.SpanId).Distinct().Count());
+
+ var segments = spans.All("flaky").OrderBy(s => s.StartTimeUtc).ToList();
+ Assert.Equal(3, segments.Count);
+ var firstSegmentId = segments[0].SpanId;
+ Assert.All(segments.Skip(1), s => Assert.Equal(firstSegmentId, s.Links.First().Context.SpanId));
+ // The attempt number is set when the operation finishes, so only the last segment has one.
+ Assert.Equal("3", Tag(segments[2], "durable.attempt.number"));
+ Assert.Equal("SUCCEEDED", Tag(segments[2], "durable.operation.status"));
+ }
+
+ [Fact]
+ public async Task UpstreamNotSampled_ExportsNothingAndStillRuns()
+ {
+ using var spans = new SpanCollector();
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"),
+ RemoteParent(UpstreamSampling.NotSampled));
+
+ result.EnsureSucceeded();
+ Assert.Empty(spans.Spans);
+ }
+
+ [Theory]
+ [InlineData(OtelView.Invocation)]
+ [InlineData(OtelView.Execution)]
+ public async Task UpstreamNotSampled_ExportsNothing_EvenWithASamplerThatIgnoresTheParent(OtelView view)
+ {
+ using var spans = new SpanCollector(SpanCollector.AlwaysOn);
+ var options = spans.ExecutionOptions(spans.Options(RemoteParent(UpstreamSampling.NotSampled)), view);
+ await using var runner = new DurableTestRunner(async (_, ctx) =>
+ {
+ await ctx.StepAsync((_, _) => Task.FromResult("a"), name: "charge");
+ await ctx.WaitAsync(TimeSpan.FromSeconds(1), name: "pause");
+ return await ctx.RunInChildContextAsync((child, _) => child.StepAsync((_, _) => Task.FromResult("b"), name: "inner"), name: "outer");
+ }, Runner(options));
+
+ var result = await runner.RunAsync("in");
+
+ result.EnsureSucceeded();
+ Assert.Empty(spans.Spans);
+ }
+
+ [Theory]
+ [InlineData(OtelView.Invocation)]
+ [InlineData(OtelView.Execution)]
+ public async Task WithoutAnUpstreamDecision_TheInvocationSpansSamplingDecidesForTheRest(OtelView view)
+ {
+ // AlwaysOn for everything but the Invocation span: the plugin must not export the rest of a dropped invocation.
+ using var spans = new SpanCollector((name, _) => name != "Invocation");
+ var options = spans.ExecutionOptions(spans.Options(), view);
+ await using var runner = new DurableTestRunner(
+ (_, ctx) => ctx.StepAsync((_, _) => Task.FromResult("a"), name: "charge"), Runner(options));
+
+ var result = await runner.RunAsync("in");
+
+ result.EnsureSucceeded();
+ Assert.Empty(spans.Spans);
+ }
+
+ [Fact]
+ public async Task UpstreamSampled_WithAlwaysOn_ExportsTheWholeExecution()
+ {
+ using var spans = new SpanCollector(SpanCollector.AlwaysOn);
+
+ var result = await Run(spans, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"), RemoteParent());
+
+ result.EnsureSucceeded();
+ Assert.Single(spans.All("Workflow"));
+ Assert.Single(spans.All("Invocation"));
+ Assert.Single(spans.All("charge"));
+ Assert.Single(spans.All("charge attempt 1"));
+ }
+
+ [Fact]
+ public async Task NoListener_RunsTheWorkflowWithoutSpans()
+ {
+ var options = new DurableExecutionOptions();
+ options.AddOpenTelemetry(OtelView.Invocation, new OtelPluginOptions { InstrumentationName = "nobody-listens-" + Guid.NewGuid().ToString("N") });
+ await using var runner = new DurableTestRunner(
+ async (_, ctx) => await ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge"), Runner(options));
+
+ var result = await runner.RunAsync("in");
+
+ result.EnsureSucceeded();
+ }
+
+ [Fact]
+ public async Task FlushIsCalledAfterTheInvocationSpanEnded_OncePerInvocation()
+ {
+ var invocationEndedWhenFlushed = new List();
+ var timeouts = new List();
+
+ using var flushing = new SpanCollector();
+ var options = flushing.ExecutionOptions(flushing.Options(RemoteParent(), flush: (timeout, _) =>
+ {
+ timeouts.Add(timeout);
+ invocationEndedWhenFlushed.Add(flushing.All("Invocation").Count == invocationEndedWhenFlushed.Count + 1);
+ return Task.CompletedTask;
+ }));
+ await using var runner = new DurableTestRunner(
+ async (_, ctx) => { await ctx.WaitAsync(TimeSpan.FromSeconds(5), name: "pause"); return "done"; }, Runner(options));
+
+ var result = await runner.RunAsync("in");
+
+ Assert.Equal(result.InvocationCount, invocationEndedWhenFlushed.Count);
+ Assert.All(invocationEndedWhenFlushed, ended => Assert.True(ended));
+ Assert.All(timeouts, t => Assert.Equal(TimeSpan.FromSeconds(1), t));
+ }
+
+ [Fact]
+ public async Task AFailingFlush_DoesNotFailTheInvocation()
+ {
+ using var spans = new SpanCollector();
+ var options = spans.ExecutionOptions(spans.Options(RemoteParent(), flush: (_, _) => throw new InvalidOperationException("exporter down")));
+ await using var runner = new DurableTestRunner(
+ async (_, ctx) => await ctx.StepAsync((_, _) => Task.FromResult("v"), name: "s"), Runner(options));
+
+ var result = await runner.RunAsync("in");
+
+ result.EnsureSucceeded();
+ }
+
+ [Fact]
+ public async Task UserCode_SeesTheMatchingSpanAsCurrent_AndTheCallersActivityIsRestored()
+ {
+ using var spans = new SpanCollector();
+ string? inWorkflow = null, inStep = null, inChild = null, afterStep = null;
+
+ var options = spans.ExecutionOptions(spans.Options(RemoteParent()));
+ await using var runner = new DurableTestRunner(async (_, ctx) =>
+ {
+ inWorkflow = Activity.Current?.OperationName;
+ await ctx.RunInChildContextAsync(async (_, _) =>
+ {
+ inChild = Activity.Current?.OperationName;
+ await Task.Yield();
+ return 1;
+ }, name: "outer");
+ await ctx.StepAsync((_, _) => { inStep = Activity.Current?.OperationName; return Task.FromResult("v"); }, name: "charge");
+ afterStep = Activity.Current?.OperationName;
+ return "done";
+ }, Runner(options));
+
+ (await runner.RunAsync("in")).EnsureSucceeded();
+
+ Assert.Equal("Invocation", inWorkflow);
+ Assert.Equal("outer", inChild);
+ Assert.Equal("charge attempt 1", inStep);
+ Assert.Equal("Invocation", afterStep);
+ Assert.Null(Activity.Current);
+ }
+
+ [Fact]
+ public async Task TwoOtelFactories_AreRejectedBeforeAnythingRuns()
+ {
+ using var spans = new SpanCollector();
+ var options = new DurableExecutionOptions();
+ options.AddOpenTelemetry(OtelView.Invocation, spans.Options());
+ options.AddOpenTelemetry(OtelView.Invocation, spans.Options());
+ var ran = false;
+ await using var runner = new DurableTestRunner((_, _) => { ran = true; return Task.FromResult("x"); }, Runner(options));
+
+ await Assert.ThrowsAsync(() => runner.RunAsync("in"));
+
+ Assert.False(ran);
+ Assert.Empty(spans.Spans);
+ }
+}
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/PluginHookTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/PluginHookTests.cs
new file mode 100644
index 000000000..6edf1ac42
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/PluginHookTests.cs
@@ -0,0 +1,335 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+using Xunit;
+using static Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.SpanCollector;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry.Tests;
+
+/// Calls the plugin's hooks directly, for cases the in-memory service cannot produce.
+public class PluginHookTests
+{
+ private const string Arn = "arn:aws:lambda:us-east-1:123456789012:execution:direct";
+
+ private static OperationInfo Op(string id, string type, string status, string? name = null, string? parent = null, string? subType = null, bool replay = false) =>
+ new() { Id = id, Type = type, Status = status, Name = name, ParentId = parent, SubType = subType, IsReplay = replay };
+
+ private static InvocationInfo Info(params OperationInfo[] updated) => new()
+ {
+ ExecutionArn = Arn,
+ RequestId = "req-1",
+ IsFirstInvocation = false,
+ UpdatedOperations = updated.ToDictionary(o => o.Id),
+ Operations = updated.ToDictionary(o => o.Id),
+ };
+
+ private static OperationEndInfo End(OperationInfo op, bool replay) => new()
+ {
+ Id = op.Id, Type = op.Type, Name = op.Name, ParentId = op.ParentId, SubType = op.SubType,
+ Status = op.Status, IsReplay = replay,
+ };
+
+ private static IDurableInstrumentationPlugin Start(SpanCollector spans, InvocationInfo info)
+ {
+ var factory = OtelPlugin.CreateFactory(OtelView.Invocation, spans.Options(RemoteParent()));
+ var plugin = factory.CreatePlugin(info)!;
+ plugin.OnInvocationStart(info);
+ return plugin;
+ }
+
+ private static Task Finish(IDurableInstrumentationPlugin plugin, InvocationEndStatus status = InvocationEndStatus.Pending) =>
+ plugin.OnInvocationEndAsync(new InvocationEndInfo { ExecutionArn = Arn, Status = status }, CancellationToken.None);
+
+ [Fact]
+ public async Task WaitThatElapsedWhileSuspended_IsExportedOnceInTheInvocationThatReachesIt()
+ {
+ using var spans = new SpanCollector();
+ var wait = Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause");
+ var plugin = Start(spans, Info(wait));
+
+ // The workflow reaches the finished wait again: a replay.
+ plugin.OnOperationStart(Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause", replay: true));
+ plugin.OnOperationEnd(End(wait, replay: true));
+ await Finish(plugin);
+
+ var pause = Assert.Single(spans.All("pause"));
+ Assert.Equal(spans.Single("Invocation").SpanId, pause.ParentSpanId);
+ Assert.Equal("SUCCEEDED", Tag(pause, "durable.operation.status"));
+ Assert.Equal(ActivityStatusCode.Ok, pause.Status);
+ // It links the first segment of the wait (started by an earlier invocation) and the Workflow span.
+ Assert.Equal(
+ new[] { DeterministicIds.SpanIdFromOperationId("wait-1", Arn) },
+ pause.Links.Select(l => l.Context.SpanId.ToHexString()).Take(1));
+ Assert.Equal(2, pause.Links.Count());
+ }
+
+ [Fact]
+ public async Task CompletionTheWorkflowDidNotReach_IsExportedWhenTheInvocationEnds_WithItsParent()
+ {
+ using var spans = new SpanCollector();
+ var callback = Op("cb-1", OperationTypes.Callback, OperationStatuses.Succeeded, name: null, parent: "ctx-1");
+ var parent = Op("ctx-1", OperationTypes.Context, OperationStatuses.Started, "approve", subType: OperationSubTypes.WaitForCallback);
+ var info = new InvocationInfo
+ {
+ ExecutionArn = Arn,
+ UpdatedOperations = new Dictionary { [callback.Id] = callback },
+ Operations = new Dictionary { [callback.Id] = callback, [parent.Id] = parent },
+ };
+ var plugin = OtelPlugin.CreateFactory(OtelView.Invocation, spans.Options(RemoteParent())).CreatePlugin(info)!;
+ plugin.OnInvocationStart(info);
+
+ await Finish(plugin);
+
+ // A wait-for-callback's callback has no name of its own, so it is named after its parent.
+ var span = Assert.Single(spans.All("approve-callback"));
+ Assert.Equal("CALLBACK", Tag(span, "durable.operation.type"));
+ Assert.Equal("SUCCEEDED", Tag(span, "durable.operation.status"));
+ }
+
+ [Fact]
+ public async Task ACompletionThatWasExported_IsNotExportedAgain()
+ {
+ using var spans = new SpanCollector();
+ var wait = Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause");
+ var plugin = Start(spans, Info(wait));
+ plugin.OnOperationEnd(End(wait, replay: true));
+
+ plugin.OnOperationEnd(End(wait, replay: false));
+ await Finish(plugin);
+
+ Assert.Single(spans.All("pause"));
+ }
+
+ [Fact]
+ public async Task StepResumedAfterARetry_GetsANewSpanThatLinksItsFirstSegment()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var step = Op("step-1", OperationTypes.Step, OperationStatuses.Ready, "flaky", replay: true);
+
+ // An earlier invocation started this step and scheduled a retry. This one runs the second attempt.
+ plugin.OnOperationStart(step);
+ plugin.OnOperationEnd(new OperationEndInfo
+ {
+ Id = "step-1", Type = OperationTypes.Step, Name = "flaky", Status = OperationStatuses.Succeeded, Attempt = 2, IsReplay = false,
+ });
+ await Finish(plugin);
+
+ var segment = Assert.Single(spans.All("flaky"));
+ var firstSegmentId = DeterministicIds.SpanIdFromOperationId("step-1", Arn);
+ // The derived id belongs to the first segment, exported by the invocation that started the step.
+ Assert.NotEqual(firstSegmentId, segment.SpanId.ToHexString());
+ Assert.Equal(firstSegmentId, segment.Links.First().Context.SpanId.ToHexString());
+ Assert.Equal("SUCCEEDED", Tag(segment, "durable.operation.status"));
+ Assert.Equal("2", Tag(segment, "durable.attempt.number"));
+ }
+
+ [Fact]
+ public async Task ReplayedWaitWithNoCompletionNews_IsNotExported()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var wait = Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause");
+
+ plugin.OnOperationStart(Op("wait-1", OperationTypes.Wait, OperationStatuses.Succeeded, "pause", replay: true));
+ plugin.OnOperationEnd(End(wait, replay: true));
+ await Finish(plugin);
+
+ Assert.Empty(spans.All("pause"));
+ }
+
+ [Fact]
+ public async Task OperationChange_MakesALaterCompletionExportable()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var callback = Op("cb-1", OperationTypes.Callback, OperationStatuses.Failed, "approval");
+
+ plugin.OnOperationChange(new OperationChangeInfo
+ {
+ ExecutionArn = Arn,
+ UpdatedOperations = new Dictionary { [callback.Id] = callback },
+ Operations = new Dictionary { [callback.Id] = callback },
+ });
+ await Finish(plugin);
+
+ var span = Assert.Single(spans.All("approval"));
+ Assert.Equal(ActivityStatusCode.Error, span.Status);
+ }
+
+ [Fact]
+ public async Task ErrorDetails_UseTheStoredErrorTypeVerbatim()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var op = Op("step-1", OperationTypes.Step, OperationStatuses.Failed, "charge");
+ plugin.OnOperationStart(op);
+
+ plugin.OnOperationEnd(new OperationEndInfo
+ {
+ Id = op.Id, Type = op.Type, Name = op.Name, Status = OperationStatuses.Failed, Attempt = 2,
+ Error = new ErrorObject { ErrorType = "PaymentDeclined", ErrorMessage = "no funds", StackTrace = new[] { "at A", "at B" } },
+ });
+ await Finish(plugin);
+
+ var charge = spans.Single("charge");
+ var exception = Assert.Single(charge.Events);
+ Assert.Equal("PaymentDeclined", exception.Tags.Single(t => t.Key == "exception.type").Value);
+ Assert.Equal("at A\nat B", exception.Tags.Single(t => t.Key == "exception.stacktrace").Value);
+ Assert.Equal("2", Tag(charge, "durable.attempt.number"));
+ Assert.Equal("no funds", charge.StatusDescription);
+ }
+
+ [Theory]
+ [InlineData(OperationStatuses.Failed)]
+ [InlineData(OperationStatuses.TimedOut)]
+ [InlineData(OperationStatuses.Stopped)]
+ public async Task FailureStatuses_AreErrorsEvenWithoutErrorDetails(string status)
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ var op = Op("cb-1", OperationTypes.Callback, OperationStatuses.Started, "approval");
+ plugin.OnOperationStart(op);
+
+ plugin.OnOperationEnd(End(Op("cb-1", OperationTypes.Callback, status, "approval"), replay: false));
+ await Finish(plugin);
+
+ var span = spans.Single("approval");
+ Assert.Equal(ActivityStatusCode.Error, span.Status);
+ Assert.Equal(status, span.StatusDescription);
+ Assert.Empty(span.Events);
+ }
+
+ [Fact]
+ public async Task SuspendingInvocation_EndsOpenSpansAsStarted()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ plugin.OnOperationStart(Op("wait-1", OperationTypes.Wait, OperationStatuses.Started, "pause"));
+ plugin.OnOperationStart(Op("step-1", OperationTypes.Step, OperationStatuses.Started, "retrying"));
+ plugin.OnAttemptStart(new AttemptInfo { Id = "step-1", Type = OperationTypes.Step, Name = "retrying", Attempt = 1 });
+
+ await Finish(plugin);
+
+ Assert.Equal("STARTED", Tag(spans.Single("pause"), "durable.operation.status"));
+ Assert.Equal("STARTED", Tag(spans.Single("retrying"), "durable.operation.status"));
+ Assert.Single(spans.All("retrying attempt 1"));
+ Assert.Equal("PENDING", Tag(spans.Single("Invocation"), "durable.invocation.status"));
+ // The execution is not finished, so there is no Workflow span.
+ Assert.Empty(spans.All("Workflow"));
+ }
+
+ [Fact]
+ public async Task RetryingInvocation_LeavesItsStatusUnset()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+
+ await Finish(plugin, InvocationEndStatus.Retrying);
+
+ var invocation = spans.Single("Invocation");
+ Assert.Equal("RETRYING", Tag(invocation, "durable.invocation.status"));
+ Assert.Equal(ActivityStatusCode.Unset, invocation.Status);
+ Assert.Empty(spans.All("Workflow"));
+ }
+
+ [Fact]
+ public async Task PropagationHeader_ContinuesTheTraceFromTheCallingOperation()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+
+ var header = plugin.ProvidePropagationMetadata(new PropagationInput
+ {
+ ExecutionArn = Arn, OperationId = "invoke-1", TargetFunctionName = "other",
+ });
+
+ Assert.Equal(
+ $"Root=1-5759e988-bd862e3fe1be46a994272793;Parent={DeterministicIds.SpanIdFromOperationId("invoke-1", Arn)};Sampled=1",
+ header);
+ Assert.Null(plugin.ProvidePropagationMetadata(new PropagationInput
+ {
+ ExecutionArn = "arn:other", OperationId = "invoke-1", TargetFunctionName = "other",
+ }));
+ await Finish(plugin);
+ // After the invocation ended there is nothing to continue.
+ Assert.Null(plugin.ProvidePropagationMetadata(new PropagationInput
+ {
+ ExecutionArn = Arn, OperationId = "invoke-1", TargetFunctionName = "other",
+ }));
+ }
+
+ [Fact]
+ public async Task PropagationHeader_CarriesTheUpstreamDecisionNotToSample()
+ {
+ using var spans = new SpanCollector();
+ var factory = OtelPlugin.CreateFactory(OtelView.Invocation, spans.Options(RemoteParent(UpstreamSampling.NotSampled)));
+ var info = Info();
+ var plugin = factory.CreatePlugin(info)!;
+ plugin.OnInvocationStart(info);
+
+ var header = plugin.ProvidePropagationMetadata(new PropagationInput { ExecutionArn = Arn, OperationId = "i", TargetFunctionName = "f" });
+
+ Assert.EndsWith(";Sampled=0", header);
+ await Finish(plugin);
+ }
+
+ [Fact]
+ public async Task PropagationHeader_IsNotSampled_WhenTheSamplerDroppedTheInvocation()
+ {
+ // No upstream decision, and a sampler that drops the Invocation span: the invoked function must not record.
+ using var spans = new SpanCollector((name, _) => name != "Invocation");
+ var factory = OtelPlugin.CreateFactory(OtelView.Invocation, spans.Options());
+ var info = Info();
+ var plugin = factory.CreatePlugin(info)!;
+ plugin.OnInvocationStart(info);
+
+ var header = plugin.ProvidePropagationMetadata(new PropagationInput { ExecutionArn = Arn, OperationId = "i", TargetFunctionName = "f" });
+
+ Assert.EndsWith(";Sampled=0", header);
+ await Finish(plugin);
+ }
+
+ [Fact]
+ public async Task LogScope_ReportsTheCurrentSpan_AndCanBeSwitchedOff()
+ {
+ using var spans = new SpanCollector();
+ var plugin = Start(spans, Info());
+ Assert.Null(plugin.GetLogScope()); // no span is current
+
+ using var source = new ActivitySource(spans.SourceName);
+ using var current = source.StartActivity("user span");
+ var scope = plugin.GetLogScope();
+ Assert.NotNull(scope);
+ Assert.Equal(current!.TraceId.ToHexString(), scope!["otelTraceId"]);
+ Assert.Equal(current.SpanId.ToHexString(), scope["otelSpanId"]);
+ Assert.Equal(true, scope["otelTraceSampled"]);
+ await Finish(plugin);
+
+ var off = OtelPlugin.CreateFactory(OtelView.Invocation, new OtelPluginOptions
+ {
+ InstrumentationName = spans.SourceName, EnrichLogger = false, ContextExtractor = RemoteParent(),
+ });
+ var info = Info();
+ var disabled = off.CreatePlugin(info)!;
+ disabled.OnInvocationStart(info);
+ Assert.Null(disabled.GetLogScope());
+ await Finish(disabled);
+ }
+
+ [Fact]
+ public async Task Hooks_BeforeTheInvocationStarted_Do_Nothing()
+ {
+ using var spans = new SpanCollector();
+ var info = Info();
+ var plugin = OtelPlugin.CreateFactory(OtelView.Invocation, spans.Options(RemoteParent())).CreatePlugin(info)!;
+
+ plugin.OnOperationStart(Op("a", OperationTypes.Step, OperationStatuses.Started, "x"));
+ plugin.OnOperationEnd(End(Op("a", OperationTypes.Step, OperationStatuses.Succeeded, "x"), replay: false));
+ await Finish(plugin);
+
+ Assert.Empty(spans.Spans);
+ }
+}
diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/SpanCollector.cs b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/SpanCollector.cs
new file mode 100644
index 000000000..06ae1965b
--- /dev/null
+++ b/Libraries/test/Amazon.Lambda.DurableExecution.OpenTelemetry.Tests/SpanCollector.cs
@@ -0,0 +1,87 @@
+// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+using System.Diagnostics;
+using Amazon.Lambda.DurableExecution.Instrumentation;
+using Amazon.Lambda.DurableExecution.Testing;
+
+namespace Amazon.Lambda.DurableExecution.OpenTelemetry.Tests;
+
+///
+/// Collects the spans the plugin exports. The sampler defaults to the OpenTelemetry SDK's default,
+/// ParentBased(AlwaysOn): a span follows the sampled flag of its parent, and a span without one is sampled.
+///
+internal sealed class SpanCollector : IDisposable
+{
+ // Each test uses a distinct source name so tests running in parallel do not see each other's spans.
+ internal string SourceName { get; } = "test-" + Guid.NewGuid().ToString("N");
+
+ private readonly ActivityListener _listener;
+ private readonly object _lock = new();
+ private readonly List _stopped = new();
+
+ /// A sampler: given a span's name and parent, whether to record it.
+ internal delegate bool SamplerFunc(string name, ActivityContext parent);
+
+ /// The OpenTelemetry SDK's default, ParentBased(AlwaysOn).
+ internal static readonly SamplerFunc ParentBased = (_, parent) =>
+ parent == default || (parent.TraceFlags & ActivityTraceFlags.Recorded) != 0;
+
+ /// AlwaysOn, which ignores the parent's sampled flag (OTEL_TRACES_SAMPLER=always_on).
+ internal static readonly SamplerFunc AlwaysOn = (_, _) => true;
+
+ internal SpanCollector(SamplerFunc? sampler = null)
+ {
+ var sample = sampler ?? ParentBased;
+ _listener = new ActivityListener
+ {
+ ShouldListenTo = source => source.Name == SourceName,
+ Sample = (ref ActivityCreationOptions options) =>
+ sample(options.Name, options.Parent)
+ ? ActivitySamplingResult.AllDataAndRecorded
+ : ActivitySamplingResult.None,
+ ActivityStopped = activity => { lock (_lock) _stopped.Add(activity); },
+ };
+ ActivitySource.AddActivityListener(_listener);
+ }
+
+ internal IReadOnlyList Spans
+ {
+ get { lock (_lock) return _stopped.ToList(); }
+ }
+
+ internal Activity Single(string name) => Spans.Single(s => s.OperationName == name);
+
+ internal IReadOnlyList All(string name) => Spans.Where(s => s.OperationName == name).ToList();
+
+ internal OtelPluginOptions Options(
+ Func? extractor = null, Func? flush = null) => new()
+ {
+ InstrumentationName = SourceName,
+ ContextExtractor = extractor ?? (_ => null),
+ FlushAsync = flush,
+ };
+
+ internal DurableExecutionOptions ExecutionOptions(OtelPluginOptions options, OtelView view = OtelView.Invocation)
+ {
+ var executionOptions = new DurableExecutionOptions();
+ executionOptions.AddOpenTelemetry(view, options);
+ return executionOptions;
+ }
+
+ public void Dispose() => _listener.Dispose();
+
+ // Fixed upstream context used by the tests that need a remote parent.
+ internal const string RemoteTraceId = "5759e988bd862e3fe1be46a994272793";
+ internal const string RemoteParentSpanId = "53995c3f42cd8ad8";
+
+ internal static Func RemoteParent(UpstreamSampling sampling = UpstreamSampling.Sampled) =>
+ _ => new ExtractedContext { TraceId = RemoteTraceId, ParentSpanId = RemoteParentSpanId, Sampling = sampling };
+
+ internal static TestRunnerOptions Runner(DurableExecutionOptions options) => new() { ExecutionOptions = options };
+
+ internal static string Tag(Activity span, string key) =>
+ span.TagObjects.FirstOrDefault(t => t.Key == key).Value?.ToString() ?? string.Empty;
+
+ internal static bool HasTag(Activity span, string key) => span.TagObjects.Any(t => t.Key == key);
+}