diff --git a/.autover/changes/snapstart-trace-id-generator.json b/.autover/changes/snapstart-trace-id-generator.json
new file mode 100644
index 000000000..3323b41dd
--- /dev/null
+++ b/.autover/changes/snapstart-trace-id-generator.json
@@ -0,0 +1,11 @@
+{
+ "Projects": [
+ {
+ "Name": "Amazon.Lambda.RuntimeSupport",
+ "Type": "Patch",
+ "ChangelogMessages": [
+ "Set Activity.TraceIdGenerator to a cryptographically random generator after a SnapStart restore so restored execution environments don't repeat trace IDs. A generator set by the function during initialization is not replaced."
+ ]
+ }
+ ]
+}
diff --git a/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapStartTraceIdGenerator.cs b/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapStartTraceIdGenerator.cs
new file mode 100644
index 000000000..7726cdccb
--- /dev/null
+++ b/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapStartTraceIdGenerator.cs
@@ -0,0 +1,44 @@
+using System;
+using System.Diagnostics;
+using System.Security.Cryptography;
+
+namespace Amazon.Lambda.RuntimeSupport.Helpers
+{
+ ///
+ /// Trace ID generator used for SnapStart restored execution environments.
+ ///
+ ///
+ /// By default generates trace IDs from an in-memory, per-thread pseudo-random
+ /// generator. A SnapStart snapshot captures that generator's state, so every execution environment restored
+ /// from the same snapshot continues the same sequence and produces the same trace IDs. This generator reads
+ /// from the operating system's cryptographic random source instead, which Lambda reseeds after restore.
+ ///
+ internal static class SnapStartTraceIdGenerator
+ {
+ ///
+ /// Sets to the SnapStart safe generator, unless a generator is
+ /// already set. Leaving an existing generator in place keeps one the function set during initialization.
+ ///
+ /// True if the generator was set; false if a generator was already set.
+ internal static bool TrySetTraceIdGenerator()
+ {
+ if (Activity.TraceIdGenerator != null)
+ {
+ return false;
+ }
+
+ Activity.TraceIdGenerator = GenerateTraceId;
+ return true;
+ }
+
+ ///
+ /// Creates a trace ID from 16 cryptographically random bytes.
+ ///
+ internal static ActivityTraceId GenerateTraceId()
+ {
+ Span bytes = stackalloc byte[16];
+ RandomNumberGenerator.Fill(bytes);
+ return ActivityTraceId.CreateFromBytes(bytes);
+ }
+ }
+}
diff --git a/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapstartHelperInitializeWithSnapstartIsolatedAsync.cs b/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapstartHelperInitializeWithSnapstartIsolatedAsync.cs
index 83d343f76..cc1b53193 100644
--- a/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapstartHelperInitializeWithSnapstartIsolatedAsync.cs
+++ b/Libraries/src/Amazon.Lambda.RuntimeSupport/Helpers/SnapstartHelperInitializeWithSnapstartIsolatedAsync.cs
@@ -34,6 +34,15 @@ internal static async Task InitializeWithSnapstartAsync(IRuntimeApiClient
await client.ReportInitializationErrorAsync(ex, Constants.LAMBDA_ERROR_TYPE_BEFORE_SNAPSHOT);
return false;
}
+
+ // The snapshot copied Activity's in-memory trace ID generator state, so restored environments would
+ // repeat trace IDs. Switch to a generator backed by OS randomness before the function's after restore
+ // hooks run, so a hook can still replace it. A generator the function set during init is left as is.
+ if (SnapStartTraceIdGenerator.TrySetTraceIdGenerator())
+ {
+ logger.LogDebug("Set Activity.TraceIdGenerator to a SnapStart safe trace ID generator.");
+ }
+
try
{
await ((SnapshotRestore.Registry.RestoreHooksRegistry)restoreHooksRegistry).InvokeAfterRestoreCallbacks();
diff --git a/Libraries/test/Amazon.Lambda.RuntimeSupport.Tests/Amazon.Lambda.RuntimeSupport.UnitTests/SnapstartTests.cs b/Libraries/test/Amazon.Lambda.RuntimeSupport.Tests/Amazon.Lambda.RuntimeSupport.UnitTests/SnapstartTests.cs
index 430b51702..c892b5d71 100644
--- a/Libraries/test/Amazon.Lambda.RuntimeSupport.Tests/Amazon.Lambda.RuntimeSupport.UnitTests/SnapstartTests.cs
+++ b/Libraries/test/Amazon.Lambda.RuntimeSupport.Tests/Amazon.Lambda.RuntimeSupport.UnitTests/SnapstartTests.cs
@@ -1,12 +1,14 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Threading.Tasks;
+using Amazon.Lambda.RuntimeSupport.Helpers;
using Xunit;
using static Amazon.Lambda.RuntimeSupport.Bootstrap.Constants;
namespace Amazon.Lambda.RuntimeSupport.UnitTests;
[Collection("RuntimeSupportStateCheck")]
-public class SnapstartTests
+public class SnapstartTests : IDisposable
{
readonly TestHandler _testFunction;
readonly TestInitializer _testInitializer;
@@ -78,4 +80,51 @@ public async Task VerifyRestoreErrorIsCalledWhenExceptionInAfterRestoreCallables
Assert.True(_testRuntimeApiClient.ReportRestoreErrorAsyncCalled);
}
}
+
+ [Fact]
+ public async Task VerifyTraceIdGeneratorIsSetBeforeAfterRestoreCallbacks()
+ {
+ Activity.TraceIdGenerator = null;
+ Func generatorSeenByHook = null;
+ using var bootstrap =
+ new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeTrueAsync, configuration: new LambdaBootstrapConfiguration(false, true));
+ bootstrap.Client = _testRuntimeApiClient;
+ Core.SnapshotRestore.RegisterAfterRestore(() =>
+ {
+ generatorSeenByHook = Activity.TraceIdGenerator;
+ return ValueTask.CompletedTask;
+ });
+ await bootstrap.RunAsync(_testFunction.CancellationSource.Token);
+
+ Assert.Equal((Func)SnapStartTraceIdGenerator.GenerateTraceId, generatorSeenByHook);
+ }
+
+ [Fact]
+ public async Task VerifyTraceIdGeneratorSetDuringInitIsNotReplaced()
+ {
+ Func customGenerator = ActivityTraceId.CreateRandom;
+ Activity.TraceIdGenerator = customGenerator;
+ using var bootstrap =
+ new LambdaBootstrap(_testFunction.BaseHandlerAsync, _testInitializer.InitializeTrueAsync, configuration: new LambdaBootstrapConfiguration(false, true));
+ bootstrap.Client = _testRuntimeApiClient;
+ await bootstrap.RunAsync(_testFunction.CancellationSource.Token);
+
+ Assert.Same(customGenerator, Activity.TraceIdGenerator);
+ }
+
+ [Fact]
+ public void VerifyGeneratedTraceIdsAreUnique()
+ {
+ var first = SnapStartTraceIdGenerator.GenerateTraceId();
+ var second = SnapStartTraceIdGenerator.GenerateTraceId();
+
+ Assert.NotEqual(default, first);
+ Assert.NotEqual(first, second);
+ }
+
+ public void Dispose()
+ {
+ // Activity.TraceIdGenerator is process wide, so reset it for the tests that follow.
+ Activity.TraceIdGenerator = null;
+ }
}