Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .autover/changes/durable-parallel-branch-result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Projects": [
{
"Name": "Amazon.Lambda.DurableExecution",
"Type": "Patch",
"ChangelogMessages": [
"Fix a durable execution failing with \"Invalid checkpoint token\" on every retry when the branches of a parallel operation completed in different invocations."
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
<PropertyGroup>
<_DurableUserAgentVersionFile>$(IntermediateOutputPath)DurableUserAgentVersion.g.cs</_DurableUserAgentVersionFile>
</PropertyGroup>
<WriteLinesToFile File="$(_DurableUserAgentVersionFile)" Lines="namespace Amazon.Lambda.DurableExecution.Internal { internal static partial class DurableUserAgent { internal const string AssemblyVersion = &quot;$(Version)&quot;%3B } }" Overwrite="true" />
<WriteLinesToFile File="$(_DurableUserAgentVersionFile)" Lines="namespace Amazon.Lambda.DurableExecution.Internal { internal static partial class DurableUserAgent { internal const string AssemblyVersion = &quot;$(Version)&quot;%3B } }" Overwrite="true" WriteOnlyWhenDifferent="true" />
<ItemGroup>
<Compile Include="$(_DurableUserAgentVersionFile)" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,10 @@ protected override Task<T> ReplayAsync(Operation existing, CancellationToken can
return ExecuteFuncNoCheckpoint(cancellationToken);
}
// Side-effecting code runs at most once: replay returns the
// cached result without invoking the user func.
// cached result without invoking the user func. The payload is
// exposed as on a fresh success, so a parent that completes in a
// later invocation than this child still inlines the child's result.
SerializedResultPayload = existing.ContextDetails?.Result;
return Task.FromResult(DeserializeResult(existing.ContextDetails?.Result));

case OperationStatuses.Failed:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -736,13 +736,13 @@ private async Task EnsureAllFunctionsPublishedAsync()
Projects="@(FunctionProject)"
Targets="Restore"
BuildInParallel="false"
Properties="Configuration=Release;RuntimeIdentifier=linux-x64;SelfContained=false" />
Properties="Configuration=Release;RuntimeIdentifier=linux-x64;SelfContained=false;GenerateRuntimeConfigurationFiles=true" />
<!-- Then publish in parallel; restore is already done so no shared-output race. -->
<MSBuild
Projects="@(FunctionProject)"
Targets="Publish"
BuildInParallel="true"
Properties="Configuration=Release;RuntimeIdentifier=linux-x64;SelfContained=false;PublishDir=bin\publish\" />
Properties="Configuration=Release;RuntimeIdentifier=linux-x64;SelfContained=false;GenerateRuntimeConfigurationFiles=true;PublishDir=bin\publish\" />
</Target>
</Project>
""";
Expand Down Expand Up @@ -783,6 +783,12 @@ private async Task RunProcess(string fileName, string arguments, string workingD
UseShellExecute = false
};

// MSBuild worker nodes and build servers started by the child outlive it and inherit the
// redirected stdout/stderr pipes. Reading those streams to the end below would then block
// for the ~15 minute idle lifetime of the nodes, so make them exit with the build.
psi.Environment["MSBUILDDISABLENODEREUSE"] = "1";
psi.Environment["DOTNET_CLI_USE_MSBUILD_SERVER"] = "0";

var process = System.Diagnostics.Process.Start(psi)!;

if (stdin != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,30 @@ public async Task CreateParallel_ReplaySucceeded_CorruptSummary_RecoversFromChil
Assert.Empty(recorder.Flushed); // terminal parent → no re-checkpoint
}

[Fact]
public async Task ParentSummary_IncludesResultOfBranchCompletedInEarlierInvocation()
{
var parentOpId = IdAt(1);
var (context, recorder, _, _) = CreateContext(new InitialExecutionState
{
Operations = new List<Operation>
{
new() { Id = parentOpId, Type = OperationTypes.Context, Status = OperationStatuses.Started },
new() { Id = ChildIdAt(parentOpId, 1), Type = OperationTypes.Context, Status = OperationStatuses.Succeeded,
Name = "a", ContextDetails = new ContextDetails { Result = "1" } }
}
});

await using (var parallel = context.CreateParallel())
{
Assert.Equal(1, await parallel.Branch("a", (_, _) => Task.FromResult(-1)));
}
await recorder.Batcher.DrainAsync();

var parentSucceed = Assert.Single(recorder.Flushed, o => o.Id == parentOpId && o.Action == "SUCCEED");
Assert.Equal("1", BatchSummaryCodec.ParseSummary(parentSucceed.Payload)!.Units[0].Result);
}

/// <summary>
/// A serializer whose context-aware (durable) Serialize always throws, used to prove a
/// serialization failure fails the branch terminally instead of completing the handle.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,10 @@ private async Task WaitForEndpointAsync()
{
try
{
// Only a successful response means the endpoint is serving. API Gateway returns
// other errors (not just 500) while a new deployment is still propagating.
var response = await httpClient.GetAsync(_apiUrl);
if (response.StatusCode != HttpStatusCode.InternalServerError)
if (response.StatusCode == HttpStatusCode.OK)
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ namespace Amazon.Lambda.RuntimeSupport.UnitTests
// structured-logging callback target. That is the same static state the StructuredLogging collection guards, so this
// class must run serially with those tests to avoid overwriting each other's callback registration. See
// https://github.com/aws/aws-lambda-dotnet/issues/2350.
[Collection("StructuredLogging")]
[Collection("RuntimeSupportStateCheck")]
public class LambdaBootstrapMultiConcurrencyTests
{
JsonSerializer _serializer = new JsonSerializer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ namespace Amazon.Lambda.RuntimeSupport.UnitTests
/// Without both changes, blocking handlers (Thread.Sleep, .Result, .Wait()) exhaust the
/// ThreadPool, preventing polling tasks from cycling back to /next.
/// </summary>
[Collection("RuntimeSupportStateCheck")]
public class LambdaBootstrapMultiConcurrencyThreadPoolStarvationTests
{
private readonly JsonSerializer _serializer = new JsonSerializer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ namespace Amazon.Lambda.RuntimeSupport.UnitTests
/// <see cref="LambdaBootstrapBuilder"/> is exposed on the per-invocation
/// <see cref="ILambdaContext.Serializer"/> via <see cref="LambdaContext"/>.
/// </summary>
[Collection("RuntimeSupportStateCheck")]
public class LambdaContextSerializerTests
{
private static readonly JsonSerializer SharedSerializer = new JsonSerializer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace Amazon.Lambda.RuntimeSupport.UnitTests
{
[Collection("StructuredLogging")]
[Collection("RuntimeSupportStateCheck")]
public class LogMessageFormatterTests
{
[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ namespace Amazon.Lambda.RuntimeSupport.UnitTests
/// share a single formatter instance.
///
/// The test injects an IEnvironmentVariables so it never mutates the process-wide AWS_LAMBDA_LOG_FORMAT (which
/// would race with other tests). It is placed in the serial "StructuredLogging" collection because
/// would race with other tests). It is placed in the serial "RuntimeSupportStateCheck" collection because
/// ConfigureStructuredLogging mutates a process-wide static on LambdaLogger.
/// </summary>
[Collection("StructuredLogging")]
[Collection("RuntimeSupportStateCheck")]
public class SharedFormatterStructuredLoggingTests
{
/// <summary>A value type that serializes to "{}" under default options (mirrors NodaTime.Instant).</summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using static Amazon.Lambda.RuntimeSupport.Bootstrap.Constants;

namespace Amazon.Lambda.RuntimeSupport.UnitTests;
[Collection("RuntimeSupportStateCheck")]
public class SnapstartTests
{
readonly TestHandler _testFunction;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,16 @@

namespace Amazon.Lambda.RuntimeSupport.UnitTests
{
[CollectionDefinition("RuntimeSupportStateCheck")]
/// <summary>
/// Serializes every test class that mutates process-wide state on <c>Amazon.Lambda.Core.LambdaLogger</c>.
/// Constructing a <c>LogLevelLoggerWriter</c> (which every test runtime API client does) or calling
/// <c>LambdaLogger.ConfigureStructuredLogging</c> replaces LambdaLogger's static logging callbacks, so the
/// last one constructed wins. Tests that assert on captured log output fail intermittently if another
/// class replaces the callbacks in parallel, so all such classes must be in this single collection.
/// Parallelization is disabled so the collection also never runs alongside classes outside it,
/// some of which construct a <c>LogLevelLoggerWriter</c> as well.
/// </summary>
[CollectionDefinition("RuntimeSupportStateCheck", DisableParallelization = true)]
public class RuntimeSupportStateCheckCollection { }

/// <summary>
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ public static async Task RunAsync(string command, string workingDirectory = "",
WorkingDirectory = workingDirectory
};

// Build commands run by the child (dotnet restore, dotnet lambda deploy-serverless) can leave
// MSBuild worker nodes and build servers running after the command exits. Those processes
// inherit the redirected stdout/stderr pipes, and WaitForExitAsync does not return until the
// pipes close, so the caller would block for the ~15 minute idle lifetime of the nodes.
processStartInfo.Environment["MSBUILDDISABLENODEREUSE"] = "1";
processStartInfo.Environment["DOTNET_CLI_USE_MSBUILD_SERVER"] = "0";

var process = Process.Start(processStartInfo);
if (null == process)
throw new Exception("Process.Start failed to return a non-null process");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ try
{
throw "Failed to create the following bucket: $identifier"
}
dotnet restore

# Deploy with retries. The stack contains many Lambda functions that each reference
# an IAM role created in the same stack. CloudFormation occasionally calls Lambda
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ try
throw "Failed to create the following bucket: $identifier"
}

dotnet restore
Write-Host "Creating CloudFormation Stack $identifier"
dotnet lambda deploy-serverless
if (!$?)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ try
throw "Failed to create the following bucket: $identifier"
}

dotnet restore
Write-Host "Creating CloudFormation Stack $identifier, Architecture $arch"
dotnet lambda deploy-serverless
if (!$?)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ try
Write-Host "Added TestTable resource to serverless.template"
}

dotnet restore
Write-Host "Creating CloudFormation Stack $identifier, Architecture $arch, Runtime $runtime"
dotnet lambda deploy-serverless --template-parameters "ArchitectureTypeParameter=$arch"
if (!$?)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IntegrationTests.Helpers;
using Xunit;
using Xunit.Extensions.AssemblyFixture;

Expand All @@ -20,37 +21,40 @@ public SimpleCalculator(IntegrationTestContextFixture fixture)
[Fact]
public async Task Add_FromQuery_ReturnsIntAsString()
{
var response = await _fixture.HttpClient.GetAsync($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Add?x=2&y=4");
var response = await RetryHelper.SendWithRetryOnForbiddenAsync(_fixture.HttpClient,
() => new HttpRequestMessage(HttpMethod.Get, $"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Add?x=2&y=4"));
response.EnsureSuccessStatusCode();
Assert.Equal("6", await response.Content.ReadAsStringAsync());
}

[Fact]
public async Task Subtract_FromHeader_ReturnsIntAsString()
{
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Subtract"),
Headers = {{ "x", "10" }, {"y", "2"}}
};
var response = await _fixture.HttpClient.SendAsync(httpRequestMessage);
var response = await RetryHelper.SendWithRetryOnForbiddenAsync(_fixture.HttpClient,
() => new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Subtract"),
Headers = {{ "x", "10" }, {"y", "2"}}
});
response.EnsureSuccessStatusCode();
Assert.Equal("8", await response.Content.ReadAsStringAsync());
}

[Fact]
public async Task Multiply_FromPath_ReturnsIntAsString()
{
var response = await _fixture.HttpClient.GetAsync($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Multiply/2/10");
var response = await RetryHelper.SendWithRetryOnForbiddenAsync(_fixture.HttpClient,
() => new HttpRequestMessage(HttpMethod.Get, $"{_fixture.RestApiUrlPrefix}/SimpleCalculator/Multiply/2/10"));
response.EnsureSuccessStatusCode();
Assert.Equal("20", await response.Content.ReadAsStringAsync());
}

[Fact]
public async Task DivideAsync_FromPath_ReturnsIntAsString()
{
var response = await _fixture.HttpClient.GetAsync($"{_fixture.RestApiUrlPrefix}/SimpleCalculator/DivideAsync/50/5");
var response = await RetryHelper.SendWithRetryOnForbiddenAsync(_fixture.HttpClient,
() => new HttpRequestMessage(HttpMethod.Get, $"{_fixture.RestApiUrlPrefix}/SimpleCalculator/DivideAsync/50/5"));
response.EnsureSuccessStatusCode();
Assert.Equal("10", await response.Content.ReadAsStringAsync());
}
Expand Down
24 changes: 20 additions & 4 deletions buildtools/build.proj
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,25 @@
projects share no state and are run concurrently to cut the integ-test wall-clock time.
The helper script discovers projects by convention (*.IntegrationTests.csproj) so new
projects are picked up automatically, and exits non-zero if any project fails. -->
<Exec Command="pwsh -NoProfile -File &quot;$(MSBuildThisFileDirectory)run-integ-tests-parallel.ps1&quot; -Configuration $(Configuration)"/>
</Target>
<Target Name="create-nuget-packages-cicd" DependsOnTargets="build-project-packages">
<Exec Command="$(PackCommand)" WorkingDirectory="..\Libraries\src\%(LibraryName.FileName)"/>
<Exec Command="pwsh -NoProfile -File &quot;$(MSBuildThisFileDirectory)run-integ-tests-parallel.ps1&quot; -Configuration $(Configuration)" IgnoreStandardErrorWarningFormat="true"/>
</Target>
<!-- Builds and packs every library in one MSBuild session (this file re-invoked with -restore -m)
instead of one "dotnet msbuild" and one "dotnet pack" process per library. Each shared project
reference is then built once and independent libraries build in parallel. Used by the test
targets only; the release build keeps using build-project-packages. -->
<Target Name="create-nuget-packages-cicd">
<Exec Command="dotnet msbuild &quot;$(MSBuildThisFileFullPath)&quot; -restore -m -t:build-libraries -t:pack-libraries /p:Configuration=$(Configuration) /p:AssemblyOriginatorKeyFile=$(AssemblyOriginatorKeyFile) /p:SignAssembly=$(SignAssembly)"/>
</Target>
<!-- Run by the -restore switch above. Restores run one at a time because the libraries share
project references, and concurrent restores of the same project race on its obj folder. -->
<Target Name="Restore">
<MSBuild Projects="@(LibraryName)" Targets="Restore" BuildInParallel="false"/>
</Target>
<Target Name="build-libraries">
<MSBuild Projects="@(LibraryName)" Targets="Build" BuildInParallel="true"/>
</Target>
<!-- Equivalent of running $(PackCommand) in each library folder. -->
<Target Name="pack-libraries">
<MSBuild Projects="@(LibraryName)" Targets="Pack" BuildInParallel="true" Properties="NoBuild=true;_IsPacking=true;PackageOutputPath=$(MSBuildThisFileDirectory)/../Deployment/nuget-packages"/>
</Target>
</Project>
20 changes: 20 additions & 0 deletions buildtools/run-integ-tests-parallel.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ param(

$ErrorActionPreference = 'Stop'

# The tests start builds as child processes (deployment scripts, dotnet lambda, dotnet build) and wait
# for the child's redirected output to close. MSBuild worker nodes and build servers left running by
# those builds inherit the output pipes and keep them open for their ~15 minute idle lifetime, which
# stalled whichever test project happened to start them. Every process started from here inherits
# these settings, so no build in the integ test phase leaves such processes behind.
$env:MSBUILDDISABLENODEREUSE = '1'
$env:DOTNET_CLI_USE_MSBUILD_SERVER = '0'

$projects = Get-ChildItem -Path $TestRoot -Recurse -Filter "*.IntegrationTests.csproj" |
Select-Object -ExpandProperty FullName |
Sort-Object
Expand Down Expand Up @@ -47,6 +55,18 @@ foreach ($project in $projects)
}
}

# The deployments also build in parallel, and they share the libraries under Libraries/src. Publish
# the deployed apps once here, the way the deployments do, so the parallel builds leave the libraries alone.
foreach ($app in 'TestCustomAuthorizerApp', 'TestDurableServerlessApp', 'TestServerlessApp', 'TestServerlessApp.ALB')
{
dotnet publish -c $Configuration --os linux -p:GenerateRuntimeConfigurationFiles=true (Join-Path $TestRoot $app)
if ($LASTEXITCODE -ne 0)
{
Write-Host "Publish failed for $app (exit $LASTEXITCODE)."
exit 1
}
}

$results = $projects | ForEach-Object -ThrottleLimit $ThrottleLimit -Parallel {
$project = $_
$name = [System.IO.Path]::GetFileNameWithoutExtension($project)
Expand Down
Loading