From 1db10264563f5b13bbeaa7204e13714b4199ec70 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 01:41:49 +0000 Subject: [PATCH 1/9] Add the durable instrumentation plugin API and plugin runner Adds IDurableInstrumentationPlugin, its factory, the info types and DurableExecutionOptions.Plugins, plus an internal PluginRunner that dispatches hooks with per-plugin exception isolation, ordered start/end, a WrapAsync chain that always runs the user code exactly once, first-wins trace propagation and a bounded OnInvocationEndAsync. Not wired into DurableFunction yet. --- .../DurableExecutionOptions.cs | 19 + .../IDurableInstrumentationPlugin.cs | 76 ++++ .../IDurableInstrumentationPluginFactory.cs | 24 ++ .../Instrumentation/InstrumentationInfo.cs | 203 +++++++++++ .../Instrumentation/PluginLoadException.cs | 15 + .../Internal/PluginRunner.cs | 340 ++++++++++++++++++ .../PluginRunnerTests.cs | 294 +++++++++++++++ 7 files changed, 971 insertions(+) create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionOptions.cs create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPlugin.cs create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPluginFactory.cs create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/PluginLoadException.cs create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginRunnerTests.cs diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionOptions.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionOptions.cs new file mode 100644 index 000000000..69d4fdb13 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionOptions.cs @@ -0,0 +1,19 @@ +// 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; + +/// +/// Optional settings passed to DurableFunction.WrapAsync. +/// Create it once, for example in a static field, and reuse it for every invocation. +/// +public sealed class DurableExecutionOptions +{ + /// + /// Instrumentation plugin factories, in registration order. The SDK asks each factory for a new plugin on + /// every invocation. + /// + public IList Plugins { get; } = new List(); +} diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPlugin.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPlugin.cs new file mode 100644 index 000000000..29d3577d4 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPlugin.cs @@ -0,0 +1,76 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +namespace Amazon.Lambda.DurableExecution.Instrumentation; + +/// +/// Observes the lifecycle of one durable execution invocation, for example to emit traces or metrics. +/// A plugin instance serves a single invocation: the SDK creates it through +/// at the start of every invocation, so +/// per-invocation state can live in ordinary fields and concurrent invocations never share a plugin. +/// +/// +/// Every member is optional. An exception thrown by a hook is logged and ignored; it never fails the +/// invocation or the workflow. +/// The operation and attempt hooks are synchronous and the SDK does not wait for any work a plugin +/// starts from them, so a plugin cannot delay an operation or the decision to suspend the invocation. +/// Work that must finish before the response is returned belongs in . +/// With several plugins, start hooks run in registration order and +/// runs in reverse order. For the first +/// registered plugin is the outermost. +/// +public interface IDurableInstrumentationPlugin +{ + /// Called once, before any workflow code runs. + void OnInvocationStart(InvocationInfo info) { } + + /// + /// Called last, after the workflow outcome is decided and checkpoints are flushed. The SDK waits for the + /// returned task, but only until shortly before the invocation's remaining time runs out; it then cancels + /// and continues without waiting. + /// + Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken cancellationToken) => Task.CompletedTask; + + /// Called when an operation starts or is reached again during replay. + void OnOperationStart(OperationInfo info) { } + + /// Called when an operation reaches a terminal state in this invocation or is replayed as terminal. + void OnOperationEnd(OperationEndInfo info) { } + + /// Called before each execution of the user function of a step or similar operation. + void OnAttemptStart(AttemptInfo info) { } + + /// Called after each execution of the user function, whether it succeeded or failed. + void OnAttemptEnd(AttemptEndInfo info) { } + + /// + /// Called when a checkpoint response changes the state of operations, for example when a callback is + /// completed by an external system. + /// + void OnOperationChange(OperationChangeInfo info) { } + + /// + /// Runs user code inside the plugin's own context, for example so an ambient activity is current while it + /// executes. The plugin must call exactly once and await it. The SDK guarantees the + /// user code runs even if the plugin throws or never calls , and an exception from the + /// user code always reaches the caller unchanged. + /// + /// + /// When an invocation suspends, user code that is still running is abandoned and never completes, so code + /// after the await of (including finally blocks) does not run for that + /// work. Release anything held across from too. + /// + Task WrapAsync(UserCodeInfo info, Func next) => next(); + + /// + /// Called before a chained invoke is checkpointed. Returns an X-Amzn-Trace-Id header value that is + /// sent to the invoked function, or null to contribute nothing. Not called when the invoke is replayed. + /// + string? ProvidePropagationMetadata(PropagationInput input) => null; + + /// + /// Returns fields, such as a trace id, that the SDK adds to the logging scope of durable log entries. + /// Called for the workflow's logger, so keep it fast. Return null to add nothing. + /// + IReadOnlyDictionary? GetLogScope() => null; +} diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPluginFactory.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPluginFactory.cs new file mode 100644 index 000000000..929da6cad --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/IDurableInstrumentationPluginFactory.cs @@ -0,0 +1,24 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +namespace Amazon.Lambda.DurableExecution.Instrumentation; + +/// +/// Registered once, typically at cold start, and asked for a new plugin at the start of every invocation. +/// The factory owns whatever outlives an invocation (exporters, resolved configuration); the plugin it +/// returns owns the state of one invocation. +/// +public interface IDurableInstrumentationPluginFactory +{ + /// + /// Creates the plugin for one invocation, or returns null to skip this invocation. Always return a new + /// instance; do not cache one. An exception is logged and the plugin is skipped. + /// + IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info); + + /// + /// When non-null, at most one registered factory may use this value. Registering two factories with the + /// same group throws before any plugin is created. + /// + string? ExclusiveGroup => null; +} diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs new file mode 100644 index 000000000..491584362 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs @@ -0,0 +1,203 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +namespace Amazon.Lambda.DurableExecution.Instrumentation; + +/// Details of an invocation when it starts. +public sealed class InvocationInfo +{ + /// ARN of the durable execution. + public required string ExecutionArn { get; init; } + + /// The Lambda request id of this invocation. + public string? RequestId { get; init; } + + /// True when the execution has no checkpointed history, apart from its input. + public bool IsFirstInvocation { get; init; } + + /// When the durable execution started, as recorded by the service. + public DateTimeOffset? ExecutionStartTimestamp { get; init; } + + /// + /// The X-Ray trace header of this invocation (ILambdaContext.TraceId), or null when the runtime + /// provides none. + /// + public string? XRayTraceId { get; init; } + + /// Every operation known at the start of the invocation, by operation id. + public IReadOnlyDictionary Operations { get; init; } = EmptyOperations.Instance; + + /// The operations the service reports as changed since the previous invocation, by operation id. + public IReadOnlyDictionary UpdatedOperations { get; init; } = EmptyOperations.Instance; +} + +/// How an invocation ended. +public enum InvocationEndStatus +{ + /// The workflow returned a result. + Succeeded, + + /// The workflow failed permanently. + Failed, + + /// The invocation suspended and the service will invoke the function again. + Pending, + + /// + /// The invocation ended with an exception that is not a workflow failure, such as a missed deadline or a + /// transient checkpoint error, so Lambda will retry it. + /// + Retrying, +} + +/// Details of an invocation when it ends. +public sealed class InvocationEndInfo +{ + /// ARN of the durable execution. + public required string ExecutionArn { get; init; } + + /// The Lambda request id of this invocation. + public string? RequestId { get; init; } + + /// How the invocation ended. + public required InvocationEndStatus Status { get; init; } + + /// The workflow failure or the exception behind , if any. + public Exception? Exception { get; init; } + + /// True when the execution has no checkpointed history, apart from its input. + public bool IsFirstInvocation { get; init; } + + /// When the durable execution started, as recorded by the service. + public DateTimeOffset? ExecutionStartTimestamp { get; init; } + + /// Every operation known at the end of the invocation, by operation id. + public IReadOnlyDictionary Operations { get; init; } = EmptyOperations.Instance; +} + +/// A durable operation. +public class OperationInfo +{ + /// The deterministic operation id. + public required string Id { get; init; } + + /// The operation name given by the workflow, if any. + public string? Name { get; init; } + + /// The operation type, one of . + public required string Type { get; init; } + + /// The operation sub-type, one of , if any. + public string? SubType { get; init; } + + /// The id of the enclosing child-context operation, or null at the top level. + public string? ParentId { get; init; } + + /// The checkpointed status, one of , if known. + public string? Status { get; init; } + + /// When the operation started, as recorded by the service, if known. + public DateTimeOffset? StartTimestamp { get; init; } + + /// When the operation ended, as recorded by the service, if known. + public DateTimeOffset? EndTimestamp { get; init; } + + /// The attempt number (1-based) for operations that retry, if applicable. + public int? Attempt { get; init; } + + /// True when the workflow reached this operation by replaying checkpointed history. + public bool IsReplay { get; init; } +} + +/// An operation that reached a terminal state. +public sealed class OperationEndInfo : OperationInfo +{ + /// The error recorded for the operation, if it failed. + public ErrorObject? Error { get; init; } + + /// The exception observed in this invocation, if any. Null for operations replayed from history. + public Exception? Exception { get; init; } +} + +/// One execution of the user function of an operation. is set. +public class AttemptInfo : OperationInfo +{ +} + +/// How an attempt ended. +public enum AttemptOutcome +{ + /// The user function returned. + Succeeded, + + /// The user function threw. + Failed, +} + +/// An attempt that finished. +public sealed class AttemptEndInfo : AttemptInfo +{ + /// How the attempt ended. + public required AttemptOutcome Outcome { get; init; } + + /// The exception thrown by the user function, if the attempt failed. + public Exception? Exception { get; init; } +} + +/// Operations whose state changed because of a checkpoint response. +public sealed class OperationChangeInfo +{ + /// ARN of the durable execution. + public required string ExecutionArn { get; init; } + + /// The operations that changed, by operation id. + public required IReadOnlyDictionary UpdatedOperations { get; init; } + + /// Every operation known after the change, by operation id. + public required IReadOnlyDictionary Operations { get; init; } +} + +/// What kind of user code is wrapping. +public enum UserCodeKind +{ + /// The whole workflow function of the invocation. + Invocation, + + /// The function of a child context (including map and parallel branches). + ChildContext, + + /// One attempt of an operation's user function, such as a step. + Attempt, +} + +/// Identifies the user code being wrapped. +public sealed class UserCodeInfo +{ + /// What is being wrapped. + public required UserCodeKind Kind { get; init; } + + /// The operation the code belongs to. Null for . + public OperationInfo? Operation { get; init; } +} + +/// Identifies a chained invoke for which trace headers are requested. +public sealed class PropagationInput +{ + /// ARN of the calling durable execution. + public required string ExecutionArn { get; init; } + + /// Id of the chained invoke operation. + public required string OperationId { get; init; } + + /// Id of the enclosing child context of the invoke, if any. + public string? ParentOperationId { get; init; } + + /// The function being invoked. + public required string TargetFunctionName { get; init; } +} + +internal static class EmptyOperations +{ + internal static readonly IReadOnlyDictionary Instance = + new Dictionary(0); +} diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/PluginLoadException.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/PluginLoadException.cs new file mode 100644 index 000000000..a40dae974 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/PluginLoadException.cs @@ -0,0 +1,15 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +namespace Amazon.Lambda.DurableExecution.Instrumentation; + +/// The plugin registration is invalid, for example a null factory or two factories in one exclusive group. +public class PluginLoadException : DurableExecutionException +{ + /// Creates an empty . + public PluginLoadException() { } + /// Creates a with the given message. + public PluginLoadException(string message) : base(message) { } + /// Creates a wrapping an inner exception. + public PluginLoadException(string message, Exception innerException) : base(message, innerException) { } +} diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs new file mode 100644 index 000000000..e7de0dc11 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs @@ -0,0 +1,340 @@ +// 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 Microsoft.Extensions.Logging; + +namespace Amazon.Lambda.DurableExecution.Internal; + +/// +/// Dispatches lifecycle events to the plugins of one invocation. A plugin can never fail the invocation: +/// every hook exception is logged and dropped. The runner only exists when at least one plugin was created, +/// so callers hold a nullable reference and pay nothing when no plugin is registered. +/// +internal sealed class PluginRunner +{ + /// Time kept free after OnInvocationEndAsync so the response can still be returned. + internal static readonly TimeSpan EndReserve = TimeSpan.FromMilliseconds(50); + + private readonly IDurableInstrumentationPlugin[] _plugins; + private readonly ILogger _logger; + private readonly Func _remainingTime; + + private PluginRunner(IDurableInstrumentationPlugin[] plugins, ILogger logger, Func remainingTime) + { + _plugins = plugins; + _logger = logger; + _remainingTime = remainingTime; + } + + /// + /// Validates the registration and creates one plugin per factory for this invocation. + /// Returns null when there is nothing to run. + /// + /// A factory is null or two factories share an exclusive group. + internal static PluginRunner? Create( + DurableExecutionOptions? options, + InvocationInfo info, + ILogger logger, + Func remainingTime) + { + if (options == null || options.Plugins.Count == 0) + return null; + + ValidateRegistration(options.Plugins); + + var plugins = new List(options.Plugins.Count); + foreach (var factory in options.Plugins) + { + try + { + var plugin = factory.CreatePlugin(info); + if (plugin != null) + plugins.Add(plugin); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Plugin factory {Factory} threw from CreatePlugin and is skipped for this invocation.", + factory.GetType().FullName); + } + } + + return plugins.Count == 0 ? null : new PluginRunner(plugins.ToArray(), logger, remainingTime); + } + + private static void ValidateRegistration(IList factories) + { + Dictionary? groups = null; + for (var i = 0; i < factories.Count; i++) + { + var factory = factories[i]; + if (factory == null) + throw new PluginLoadException($"DurableExecutionOptions.Plugins[{i}] is null."); + + var group = factory.ExclusiveGroup; + if (string.IsNullOrEmpty(group)) + continue; + + groups ??= new Dictionary(StringComparer.Ordinal); + if (groups.TryGetValue(group, out var first)) + { + throw new PluginLoadException( + $"Plugin factories '{first.GetType().FullName}' and '{factory.GetType().FullName}' are both in the " + + $"exclusive group '{group}'. Register only one of them."); + } + groups.Add(group, factory); + } + } + + internal void InvocationStart(InvocationInfo info) => + ForEach(nameof(IDurableInstrumentationPlugin.OnInvocationStart), p => p.OnInvocationStart(info)); + + internal void OperationStart(OperationInfo info) => + ForEach(nameof(IDurableInstrumentationPlugin.OnOperationStart), p => p.OnOperationStart(info)); + + internal void OperationEnd(OperationEndInfo info) => + ForEach(nameof(IDurableInstrumentationPlugin.OnOperationEnd), p => p.OnOperationEnd(info)); + + internal void AttemptStart(AttemptInfo info) => + ForEach(nameof(IDurableInstrumentationPlugin.OnAttemptStart), p => p.OnAttemptStart(info)); + + internal void AttemptEnd(AttemptEndInfo info) => + ForEach(nameof(IDurableInstrumentationPlugin.OnAttemptEnd), p => p.OnAttemptEnd(info)); + + internal void OperationChange(OperationChangeInfo info) => + ForEach(nameof(IDurableInstrumentationPlugin.OnOperationChange), p => p.OnOperationChange(info)); + + private void ForEach(string hook, Action call) + { + foreach (var plugin in _plugins) + { + try + { + call(plugin); + } + catch (Exception ex) + { + LogHookFailure(plugin, hook, ex); + } + } + } + + /// + /// Runs inside every plugin's WrapAsync, the first plugin outermost. + /// The user code runs exactly once whatever the plugins do, and its exception, if any, is the one thrown. + /// + internal Task WrapAsync(UserCodeInfo info, Func userCode) => WrapFrom(0, info, userCode); + + private async Task WrapFrom(int index, UserCodeInfo info, Func userCode) + { + if (index == _plugins.Length) + { + await userCode().ConfigureAwait(false); + return; + } + + var plugin = _plugins[index]; + Task? inner = null; + Task Next() => inner ??= WrapFrom(index + 1, info, userCode); + + try + { + await plugin.WrapAsync(info, Next).ConfigureAwait(false); + } + catch (Exception ex) + { + if (inner == null) + { + // The plugin failed before it called next, so the user code has not started. Run it unwrapped. + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.WrapAsync), ex); + await Next().ConfigureAwait(false); + return; + } + + if (!inner.IsCompleted) + { + // The plugin threw while the user code is still running. Let the user code finish; the plugin's + // exception is not the workflow's outcome. + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.WrapAsync), ex); + await inner.ConfigureAwait(false); + return; + } + + if (inner.IsFaulted || inner.IsCanceled) + { + // The user code failed. Whatever the plugin threw (usually the same exception passing through), + // the caller must see the user code's own exception. + await inner.ConfigureAwait(false); + } + + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.WrapAsync), ex); + return; + } + + if (inner == null) + { + // The plugin returned without calling next. Skipping the user code would silently drop the workflow. + _logger.LogWarning( + "Plugin {Plugin} returned from WrapAsync without calling next. The user code is run anyway.", + plugin.GetType().FullName); + await Next().ConfigureAwait(false); + return; + } + + // A plugin that swallowed the user code's exception must not turn a failure into a success. + await inner.ConfigureAwait(false); + } + + /// + /// Returns the first non-blank header contributed by a plugin, in registration order. Later different values + /// are logged and ignored. + /// + internal string? ProvidePropagationMetadata(PropagationInput input) + { + string? chosen = null; + IDurableInstrumentationPlugin? chosenBy = null; + foreach (var plugin in _plugins) + { + string? value; + try + { + value = plugin.ProvidePropagationMetadata(input); + } + catch (Exception ex) + { + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.ProvidePropagationMetadata), ex); + continue; + } + + if (string.IsNullOrWhiteSpace(value)) + continue; + + if (chosen == null) + { + chosen = value; + chosenBy = plugin; + } + else if (!string.Equals(chosen, value, StringComparison.Ordinal)) + { + // The header itself is not logged: it identifies a trace. + _logger.LogWarning( + "Plugin {Plugin} contributed trace propagation metadata that differs from the one from {Winner}. It is ignored.", + plugin.GetType().FullName, chosenBy!.GetType().FullName); + } + } + + return chosen; + } + + /// Merges the log scope fields of all plugins. A later plugin cannot replace an earlier plugin's key. + internal IReadOnlyDictionary? GetLogScope() + { + Dictionary? merged = null; + foreach (var plugin in _plugins) + { + IReadOnlyDictionary? fields; + try + { + fields = plugin.GetLogScope(); + } + catch (Exception ex) + { + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.GetLogScope), ex); + continue; + } + + if (fields == null || fields.Count == 0) + continue; + + merged ??= new Dictionary(StringComparer.Ordinal); + foreach (var kv in fields) + merged.TryAdd(kv.Key, kv.Value); + } + + return merged; + } + + /// + /// Awaits OnInvocationEndAsync of each plugin in reverse registration order, sharing one time budget: + /// the remaining invocation time minus . A plugin that is still running when the + /// budget ends is cancelled and abandoned. + /// + internal async Task InvocationEndAsync(InvocationEndInfo info) + { + var remaining = ReadRemainingTime(); + var started = Stopwatch.GetTimestamp(); + + for (var i = _plugins.Length - 1; i >= 0; i--) + { + var plugin = _plugins[i]; + using var cts = new CancellationTokenSource(); + + Task work; + try + { + work = plugin.OnInvocationEndAsync(info, cts.Token) ?? Task.CompletedTask; + } + catch (Exception ex) + { + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.OnInvocationEndAsync), ex); + continue; + } + + try + { + if (remaining is null) + { + await work.ConfigureAwait(false); + continue; + } + + var budget = remaining.Value - EndReserve - Stopwatch.GetElapsedTime(started); + if (budget < TimeSpan.Zero) + budget = TimeSpan.Zero; + + using var delayCts = new CancellationTokenSource(); + var winner = await Task.WhenAny(work, Task.Delay(budget, delayCts.Token)).ConfigureAwait(false); + if (winner == work) + { + delayCts.Cancel(); + await work.ConfigureAwait(false); + continue; + } + + cts.Cancel(); + _logger.LogWarning( + "Plugin {Plugin} did not finish OnInvocationEndAsync within the remaining invocation time and is abandoned.", + plugin.GetType().FullName); + // Nothing else observes the abandoned task; keep its fault from surfacing as unobserved. + _ = work.ContinueWith( + static t => _ = t.Exception, + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + catch (Exception ex) + { + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.OnInvocationEndAsync), ex); + } + } + } + + private TimeSpan? ReadRemainingTime() + { + try + { + var value = _remainingTime(); + return value is { } v && v > TimeSpan.Zero ? v : null; + } + catch + { + // A context that cannot report its remaining time has no deadline we can honor. + return null; + } + } + + private void LogHookFailure(IDurableInstrumentationPlugin plugin, string hook, Exception ex) => + _logger.LogWarning(ex, "Plugin {Plugin} threw from {Hook}. The exception is ignored.", + plugin.GetType().FullName, hook); +} diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginRunnerTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginRunnerTests.cs new file mode 100644 index 000000000..7296521e6 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginRunnerTests.cs @@ -0,0 +1,294 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.DurableExecution.Instrumentation; +using Amazon.Lambda.DurableExecution.Internal; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Tests; + +public class PluginRunnerTests +{ + private static readonly InvocationInfo Info = new() { ExecutionArn = "arn:test" }; + private static readonly UserCodeInfo Code = new() { Kind = UserCodeKind.Invocation }; + + private sealed class RecordingPlugin : IDurableInstrumentationPlugin + { + private readonly string _name; + private readonly List _log; + public RecordingPlugin(string name, List log) { _name = name; _log = log; } + + public void OnInvocationStart(InvocationInfo info) => _log.Add($"{_name}.start"); + public Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken ct) + { + _log.Add($"{_name}.end"); + return Task.CompletedTask; + } + + public async Task WrapAsync(UserCodeInfo info, Func next) + { + _log.Add($"{_name}.wrap.before"); + await next(); + _log.Add($"{_name}.wrap.after"); + } + } + + private sealed class LambdaPlugin : IDurableInstrumentationPlugin + { + public Action? Start; + public Func? End; + public Func, Task>? Wrap; + public Func? Propagate; + public Func?>? Scope; + + public void OnInvocationStart(InvocationInfo info) => Start?.Invoke(info); + public Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken ct) => End?.Invoke(info, ct) ?? Task.CompletedTask; + public Task WrapAsync(UserCodeInfo info, Func next) => Wrap?.Invoke(info, next) ?? next(); + public string? ProvidePropagationMetadata(PropagationInput input) => Propagate?.Invoke(input); + public IReadOnlyDictionary? GetLogScope() => Scope?.Invoke(); + } + + private sealed class Factory : IDurableInstrumentationPluginFactory + { + private readonly Func _create; + public Factory(Func create, string? group = null) { _create = create; ExclusiveGroup = group; } + public string? ExclusiveGroup { get; } + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => _create(); + } + + private sealed class ListLogger : ILogger + { + public readonly List Messages = new(); + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + => Messages.Add(formatter(state, exception)); + } + + private static PluginRunner Runner(ILogger? logger = null, Func? remaining = null, params IDurableInstrumentationPlugin[] plugins) + { + var options = new DurableExecutionOptions(); + foreach (var p in plugins) + { + var captured = p; + options.Plugins.Add(new Factory(() => captured)); + } + return PluginRunner.Create(options, Info, logger ?? NullLogger.Instance, remaining ?? (() => null))!; + } + + [Fact] + public void Create_ReturnsNull_WithoutPlugins() + { + Assert.Null(PluginRunner.Create(null, Info, NullLogger.Instance, () => null)); + Assert.Null(PluginRunner.Create(new DurableExecutionOptions(), Info, NullLogger.Instance, () => null)); + } + + [Fact] + public void Create_Throws_ForTwoFactoriesInOneExclusiveGroup() + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(() => new LambdaPlugin(), "view")); + options.Plugins.Add(new Factory(() => new LambdaPlugin(), "view")); + + Assert.Throws(() => PluginRunner.Create(options, Info, NullLogger.Instance, () => null)); + } + + [Fact] + public void Create_AllowsDifferentOrNoGroups_AndThrowsForNullFactory() + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(() => new LambdaPlugin(), "a")); + options.Plugins.Add(new Factory(() => new LambdaPlugin(), "b")); + options.Plugins.Add(new Factory(() => new LambdaPlugin())); + Assert.NotNull(PluginRunner.Create(options, Info, NullLogger.Instance, () => null)); + + options.Plugins.Add(null!); + Assert.Throws(() => PluginRunner.Create(options, Info, NullLogger.Instance, () => null)); + } + + [Fact] + public void Create_SkipsFactoriesThatThrowOrReturnNull() + { + var logger = new ListLogger(); + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(() => throw new InvalidOperationException("boom"))); + options.Plugins.Add(new Factory(() => null)); + var started = false; + options.Plugins.Add(new Factory(() => new LambdaPlugin { Start = _ => started = true })); + + var runner = PluginRunner.Create(options, Info, logger, () => null)!; + runner.InvocationStart(Info); + + Assert.True(started); + Assert.Single(logger.Messages); + } + + [Fact] + public void Hooks_AreIsolated_AndLaterPluginsStillRun() + { + var logger = new ListLogger(); + var secondRan = false; + var runner = Runner(logger, null, + new LambdaPlugin { Start = _ => throw new InvalidOperationException("boom") }, + new LambdaPlugin { Start = _ => secondRan = true }); + + runner.InvocationStart(Info); + + Assert.True(secondRan); + Assert.Contains(logger.Messages, m => m.Contains("OnInvocationStart")); + } + + [Fact] + public async Task Ordering_StartForward_EndReverse_WrapFirstOutermost() + { + var log = new List(); + var runner = Runner(null, null, new RecordingPlugin("A", log), new RecordingPlugin("B", log)); + + runner.InvocationStart(Info); + await runner.WrapAsync(Code, () => { log.Add("user"); return Task.CompletedTask; }); + await runner.InvocationEndAsync(new InvocationEndInfo { ExecutionArn = "arn:test", Status = InvocationEndStatus.Succeeded }); + + Assert.Equal( + new[] { "A.start", "B.start", "A.wrap.before", "B.wrap.before", "user", "B.wrap.after", "A.wrap.after", "B.end", "A.end" }, + log); + } + + [Fact] + public async Task Wrap_PluginThrowsBeforeNext_UserCodeStillRunsOnce() + { + var runs = 0; + var runner = Runner(null, null, new LambdaPlugin { Wrap = (_, _) => throw new InvalidOperationException("boom") }); + + await runner.WrapAsync(Code, () => { runs++; return Task.CompletedTask; }); + + Assert.Equal(1, runs); + } + + [Fact] + public async Task Wrap_PluginNeverCallsNext_UserCodeStillRunsOnce() + { + var runs = 0; + var runner = Runner(null, null, new LambdaPlugin { Wrap = (_, _) => Task.CompletedTask }); + + await runner.WrapAsync(Code, () => { runs++; return Task.CompletedTask; }); + + Assert.Equal(1, runs); + } + + [Fact] + public async Task Wrap_UserExceptionReachesCaller_EvenWhenPluginThrowsOrSwallowsIt() + { + var userException = new ApplicationException("user"); + + var rethrowing = Runner(null, null, new LambdaPlugin + { + Wrap = async (_, next) => { try { await next(); } catch { throw new InvalidOperationException("plugin"); } } + }); + Assert.Same(userException, await Assert.ThrowsAsync( + () => rethrowing.WrapAsync(Code, () => throw userException))); + + var swallowing = Runner(null, null, new LambdaPlugin + { + Wrap = async (_, next) => { try { await next(); } catch { } } + }); + Assert.Same(userException, await Assert.ThrowsAsync( + () => swallowing.WrapAsync(Code, () => throw userException))); + } + + [Fact] + public async Task Wrap_PluginThrowingAfterSuccessfulUserCode_IsIgnored() + { + var runner = Runner(null, null, new LambdaPlugin + { + Wrap = async (_, next) => { await next(); throw new InvalidOperationException("plugin"); } + }); + + await runner.WrapAsync(Code, () => Task.CompletedTask); + } + + [Fact] + public void Propagation_FirstNonBlankWins_AndConflictsAreLoggedWithoutTheHeader() + { + var logger = new ListLogger(); + var input = new PropagationInput { ExecutionArn = "arn", OperationId = "op", TargetFunctionName = "fn" }; + var runner = Runner(logger, null, + new LambdaPlugin { Propagate = _ => " " }, + new LambdaPlugin { Propagate = _ => throw new InvalidOperationException("boom") }, + new LambdaPlugin { Propagate = _ => "Root=1-a" }, + new LambdaPlugin { Propagate = _ => "Root=1-b" }, + new LambdaPlugin { Propagate = _ => "Root=1-a" }); + + Assert.Equal("Root=1-a", runner.ProvidePropagationMetadata(input)); + Assert.Equal(2, logger.Messages.Count); + Assert.DoesNotContain(logger.Messages, m => m.Contains("Root=1-b")); + } + + [Fact] + public void LogScope_MergesPlugins_FirstKeyWins() + { + var runner = Runner(null, null, + new LambdaPlugin { Scope = () => new Dictionary { ["traceId"] = "one", ["a"] = 1 } }, + new LambdaPlugin { Scope = () => throw new InvalidOperationException("boom") }, + new LambdaPlugin { Scope = () => new Dictionary { ["traceId"] = "two", ["b"] = 2 } }); + + var scope = runner.GetLogScope()!; + + Assert.Equal("one", scope["traceId"]); + Assert.Equal(1, scope["a"]); + Assert.Equal(2, scope["b"]); + } + + [Fact] + public async Task InvocationEnd_SlowPlugin_IsCancelledAndAbandonedWithinTheRemainingTime() + { + var cancelled = new TaskCompletionSource(); + var logger = new ListLogger(); + var neverFinishes = new LambdaPlugin + { + End = (_, ct) => { ct.Register(() => cancelled.TrySetResult()); return new TaskCompletionSource().Task; } + }; + var after = false; + var runner = Runner(logger, () => TimeSpan.FromMilliseconds(250), neverFinishes, new LambdaPlugin { End = (_, _) => { after = true; return Task.CompletedTask; } }); + + // The second plugin runs first (reverse order), then the hung one is cut off. + await runner.InvocationEndAsync(new InvocationEndInfo { ExecutionArn = "arn:test", Status = InvocationEndStatus.Succeeded }); + + Assert.True(after); + await cancelled.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Contains(logger.Messages, m => m.Contains("abandoned")); + } + + [Fact] + public async Task InvocationEnd_ExceptionIsIsolated_WithAndWithoutADeadline() + { + foreach (Func remaining in new Func[] { () => null, () => TimeSpan.FromSeconds(30) }) + { + var logger = new ListLogger(); + var runner = Runner(logger, remaining, new LambdaPlugin + { + End = (_, _) => throw new InvalidOperationException("sync"), + }, new LambdaPlugin + { + End = async (_, _) => { await Task.Yield(); throw new InvalidOperationException("async"); }, + }); + + await runner.InvocationEndAsync(new InvocationEndInfo { ExecutionArn = "arn:test", Status = InvocationEndStatus.Failed }); + + Assert.Equal(2, logger.Messages.Count); + } + } + + [Fact] + public async Task InvocationEnd_RemainingTimeThatThrows_MeansNoDeadline() + { + var done = false; + var runner = Runner(null, () => throw new InvalidOperationException("no deadline"), + new LambdaPlugin { End = async (_, _) => { await Task.Delay(20); done = true; } }); + + await runner.InvocationEndAsync(new InvocationEndInfo { ExecutionArn = "arn:test", Status = InvocationEndStatus.Succeeded }); + + Assert.True(done); + } +} From 702968f2bb6660aef418f46fa89681d75f2475d1 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 01:46:42 +0000 Subject: [PATCH 2/9] Wire instrumentation plugins into DurableFunction.WrapAsync Adds WrapAsync overloads that take DurableExecutionOptions. A plugin is created per invocation, gets the invocation start and end hooks and wraps the workflow function. The invocation ends as Succeeded, Failed, Pending, or Retrying when the invocation throws. InvocationInfo carries the trace header from ILambdaContext.TraceId and the operations the service reports as updated (UpdatedOperationIds). With no plugins registered the code path is unchanged. --- .../3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json | 11 + .../DurableExecutionInvocationInput.cs | 7 + .../DurableFunction.cs | 156 +++++++++- .../Instrumentation/InstrumentationInfo.cs | 5 +- .../Internal/DurableInvocationOptions.cs | 3 + .../Internal/ExecutionState.cs | 9 + .../Internal/PluginInfoConverter.cs | 96 +++++++ .../DurableFunctionPluginTests.cs | 266 ++++++++++++++++++ 8 files changed, 551 insertions(+), 2 deletions(-) create mode 100644 .autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs diff --git a/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json b/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json new file mode 100644 index 000000000..70f4f7125 --- /dev/null +++ b/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json @@ -0,0 +1,11 @@ +{ + "Projects": [ + { + "Name": "Amazon.Lambda.DurableExecution", + "Type": "Minor", + "ChangelogMessages": [ + "Add an instrumentation plugin API (IDurableInstrumentationPlugin and IDurableInstrumentationPluginFactory) and DurableExecutionOptions, accepted by new DurableFunction.WrapAsync overloads. Plugins observe the invocation lifecycle and can run the workflow function inside their own context." + ] + } + ] +} diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionInvocationInput.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionInvocationInput.cs index 9c2b22b41..ac3ec0b33 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionInvocationInput.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableExecutionInvocationInput.cs @@ -30,6 +30,13 @@ public sealed class DurableExecutionInvocationInput /// [JsonPropertyName("InitialExecutionState")] public InitialExecutionState? InitialExecutionState { get; set; } + + /// + /// Ids of operations that changed since the previous invocation of this execution, as reported by the + /// service. Absent on the first invocation. + /// + [JsonPropertyName("UpdatedOperationIds")] + public IReadOnlyList? UpdatedOperationIds { get; set; } } /// diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs index d195b18d9..38b0cd9b2 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs @@ -7,6 +7,7 @@ using System.Threading; using Amazon.Lambda; using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution.Instrumentation; using Amazon.Lambda.DurableExecution.Internal; using Amazon.Lambda.DurableExecution.Services; using Amazon.Lambda.Model; @@ -74,6 +75,61 @@ public static Task WrapAsync( invocationInput, lambdaContext, new LambdaDurableServiceClient(lambdaClient)); + /// + /// Wrap a workflow (typed input + output) with , for example to + /// register instrumentation plugins. Create the options once and reuse them for every invocation. + /// + public static Task WrapAsync( + Func> workflow, + DurableExecutionInvocationInput invocationInput, + ILambdaContext lambdaContext, + DurableExecutionOptions options) + => WrapAsyncCore(workflow, invocationInput, lambdaContext, + new LambdaDurableServiceClient(_cachedLambdaClient.Value), ToInvocationOptions(options)); + + /// + /// Wrap a workflow (typed input + output) with an explicit Lambda client and + /// . + /// + public static Task WrapAsync( + Func> workflow, + DurableExecutionInvocationInput invocationInput, + ILambdaContext lambdaContext, + IAmazonLambda lambdaClient, + DurableExecutionOptions options) + => WrapAsyncCore(workflow, invocationInput, lambdaContext, + new LambdaDurableServiceClient(lambdaClient), ToInvocationOptions(options)); + + /// + /// Wrap a void workflow with . + /// + public static Task WrapAsync( + Func workflow, + DurableExecutionInvocationInput invocationInput, + ILambdaContext lambdaContext, + DurableExecutionOptions options) + => WrapAsync(workflow, invocationInput, lambdaContext, _cachedLambdaClient.Value, options); + + /// + /// Wrap a void workflow with an explicit Lambda client and . + /// + public static Task WrapAsync( + Func workflow, + DurableExecutionInvocationInput invocationInput, + ILambdaContext lambdaContext, + IAmazonLambda lambdaClient, + DurableExecutionOptions options) + => WrapAsyncCore( + async (input, ctx) => { await workflow(input, ctx); return null; }, + invocationInput, lambdaContext, + new LambdaDurableServiceClient(lambdaClient), ToInvocationOptions(options)); + + private static DurableInvocationOptions ToInvocationOptions(DurableExecutionOptions options) + { + ArgumentNullException.ThrowIfNull(options); + return new DurableInvocationOptions { Execution = options }; + } + /// /// Internal overload for the testing package — accepts an /// directly so the testing SDK can @@ -153,6 +209,93 @@ private static async Task WrapAsyncCore 0 }) + { + invocationInfo = PluginInfoConverter.ToInvocationInfo(invocationInput, state, lambdaContext, isMultiConcurrency); + plugins = PluginRunner.Create( + options.Execution, invocationInfo, new LambdaCoreLogger(), () => lambdaContext.RemainingTime); + } + + if (plugins == null) + { + return await RunInvocationAsync( + workflow, invocationInput, lambdaContext, serviceClient, serializer, state, terminationManager, + workflowCancellation, deadline, cleanupTimeout, startTimestamp, checkpointToken, plugins: null); + } + + plugins.InvocationStart(invocationInfo!); + + DurableExecutionInvocationOutput output; + try + { + output = await RunInvocationAsync( + workflow, invocationInput, lambdaContext, serviceClient, serializer, state, terminationManager, + workflowCancellation, deadline, cleanupTimeout, startTimestamp, checkpointToken, plugins); + } + catch (Exception ex) + { + // The invocation throws, so Lambda retries it (a missed deadline, a transient checkpoint error). + await plugins.InvocationEndAsync(CreateEndInfo( + invocationInput, lambdaContext, state, InvocationEndStatus.Retrying, error: null, ex)); + throw; + } + + await plugins.InvocationEndAsync(CreateEndInfo( + invocationInput, lambdaContext, state, + output.Status switch + { + InvocationStatus.Succeeded => InvocationEndStatus.Succeeded, + InvocationStatus.Pending => InvocationEndStatus.Pending, + _ => InvocationEndStatus.Failed, + }, + output.Error, exception: null)); + return output; + } + + private static InvocationEndInfo CreateEndInfo( + DurableExecutionInvocationInput invocationInput, + ILambdaContext lambdaContext, + ExecutionState state, + InvocationEndStatus status, + ErrorObject? error, + Exception? exception) + { + var operations = state.GetAllOperations(); + var execution = operations.FirstOrDefault(op => op.Type == OperationTypes.Execution); + return new InvocationEndInfo + { + ExecutionArn = invocationInput.DurableExecutionArn, + RequestId = lambdaContext.AwsRequestId, + Status = status, + Error = error, + Exception = exception, + IsFirstInvocation = operations.All(op => op.Type == OperationTypes.Execution), + ExecutionStartTimestamp = execution?.StartTimestamp is { } ms ? DateTimeOffset.FromUnixTimeMilliseconds(ms) : null, + Operations = PluginInfoConverter.ToOperationMap(operations), + }; + } + + private static async Task RunInvocationAsync( + Func> workflow, + DurableExecutionInvocationInput invocationInput, + ILambdaContext lambdaContext, + IDurableServiceClient serviceClient, + ILambdaSerializer serializer, + ExecutionState state, + TerminationManager terminationManager, + WorkflowCancellation workflowCancellation, + TimeSpan? deadline, + TimeSpan cleanupTimeout, + long startTimestamp, + string? checkpointToken, + PluginRunner? plugins) + { var userPayload = ExtractUserPayload(invocationInput, serializer); var idGenerator = new OperationIdGenerator(); @@ -189,7 +332,18 @@ private static async Task WrapAsyncCore( state, terminationManager, - async () => await workflow(userPayload, context), + plugins == null + ? async () => await workflow(userPayload, context) + : async () => + { + // Runs inside the plugins' WrapAsync so their ambient context (for example a + // current activity) is in effect for the whole workflow function. + TOutput? workflowResult = default; + await plugins.WrapAsync( + new UserCodeInfo { Kind = UserCodeKind.Invocation }, + async () => workflowResult = await workflow(userPayload, context)); + return workflowResult!; + }, workflowCancellation); } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs index 491584362..1709062ef 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs @@ -62,7 +62,10 @@ public sealed class InvocationEndInfo /// How the invocation ended. public required InvocationEndStatus Status { get; init; } - /// The workflow failure or the exception behind , if any. + /// The error the workflow failed with, when is . + public ErrorObject? Error { get; init; } + + /// The exception behind , if any. public Exception? Exception { get; init; } /// True when the execution has no checkpointed history, apart from its input. diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableInvocationOptions.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableInvocationOptions.cs index 5f14140eb..d19150437 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableInvocationOptions.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableInvocationOptions.cs @@ -31,4 +31,7 @@ internal sealed class DurableInvocationOptions /// instead of racing a real timer. /// public Action? OnWorkflowCancellationCreated { get; init; } + + /// The public options passed to DurableFunction.WrapAsync, if any (instrumentation plugins). + public DurableExecutionOptions? Execution { get; init; } } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs index 7ff404675..9408aba14 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs @@ -92,6 +92,15 @@ public void AddOperations(IEnumerable operations) } } + /// A point-in-time copy of every known operation, for plugin snapshots. + public Operation[] GetAllOperations() + { + lock (_lock) + { + return _operations.Values.ToArray(); + } + } + /// /// Returns the checkpointed record for , or null /// if none. Callers should switch on against diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs new file mode 100644 index 000000000..872d889e2 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs @@ -0,0 +1,96 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution.Instrumentation; + +namespace Amazon.Lambda.DurableExecution.Internal; + +/// Builds the immutable info objects handed to plugins from the SDK's checkpoint model. +internal static class PluginInfoConverter +{ + internal static OperationInfo ToOperationInfo(Operation op, bool isReplay = false) => new() + { + Id = op.Id ?? string.Empty, + Name = op.Name, + Type = op.Type ?? string.Empty, + SubType = op.SubType, + ParentId = op.ParentId, + Status = op.Status, + StartTimestamp = FromEpochMilliseconds(op.StartTimestamp), + EndTimestamp = FromEpochMilliseconds(op.EndTimestamp), + Attempt = op.StepDetails?.Attempt, + IsReplay = isReplay, + }; + + internal static IReadOnlyDictionary ToOperationMap(IEnumerable operations, ISet? onlyIds = null) + { + var map = new Dictionary(StringComparer.Ordinal); + foreach (var op in operations) + { + if (op.Id == null || (onlyIds != null && !onlyIds.Contains(op.Id))) + continue; + map[op.Id] = ToOperationInfo(op); + } + return map; + } + + internal static InvocationInfo ToInvocationInfo( + DurableExecutionInvocationInput input, + ExecutionState state, + ILambdaContext lambdaContext, + bool isMultiConcurrency) + { + var operations = state.GetAllOperations(); + + // The EXECUTION operation only carries the input, so an execution with nothing else checkpointed is on + // its first invocation. + var hasHistory = false; + DateTimeOffset? executionStart = null; + foreach (var op in operations) + { + if (op.Type == OperationTypes.Execution) + executionStart ??= FromEpochMilliseconds(op.StartTimestamp); + else + hasHistory = true; + } + + ISet? updatedIds = input.UpdatedOperationIds is { Count: > 0 } ids + ? new HashSet(ids, StringComparer.Ordinal) + : null; + + return new InvocationInfo + { + ExecutionArn = input.DurableExecutionArn, + RequestId = lambdaContext.AwsRequestId, + IsFirstInvocation = !hasHistory, + ExecutionStartTimestamp = executionStart, + XRayTraceId = ResolveTraceId(lambdaContext, isMultiConcurrency), + Operations = ToOperationMap(operations), + UpdatedOperations = updatedIds == null + ? EmptyOperations.Instance + : ToOperationMap(operations, updatedIds), + }; + } + + /// + /// The trace header of this invocation. ILambdaContext.TraceId is per invocation. The environment + /// variable is only a fallback for runtimes that do not fill it in, and only where it is safe: on Lambda + /// Managed Instances several invocations share the process, so it does not identify this one. + /// + private static string? ResolveTraceId(ILambdaContext lambdaContext, bool isMultiConcurrency) + { + var traceId = lambdaContext.TraceId; + if (!string.IsNullOrEmpty(traceId)) + return traceId; + + if (isMultiConcurrency) + return null; + + var fromEnvironment = Environment.GetEnvironmentVariable("_X_AMZN_TRACE_ID"); + return string.IsNullOrEmpty(fromEnvironment) ? null : fromEnvironment; + } + + private static DateTimeOffset? FromEpochMilliseconds(long? value) => + value is { } ms ? DateTimeOffset.FromUnixTimeMilliseconds(ms) : null; +} diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs new file mode 100644 index 000000000..8ae0ce60d --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs @@ -0,0 +1,266 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using System.Net; +using Amazon.Lambda.DurableExecution.Instrumentation; +using Amazon.Lambda.Serialization.SystemTextJson; +using Amazon.Lambda.TestUtilities; +using Amazon.Runtime; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Tests; + +/// Invocation-level plugin wiring in . +public class DurableFunctionPluginTests +{ + private const string Arn = "arn:aws:lambda:us-east-1:123:durable-execution:plugin-test"; + + private sealed class Recorder : IDurableInstrumentationPlugin + { + public InvocationInfo? Started; + public InvocationEndInfo? Ended; + public List Wraps = new(); + public List Order = new(); + + public void OnInvocationStart(InvocationInfo info) { Started = info; Order.Add("start"); } + + public async Task WrapAsync(UserCodeInfo info, Func next) + { + Wraps.Add(info); + Order.Add("wrap.before"); + await next(); + Order.Add("wrap.after"); + } + + public Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken cancellationToken) + { + Ended = info; + Order.Add("end"); + return Task.CompletedTask; + } + } + + private sealed class Factory : IDurableInstrumentationPluginFactory + { + private readonly Func _create; + public Factory(IDurableInstrumentationPlugin plugin, string? group = null) : this(() => plugin, group) { } + public Factory(Func create, string? group = null) { _create = create; ExclusiveGroup = group; } + public string? ExclusiveGroup { get; } + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => _create(); + } + + private sealed class ThrowingPlugin : IDurableInstrumentationPlugin + { + public void OnInvocationStart(InvocationInfo info) => throw new InvalidOperationException("start"); + public Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken ct) => throw new InvalidOperationException("end"); + public Task WrapAsync(UserCodeInfo info, Func next) => throw new InvalidOperationException("wrap"); + } + + private static TestLambdaContext Context(string? traceId = null) => new() + { + Serializer = new DefaultLambdaJsonSerializer(), + AwsRequestId = "request-1", + TraceId = traceId!, + }; + + private static DurableExecutionInvocationInput Input(IEnumerable? extra = null, IReadOnlyList? updated = null) + { + var ops = new List + { + new() + { + Id = "exec-0", + Type = OperationTypes.Execution, + Status = OperationStatuses.Started, + StartTimestamp = 1_700_000_000_000, + ExecutionDetails = new ExecutionDetails { InputPayload = "\"in\"" }, + }, + }; + if (extra != null) ops.AddRange(extra); + return new DurableExecutionInvocationInput + { + DurableExecutionArn = Arn, + UpdatedOperationIds = updated, + InitialExecutionState = new InitialExecutionState { Operations = ops }, + }; + } + + private static DurableExecutionOptions Options(Recorder recorder) + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(recorder)); + return options; + } + + [Fact] + public async Task Succeeded_ReportsStartWrapAndEnd_InOrder() + { + var recorder = new Recorder(); + + var output = await DurableFunction.WrapAsync( + (input, ctx) => Task.FromResult(input + "!"), Input(), Context("Root=1-abc;Parent=def;Sampled=1"), + new MockLambdaClient(), Options(recorder)); + + Assert.Equal(InvocationStatus.Succeeded, output.Status); + Assert.Equal("\"in!\"", output.Result); + Assert.Equal(new[] { "start", "wrap.before", "wrap.after", "end" }, recorder.Order); + + Assert.Equal(Arn, recorder.Started!.ExecutionArn); + Assert.Equal("request-1", recorder.Started.RequestId); + Assert.True(recorder.Started.IsFirstInvocation); + Assert.Equal("Root=1-abc;Parent=def;Sampled=1", recorder.Started.XRayTraceId); + Assert.Equal(DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000), recorder.Started.ExecutionStartTimestamp); + + var wrap = Assert.Single(recorder.Wraps); + Assert.Equal(UserCodeKind.Invocation, wrap.Kind); + Assert.Null(wrap.Operation); + + Assert.Equal(InvocationEndStatus.Succeeded, recorder.Ended!.Status); + Assert.Null(recorder.Ended.Error); + } + + [Fact] + public async Task WorkflowFailure_EndsAsFailed_WithTheError() + { + var recorder = new Recorder(); + + var output = await DurableFunction.WrapAsync( + (_, _) => throw new InvalidOperationException("workflow broke"), Input(), Context(), + new MockLambdaClient(), Options(recorder)); + + Assert.Equal(InvocationStatus.Failed, output.Status); + Assert.Equal(InvocationEndStatus.Failed, recorder.Ended!.Status); + Assert.Equal("workflow broke", recorder.Ended.Error!.ErrorMessage); + } + + [Fact] + public async Task Suspension_EndsAsPending() + { + var recorder = new Recorder(); + + var output = await DurableFunction.WrapAsync( + async (_, ctx) => { await ctx.WaitAsync(TimeSpan.FromMinutes(5)); return "done"; }, Input(), Context(), + new MockLambdaClient(), Options(recorder)); + + Assert.Equal(InvocationStatus.Pending, output.Status); + Assert.Equal(InvocationEndStatus.Pending, recorder.Ended!.Status); + } + + [Fact] + public async Task ThrownInvocation_EndsAsRetrying_AndRethrows() + { + var recorder = new Recorder(); + var client = new MockLambdaClient + { + // A transient service error on the final checkpoint drain escapes so Lambda retries the invocation. + CheckpointThrows = new AmazonServiceException("unavailable") { StatusCode = HttpStatusCode.ServiceUnavailable }, + }; + + await Assert.ThrowsAnyAsync(() => DurableFunction.WrapAsync( + async (_, ctx) => await ctx.StepAsync((_, _) => Task.FromResult("x"), name: "s"), Input(), Context(), + client, Options(recorder))); + + Assert.Equal(InvocationEndStatus.Retrying, recorder.Ended!.Status); + Assert.NotNull(recorder.Ended.Exception); + } + + [Fact] + public async Task ResumedInvocation_ReportsHistoryAndUpdatedOperations() + { + var recorder = new Recorder(); + var history = new[] + { + new Operation { Id = "a", Type = OperationTypes.Step, Name = "first", Status = OperationStatuses.Succeeded, StepDetails = new StepDetails { Attempt = 2 } }, + new Operation { Id = "b", Type = OperationTypes.Wait, Status = OperationStatuses.Succeeded }, + }; + + await DurableFunction.WrapAsync( + (input, _) => Task.FromResult(input), Input(history, updated: new[] { "b" }), Context(), + new MockLambdaClient(), Options(recorder)); + + var started = recorder.Started!; + Assert.False(started.IsFirstInvocation); + Assert.Equal(3, started.Operations.Count); + Assert.Equal("first", started.Operations["a"].Name); + Assert.Equal(2, started.Operations["a"].Attempt); + var updated = Assert.Single(started.UpdatedOperations); + Assert.Equal("b", updated.Key); + Assert.Equal(OperationTypes.Wait, updated.Value.Type); + } + + [Fact] + public async Task PluginsThatThrow_DoNotAffectTheWorkflow() + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(new ThrowingPlugin())); + + var output = await DurableFunction.WrapAsync( + (input, _) => Task.FromResult(input), Input(), Context(), new MockLambdaClient(), options); + + Assert.Equal(InvocationStatus.Succeeded, output.Status); + } + + [Fact] + public async Task FactoryReturningNull_RunsWithoutPlugin() + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(() => null)); + + var output = await DurableFunction.WrapAsync( + (input, _) => Task.FromResult(input), Input(), Context(), new MockLambdaClient(), options); + + Assert.Equal(InvocationStatus.Succeeded, output.Status); + } + + [Fact] + public async Task EachInvocationGetsAFreshPluginFromTheFactory() + { + var created = new List(); + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(() => { var r = new Recorder(); created.Add(r); return r; })); + + for (var i = 0; i < 3; i++) + { + await DurableFunction.WrapAsync( + (input, _) => Task.FromResult(input), Input(), Context(), new MockLambdaClient(), options); + } + + Assert.Equal(3, created.Count); + Assert.All(created, r => Assert.Equal(InvocationEndStatus.Succeeded, r.Ended!.Status)); + } + + [Fact] + public async Task ConflictingExclusiveGroups_ThrowPluginLoadException() + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(new Recorder(), group: "view")); + options.Plugins.Add(new Factory(new Recorder(), group: "view")); + var ran = false; + + await Assert.ThrowsAsync(() => DurableFunction.WrapAsync( + (input, _) => { ran = true; return Task.FromResult(input); }, Input(), Context(), new MockLambdaClient(), options)); + + Assert.False(ran); + } + + [Fact] + public async Task VoidWorkflowOverload_RunsPlugins() + { + var recorder = new Recorder(); + var ran = false; + + var output = await DurableFunction.WrapAsync( + (_, _) => { ran = true; return Task.CompletedTask; }, Input(), Context(), new MockLambdaClient(), Options(recorder)); + + Assert.True(ran); + Assert.Equal(InvocationStatus.Succeeded, output.Status); + Assert.Equal(InvocationEndStatus.Succeeded, recorder.Ended!.Status); + } + + [Fact] + public async Task NullOptions_Throws() + { + await Assert.ThrowsAsync(() => DurableFunction.WrapAsync( + (input, _) => Task.FromResult(input), Input(), Context(), new MockLambdaClient(), (DurableExecutionOptions)null!)); + } +} From 14d67bb9b32db26276d2a20297178200f66445ac Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 04:13:00 +0000 Subject: [PATCH 3/9] Report operations, attempts and child contexts to instrumentation plugins DurableOperation.ExecuteAsync reports OperationStart when the workflow reaches an operation and OperationEnd when it reaches a terminal state (or is replayed as terminal). Operations that suspend, or are cancelled, report no end. Steps and wait-for-condition polls report AttemptStart/AttemptEnd and run their user function inside the plugins' WrapAsync; child contexts wrap their function the same way. Map, parallel, incremental parallel and their branches carry the plugins too. OperationInfo.Attempt is the 1-based latest attempt (the service records the number of earlier attempts). Operations without plugins take the unchanged code path. --- .../DurableContext.cs | 25 +- .../DurableFunction.cs | 2 +- .../Internal/CallbackOperation.cs | 2 + .../Internal/ChildContextOperation.cs | 4 +- .../Internal/ConcurrentOperation.cs | 6 +- .../Internal/DurableOperation.cs | 149 +++++++- .../Internal/IncrementalParallelOperation.cs | 16 +- .../Internal/InvokeOperation.cs | 2 + .../Internal/PluginInfoConverter.cs | 64 +++- .../Internal/StepOperation.cs | 4 +- .../Internal/WaitForConditionOperation.cs | 4 +- .../Internal/WaitOperation.cs | 2 + .../DurableFunctionPluginTests.cs | 2 +- .../OperationPluginTests.cs | 349 ++++++++++++++++++ 14 files changed, 589 insertions(+), 42 deletions(-) create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs index d2444c3a8..8ba1028ca 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs @@ -20,6 +20,7 @@ internal sealed class DurableContext : IDurableContext private readonly OperationIdGenerator _idGenerator; private readonly string _durableExecutionArn; private readonly CheckpointBatcher? _batcher; + private readonly PluginRunner? _plugins; private ILogger _logger; public DurableContext( @@ -29,8 +30,10 @@ public DurableContext( OperationIdGenerator idGenerator, string durableExecutionArn, ILambdaContext lambdaContext, - CheckpointBatcher? batcher = null) + CheckpointBatcher? batcher = null, + PluginRunner? plugins = null) { + _plugins = plugins; _state = state; _terminationManager = terminationManager; _workflowCancellation = workflowCancellation; @@ -91,7 +94,7 @@ private Task RunStep( var operationId = _idGenerator.NextId(); var op = new StepOperation( operationId, name, _idGenerator.ParentId, func, config, serializer, Logger, - _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher); + _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -115,7 +118,7 @@ public Task WaitAsync( var waitSeconds = (int)Math.Max(1, Math.Ceiling(duration.TotalSeconds)); var op = new WaitOperation( operationId, name, _idGenerator.ParentId, waitSeconds, - _state, _terminationManager, _durableExecutionArn, _batcher); + _state, _terminationManager, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -156,7 +159,7 @@ public Task WaitForConditionAsync( var operationId = _idGenerator.NextId(); var op = new WaitForConditionOperation( operationId, name, _idGenerator.ParentId, check, config, serializer, Logger, - _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher); + _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -175,7 +178,7 @@ private Task RunChildContext( var op = new ChildContextOperation( operationId, name, _idGenerator.ParentId, func, config, serializer, MakeChildFactory(), _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher, - isVirtual: config?.NestingType == NestingType.Flat); + isVirtual: config?.NestingType == NestingType.Flat) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -196,7 +199,7 @@ private Task> RunCallback( var operationId = _idGenerator.NextId(); var op = new CallbackOperation( operationId, name, _idGenerator.ParentId, config, serializer, - _state, _terminationManager, _durableExecutionArn, _batcher); + _state, _terminationManager, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -230,7 +233,7 @@ public IDurableParallel CreateParallel( var operationId = _idGenerator.NextId(); return new Internal.IncrementalParallelOperation( operationId, name, _idGenerator.ParentId, effectiveConfig, defaultSerializerFactory, MakeChildFactory(), - _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher); + _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher, _plugins); } public Task> ParallelAsync( @@ -294,7 +297,7 @@ private Task> RunParallel( var operationId = _idGenerator.NextId(); var op = new Internal.ParallelOperation( operationId, name, _idGenerator.ParentId, branches, effectiveConfig, serializer, MakeChildFactory(), - _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher); + _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -329,7 +332,7 @@ private Task> RunMap( var operationId = _idGenerator.NextId(); var op = new Internal.MapOperation( operationId, name, _idGenerator.ParentId, items, func, effectiveConfig, serializer, MakeChildFactory(), - _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher); + _state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -554,7 +557,7 @@ private Task RunInvoke( var op = new InvokeOperation( operationId, name, _idGenerator.ParentId, functionName, payload, config, serializer, - _state, _terminationManager, _durableExecutionArn, _batcher); + _state, _terminationManager, _durableExecutionArn, _batcher) { Plugins = _plugins }; return op.ExecuteAsync(cancellationToken); } @@ -591,7 +594,7 @@ private Task RunInvoke( isVirtual ? _idGenerator.CreateVirtualChild(operationId, reportedParentId) : _idGenerator.CreateChild(operationId), - _durableExecutionArn, LambdaContext, _batcher); + _durableExecutionArn, LambdaContext, _batcher, _plugins); } } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs index 38b0cd9b2..e921968d5 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs @@ -312,7 +312,7 @@ private static async Task RunInvocationAsync result; try diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs index 5e3ce0c9b..dc5031f22 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs @@ -84,6 +84,8 @@ public CallbackOperation( protected override string OperationType => OperationTypes.Callback; + protected override string? OperationSubType => _subType; + /// /// Set when an existing terminal-state checkpoint was observed during /// dispatch. reads this directly to short- diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ChildContextOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ChildContextOperation.cs index 6c97a8b20..7d79874f0 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ChildContextOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ChildContextOperation.cs @@ -97,6 +97,8 @@ public ChildContextOperation( protected override string OperationType => OperationTypes.Context; + protected override string? OperationSubType => _subType; + protected override async Task StartAsync(CancellationToken cancellationToken) { // Virtual (NestingType.Flat) branches emit no CONTEXT checkpoint of their @@ -194,7 +196,7 @@ private async Task ExecuteFunc(CancellationToken cancellationToken) // the deadline while its timer has not run yet. _workflowCancellation.ThrowIfDeadlineExceeded( "The invocation deadline passed before the child context started."); - result = await _func(childContext, linked.Token); + result = await RunChildContextAsync(() => _func(childContext, linked.Token)); } catch (OperationCanceledException) when ( linked.IsCancellationRequested || _workflowCancellation.Token.IsCancellationRequested) diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ConcurrentOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ConcurrentOperation.cs index 0e023ebe0..877c50e78 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ConcurrentOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ConcurrentOperation.cs @@ -101,6 +101,8 @@ protected ConcurrentOperation( /// Parent CONTEXT sub-type label (e.g. Parallel / Map). protected abstract string ParentSubType { get; } + protected override string? OperationSubType => ParentSubType; + /// Per-unit child-context sub-type label (e.g. ParallelBranch / MapIteration). protected abstract string ChildSubType { get; } @@ -523,7 +525,7 @@ private async Task RunUnitAsync( DurableExecutionArn, Batcher, shortCircuitToken, - isVirtual: _isVirtual); + isVirtual: _isVirtual) { Plugins = Plugins }; try { @@ -644,7 +646,7 @@ private async Task RunSingleUnitAsync(int index, CancellationToken _workflowCancellation, DurableExecutionArn, Batcher, - isVirtual: _isVirtual); + isVirtual: _isVirtual) { Plugins = Plugins }; try { diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs index 9f3570fac..53b9749f1 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +using Amazon.Lambda.DurableExecution.Instrumentation; using SdkOperationUpdate = Amazon.Lambda.Model.OperationUpdate; namespace Amazon.Lambda.DurableExecution.Internal; @@ -39,13 +40,17 @@ protected DurableOperation( Batcher = batcher; } - /// The wire-format operation type (e.g. "STEP", "WAIT"). protected abstract string OperationType { get; } + /// The checkpoint sub-type, reported to instrumentation plugins. Null when the operation has none. + protected virtual string? OperationSubType => null; + /// - /// Looks up any prior checkpoint for this op and dispatches to - /// (none) or (some). + /// The plugins of this invocation, or null when none is registered. Set by whoever creates the operation, + /// so the constructors stay unchanged. /// + internal PluginRunner? Plugins { get; init; } + public Task ExecuteAsync(CancellationToken cancellationToken) { State.ValidateReplayConsistency(OperationId, OperationType, Name); @@ -55,25 +60,145 @@ public Task ExecuteAsync(CancellationToken cancellationToken) State.TrackReplay(OperationId); var existing = State.GetOperation(OperationId); + if (Plugins != null) + return ExecuteWithPluginsAsync(Plugins, existing, cancellationToken); + return existing == null ? StartAsync(cancellationToken) : ReplayAsync(existing, cancellationToken); } - /// First-time execution path: no prior checkpoint exists. protected abstract Task StartAsync(CancellationToken cancellationToken); + protected abstract Task ReplayAsync(Operation existing, CancellationToken cancellationToken); + + protected Task EnqueueAsync(SdkOperationUpdate update, CancellationToken cancellationToken = default) + => Batcher?.EnqueueAsync(update, cancellationToken) ?? Task.CompletedTask; + /// - /// Replay path: a checkpoint from a prior invocation exists. Subclasses - /// switch on . - /// against constants. + /// Runs the operation and reports its start and, when it reaches a terminal state, its end to the plugins. + /// An operation that suspends the invocation never completes, so it reports no end. Neither does one + /// cancelled by the workflow or stopped by the invocation deadline: those are not operation outcomes. /// - protected abstract Task ReplayAsync(Operation existing, CancellationToken cancellationToken); + private async Task ExecuteWithPluginsAsync( + PluginRunner plugins, Operation? existing, CancellationToken cancellationToken) + { + // An operation is replayed when the workflow reaches it again after it already finished. + var isReplay = existing != null && PluginInfoConverter.IsTerminal(existing.Status); + + plugins.OperationStart(PluginInfoConverter.ToOperationInfo( + existing, OperationId, Name, OperationType, OperationSubType, ParentId, isReplay, + fallbackStatus: OperationStatuses.Started)); + + TResult result; + try + { + result = await (existing == null ? StartAsync(cancellationToken) : ReplayAsync(existing, cancellationToken)); + } + catch (Exception ex) when (IsOperationFailure(ex)) + { + plugins.OperationEnd(CreateEndInfo(existing, isReplay, OperationStatuses.Failed, ex)); + throw; + } + + plugins.OperationEnd(CreateEndInfo(existing, isReplay, OperationStatuses.Succeeded, null)); + return result; + } + + private OperationEndInfo CreateEndInfo(Operation? existing, bool isReplay, string status, Exception? exception) + { + // The checkpoint response may have stamped the terminal record with the service's timestamps. + var latest = State.GetOperation(OperationId) ?? existing; + return PluginInfoConverter.ToOperationEndInfo( + latest, OperationId, Name, OperationType, OperationSubType, ParentId, isReplay, status, exception); + } + + /// The exceptions that mean the operation itself failed, as opposed to the invocation. + private static bool IsOperationFailure(Exception ex) => + ex is StepException or ChildContextException or InvokeException or CallbackException or WaitForConditionException; /// - /// Enqueues an outbound checkpoint and awaits its batch flush. No-op when - /// no batcher is wired (e.g. unit tests that don't exercise flushing). + /// Runs one execution of an operation's user function and reports it to the plugins: attempt start, the + /// user function inside the plugins' WrapAsync, attempt end. Cancellation is not an attempt outcome. /// - protected Task EnqueueAsync(SdkOperationUpdate update, CancellationToken cancellationToken = default) - => Batcher?.EnqueueAsync(update, cancellationToken) ?? Task.CompletedTask; + /// The 1-based attempt number. + /// The user function. + protected async Task RunAttemptAsync(int attemptNumber, Func> body) + { + var plugins = Plugins; + if (plugins == null) + return await body(); + + var info = new AttemptInfo + { + Id = OperationId, + Name = Name, + Type = OperationType, + SubType = OperationSubType, + ParentId = ParentId, + Status = OperationStatuses.Started, + Attempt = attemptNumber, + IsReplay = false, + }; + plugins.AttemptStart(info); + + T result = default!; + try + { + await plugins.WrapAsync( + new UserCodeInfo { Kind = UserCodeKind.Attempt, Operation = info }, + async () => result = await body()); + } + catch (Exception ex) + { + if (ex is not OperationCanceledException) + plugins.AttemptEnd(CreateAttemptEndInfo(info, AttemptOutcome.Failed, ex)); + throw; + } + + plugins.AttemptEnd(CreateAttemptEndInfo(info, AttemptOutcome.Succeeded, null)); + return result; + } + + private static AttemptEndInfo CreateAttemptEndInfo(AttemptInfo started, AttemptOutcome outcome, Exception? exception) => new() + { + Id = started.Id, + Name = started.Name, + Type = started.Type, + SubType = started.SubType, + ParentId = started.ParentId, + Status = outcome == AttemptOutcome.Succeeded ? OperationStatuses.Succeeded : OperationStatuses.Failed, + Attempt = started.Attempt, + IsReplay = false, + Outcome = outcome, + Exception = exception, + }; + + /// + /// Runs a child context's function inside the plugins' WrapAsync so their ambient context is in + /// effect while it runs. + /// + protected Task RunChildContextAsync(Func> body) + { + var plugins = Plugins; + if (plugins == null) + return body(); + + return WrapChildContextAsync(plugins, body); + } + + private async Task WrapChildContextAsync(PluginRunner plugins, Func> body) + { + T result = default!; + await plugins.WrapAsync( + new UserCodeInfo + { + Kind = UserCodeKind.ChildContext, + Operation = PluginInfoConverter.ToOperationInfo( + State.GetOperation(OperationId), OperationId, Name, OperationType, OperationSubType, ParentId, + isReplay: false, fallbackStatus: OperationStatuses.Started), + }, + async () => result = await body()); + return result; + } } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs index 72cbe74a8..32501a517 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs @@ -343,6 +343,7 @@ internal sealed class IncrementalParallelOperation : IDurableParallel private readonly WorkflowCancellation _workflowCancellation; private readonly string _durableExecutionArn; private readonly CheckpointBatcher? _batcher; + private readonly PluginRunner? _plugins; private readonly object _lock = new(); private readonly List _branches = new(); @@ -373,8 +374,10 @@ public IncrementalParallelOperation( TerminationManager termination, WorkflowCancellation workflowCancellation, string durableExecutionArn, - CheckpointBatcher? batcher = null) + CheckpointBatcher? batcher = null, + PluginRunner? plugins = null) { + _plugins = plugins; _operationId = operationId; _name = name; _parentId = parentId; @@ -442,6 +445,11 @@ public IncrementalParallelOperation( $"'{existing.Status}' on replay."); } } + + _plugins?.OperationStart(PluginInfoConverter.ToOperationInfo( + existing, _operationId, _name, OperationTypes.Context, OperationSubTypes.Parallel, _parentId, + isReplay: existing != null && PluginInfoConverter.IsTerminal(existing.Status), + fallbackStatus: OperationStatuses.Started)); } public IParallelBranch Branch( @@ -567,6 +575,10 @@ private async Task CompleteCoreAsync(CancellationToken cancellatio ? BuildTerminalResult(controllers) : await BuildAndCheckpointRunResultAsync(controllers, cancellationToken).ConfigureAwait(false); + _plugins?.OperationEnd(PluginInfoConverter.ToOperationEndInfo( + _state.GetOperation(_operationId), _operationId, _name, OperationTypes.Context, OperationSubTypes.Parallel, + _parentId, isReplay: _mode == ParallelExecutionMode.Terminal, OperationStatuses.Succeeded, exception: null)); + return result; } @@ -657,7 +669,7 @@ async Task> Run() _durableExecutionArn, _batcher, bailToken, - isVirtual: _isVirtual); + isVirtual: _isVirtual) { Plugins = _plugins }; // Branch child ops receive CancellationToken.None here — they re-link // workflow-shutdown and the cooperative-bail token internally, and diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs index bc27ff7a3..8852c81fb 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs @@ -71,6 +71,8 @@ public InvokeOperation( protected override string OperationType => OperationTypes.ChainedInvoke; + protected override string? OperationSubType => OperationSubTypes.ChainedInvoke; + protected override async Task StartAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs index 872d889e2..8a33fea14 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs @@ -9,20 +9,64 @@ namespace Amazon.Lambda.DurableExecution.Internal; /// Builds the immutable info objects handed to plugins from the SDK's checkpoint model. internal static class PluginInfoConverter { - internal static OperationInfo ToOperationInfo(Operation op, bool isReplay = false) => new() + internal static bool IsTerminal(string? status) => + status == OperationStatuses.Succeeded + || status == OperationStatuses.Failed + || status == OperationStatuses.Cancelled + || status == OperationStatuses.Stopped; + + /// Describes a checkpointed operation, for the snapshots in invocation and change info. + internal static OperationInfo ToOperationInfo(Operation op) => + ToOperationInfo(op, op.Id ?? string.Empty, op.Name, op.Type ?? string.Empty, op.SubType, op.ParentId, + isReplay: false, fallbackStatus: null); + + /// + /// Describes an operation the workflow is running. is its checkpoint record, if + /// it has one; the identity arguments are what the SDK knows even before the first checkpoint. + /// + internal static OperationInfo ToOperationInfo( + Operation? existing, string id, string? name, string type, string? subType, string? parentId, + bool isReplay, string? fallbackStatus) => new() { - Id = op.Id ?? string.Empty, - Name = op.Name, - Type = op.Type ?? string.Empty, - SubType = op.SubType, - ParentId = op.ParentId, - Status = op.Status, - StartTimestamp = FromEpochMilliseconds(op.StartTimestamp), - EndTimestamp = FromEpochMilliseconds(op.EndTimestamp), - Attempt = op.StepDetails?.Attempt, + Id = id, + Name = name ?? existing?.Name, + Type = type, + SubType = subType ?? existing?.SubType, + ParentId = parentId, + Status = existing?.Status ?? fallbackStatus, + StartTimestamp = FromEpochMilliseconds(existing?.StartTimestamp), + EndTimestamp = existing != null && IsTerminal(existing.Status) ? FromEpochMilliseconds(existing.EndTimestamp) : null, + Attempt = AttemptOf(type, existing), IsReplay = isReplay, }; + /// Describes an operation that reached a terminal state with the given outcome. + internal static OperationEndInfo ToOperationEndInfo( + Operation? latest, string id, string? name, string type, string? subType, string? parentId, + bool isReplay, string status, Exception? exception) => new() + { + Id = id, + Name = name ?? latest?.Name, + Type = type, + SubType = subType ?? latest?.SubType, + ParentId = parentId, + Status = status, + StartTimestamp = FromEpochMilliseconds(latest?.StartTimestamp), + // Only the service's own end time. A plugin that needs one when it is missing reads its own clock. + EndTimestamp = latest != null && IsTerminal(latest.Status) ? FromEpochMilliseconds(latest.EndTimestamp) : null, + Attempt = AttemptOf(type, latest), + IsReplay = isReplay, + Error = exception != null ? ErrorObject.FromException(exception) : null, + Exception = isReplay ? null : exception, + }; + + /// + /// The 1-based number of the latest attempt of a step. The service records how many attempts came before + /// (StepDetails.Attempt), and the SDK numbers the next one from it. + /// + private static int? AttemptOf(string type, Operation? op) => + type == OperationTypes.Step ? (op?.StepDetails?.Attempt ?? 0) + 1 : null; + internal static IReadOnlyDictionary ToOperationMap(IEnumerable operations, ISet? onlyIds = null) { var map = new Dictionary(StringComparer.Ordinal); diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/StepOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/StepOperation.cs index 2dee83f69..6277783d9 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/StepOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/StepOperation.cs @@ -70,6 +70,8 @@ public StepOperation( protected override string OperationType => OperationTypes.Step; + protected override string? OperationSubType => _subType; + protected override Task StartAsync(CancellationToken cancellationToken) => ExecuteFunc(attemptNumber: 1, cancellationToken); @@ -240,7 +242,7 @@ private async Task ExecuteFunc(int attemptNumber, CancellationToken cancellat // deadline while its timer has not run yet. _workflowCancellation.ThrowIfDeadlineExceeded( "The invocation deadline passed before the step body started."); - result = await _func(stepContext, linked.Token); + result = await RunAttemptAsync(attemptNumber, () => _func(stepContext, linked.Token)); } } catch (OperationCanceledException) when ( diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitForConditionOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitForConditionOperation.cs index f6768f082..8723a3fc1 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitForConditionOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitForConditionOperation.cs @@ -81,6 +81,8 @@ public WaitForConditionOperation( protected override string OperationType => OperationTypes.Step; + protected override string? OperationSubType => OperationSubTypes.WaitForCondition; + protected override Task StartAsync(CancellationToken cancellationToken) => ExecuteIteration(_config.InitialState, attemptNumber: 1, existingStatus: null, cancellationToken); @@ -212,7 +214,7 @@ private async Task ExecuteIteration(TState currentState, int attemptNumb // Also against the clock: restoring the prior state on replay can // cross the deadline while its timer has not run yet. ThrowIfDeadlineExceeded(); - newState = await _check(currentState, checkContext, linked.Token); + newState = await RunAttemptAsync(attemptNumber, () => _check(currentState, checkContext, linked.Token)); } catch (OperationCanceledException) when ( linked.IsCancellationRequested || _workflowCancellation.Token.IsCancellationRequested) diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitOperation.cs index 948503f26..3007e983c 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/WaitOperation.cs @@ -44,6 +44,8 @@ public WaitOperation( protected override string OperationType => OperationTypes.Wait; + protected override string? OperationSubType => OperationSubTypes.Wait; + protected override async Task StartAsync(CancellationToken cancellationToken) { // Sync-flush WAIT START before suspending — the service can't schedule diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs index 8ae0ce60d..402e5aee4 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs @@ -182,7 +182,7 @@ await DurableFunction.WrapAsync( Assert.False(started.IsFirstInvocation); Assert.Equal(3, started.Operations.Count); Assert.Equal("first", started.Operations["a"].Name); - Assert.Equal(2, started.Operations["a"].Attempt); + Assert.Equal(3, started.Operations["a"].Attempt); // one more than the 2 attempts the service recorded var updated = Assert.Single(started.UpdatedOperations); Assert.Equal("b", updated.Key); Assert.Equal(OperationTypes.Wait, updated.Value.Type); diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs new file mode 100644 index 000000000..0d49e381d --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs @@ -0,0 +1,349 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.DurableExecution.Instrumentation; +using Amazon.Lambda.DurableExecution.Internal; +using Amazon.Lambda.Serialization.SystemTextJson; +using Amazon.Lambda.TestUtilities; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Tests; + +/// Operation, attempt and wrap hooks reported while a workflow runs. +public class OperationPluginTests +{ + private const string Arn = "arn:aws:lambda:us-east-1:123:durable-execution:operation-plugin-test"; + + private static string IdAt(int position) => OperationIdGenerator.HashOperationId(position.ToString()); + + private sealed class Recorder : IDurableInstrumentationPlugin + { + public readonly List Events = new(); + public readonly List OperationStarts = new(); + public readonly List OperationEnds = new(); + public readonly List AttemptStarts = new(); + public readonly List AttemptEnds = new(); + public readonly List Wraps = new(); + private readonly object _lock = new(); + + private void Add(string e) { lock (_lock) Events.Add(e); } + + public void OnOperationStart(OperationInfo info) { lock (_lock) OperationStarts.Add(info); Add($"start:{info.Name ?? info.Type}"); } + public void OnOperationEnd(OperationEndInfo info) { lock (_lock) OperationEnds.Add(info); Add($"end:{info.Name ?? info.Type}:{info.Status}"); } + public void OnAttemptStart(AttemptInfo info) { lock (_lock) AttemptStarts.Add(info); Add($"attemptStart:{info.Name}:{info.Attempt}"); } + public void OnAttemptEnd(AttemptEndInfo info) { lock (_lock) AttemptEnds.Add(info); Add($"attemptEnd:{info.Name}:{info.Attempt}:{info.Outcome}"); } + + public async Task WrapAsync(UserCodeInfo info, Func next) + { + lock (_lock) Wraps.Add(info); + Add($"wrap>{info.Kind}:{info.Operation?.Name}"); + await next(); + Add($"wrap<{info.Kind}:{info.Operation?.Name}"); + } + } + + private sealed class Factory : IDurableInstrumentationPluginFactory + { + private readonly IDurableInstrumentationPlugin _plugin; + public Factory(IDurableInstrumentationPlugin plugin) => _plugin = plugin; + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => _plugin; + } + + private static TestLambdaContext Context() => new() { Serializer = new DefaultLambdaJsonSerializer() }; + + private static DurableExecutionInvocationInput Input(params Operation[] history) + { + var ops = new List + { + new() + { + Id = "exec-0", + Type = OperationTypes.Execution, + Status = OperationStatuses.Started, + ExecutionDetails = new ExecutionDetails { InputPayload = "\"in\"" }, + }, + }; + ops.AddRange(history); + return new DurableExecutionInvocationInput + { + DurableExecutionArn = Arn, + InitialExecutionState = new InitialExecutionState { Operations = ops }, + }; + } + + private static Task Run( + Recorder recorder, Func> workflow, params Operation[] history) + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(recorder)); + return DurableFunction.WrapAsync( + (_, ctx) => workflow(ctx), Input(history), Context(), new MockLambdaClient(), options); + } + + [Fact] + public async Task Step_ReportsOperationAndAttemptInOrder_WithIdentity() + { + var recorder = new Recorder(); + + var output = await Run(recorder, ctx => ctx.StepAsync((_, _) => Task.FromResult("v"), name: "charge")); + + Assert.Equal(InvocationStatus.Succeeded, output.Status); + Assert.Equal( + new[] + { + "wrap>Invocation:", + "start:charge", "attemptStart:charge:1", "wrap>Attempt:charge", "wrap + recorder.Wraps.Single(w => w.Kind == kind).Operation?.Id; + + [Fact] + public async Task Step_TerminalFailure_ReportsFailedAttemptAndOperation_AndThrowsToTheWorkflow() + { + var recorder = new Recorder(); + StepException? caught = null; + + await Run(recorder, async ctx => + { + try { await ctx.StepAsync((_, _) => throw new InvalidOperationException("nope"), name: "charge"); } + catch (StepException ex) { caught = ex; } + return "handled"; + }); + + Assert.NotNull(caught); + var attemptEnd = Assert.Single(recorder.AttemptEnds); + Assert.Equal(AttemptOutcome.Failed, attemptEnd.Outcome); + Assert.IsType(attemptEnd.Exception); + + var end = Assert.Single(recorder.OperationEnds); + Assert.Equal(OperationStatuses.Failed, end.Status); + Assert.Equal("nope", end.Error!.ErrorMessage); + Assert.IsType(end.Exception); + } + + [Fact] + public async Task Step_RetryScheduled_EndsTheAttemptButNotTheOperation() + { + var recorder = new Recorder(); + var retryOnce = new StepConfig + { + RetryStrategy = RetryStrategy.FromDelegate((_, attempt) => attempt < 2 + ? RetryDecision.RetryAfter(TimeSpan.FromSeconds(30)) + : RetryDecision.DoNotRetry()), + }; + + var output = await Run(recorder, ctx => ctx.StepAsync( + (_, _) => throw new InvalidOperationException("transient"), name: "flaky", config: retryOnce)); + + Assert.Equal(InvocationStatus.Pending, output.Status); + Assert.Single(recorder.AttemptEnds); + Assert.Equal(AttemptOutcome.Failed, recorder.AttemptEnds[0].Outcome); + Assert.Empty(recorder.OperationEnds); + } + + [Fact] + public async Task Step_ResumedAfterRetry_ReportsTheSecondAttempt() + { + var recorder = new Recorder(); + var ready = new Operation + { + Id = IdAt(1), Type = OperationTypes.Step, Name = "flaky", Status = OperationStatuses.Ready, + StepDetails = new StepDetails { Attempt = 1 }, + }; + + await Run(recorder, ctx => ctx.StepAsync((_, _) => Task.FromResult("ok"), name: "flaky"), ready); + + Assert.Equal(2, Assert.Single(recorder.AttemptStarts).Attempt); + Assert.Equal(OperationStatuses.Succeeded, Assert.Single(recorder.OperationEnds).Status); + Assert.False(recorder.OperationStarts[0].IsReplay); + } + + [Fact] + public async Task Step_Replayed_ReportsReplayStartAndEnd_WithoutRunningAnAttempt() + { + var recorder = new Recorder(); + var ran = false; + var done = new Operation + { + Id = IdAt(1), Type = OperationTypes.Step, Name = "charge", Status = OperationStatuses.Succeeded, + StartTimestamp = 1_700_000_000_000, EndTimestamp = 1_700_000_005_000, + StepDetails = new StepDetails { Result = "\"v\"" }, + }; + + await Run(recorder, ctx => ctx.StepAsync((_, _) => { ran = true; return Task.FromResult("v"); }, name: "charge"), done); + + Assert.False(ran); + Assert.Empty(recorder.AttemptStarts); + Assert.True(recorder.OperationStarts.Single().IsReplay); + var end = Assert.Single(recorder.OperationEnds); + Assert.True(end.IsReplay); + Assert.Equal(DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000), end.StartTimestamp); + Assert.Equal(DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_005_000), end.EndTimestamp); + } + + [Fact] + public async Task Wait_Suspends_ReportsStartButNoEnd() + { + var recorder = new Recorder(); + + var output = await Run(recorder, async ctx => { await ctx.WaitAsync(TimeSpan.FromMinutes(5), name: "pause"); return "x"; }); + + Assert.Equal(InvocationStatus.Pending, output.Status); + var start = Assert.Single(recorder.OperationStarts); + Assert.Equal(OperationTypes.Wait, start.Type); + Assert.Empty(recorder.OperationEnds); + } + + [Fact] + public async Task ChildContext_NestsStartsAndEnds_AndWrapsTheChildFunction() + { + var recorder = new Recorder(); + + await Run(recorder, ctx => ctx.RunInChildContextAsync( + async (child, _) => await child.StepAsync((_, _) => Task.FromResult("inner"), name: "inner"), + name: "outer")); + + // parent start -> child start -> child end -> parent end + var order = recorder.Events.Where(e => e.StartsWith("start:") || e.StartsWith("end:")).ToArray(); + Assert.Equal(new[] { "start:outer", "start:inner", $"end:inner:{OperationStatuses.Succeeded}", $"end:outer:{OperationStatuses.Succeeded}" }, order); + + var inner = recorder.OperationStarts.Single(o => o.Name == "inner"); + var outer = recorder.OperationStarts.Single(o => o.Name == "outer"); + Assert.Equal(outer.Id, inner.ParentId); + Assert.Equal(OperationTypes.Context, outer.Type); + + var childWrap = recorder.Wraps.Single(w => w.Kind == UserCodeKind.ChildContext); + Assert.Equal(outer.Id, childWrap.Operation!.Id); + } + + [Fact] + public async Task WrapAsync_AmbientContextIsVisibleToUserCode_AndNotAfterIt() + { + var seen = new List(); + var ambient = new AsyncLocal(); + var plugin = new AmbientPlugin(ambient); + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(plugin)); + + string? afterStep = null; + await DurableFunction.WrapAsync(async (_, ctx) => + { + seen.Add(ambient.Value); // inside the invocation wrap + await ctx.StepAsync((_, _) => { seen.Add(ambient.Value); return Task.FromResult("s"); }, name: "step"); + afterStep = ambient.Value; + return "done"; + }, Input(), Context(), new MockLambdaClient(), options); + + Assert.Equal(new[] { "Invocation", "Attempt" }, seen); + Assert.Equal("Invocation", afterStep); + } + + private sealed class AmbientPlugin : IDurableInstrumentationPlugin + { + private readonly AsyncLocal _ambient; + public AmbientPlugin(AsyncLocal ambient) => _ambient = ambient; + + public async Task WrapAsync(UserCodeInfo info, Func next) + { + var previous = _ambient.Value; + _ambient.Value = info.Kind.ToString(); + try { await next(); } + finally { _ambient.Value = previous; } + } + } + + [Fact] + public async Task Parallel_ReportsTheOperationAndEveryBranch() + { + var recorder = new Recorder(); + + await Run(recorder, async ctx => + { + await ctx.ParallelAsync(new Func>[] + { + async (c, _) => await c.StepAsync((_, _) => Task.FromResult("a"), name: "a"), + async (c, _) => await c.StepAsync((_, _) => Task.FromResult("b"), name: "b"), + }, name: "fan"); + return "done"; + }); + + var fan = recorder.OperationStarts.Single(o => o.Name == "fan"); + Assert.Equal(OperationSubTypes.Parallel, fan.SubType); + Assert.Equal(2, recorder.OperationStarts.Count(o => o.SubType == OperationSubTypes.ParallelBranch && o.ParentId == fan.Id)); + Assert.Equal(OperationStatuses.Succeeded, recorder.OperationEnds.Single(o => o.Id == fan.Id).Status); + Assert.Equal(recorder.OperationStarts.Count, recorder.OperationEnds.Count); + } + + [Fact] + public async Task IncrementalParallel_ReportsTheOperationAndItsBranches() + { + var recorder = new Recorder(); + + await Run(recorder, async ctx => + { + await using (var parallel = ctx.CreateParallel(name: "fan")) + { + _ = parallel.Branch("a", async (_, _) => { await Task.Yield(); return 1; }); + _ = parallel.Branch("b", async (_, _) => { await Task.Yield(); return 2; }); + await parallel.CompleteAsync(); + } + return "done"; + }); + + var fan = recorder.OperationStarts.Single(o => o.Name == "fan"); + Assert.Equal(OperationSubTypes.Parallel, fan.SubType); + Assert.Equal(2, recorder.OperationStarts.Count(o => o.ParentId == fan.Id)); + Assert.Equal(OperationStatuses.Succeeded, recorder.OperationEnds.Single(o => o.Id == fan.Id).Status); + // The operation starts first and ends last. + Assert.Equal($"start:fan", recorder.Events.First(e => e.StartsWith("start:"))); + Assert.Equal($"end:fan:{OperationStatuses.Succeeded}", recorder.Events.Last(e => e.StartsWith("end:"))); + } + + [Fact] + public async Task Step_CancelledByTheCaller_IsNotReportedAsAFailedAttemptOrOperation() + { + var recorder = new Recorder(); + using var cts = new CancellationTokenSource(); + + await Run(recorder, async ctx => + { + await ctx.StepAsync((_, _) => + { + cts.Cancel(); + throw new OperationCanceledException(cts.Token); + }, name: "cancelled", cancellationToken: cts.Token); + return "x"; + }); + + Assert.Single(recorder.AttemptStarts); + Assert.Empty(recorder.AttemptEnds); + Assert.Empty(recorder.OperationEnds); + } + + [Fact] + public async Task NoPlugins_RunsWorkflowWithoutAnyHooks() + { + var output = await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.StepAsync((_, _) => Task.FromResult("v"), name: "s"), + Input(), Context(), new MockLambdaClient()); + + Assert.Equal(InvocationStatus.Succeeded, output.Status); + } +} From bbc6202c88df35d7447da04b62daef2f22c95190 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 04:19:45 +0000 Subject: [PATCH 4/9] Add plugin log scope fields and chained-invoke trace propagation The durable logger adds the fields a plugin returns from GetLogScope to the scope of every entry, read per entry because they follow the active span. A chained invoke asks the plugins for a trace header after the payload is serialized and writes it to ChainedInvokeOptions.XAmznTraceId on the START checkpoint; an invoke that is replayed does not ask again. Raises the AWSSDK.Lambda minimum to 4.0.110.1, the first version with that field. --- .../3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json | 3 +- .../Amazon.Lambda.DurableExecution.csproj | 2 +- .../DurableContext.cs | 6 +- .../Internal/InvokeOperation.cs | 15 +- .../Internal/PluginRunner.cs | 5 +- .../Internal/ReplayAwareLogger.cs | 11 +- ...a.DurableExecution.IntegrationTests.csproj | 2 +- ...mbda.DurableExecution.Testing.Tests.csproj | 2 +- .../PluginLogAndPropagationTests.cs | 280 ++++++++++++++++++ 9 files changed, 317 insertions(+), 9 deletions(-) create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginLogAndPropagationTests.cs diff --git a/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json b/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json index 70f4f7125..58c4bb361 100644 --- a/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json +++ b/.autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json @@ -4,7 +4,8 @@ "Name": "Amazon.Lambda.DurableExecution", "Type": "Minor", "ChangelogMessages": [ - "Add an instrumentation plugin API (IDurableInstrumentationPlugin and IDurableInstrumentationPluginFactory) and DurableExecutionOptions, accepted by new DurableFunction.WrapAsync overloads. Plugins observe the invocation lifecycle and can run the workflow function inside their own context." + "Add an instrumentation plugin API (IDurableInstrumentationPlugin and IDurableInstrumentationPluginFactory) and DurableExecutionOptions, accepted by new DurableFunction.WrapAsync overloads. Plugins observe the invocation lifecycle and can run the workflow function inside their own context.", + "Raise the minimum AWSSDK.Lambda version to 4.0.110.1, which adds the trace header on chained invokes (ChainedInvokeOptions.XAmznTraceId). Plugins can supply that header and add fields to the log scope of durable log entries." ] } ] diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Amazon.Lambda.DurableExecution.csproj b/Libraries/src/Amazon.Lambda.DurableExecution/Amazon.Lambda.DurableExecution.csproj index 36d4d693f..de249d741 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Amazon.Lambda.DurableExecution.csproj +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Amazon.Lambda.DurableExecution.csproj @@ -47,7 +47,7 @@ - + diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs index 8ba1028ca..d927bb5c1 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs @@ -41,9 +41,11 @@ public DurableContext( _durableExecutionArn = durableExecutionArn; _batcher = batcher; LambdaContext = lambdaContext; - _logger = new ReplayAwareLogger(new LambdaCoreLogger(), state, modeAware: true); + _logger = new ReplayAwareLogger(new LambdaCoreLogger(), state, modeAware: true, ScopeFields); } + private Func?>? ScopeFields => _plugins == null ? null : _plugins.GetLogScope; + public ILogger Logger => _logger; public IExecutionContext ExecutionContext => new DurableExecutionContext(_durableExecutionArn); public ILambdaContext LambdaContext { get; } @@ -57,7 +59,7 @@ public void ConfigureLogger(LoggerConfig config) // so toggling ModeAware works without losing the previous custom logger. var inner = config.CustomLogger ?? (_logger is ReplayAwareLogger existing ? existing.Inner : _logger); - _logger = new ReplayAwareLogger(inner, _state, config.ModeAware); + _logger = new ReplayAwareLogger(inner, _state, config.ModeAware, ScopeFields); } public Task StepAsync( diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs index 8852c81fb..76e57fae6 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/InvokeOperation.cs @@ -4,6 +4,7 @@ using System.IO; using System.Text; using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution.Instrumentation; using SdkChainedInvokeOptions = Amazon.Lambda.Model.ChainedInvokeOptions; using SdkOperationUpdate = Amazon.Lambda.Model.OperationUpdate; @@ -79,6 +80,17 @@ protected override async Task StartAsync(CancellationToken cancellation var serializedPayload = SerializeValue(_payload); + // The invoked function's trace continues from the header a plugin builds for this call. Asked after the + // payload is serialized (a payload failure should not run plugin code) and only here, so replaying an + // invoke that already has its START does not ask again. + var traceHeader = Plugins?.ProvidePropagationMetadata(new PropagationInput + { + ExecutionArn = DurableExecutionArn, + OperationId = OperationId, + ParentOperationId = ParentId, + TargetFunctionName = _functionName, + }); + // The service is what actually invokes the chained function, so it // must receive this START before we suspend. If we only batched it // locally and the parent process were recycled at suspend, the START @@ -95,7 +107,8 @@ await EnqueueAsync(new SdkOperationUpdate ChainedInvokeOptions = new SdkChainedInvokeOptions { FunctionName = _functionName, - TenantId = _config?.TenantId + TenantId = _config?.TenantId, + XAmznTraceId = traceHeader } }, cancellationToken); diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs index e7de0dc11..dc2f5eefa 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginRunner.cs @@ -20,6 +20,7 @@ internal sealed class PluginRunner private readonly IDurableInstrumentationPlugin[] _plugins; private readonly ILogger _logger; private readonly Func _remainingTime; + private int _logScopeFailureLogged; private PluginRunner(IDurableInstrumentationPlugin[] plugins, ILogger logger, Func remainingTime) { @@ -240,7 +241,9 @@ private async Task WrapFrom(int index, UserCodeInfo info, Func userCode) } catch (Exception ex) { - LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.GetLogScope), ex); + // Called for every log entry, so report a failing plugin once instead of once per entry. + if (Interlocked.Exchange(ref _logScopeFailureLogged, 1) == 0) + LogHookFailure(plugin, nameof(IDurableInstrumentationPlugin.GetLogScope), ex); continue; } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ReplayAwareLogger.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ReplayAwareLogger.cs index 5e24f53fe..f05995903 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ReplayAwareLogger.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ReplayAwareLogger.cs @@ -19,12 +19,18 @@ internal sealed class ReplayAwareLogger : ILogger private readonly ILogger _inner; private readonly ExecutionState _state; private readonly bool _modeAware; + private readonly Func?>? _scopeFields; - public ReplayAwareLogger(ILogger inner, ExecutionState state, bool modeAware) + // scopeFields: fields from instrumentation plugins (for example a trace id) added to the scope of every + // entry. Read on each call because they change as the active span does. Null when no plugin is registered. + public ReplayAwareLogger( + ILogger inner, ExecutionState state, bool modeAware, + Func?>? scopeFields = null) { _inner = inner; _state = state; _modeAware = modeAware; + _scopeFields = scopeFields; } /// The wrapped logger; exposed so ConfigureLogger can rewrap without losing it. @@ -50,6 +56,9 @@ public void Log( Func formatter) { if (ShouldSuppress()) return; + + var fields = _scopeFields?.Invoke(); + using var scope = fields != null ? _inner.BeginScope(fields) : null; _inner.Log(logLevel, eventId, state, exception, formatter); } diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.IntegrationTests/Amazon.Lambda.DurableExecution.IntegrationTests.csproj b/Libraries/test/Amazon.Lambda.DurableExecution.IntegrationTests/Amazon.Lambda.DurableExecution.IntegrationTests.csproj index 698d8d7d0..6be5ce6f6 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.IntegrationTests/Amazon.Lambda.DurableExecution.IntegrationTests.csproj +++ b/Libraries/test/Amazon.Lambda.DurableExecution.IntegrationTests/Amazon.Lambda.DurableExecution.IntegrationTests.csproj @@ -32,7 +32,7 @@ - + diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/Amazon.Lambda.DurableExecution.Testing.Tests.csproj b/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/Amazon.Lambda.DurableExecution.Testing.Tests.csproj index ae3673d21..80ccbdf4a 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/Amazon.Lambda.DurableExecution.Testing.Tests.csproj +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/Amazon.Lambda.DurableExecution.Testing.Tests.csproj @@ -31,7 +31,7 @@ - + diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginLogAndPropagationTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginLogAndPropagationTests.cs new file mode 100644 index 000000000..bca3917e8 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginLogAndPropagationTests.cs @@ -0,0 +1,280 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.DurableExecution.Instrumentation; +using Amazon.Lambda.DurableExecution.Internal; +using Amazon.Lambda.Serialization.SystemTextJson; +using Amazon.Lambda.TestUtilities; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Tests; + +/// Log scope fields from plugins and trace header propagation on chained invokes. +public class PluginLogAndPropagationTests +{ + private const string Arn = "arn:aws:lambda:us-east-1:123:durable-execution:log-propagation-test"; + + private static string IdAt(int position) => OperationIdGenerator.HashOperationId(position.ToString()); + + private sealed class ConfigurablePlugin : IDurableInstrumentationPlugin + { + public Func? Propagate; + public Func?>? Scope; + public readonly List PropagationRequests = new(); + + public string? ProvidePropagationMetadata(PropagationInput input) + { + PropagationRequests.Add(input); + return Propagate?.Invoke(input); + } + + public IReadOnlyDictionary? GetLogScope() => Scope?.Invoke(); + } + + private sealed class Factory : IDurableInstrumentationPluginFactory + { + private readonly IDurableInstrumentationPlugin _plugin; + public Factory(IDurableInstrumentationPlugin plugin) => _plugin = plugin; + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => _plugin; + } + + /// A logger that records the scope fields in effect at each entry, as a structured provider would. + private sealed class ScopeCapturingLogger : ILogger + { + private readonly AsyncLocal>?> _scopes = new(); + public readonly List<(string Message, Dictionary Scope)> Entries = new(); + + public IDisposable? BeginScope(TState state) where TState : notnull + { + var previous = _scopes.Value; + var next = new List>(previous ?? new()); + if (state is IReadOnlyDictionary fields) next.Add(fields); + _scopes.Value = next; + return new Restore(() => _scopes.Value = previous); + } + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + var merged = new Dictionary(); + foreach (var scope in _scopes.Value ?? new()) + foreach (var kv in scope) merged[kv.Key] = kv.Value; + lock (Entries) Entries.Add((formatter(state, exception), merged)); + } + + private sealed class Restore : IDisposable + { + private readonly Action _restore; + public Restore(Action restore) => _restore = restore; + public void Dispose() => _restore(); + } + } + + private static TestLambdaContext Context() => new() { Serializer = new DefaultLambdaJsonSerializer() }; + + private static DurableExecutionInvocationInput Input(params Operation[] history) + { + var ops = new List + { + new() + { + Id = "exec-0", + Type = OperationTypes.Execution, + Status = OperationStatuses.Started, + ExecutionDetails = new ExecutionDetails { InputPayload = "\"in\"" }, + }, + }; + ops.AddRange(history); + return new DurableExecutionInvocationInput + { + DurableExecutionArn = Arn, + InitialExecutionState = new InitialExecutionState { Operations = ops }, + }; + } + + private static DurableExecutionOptions Options(IDurableInstrumentationPlugin? plugin) + { + var options = new DurableExecutionOptions(); + if (plugin != null) options.Plugins.Add(new Factory(plugin)); + return options; + } + + // ── Log scope ─────────────────────────────────────────────────────────── + + [Fact] + public async Task LogEntries_CarryPluginScopeFields_ReadAtEachEntry() + { + var current = "span-1"; + var plugin = new ConfigurablePlugin { Scope = () => new Dictionary { ["spanId"] = current } }; + var logger = new ScopeCapturingLogger(); + + await DurableFunction.WrapAsync((_, ctx) => + { + ctx.ConfigureLogger(new LoggerConfig { CustomLogger = logger }); + ctx.Logger.LogInformation("first"); + current = "span-2"; + ctx.Logger.LogInformation("second"); + return Task.FromResult("done"); + }, Input(), Context(), new MockLambdaClient(), Options(plugin)); + + Assert.Equal("span-1", logger.Entries.Single(e => e.Message == "first").Scope["spanId"]); + Assert.Equal("span-2", logger.Entries.Single(e => e.Message == "second").Scope["spanId"]); + } + + [Fact] + public async Task LogEntries_HaveNoPluginFields_WhenNoPluginIsRegistered() + { + var logger = new ScopeCapturingLogger(); + + await DurableFunction.WrapAsync((_, ctx) => + { + ctx.ConfigureLogger(new LoggerConfig { CustomLogger = logger }); + ctx.Logger.LogInformation("hello"); + return Task.FromResult("done"); + }, Input(), Context(), new MockLambdaClient(), Options(null)); + + Assert.Empty(Assert.Single(logger.Entries).Scope); + } + + [Fact] + public async Task LogEntries_ArePlainWhenThePluginReturnsNullOrThrows() + { + var calls = 0; + var plugin = new ConfigurablePlugin { Scope = () => { calls++; throw new InvalidOperationException("boom"); } }; + var logger = new ScopeCapturingLogger(); + + await DurableFunction.WrapAsync((_, ctx) => + { + ctx.ConfigureLogger(new LoggerConfig { CustomLogger = logger }); + ctx.Logger.LogInformation("a"); + ctx.Logger.LogInformation("b"); + return Task.FromResult("done"); + }, Input(), Context(), new MockLambdaClient(), Options(plugin)); + + Assert.Equal(2, logger.Entries.Count); + Assert.All(logger.Entries, e => Assert.Empty(e.Scope)); + Assert.Equal(2, calls); + } + + [Fact] + public async Task ReplayedLogEntries_AreSuppressed_AsBefore() + { + var plugin = new ConfigurablePlugin { Scope = () => new Dictionary { ["spanId"] = "s" } }; + var logger = new ScopeCapturingLogger(); + var done = new Operation + { + Id = IdAt(1), Type = OperationTypes.Step, Name = "s", Status = OperationStatuses.Succeeded, + StepDetails = new StepDetails { Result = "\"v\"" }, + }; + + await DurableFunction.WrapAsync(async (_, ctx) => + { + ctx.ConfigureLogger(new LoggerConfig { CustomLogger = logger }); + ctx.Logger.LogInformation("during replay"); + await ctx.StepAsync((_, _) => Task.FromResult("v"), name: "s"); + ctx.Logger.LogInformation("after replay"); + return "done"; + }, Input(done), Context(), new MockLambdaClient(), Options(plugin)); + + Assert.DoesNotContain(logger.Entries, e => e.Message == "during replay"); + Assert.Equal("s", logger.Entries.Single(e => e.Message == "after replay").Scope["spanId"]); + } + + // ── Chained-invoke propagation ────────────────────────────────────────── + + private static string? TraceHeaderSent(MockLambdaClient client) => + client.CheckpointCalls + .SelectMany(c => c.Updates) + .Single(u => u.Type == OperationTypes.ChainedInvoke && u.Action == Amazon.Lambda.OperationAction.START) + .ChainedInvokeOptions.XAmznTraceId; + + [Fact] + public async Task ChainedInvoke_SendsThePluginsTraceHeader_AndDescribesTheCall() + { + var plugin = new ConfigurablePlugin { Propagate = _ => "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1" }; + var client = new MockLambdaClient(); + + var output = await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.InvokeAsync("other-function", "payload", name: "call"), + Input(), Context(), client, Options(plugin)); + + Assert.Equal(InvocationStatus.Pending, output.Status); + Assert.Equal("Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1", TraceHeaderSent(client)); + + var request = Assert.Single(plugin.PropagationRequests); + Assert.Equal(Arn, request.ExecutionArn); + Assert.Equal(IdAt(1), request.OperationId); + Assert.Equal("other-function", request.TargetFunctionName); + Assert.Null(request.ParentOperationId); + } + + [Fact] + public async Task ChainedInvoke_InsideAChildContext_ReportsTheParentOperation() + { + var plugin = new ConfigurablePlugin { Propagate = _ => "Root=1-a" }; + + await DurableFunction.WrapAsync( + (_, ctx) => ctx.RunInChildContextAsync( + async (child, _) => await child.InvokeAsync("other", "p"), name: "outer"), + Input(), Context(), new MockLambdaClient(), Options(plugin)); + + Assert.Equal(IdAt(1), Assert.Single(plugin.PropagationRequests).ParentOperationId); + } + + [Fact] + public async Task ChainedInvoke_WithoutAContribution_OmitsTheHeader() + { + var plugin = new ConfigurablePlugin { Propagate = _ => null }; + var client = new MockLambdaClient(); + + await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.InvokeAsync("other", "p"), + Input(), Context(), client, Options(plugin)); + + Assert.Null(TraceHeaderSent(client)); + } + + [Fact] + public async Task ChainedInvoke_WithoutPlugins_SendsNoHeader() + { + var client = new MockLambdaClient(); + + await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.InvokeAsync("other", "p"), + Input(), Context(), client, Options(null)); + + Assert.Null(TraceHeaderSent(client)); + } + + [Fact] + public async Task ChainedInvoke_ThatThrowsFromThePlugin_StillStartsTheInvoke() + { + var plugin = new ConfigurablePlugin { Propagate = _ => throw new InvalidOperationException("boom") }; + var client = new MockLambdaClient(); + + var output = await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.InvokeAsync("other", "p"), + Input(), Context(), client, Options(plugin)); + + Assert.Equal(InvocationStatus.Pending, output.Status); + Assert.Null(TraceHeaderSent(client)); + } + + [Fact] + public async Task ChainedInvoke_AlreadyStarted_DoesNotAskThePluginAgain() + { + var plugin = new ConfigurablePlugin { Propagate = _ => "Root=1-a" }; + var started = new Operation + { + Id = IdAt(1), Type = OperationTypes.ChainedInvoke, Name = "call", Status = OperationStatuses.Started, + }; + + await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.InvokeAsync("other", "p", name: "call"), + Input(started), Context(), new MockLambdaClient(), Options(plugin)); + + Assert.Empty(plugin.PropagationRequests); + } +} From 5d6f37212680a4bc6b4c2bbf3c7119a857be7315 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 04:28:14 +0000 Subject: [PATCH 5/9] Report operation changes to plugins and run plugins in the Testing runner Operations that a checkpoint response adds or whose status it changes (a callback completed by an external system, a timer that fired) are reported through OnOperationChange with a snapshot of every known operation. A response that repeats a known status reports nothing. TestRunnerOptions.ExecutionOptions passes DurableExecutionOptions to every invocation of a local test run so plugins can be tested end to end. --- .../ExecutionOrchestrator.cs | 9 +- .../TestRunnerOptions.cs | 7 + .../DurableFunction.cs | 23 ++- .../Internal/ExecutionState.cs | 21 +++ .../PluginTests.cs | 80 ++++++++++ .../OperationChangePluginTests.cs | 145 ++++++++++++++++++ 6 files changed, 282 insertions(+), 3 deletions(-) create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/PluginTests.cs create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationChangePluginTests.cs diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.Testing/ExecutionOrchestrator.cs b/Libraries/src/Amazon.Lambda.DurableExecution.Testing/ExecutionOrchestrator.cs index 71bb42d7d..13d17eb37 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution.Testing/ExecutionOrchestrator.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution.Testing/ExecutionOrchestrator.cs @@ -3,6 +3,7 @@ using System.Text; using Amazon.Lambda.Core; +using Amazon.Lambda.DurableExecution.Internal; using Amazon.Lambda.DurableExecution.Services; namespace Amazon.Lambda.DurableExecution.Testing; @@ -92,8 +93,12 @@ public async Task> DriveToTerminalAsync( var invocationInput = BuildInvocationInput(arn); - var output = await DurableFunction.WrapAsync( - _handler, invocationInput, _lambdaContext, _serviceClient); + var output = _options.ExecutionOptions == null + ? await DurableFunction.WrapAsync( + _handler, invocationInput, _lambdaContext, _serviceClient) + : await DurableFunction.WrapAsync( + _handler, invocationInput, _lambdaContext, _serviceClient, + new DurableInvocationOptions { Execution = _options.ExecutionOptions }); _invocationCount++; diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.Testing/TestRunnerOptions.cs b/Libraries/src/Amazon.Lambda.DurableExecution.Testing/TestRunnerOptions.cs index eed026958..952ff9e0a 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution.Testing/TestRunnerOptions.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution.Testing/TestRunnerOptions.cs @@ -68,4 +68,11 @@ public int MaxInvocations /// omit its token from the response, which suspends the invocation. Default: null. /// public Func? OmitCheckpointToken { get; init; } + + /// + /// Options passed to every invocation of the workflow, for example to run it with instrumentation plugins. + /// The in-memory service does not report UpdatedOperationIds, so plugins see no updated operations + /// at invocation start. Default: null. + /// + public DurableExecutionOptions? ExecutionOptions { get; init; } } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs b/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs index e921968d5..f7f581eca 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/DurableFunction.cs @@ -258,6 +258,25 @@ await plugins.InvocationEndAsync(CreateEndInfo( return output; } + /// + /// Merges the operations a checkpoint response returned and tells the plugins which of them changed. + /// Runs on the checkpoint worker, and plugin exceptions are contained by the runner. + /// + private static void MergeAndReportChanges( + IReadOnlyList newOperations, ExecutionState state, PluginRunner plugins, string executionArn) + { + var changed = state.AddOperationsReportingChanges(newOperations); + if (changed.Count == 0) + return; + + plugins.OperationChange(new OperationChangeInfo + { + ExecutionArn = executionArn, + UpdatedOperations = PluginInfoConverter.ToOperationMap(changed), + Operations = PluginInfoConverter.ToOperationMap(state.GetAllOperations()), + }); + } + private static InvocationEndInfo CreateEndInfo( DurableExecutionInvocationInput invocationInput, ILambdaContext lambdaContext, @@ -306,7 +325,9 @@ private static async Task RunInvocationAsync MergeAndReportChanges(newOperations, state, plugins, invocationInput.DurableExecutionArn), cancellationToken: ct), termination: terminationManager); diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs index 9408aba14..e6fe4113c 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/ExecutionState.cs @@ -92,6 +92,27 @@ public void AddOperations(IEnumerable operations) } } + /// + /// Merges operations from a checkpoint response and returns the ones that are new or whose status changed, + /// so plugins hear about a callback completing or a timer firing but not about a repeated record. + /// + public IReadOnlyList AddOperationsReportingChanges(IEnumerable operations) + { + lock (_lock) + { + var changed = new List(); + foreach (var op in operations) + { + if (op.Id == null) continue; + if (!_operations.TryGetValue(op.Id, out var previous) || previous.Status != op.Status) + changed.Add(op); + } + + AddOperationsLocked(operations); + return changed; + } + } + /// A point-in-time copy of every known operation, for plugin snapshots. public Operation[] GetAllOperations() { diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/PluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/PluginTests.cs new file mode 100644 index 000000000..55e2e5a7e --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Testing.Tests/PluginTests.cs @@ -0,0 +1,80 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.DurableExecution.Instrumentation; +using Amazon.Lambda.DurableExecution.Testing; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Testing.Tests; + +public class PluginTests +{ + private sealed class Recorder : IDurableInstrumentationPlugin + { + private readonly List _events; + public Recorder(List events) => _events = events; + + public void OnInvocationStart(InvocationInfo info) { lock (_events) _events.Add($"start first={info.IsFirstInvocation}"); } + public Task OnInvocationEndAsync(InvocationEndInfo info, CancellationToken ct) + { + lock (_events) _events.Add($"end {info.Status}"); + return Task.CompletedTask; + } + public void OnOperationEnd(OperationEndInfo info) { lock (_events) _events.Add($"op {info.Name} replay={info.IsReplay}"); } + } + + private sealed class RecorderFactory : IDurableInstrumentationPluginFactory + { + private readonly List _events; + public int Created; + public RecorderFactory(List events) => _events = events; + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) + { + Interlocked.Increment(ref Created); + return new Recorder(_events); + } + } + + [Fact] + public async Task ExecutionOptions_RunPluginsOnEveryInvocationOfTheRun() + { + var events = new List(); + var factory = new RecorderFactory(events); + var options = new DurableExecutionOptions(); + options.Plugins.Add(factory); + + await using var runner = new DurableTestRunner( + 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"; + }, + new TestRunnerOptions { ExecutionOptions = options }); + + var result = await runner.RunAsync("in"); + + result.EnsureSucceeded(); + Assert.Equal(2, result.InvocationCount); + Assert.Equal(2, factory.Created); + Assert.Equal( + string.Join(" | ", new[] + { + "start first=True", "op first replay=False", "end Pending", + "start first=False", "op first replay=True", "op pause replay=True", "op second replay=False", "end Succeeded", + }), + string.Join(" | ", events)); + } + + [Fact] + public async Task WithoutExecutionOptions_NoPluginRuns() + { + await using var runner = new DurableTestRunner( + async (_, ctx) => await ctx.StepAsync((_, _) => Task.FromResult("a"), name: "only")); + + var result = await runner.RunAsync("in"); + + result.EnsureSucceeded(); + } +} diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationChangePluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationChangePluginTests.cs new file mode 100644 index 000000000..04be7d43b --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationChangePluginTests.cs @@ -0,0 +1,145 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.DurableExecution.Instrumentation; +using Amazon.Lambda.Serialization.SystemTextJson; +using Amazon.Lambda.TestUtilities; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Tests; + +/// from checkpoint responses. +public class OperationChangePluginTests +{ + private const string Arn = "arn:aws:lambda:us-east-1:123:durable-execution:change-test"; + + private sealed class ChangeRecorder : IDurableInstrumentationPlugin + { + public readonly List Changes = new(); + public void OnOperationChange(OperationChangeInfo info) { lock (Changes) Changes.Add(info); } + } + + private sealed class ThrowingChangePlugin : IDurableInstrumentationPlugin + { + public void OnOperationChange(OperationChangeInfo info) => throw new InvalidOperationException("boom"); + } + + private sealed class Factory : IDurableInstrumentationPluginFactory + { + private readonly IDurableInstrumentationPlugin _plugin; + public Factory(IDurableInstrumentationPlugin plugin) => _plugin = plugin; + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => _plugin; + } + + private static DurableExecutionInvocationInput Input() => new() + { + DurableExecutionArn = Arn, + InitialExecutionState = new InitialExecutionState + { + Operations = new List + { + new() + { + Id = "exec-0", Type = OperationTypes.Execution, Status = OperationStatuses.Started, + ExecutionDetails = new ExecutionDetails { InputPayload = "\"in\"" }, + }, + }, + }, + }; + + /// + /// A service that answers every checkpoint with all the callbacks started so far, the way a response that + /// repeats earlier records would look. + /// + private static MockLambdaClient ServiceEchoingStartedCallbacks() + { + var known = new List(); + return new MockLambdaClient + { + CheckpointHandler = req => + { + foreach (var u in req.Updates) + { + if (u.Type == OperationTypes.Callback && u.Action == "START") + { + known.Add(new Amazon.Lambda.Model.Operation + { + Id = u.Id, Type = OperationTypes.Callback, Status = OperationStatuses.Started, Name = u.Name, + CallbackDetails = new Amazon.Lambda.Model.CallbackDetails { CallbackId = "cb-" + u.Name }, + }); + } + } + return new Amazon.Lambda.Model.CheckpointDurableExecutionResponse + { + NewExecutionState = known.Count == 0 + ? null + : new Amazon.Lambda.Model.CheckpointUpdatedExecutionState { Operations = new List(known) }, + }; + }, + }; + } + + private static Task RunWithTwoCallbacks(IDurableInstrumentationPlugin plugin, MockLambdaClient client) + { + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(plugin)); + return DurableFunction.WrapAsync( + async (_, ctx) => + { + var first = await ctx.CreateCallbackAsync(name: "first"); + var second = await ctx.CreateCallbackAsync(name: "second"); + return await first.GetResultAsync() + await second.GetResultAsync(); + }, + Input(), new TestLambdaContext { Serializer = new DefaultLambdaJsonSerializer() }, client, options); + } + + [Fact] + public async Task NewOperationFromACheckpointResponse_IsReported_WithASnapshotOfEverything() + { + var recorder = new ChangeRecorder(); + + await RunWithTwoCallbacks(recorder, ServiceEchoingStartedCallbacks()); + + var first = recorder.Changes[0]; + Assert.Equal(Arn, first.ExecutionArn); + var updated = Assert.Single(first.UpdatedOperations).Value; + Assert.Equal(OperationTypes.Callback, updated.Type); + Assert.Equal("first", updated.Name); + Assert.Equal(OperationStatuses.Started, updated.Status); + Assert.Contains(first.Operations.Values, o => o.Type == OperationTypes.Execution); + } + + [Fact] + public async Task ResponseThatRepeatsAKnownStatus_IsNotReportedAgain() + { + var recorder = new ChangeRecorder(); + + await RunWithTwoCallbacks(recorder, ServiceEchoingStartedCallbacks()); + + // The second response repeats "first" unchanged and adds "second": only "second" is a change. + Assert.Equal(2, recorder.Changes.Count); + Assert.Equal("second", Assert.Single(recorder.Changes[1].UpdatedOperations).Value.Name); + } + + [Fact] + public async Task NoNewOperations_ReportsNothing() + { + var recorder = new ChangeRecorder(); + var options = new DurableExecutionOptions(); + options.Plugins.Add(new Factory(recorder)); + + await DurableFunction.WrapAsync( + async (_, ctx) => await ctx.StepAsync((_, _) => Task.FromResult("x"), name: "s"), + Input(), new TestLambdaContext { Serializer = new DefaultLambdaJsonSerializer() }, new MockLambdaClient(), options); + + Assert.Empty(recorder.Changes); + } + + [Fact] + public async Task ThrowingPlugin_DoesNotBreakTheCheckpointOrTheWorkflow() + { + var output = await RunWithTwoCallbacks(new ThrowingChangePlugin(), ServiceEchoingStartedCallbacks()); + + Assert.Equal(InvocationStatus.Pending, output.Status); + } +} From 73b4ded431289d35566df6f6be40d4b0f1a14b3f Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 04:37:11 +0000 Subject: [PATCH 6/9] Fix plugin attempt numbers, callback end and missing service timestamps Found by running a plugin against real durable executions in us-west-2. - StepDetails.Attempt counts finished attempts. A finished step record already holds the number of its last attempt (SUCCEEDED on the second try reports 2), while a ready or pending one is on the attempt after it. The attempt number was one too high on finished records. - A callback is registered long before it finishes. Its operation now ends when the result is read (replayed from history, failed or timed out), not when CreateCallbackAsync returns the handle. - StartTimestamp and EndTimestamp were not copied from checkpoint responses and state pages, so operations that finished in the current invocation had no service timestamps. They are mapped now. --- .../Internal/CallbackOperation.cs | 29 +++++++- .../Internal/DurableOperation.cs | 16 ++++- .../Internal/PluginInfoConverter.cs | 15 ++-- .../Services/LambdaDurableServiceClient.cs | 5 ++ .../DurableFunctionPluginTests.cs | 2 +- .../OperationPluginTests.cs | 62 +++++++++++++++++ .../PluginInfoConverterTests.cs | 69 +++++++++++++++++++ 7 files changed, 189 insertions(+), 9 deletions(-) create mode 100644 Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginInfoConverterTests.cs diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs index dc5031f22..5de0aa76c 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/CallbackOperation.cs @@ -86,6 +86,12 @@ public CallbackOperation( protected override string? OperationSubType => _subType; + // The handle is returned as soon as the callback is registered. The operation ends when its result is read. + protected override bool EndsWhenExecuteReturns => false; + + private int _endReported; + private bool _terminalFromHistory; + /// /// Set when an existing terminal-state checkpoint was observed during /// dispatch. reads this directly to short- @@ -149,6 +155,7 @@ protected override Task> ReplayAsync(Operation existing, Cancellati } _callbackId = callbackId; + _terminalFromHistory = IsTerminalStatus(existing.Status); // CRITICAL: we must NOT raise on terminal state here. // CreateCallbackAsync always returns the ICallback handle so any user @@ -185,7 +192,7 @@ public async Task GetResultAsync(CancellationToken cancellationToken = defaul // (or throw) immediately without suspending. if (_terminalReplay != null) { - return ResolveTerminal(_terminalReplay); + return ResolveAndReport(_terminalReplay, isReplay: _terminalFromHistory); } // A later checkpoint in this same invocation (e.g. WaitForCallback's @@ -195,7 +202,7 @@ public async Task GetResultAsync(CancellationToken cancellationToken = defaul var current = State.GetOperation(OperationId); if (IsTerminalStatus(current?.Status)) { - return ResolveTerminal(current!); + return ResolveAndReport(current!, isReplay: false); } // No terminal state yet. Suspend the workflow; the service re-invokes @@ -205,6 +212,24 @@ public async Task GetResultAsync(CancellationToken cancellationToken = defaul $"callback:{Name ?? OperationId}"); } + /// Resolves the result and tells the plugins, once, that the operation ended. + private T ResolveAndReport(Operation op, bool isReplay) + { + try + { + var value = ResolveTerminal(op); + if (Interlocked.Exchange(ref _endReported, 1) == 0) + ReportEnd(OperationStatuses.Succeeded, isReplay, null); + return value; + } + catch (CallbackException ex) + { + if (Interlocked.Exchange(ref _endReported, 1) == 0) + ReportEnd(op.Status == OperationStatuses.TimedOut ? OperationStatuses.TimedOut : OperationStatuses.Failed, isReplay, ex); + throw; + } + } + private T ResolveTerminal(Operation op) { switch (op.Status) diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs index 53b9749f1..317bddedb 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs @@ -45,6 +45,12 @@ protected DurableOperation( /// The checkpoint sub-type, reported to instrumentation plugins. Null when the operation has none. protected virtual string? OperationSubType => null; + /// + /// Whether the operation is finished when returns. False for an operation that + /// hands back a handle and finishes later (a callback), which then calls itself. + /// + protected virtual bool EndsWhenExecuteReturns => true; + /// /// The plugins of this invocation, or null when none is registered. Set by whoever creates the operation, /// so the constructors stay unchanged. @@ -97,14 +103,20 @@ private async Task ExecuteWithPluginsAsync( } catch (Exception ex) when (IsOperationFailure(ex)) { - plugins.OperationEnd(CreateEndInfo(existing, isReplay, OperationStatuses.Failed, ex)); + if (EndsWhenExecuteReturns) + plugins.OperationEnd(CreateEndInfo(existing, isReplay, OperationStatuses.Failed, ex)); throw; } - plugins.OperationEnd(CreateEndInfo(existing, isReplay, OperationStatuses.Succeeded, null)); + if (EndsWhenExecuteReturns) + plugins.OperationEnd(CreateEndInfo(existing, isReplay, OperationStatuses.Succeeded, null)); return result; } + /// Reports that the operation reached a terminal state. For operations that finish after they return. + protected void ReportEnd(string status, bool isReplay, Exception? exception) => + Plugins?.OperationEnd(CreateEndInfo(null, isReplay, status, exception)); + private OperationEndInfo CreateEndInfo(Operation? existing, bool isReplay, string status, Exception? exception) { // The checkpoint response may have stamped the terminal record with the service's timestamps. diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs index 8a33fea14..50bb0ed87 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs @@ -61,11 +61,18 @@ internal static OperationEndInfo ToOperationEndInfo( }; /// - /// The 1-based number of the latest attempt of a step. The service records how many attempts came before - /// (StepDetails.Attempt), and the SDK numbers the next one from it. + /// The 1-based number of the latest attempt of a step. StepDetails.Attempt counts the attempts that + /// have finished, so a finished record already holds the number of its last attempt, and an unfinished one + /// (ready to retry, pending a retry, started) is on the attempt after them. /// - private static int? AttemptOf(string type, Operation? op) => - type == OperationTypes.Step ? (op?.StepDetails?.Attempt ?? 0) + 1 : null; + private static int? AttemptOf(string type, Operation? op) + { + if (type != OperationTypes.Step) + return null; + + var finished = op?.StepDetails?.Attempt ?? 0; + return op != null && IsTerminal(op.Status) ? Math.Max(finished, 1) : finished + 1; + } internal static IReadOnlyDictionary ToOperationMap(IEnumerable operations, ISet? onlyIds = null) { diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Services/LambdaDurableServiceClient.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Services/LambdaDurableServiceClient.cs index 818e95bd0..33b109e71 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Services/LambdaDurableServiceClient.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Services/LambdaDurableServiceClient.cs @@ -131,6 +131,9 @@ public LambdaDurableServiceClient(IAmazonLambda lambdaClient) return (operations, response.NextMarker); } + private static long? ToUnixMilliseconds(DateTime? value) => + value.HasValue ? new DateTimeOffset(value.Value, TimeSpan.Zero).ToUnixTimeMilliseconds() : null; + private static Operation MapFromSdkOperation(SdkOperation sdkOp) { return new Operation @@ -141,6 +144,8 @@ private static Operation MapFromSdkOperation(SdkOperation sdkOp) Name = sdkOp.Name, ParentId = sdkOp.ParentId, SubType = sdkOp.SubType, + StartTimestamp = ToUnixMilliseconds(sdkOp.StartTimestamp), + EndTimestamp = ToUnixMilliseconds(sdkOp.EndTimestamp), StepDetails = sdkOp.StepDetails != null ? new StepDetails { Result = sdkOp.StepDetails.Result, diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs index 402e5aee4..73d667c5d 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs @@ -182,7 +182,7 @@ await DurableFunction.WrapAsync( Assert.False(started.IsFirstInvocation); Assert.Equal(3, started.Operations.Count); Assert.Equal("first", started.Operations["a"].Name); - Assert.Equal(3, started.Operations["a"].Attempt); // one more than the 2 attempts the service recorded + Assert.Equal(2, started.Operations["a"].Attempt); // a finished step record already holds its last attempt number var updated = Assert.Single(started.UpdatedOperations); Assert.Equal("b", updated.Key); Assert.Equal(OperationTypes.Wait, updated.Value.Type); diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs index 0d49e381d..215bac994 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs @@ -337,6 +337,68 @@ await ctx.StepAsync((_, _) => Assert.Empty(recorder.OperationEnds); } + private static Operation CallbackRecord(string status, string? result = null, ErrorObject? error = null) => new() + { + Id = IdAt(1), Type = OperationTypes.Callback, Name = "approval", Status = status, + CallbackDetails = new CallbackDetails { CallbackId = "cb-1", Result = result, Error = error }, + }; + + [Fact] + public async Task Callback_WaitingForItsResult_HasStartedButNotEnded() + { + var recorder = new Recorder(); + + var output = await Run(recorder, async ctx => + { + var callback = await ctx.CreateCallbackAsync(name: "approval"); + return await callback.GetResultAsync(); + }, CallbackRecord(OperationStatuses.Started)); + + Assert.Equal(InvocationStatus.Pending, output.Status); + Assert.Equal(OperationTypes.Callback, Assert.Single(recorder.OperationStarts).Type); + Assert.Empty(recorder.OperationEnds); + } + + [Fact] + public async Task Callback_EndsWhenItsResultIsRead_NotWhenItIsCreated() + { + var recorder = new Recorder(); + + await Run(recorder, async ctx => + { + var callback = await ctx.CreateCallbackAsync(name: "approval"); + Assert.Empty(recorder.OperationEnds); // created, result not read yet + var first = await callback.GetResultAsync(); + await callback.GetResultAsync(); // reading again does not end it twice + return first; + }, CallbackRecord(OperationStatuses.Succeeded, result: "\"yes\"")); + + var end = Assert.Single(recorder.OperationEnds); + Assert.Equal(OperationStatuses.Succeeded, end.Status); + Assert.True(end.IsReplay); + } + + [Theory] + [InlineData(OperationStatuses.Failed, OperationStatuses.Failed)] + [InlineData(OperationStatuses.TimedOut, OperationStatuses.TimedOut)] + public async Task Callback_FailureOrTimeout_EndsWithThatStatusAndTheError(string recorded, string expected) + { + var recorder = new Recorder(); + var error = new ErrorObject { ErrorType = "Rejected", ErrorMessage = "no thanks" }; + + await Run(recorder, async ctx => + { + var callback = await ctx.CreateCallbackAsync(name: "approval"); + try { await callback.GetResultAsync(); } + catch (CallbackException) { } + return "handled"; + }, CallbackRecord(recorded, error: error)); + + var end = Assert.Single(recorder.OperationEnds); + Assert.Equal(expected, end.Status); + Assert.Equal("no thanks", end.Error!.ErrorMessage); + } + [Fact] public async Task NoPlugins_RunsWorkflowWithoutAnyHooks() { diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginInfoConverterTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginInfoConverterTests.cs new file mode 100644 index 000000000..b43f53262 --- /dev/null +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/PluginInfoConverterTests.cs @@ -0,0 +1,69 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.Lambda.DurableExecution.Internal; +using Amazon.Lambda.DurableExecution.Services; +using Xunit; + +namespace Amazon.Lambda.DurableExecution.Tests; + +public class PluginInfoConverterTests +{ + private static Operation Step(string status, int? attempt) => new() + { + Id = "op", Type = OperationTypes.Step, Status = status, + StepDetails = attempt == null ? null : new StepDetails { Attempt = attempt }, + }; + + // StepDetails.Attempt counts finished attempts. Values below were observed from the service: + // READY after one failure reports 1, and SUCCEEDED on the second attempt reports 2. + [Theory] + [InlineData(OperationStatuses.Ready, 1, 2)] + [InlineData(OperationStatuses.Pending, 1, 2)] + [InlineData(OperationStatuses.Started, null, 1)] + [InlineData(OperationStatuses.Succeeded, 1, 1)] + [InlineData(OperationStatuses.Succeeded, 2, 2)] + [InlineData(OperationStatuses.Failed, 3, 3)] + [InlineData(OperationStatuses.Succeeded, null, 1)] + public void Attempt_IsTheLatestAttemptNumber(string status, int? recorded, int expected) + { + var info = PluginInfoConverter.ToOperationInfo(Step(status, recorded)); + + Assert.Equal(expected, info.Attempt); + } + + [Fact] + public void Attempt_IsNullForOperationsThatDoNotRetry() + { + var wait = new Operation { Id = "w", Type = OperationTypes.Wait, Status = OperationStatuses.Succeeded }; + + Assert.Null(PluginInfoConverter.ToOperationInfo(wait).Attempt); + } + + [Fact] + public void ServiceTimestamps_AreCopiedFromCheckpointResponses() + { + var start = new DateTime(2026, 11, 17, 4, 30, 47, 505, DateTimeKind.Utc); + var end = start.AddSeconds(2); + var sdkOp = new Amazon.Lambda.Model.Operation + { + Id = "op", Type = "STEP", Status = "SUCCEEDED", StartTimestamp = start, EndTimestamp = end, + }; + + var mapped = LambdaDurableServiceClient.MapFromSdkOperationForTest(sdkOp); + + Assert.Equal(new DateTimeOffset(start).ToUnixTimeMilliseconds(), mapped.StartTimestamp); + Assert.Equal(new DateTimeOffset(end).ToUnixTimeMilliseconds(), mapped.EndTimestamp); + Assert.Equal(start, PluginInfoConverter.ToOperationInfo(mapped).StartTimestamp!.Value.UtcDateTime); + } + + [Fact] + public void MissingServiceTimestamps_StayNull() + { + var mapped = LambdaDurableServiceClient.MapFromSdkOperationForTest( + new Amazon.Lambda.Model.Operation { Id = "op", Type = "STEP", Status = "STARTED" }); + + Assert.Null(mapped.StartTimestamp); + Assert.Null(mapped.EndTimestamp); + } +} From 5119ca937fc4daac3a0be6de90e7aea8b3b339c2 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Tue, 17 Nov 2026 04:38:11 +0000 Subject: [PATCH 7/9] Document the instrumentation plugin API Adds a user guide for plugin authors (registration, hooks, guarantees, what the service reports, testing) and a design note with the decisions behind the hook contract. Links them from the README, the Testing README and CLAUDE.md, which lists the rules to keep when changing the plugin code. --- .../README.md | 1 + .../Amazon.Lambda.DurableExecution/CLAUDE.md | 17 ++++ .../Amazon.Lambda.DurableExecution/README.md | 1 + .../docs/core/instrumentation-plugins.md | 77 +++++++++++++++++++ .../design/instrumentation-plugin-hooks.md | 25 ++++++ 5 files changed, 121 insertions(+) create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md create mode 100644 Libraries/src/Amazon.Lambda.DurableExecution/docs/design/instrumentation-plugin-hooks.md diff --git a/Libraries/src/Amazon.Lambda.DurableExecution.Testing/README.md b/Libraries/src/Amazon.Lambda.DurableExecution.Testing/README.md index d6bd440ff..673190d2a 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution.Testing/README.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution.Testing/README.md @@ -179,6 +179,7 @@ Invoking an unregistered function throws `UnregisteredSiblingFunctionException`. | `LoggerFactory` | none | Optional logging during execution. | | `DurableExecutionArn` | synthetic test ARN | Override for tests that assert on the ARN. | | `OmitCheckpointToken` | none | Predicate over the 1-based checkpoint call number; when true, the response omits the token so the invocation suspends (`Pending`) and resumes in the next one. | +| `ExecutionOptions` | none | `DurableExecutionOptions` passed to every invocation, for example to run the workflow with instrumentation plugins. | ## Testing Against a Deployed Function diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/CLAUDE.md b/Libraries/src/Amazon.Lambda.DurableExecution/CLAUDE.md index febef270c..3ca51be55 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/CLAUDE.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution/CLAUDE.md @@ -135,6 +135,23 @@ String constants live in `OperationTypes` (STEP/WAIT/CALLBACK/CHAINED_INVOKE/CON `OperationSubTypes` (PascalCase finer classifier). Plural type names (`OperationTypes`, not `OperationType`) intentionally avoid collision with `AWSSDK.Lambda` model enums. +## Instrumentation plugins + +`Instrumentation/` holds the public plugin API and `Internal/PluginRunner.cs` dispatches to it (user guide: +`docs/core/instrumentation-plugins.md`, decisions: `docs/design/instrumentation-plugin-hooks.md`). Rules to keep when +touching it: + +- Operation and attempt hooks are synchronous and never awaited. Awaiting plugin work where no operation is + executing lets the invocation suspend early. Async plugin work belongs in `OnInvocationEndAsync`. +- A plugin must never fail the workflow: contain every hook exception, and keep `WrapAsync` running the user code + exactly once and letting its exception through. +- Operation start/end are reported in one place, `DurableOperation.ExecuteAsync`. An operation that hands back a + handle and finishes later (a callback) sets `EndsWhenExecuteReturns` to false and calls `ReportEnd` itself. + `IncrementalParallelOperation` is not a `DurableOperation` and reports its own start and end. +- With no plugin registered the `Plugins` reference is null and the original code path runs. Keep it that way. +- Plugins are passed to operations through the `Plugins` init property and to child contexts through + `DurableContext`, so operation constructors stay unchanged. + ## Conventions - **Programming model:** both the *executable* model (`Main` builds a `LambdaBootstrap` with a handler diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/README.md b/Libraries/src/Amazon.Lambda.DurableExecution/README.md index e2acd503b..3799667a0 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/README.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution/README.md @@ -22,6 +22,7 @@ Your handler delegates to `DurableFunction.WrapAsync`, which gives your workflow - `ctx.RunInChildContextAsync` — run an isolated child context with its own checkpoint log. ([docs](docs/core/child-contexts.md)) - `ctx.ParallelAsync` — run independent branches concurrently and aggregate their results. ([docs](docs/core/parallel.md)) - Every user `Func` receives a `CancellationToken` linking the caller's token with the SDK's workflow-shutdown signal. ([docs](docs/core/cancellation.md)) +- Instrumentation plugins observe the invocation and its operations, for tracing, metrics or audit. ([docs](docs/core/instrumentation-plugins.md)) ## Quick Start diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md b/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md new file mode 100644 index 000000000..ce53aea23 --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md @@ -0,0 +1,77 @@ +# Instrumentation plugins + +A plugin observes a durable execution and can run your workflow code inside its own context. Use one to emit traces, metrics or audit records. The SDK knows nothing about what a plugin does with what it sees. + +## Register a plugin + +A plugin is registered through a factory. The SDK asks the factory for a new plugin at the start of every invocation, so a plugin can keep per-invocation state in ordinary fields, and concurrent invocations on Lambda Managed Instances never share one. + +```csharp +public sealed class AuditPlugin : IDurableInstrumentationPlugin +{ + public void OnOperationEnd(OperationEndInfo info) => + Console.WriteLine($"{info.Name}: {info.Status}"); +} + +public sealed class AuditPluginFactory : IDurableInstrumentationPluginFactory +{ + public IDurableInstrumentationPlugin? CreatePlugin(InvocationInfo info) => new AuditPlugin(); +} + +// Create the options once, for example in a static field, and reuse them. +static readonly DurableExecutionOptions Options = new() +{ + Plugins = { new AuditPluginFactory() }, +}; + +public Task Handler(DurableExecutionInvocationInput input, ILambdaContext context) + => DurableFunction.WrapAsync(Workflow, input, context, Options); +``` + +The factory holds what outlives an invocation, such as an exporter. `CreatePlugin` may return null to skip an invocation. Always return a new plugin; do not cache one. + +A factory can set `ExclusiveGroup`. Two registered factories with the same group throw `PluginLoadException` before any plugin is created, which is how a feature that must run only once (for example one tracing view) is enforced. + +## Hooks + +Every member of `IDurableInstrumentationPlugin` is optional. + +| Hook | When | +|---|---| +| `OnInvocationStart` | Once, before the workflow runs. `InvocationInfo` carries the request id, whether this is the first invocation, `XRayTraceId` (from `ILambdaContext.TraceId`), and the operations known so far and those the service reports as updated. | +| `OnInvocationEndAsync` | Last. Status is `Succeeded`, `Failed`, `Pending` (suspended), or `Retrying` (the invocation threw and Lambda will retry it). This is where to flush. | +| `OnOperationStart` / `OnOperationEnd` | When the workflow reaches an operation, and when it reaches a terminal state. `IsReplay` is true when the operation had already finished in history. An operation that suspends the invocation, or is cancelled, reports no end. A callback ends when its result is read. | +| `OnAttemptStart` / `OnAttemptEnd` | Around each execution of a step's function (and each wait-for-condition poll). The attempt number is 1-based. Cancellation is not an outcome. | +| `OnOperationChange` | A checkpoint response added operations or changed their status, for example a callback completed. | +| `WrapAsync` | Runs the invocation, a child context, or one attempt inside the plugin's own context. Use it to make an ambient value, such as `Activity.Current`, visible to user code. | +| `ProvidePropagationMetadata` | Before a new chained invoke is checkpointed. Return an `X-Amzn-Trace-Id` value for the invoked function, or null. Not called when the invoke is replayed. | +| `GetLogScope` | For every durable log entry. The returned fields are added to the entry's logging scope. | + +## Guarantees + +- **A plugin cannot fail the workflow.** An exception from a hook is logged and ignored. +- **A plugin cannot slow an operation.** The operation and attempt hooks are synchronous and the SDK never waits for work a plugin starts from them. A plugin that needs to finish something before the response returns does it in `OnInvocationEndAsync`. +- **`OnInvocationEndAsync` has a budget.** It is cancelled and abandoned shortly before the invocation's remaining time runs out. With several plugins they share that budget and run in reverse registration order. +- **`WrapAsync` always runs your code, once.** If a plugin throws before calling `next`, or never calls it, the code runs anyway. The exception from your code always reaches the caller unchanged, even if a plugin swallows it. The first registered plugin is the outermost. +- **Suspension is not unwinding.** When an invocation suspends, user code still running is abandoned and never completes, so code after `await next()` (including `finally` blocks) does not run for it. Do not rely on it to release anything. +- **Order.** Start hooks run in registration order. For nested operations the order is parent start, child start, child end, parent end. The order in which asynchronous work finishes is not defined. + +## What the service reports + +Verified against real executions: + +- `ILambdaContext.TraceId` is the same for every invocation of an execution, and the same as the `_X_AMZN_TRACE_ID` environment variable. It is per invocation, so use it, not the variable, on Lambda Managed Instances. +- `StepDetails.Attempt` counts finished attempts. A finished step already holds its last attempt number; a step that is ready to retry is on the attempt after it. `OperationInfo.Attempt` is the latest attempt number either way. +- Operations that finished in a previous invocation carry the service's start and end timestamps. Operations that start in the current invocation have no start timestamp until the service reports one, so a plugin reads its own clock when a timestamp is missing. +- The header returned from `ProvidePropagationMetadata` is sent to the invoked function as its trace header. + +## Testing a plugin + +Pass the options to the local test runner: + +```csharp +await using var runner = new DurableTestRunner( + Workflow, new TestRunnerOptions { ExecutionOptions = Options }); +``` + +The in-memory service does not report which operations were updated, so `InvocationInfo.UpdatedOperations` is empty there. diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/docs/design/instrumentation-plugin-hooks.md b/Libraries/src/Amazon.Lambda.DurableExecution/docs/design/instrumentation-plugin-hooks.md new file mode 100644 index 000000000..6337d6e9a --- /dev/null +++ b/Libraries/src/Amazon.Lambda.DurableExecution/docs/design/instrumentation-plugin-hooks.md @@ -0,0 +1,25 @@ +# Design note: instrumentation plugin hooks + +Status: accepted. User guide: [instrumentation-plugins.md](../core/instrumentation-plugins.md). + +## Context + +The Python, JavaScript and Java durable execution SDKs added OpenTelemetry support as a plugin built on a generic instrumentation API in the core SDK. This SDK follows the same split so the core knows nothing about tracing, and tracing (and anything else) can be added as a plugin. + +## Decisions + +1. **A factory creates one plugin per invocation.** Plugin state is per invocation, so concurrent invocations on Lambda Managed Instances cannot overwrite each other. Whatever outlives an invocation lives on the factory. +2. **Operation and attempt hooks are synchronous and never awaited.** The SDK decides to suspend an invocation from the state of its operations, and it cannot see work a plugin has started. Awaiting a hook on a path where no operation is executing lets the invocation suspend while the plugin is still working, so the code after that point does not run. The JS SDK hit this and documents it in its ADR 0001. Work that must finish before the response belongs in `OnInvocationEndAsync`, which is awaited once within the remaining invocation time. +3. **Context is applied by `WrapAsync`, not by start and end hooks.** `Activity.Current` is an `AsyncLocal`, so a value set in a hook does not reach the caller. A hook that wraps the user's `Func` is the only way to set it for the code that follows. The wrap takes a non-generic `Func` and the call site captures its own result, which avoids a generic virtual method on the interface. +4. **The SDK defends the workflow from plugins.** Every hook exception is contained. `WrapAsync` always runs the user code exactly once and always lets its exception through. +5. **The service's attempt count is normalized.** `StepDetails.Attempt` counts finished attempts, so a finished record already names its last attempt and an unfinished one is on the next. `OperationInfo.Attempt` hides that. +6. **A callback ends when its result is read.** `CreateCallbackAsync` returns a handle immediately, so the operation is not finished when the call returns. +7. **Trace propagation is a hook, not a feature.** The SDK collects a header from plugins and writes it to `ChainedInvokeOptions.XAmznTraceId`. Header format and meaning stay in the plugin. This needs `AWSSDK.Lambda` 4.0.110.1 or later. +8. **No reflection-based discovery.** Plugins are registered in code. The library is trimmable and AOT-safe, and loading plugins by name from an environment variable would need reflection. + +## Consequences + +- A plugin cannot rely on its asynchronous work finishing before the next operation runs. +- With no plugin registered the SDK takes its previous code path. +- An invocation whose end hook is cut off at the deadline may lose its last flush. +- The hook set is public API. A hook can be added later without breaking plugins (default interface methods); changing or removing one is a breaking change. From 4ddfe68666bc12a04faac055782ffdb2605c0477 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Wed, 18 Nov 2026 01:30:01 +0000 Subject: [PATCH 8/9] Report a resumed operation as a replay at start Found by tracing a real execution: a step that was retried reached OnOperationStart as a fresh start in the invocation that ran its second attempt, so a plugin that derives an id from the operation id used it twice. IsReplay on OperationStart is now true whenever the operation already has a checkpoint when the workflow reaches it, not only when it had finished. That covers a step resumed after a retry and a child context that suspended. On OperationEnd it still means the operation had already finished, so the resumed step's end is not a replay. --- .../Instrumentation/InstrumentationInfo.cs | 6 +++++- .../Internal/DurableOperation.cs | 6 ++++-- .../Internal/IncrementalParallelOperation.cs | 2 +- .../docs/core/instrumentation-plugins.md | 2 +- .../OperationPluginTests.cs | 8 ++++++-- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs index 1709062ef..014ec4ef6 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs @@ -108,7 +108,11 @@ public class OperationInfo /// The attempt number (1-based) for operations that retry, if applicable. public int? Attempt { get; init; } - /// True when the workflow reached this operation by replaying checkpointed history. + /// + /// In : true when the operation already has a + /// checkpoint, because it finished earlier or an earlier invocation started it (a step resumed after a retry). + /// In : true when it had already finished. + /// public bool IsReplay { get; init; } } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs index 317bddedb..c0c9cf479 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/DurableOperation.cs @@ -89,11 +89,13 @@ protected Task EnqueueAsync(SdkOperationUpdate update, CancellationToken cancell private async Task ExecuteWithPluginsAsync( PluginRunner plugins, Operation? existing, CancellationToken cancellationToken) { - // An operation is replayed when the workflow reaches it again after it already finished. + // The workflow reaches an operation that already has a checkpoint when it replays history, or resumes one + // that an earlier invocation started (a step after a retry, a child context that suspended). The end is a + // replay only when the operation had already finished. var isReplay = existing != null && PluginInfoConverter.IsTerminal(existing.Status); plugins.OperationStart(PluginInfoConverter.ToOperationInfo( - existing, OperationId, Name, OperationType, OperationSubType, ParentId, isReplay, + existing, OperationId, Name, OperationType, OperationSubType, ParentId, isReplay: existing != null, fallbackStatus: OperationStatuses.Started)); TResult result; diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs index 32501a517..8b59af4bd 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/IncrementalParallelOperation.cs @@ -448,7 +448,7 @@ public IncrementalParallelOperation( _plugins?.OperationStart(PluginInfoConverter.ToOperationInfo( existing, _operationId, _name, OperationTypes.Context, OperationSubTypes.Parallel, _parentId, - isReplay: existing != null && PluginInfoConverter.IsTerminal(existing.Status), + isReplay: existing != null, fallbackStatus: OperationStatuses.Started)); } diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md b/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md index ce53aea23..b551ec212 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md @@ -40,7 +40,7 @@ Every member of `IDurableInstrumentationPlugin` is optional. |---|---| | `OnInvocationStart` | Once, before the workflow runs. `InvocationInfo` carries the request id, whether this is the first invocation, `XRayTraceId` (from `ILambdaContext.TraceId`), and the operations known so far and those the service reports as updated. | | `OnInvocationEndAsync` | Last. Status is `Succeeded`, `Failed`, `Pending` (suspended), or `Retrying` (the invocation threw and Lambda will retry it). This is where to flush. | -| `OnOperationStart` / `OnOperationEnd` | When the workflow reaches an operation, and when it reaches a terminal state. `IsReplay` is true when the operation had already finished in history. An operation that suspends the invocation, or is cancelled, reports no end. A callback ends when its result is read. | +| `OnOperationStart` / `OnOperationEnd` | When the workflow reaches an operation, and when it reaches a terminal state. At start `IsReplay` is true when the operation already has a checkpoint (it finished, or an earlier invocation started it, as with a step resumed after a retry). At end it is true when the operation had already finished. An operation that suspends the invocation, or is cancelled, reports no end. A callback ends when its result is read. | | `OnAttemptStart` / `OnAttemptEnd` | Around each execution of a step's function (and each wait-for-condition poll). The attempt number is 1-based. Cancellation is not an outcome. | | `OnOperationChange` | A checkpoint response added operations or changed their status, for example a callback completed. | | `WrapAsync` | Runs the invocation, a child context, or one attempt inside the plugin's own context. Use it to make an ambient value, such as `Activity.Current`, visible to user code. | diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs index 215bac994..928155d7f 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/OperationPluginTests.cs @@ -171,8 +171,12 @@ public async Task Step_ResumedAfterRetry_ReportsTheSecondAttempt() await Run(recorder, ctx => ctx.StepAsync((_, _) => Task.FromResult("ok"), name: "flaky"), ready); Assert.Equal(2, Assert.Single(recorder.AttemptStarts).Attempt); - Assert.Equal(OperationStatuses.Succeeded, Assert.Single(recorder.OperationEnds).Status); - Assert.False(recorder.OperationStarts[0].IsReplay); + var end = Assert.Single(recorder.OperationEnds); + Assert.Equal(OperationStatuses.Succeeded, end.Status); + // The operation was started by an earlier invocation, so reaching it is a resume. It finishes now, so + // its end is not a replay. + Assert.True(recorder.OperationStarts[0].IsReplay); + Assert.False(end.IsReplay); } [Fact] From ed03d5836b87ab493ae091250876a32eb1d00282 Mon Sep 17 00:00:00 2001 From: Norm Johanson Date: Thu, 19 Nov 2026 00:05:16 +0000 Subject: [PATCH 9/9] Expose the W3C traceparent on InvocationInfo Read from ILambdaContext.W3C, which carries clientContext.w3c. Lets a plugin extract a W3C trace context the way it already can an X-Ray one. --- .../Instrumentation/InstrumentationInfo.cs | 6 ++++++ .../Internal/PluginInfoConverter.cs | 1 + .../docs/core/instrumentation-plugins.md | 2 +- .../DurableFunctionPluginTests.cs | 18 ++++++++++++++++++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs index 014ec4ef6..1a36005e7 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Instrumentation/InstrumentationInfo.cs @@ -24,6 +24,12 @@ public sealed class InvocationInfo /// public string? XRayTraceId { get; init; } + /// + /// The W3C traceparent of this invocation (ILambdaContext.W3C["traceparent"], carried on + /// clientContext.w3c), or null when the invoke carried none. + /// + public string? TraceParent { get; init; } + /// Every operation known at the start of the invocation, by operation id. public IReadOnlyDictionary Operations { get; init; } = EmptyOperations.Instance; diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs index 50bb0ed87..33f4696ca 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs +++ b/Libraries/src/Amazon.Lambda.DurableExecution/Internal/PluginInfoConverter.cs @@ -117,6 +117,7 @@ internal static InvocationInfo ToInvocationInfo( IsFirstInvocation = !hasHistory, ExecutionStartTimestamp = executionStart, XRayTraceId = ResolveTraceId(lambdaContext, isMultiConcurrency), + TraceParent = lambdaContext.W3C.TryGetValue("traceparent", out var traceParent) ? traceParent : null, Operations = ToOperationMap(operations), UpdatedOperations = updatedIds == null ? EmptyOperations.Instance diff --git a/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md b/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md index b551ec212..886469f1c 100644 --- a/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md +++ b/Libraries/src/Amazon.Lambda.DurableExecution/docs/core/instrumentation-plugins.md @@ -38,7 +38,7 @@ Every member of `IDurableInstrumentationPlugin` is optional. | Hook | When | |---|---| -| `OnInvocationStart` | Once, before the workflow runs. `InvocationInfo` carries the request id, whether this is the first invocation, `XRayTraceId` (from `ILambdaContext.TraceId`), and the operations known so far and those the service reports as updated. | +| `OnInvocationStart` | Once, before the workflow runs. `InvocationInfo` carries the request id, whether this is the first invocation, `XRayTraceId` (from `ILambdaContext.TraceId`), `TraceParent` (the W3C `traceparent` from `ILambdaContext.W3C`, if the invoke carried one), and the operations known so far and those the service reports as updated. | | `OnInvocationEndAsync` | Last. Status is `Succeeded`, `Failed`, `Pending` (suspended), or `Retrying` (the invocation threw and Lambda will retry it). This is where to flush. | | `OnOperationStart` / `OnOperationEnd` | When the workflow reaches an operation, and when it reaches a terminal state. At start `IsReplay` is true when the operation already has a checkpoint (it finished, or an earlier invocation started it, as with a step resumed after a retry). At end it is true when the operation had already finished. An operation that suspends the invocation, or is cancelled, reports no end. A callback ends when its result is read. | | `OnAttemptStart` / `OnAttemptEnd` | Around each execution of a step's function (and each wait-for-condition poll). The attempt number is 1-based. Cancellation is not an outcome. | diff --git a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs index 73d667c5d..aed31f873 100644 --- a/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs +++ b/Libraries/test/Amazon.Lambda.DurableExecution.Tests/DurableFunctionPluginTests.cs @@ -119,6 +119,24 @@ public async Task Succeeded_ReportsStartWrapAndEnd_InOrder() Assert.Null(recorder.Ended.Error); } + [Fact] + public async Task InvocationInfo_CarriesTheW3CTraceParent_WhenTheInvokeHasOne() + { + const string traceParent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + var withHeader = new Recorder(); + var context = Context(); + context.W3CFields = new Dictionary { ["traceparent"] = traceParent }; + await DurableFunction.WrapAsync( + (input, ctx) => Task.FromResult(input), Input(), context, new MockLambdaClient(), Options(withHeader)); + + var without = new Recorder(); + await DurableFunction.WrapAsync( + (input, ctx) => Task.FromResult(input), Input(), Context(), new MockLambdaClient(), Options(without)); + + Assert.Equal(traceParent, withHeader.Started!.TraceParent); + Assert.Null(without.Started!.TraceParent); + } + [Fact] public async Task WorkflowFailure_EndsAsFailed_WithTheError() {