From 51f88c7c88fdabc4cf0579bc2de4dcb551927314 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Thu, 24 Sep 2026 21:11:07 -0400 Subject: [PATCH 1/9] Fix remaining outerloop test failures LocalArchive E2E installs copied built packages into the local hive but left the CLI on its baked channel, so aspire add could not resolve the 14.0.0-ci AppHost SDK. DCP watches also inherited the one-minute non-streaming API timeout even though the Kubernetes client buffers their long-lived response body. The dashboard smooth-scroll test separately depended on observing an intermediate compositor frame that Windows headless Chromium can skip. Select the local hive after LocalArchive installs, keep watch requests alive until their periodic restart, and drive the scrollend contract deterministically in the Playwright test. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/Aspire.Hosting/Dcp/KubernetesService.cs | 9 ++++-- .../Helpers/CliE2EAutomatorHelpers.cs | 2 ++ .../NewChannelNuGetConfigTests.cs | 12 ++++++++ .../Playwright/DashboardInteractionsTests.cs | 27 +++++++++++++----- .../Helpers/DeploymentE2EAutomatorHelpers.cs | 1 + .../Dcp/KubernetesServiceTests.cs | 28 +++++++++++++++++++ 6 files changed, 69 insertions(+), 10 deletions(-) diff --git a/src/Aspire.Hosting/Dcp/KubernetesService.cs b/src/Aspire.Hosting/Dcp/KubernetesService.cs index 433575b050f..0f98da505a3 100644 --- a/src/Aspire.Hosting/Dcp/KubernetesService.cs +++ b/src/Aspire.Hosting/Dcp/KubernetesService.cs @@ -271,22 +271,25 @@ public Task DeleteAsync(string name, string? namespaceParameter = null, Ca return ExecuteWithRetry( DcpApiOperationType.Watch, T.ObjectKind, - async (kubernetes, operationCancellationToken) => + async (kubernetes, _) => { + // The Kubernetes client buffers the streaming response body while this task is awaited. + // A healthy watch therefore lives until the periodic restart instead of completing within + // the shorter API retry budget used by non-streaming requests. var responseTask = string.IsNullOrEmpty(namespaceParameter) ? kubernetes.CustomObjects.ListClusterCustomObjectWithHttpMessagesAsync( GroupVersion.Group, GroupVersion.Version, resourceType, watch: true, - cancellationToken: operationCancellationToken) + cancellationToken: restartCancellationToken) : kubernetes.CustomObjects.ListNamespacedCustomObjectWithHttpMessagesAsync( GroupVersion.Group, GroupVersion.Version, namespaceParameter, resourceType, watch: true, - cancellationToken: operationCancellationToken); + cancellationToken: restartCancellationToken); // KubernetesClient's lazy WatchAsync does not await the HTTP response until enumeration starts. await responseTask.ConfigureAwait(false); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs index 4893bab4710..0aadcb56377 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs @@ -141,6 +141,7 @@ await auto.RunCommandAsync( counter, TimeSpan.FromSeconds(120)); await auto.SourceAspireBundleEnvironmentAsync(counter); + await auto.ConfigureLocalHiveAsync(counter); break; case CliInstallMode.InstallScript: @@ -431,6 +432,7 @@ await auto.RunCommandAsync( counter, TimeSpan.FromSeconds(120)); await auto.SourceAspireCliEnvironmentAsync(counter); + await auto.ConfigureLocalHiveAsync(counter); break; case CliInstallMode.InstallScript: diff --git a/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs index 6fb860e8482..02b560f9cb4 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/NewChannelNuGetConfigTests.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Xml.Linq; using Aspire.Cli.EndToEnd.Tests.Helpers; using Hex1b.Automation; using Xunit; @@ -66,6 +67,17 @@ public async Task AspireNew_CreatesNuGetConfig_BasedOnChannel(string? channel, b { Assert.True(File.Exists(nugetConfigPath), $"Expected nuget.config to be created for channel '{channel ?? "(default)"}' at: {nugetConfigPath}"); + + if (channel is null && strategy.Mode is CliInstallMode.LocalArchive) + { + var packageSources = XDocument.Load(nugetConfigPath) + .Descendants("packageSources") + .Elements("add") + .Select(element => (string?)element.Attribute("value")) + .OfType(); + + Assert.Contains(packageSources, source => source.Replace('\\', '/').EndsWith("/hives/local/packages", StringComparison.Ordinal)); + } } else { diff --git a/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs b/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs index 05e96943082..499aa25b413 100644 --- a/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs +++ b/tests/Aspire.Dashboard.Tests/Integration/Playwright/DashboardInteractionsTests.cs @@ -242,15 +242,14 @@ await RunTestAsync(async page => var bottomButton = page.Locator(".scroll-to-bottom"); await Assertions.Expect(bottomButton).ToBeVisibleAsync(); + // Headless browsers can skip every intermediate compositor frame under load. Capture the native + // smooth-scroll request, then dispatch scrollend explicitly so the content-growth behavior is deterministic. await page.EvaluateAsync(""" () => { const region = document.getElementById('scroll-region'); - const initialBottom = region.scrollHeight - region.clientHeight; - window.__grewDuringScroll = false; - region.addEventListener('scroll', () => { - window.__grewDuringScroll = region.scrollTop > 0 && region.scrollTop < initialBottom; - region.querySelector('.scroll-content').style.height = '4000px'; - }, { once: true }); + region.scrollTo = options => { + window.__scrollToBottomRequest = options; + }; document.querySelector('.scroll-to-bottom').addEventListener('click', event => { window.__hiddenOnClick = event.currentTarget.hidden; }, { once: true }); @@ -259,10 +258,24 @@ await page.EvaluateAsync(""" await bottomButton.ClickAsync(); Assert.True(await page.EvaluateAsync("() => window.__hiddenOnClick")); + Assert.True(await page.EvaluateAsync(""" + () => { + const region = document.getElementById('scroll-region'); + return window.__scrollToBottomRequest.behavior === 'smooth' && + window.__scrollToBottomRequest.top === region.scrollHeight; + } + """)); + await page.EvaluateAsync(""" + () => { + const region = document.getElementById('scroll-region'); + region.querySelector('.scroll-content').style.height = '4000px'; + region.dispatchEvent(new Event('scrollend')); + } + """); await page.WaitForFunctionAsync(""" () => { const region = document.getElementById('scroll-region'); - return window.__grewDuringScroll && region.scrollHeight >= 4000 && + return region.scrollHeight >= 4000 && Math.abs(region.scrollHeight - region.clientHeight - region.scrollTop) < 1; } """).DefaultTimeout(); diff --git a/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs b/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs index 740630f2b6c..e0ee11a3ace 100644 --- a/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs +++ b/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs @@ -76,6 +76,7 @@ await auto.RunCommandAsync( counter, TimeSpan.FromSeconds(120)); await auto.SourceAspireEnvironmentAsync(counter, includeBundlePath); + await auto.ConfigureLocalHiveAsync(counter); break; case CliInstallMode.InstallScript: diff --git a/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs b/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs index 751f38e921f..7edf14466a0 100644 --- a/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs +++ b/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs @@ -167,6 +167,34 @@ public async Task WatchAsync_DoesNotMarkApiReady_WhileHttpResponseIsPending() } } + [Fact] + public async Task WatchAsync_RemainsActiveBeyondApiRetryTimeout() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + using var watchCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token); + + var (service, kubeconfigPath, fileSystem) = CreateService( + maxRetryDuration: TimeSpan.FromMilliseconds(100), + kubernetesInitializationTimeout: TimeSpan.FromMilliseconds(250)); + using var disposableFileSystem = fileSystem; + using var disposableService = service; + + await using var server = await TestDcpApiServer.StartAsync(cts.Token); + server.BlockWatchResponses(); + WriteKubeconfig(kubeconfigPath, server.Port); + + await using var watchEnumerator = service.WatchAsync(cancellationToken: watchCts.Token).GetAsyncEnumerator(); + var watchTask = watchEnumerator.MoveNextAsync().AsTask(); + await server.WaitForWatchRequestAsync(cts.Token); + + await Task.Delay(TimeSpan.FromMilliseconds(500), cts.Token); + Assert.False(watchTask.IsCompleted); + + watchCts.Cancel(); + await server.WaitForRequestCancellationAsync(cts.Token); + await Assert.ThrowsAnyAsync(() => watchTask); + } + // Verifies that establishing the connection survives a partially-written kubeconfig: when the file exists // but DCP has only flushed part of it (so it does not yet parse as a valid kubeconfig), the read is retried // and the operation succeeds once the complete, valid kubeconfig is written. From b33674e340e05248a2a9820f5ee415deed545340 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Thu, 24 Sep 2026 21:26:23 -0400 Subject: [PATCH 2/9] Fix LocalArchive and watch restart edge cases LocalArchive installs can auto-detect a PR package suffix and place packages in a pr-N hive, which conflicts with configuring the installed CLI to use the local hive. Long-lived watch factories can also be canceled by their periodic restart token before returning an enumerable. That cancellation currently escapes and terminates the outer watch instead of recreating it. Force LocalArchive installs into the local hive and restart factories whose restart interval expires. Cover both LocalArchive command paths and both periodic-enumerable overloads. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Utils/PeriodicRestartAsyncEnumerable.cs | 24 ++++++- .../Helpers/CliInstallStrategyTests.cs | 14 +++- .../PeriodicRestartAsyncEnumerableTests.cs | 64 +++++++++++++++++++ tests/Shared/CliInstallStrategy.cs | 4 +- 4 files changed, 101 insertions(+), 5 deletions(-) diff --git a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs index 51c72ef36dd..32d1a5b44e9 100644 --- a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs +++ b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs @@ -26,7 +26,17 @@ public static async IAsyncEnumerable CreateAsync(Func enumerable; + try + { + enumerable = await enumerableFactory(lastValue, cts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // The restart interval can expire while the factory is still establishing a streaming + // connection. Start a fresh factory call just as we do when enumeration is canceled. + continue; + } var enumerator = enumerable.GetAsyncEnumerator(cts.Token); try @@ -82,7 +92,17 @@ public static async IAsyncEnumerable CreateAsync(Func enumerable; + try + { + enumerable = await enumerableFactory(lastValue, cts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // The restart interval can expire while the factory is still establishing a streaming + // connection. Start a fresh factory call just as we do when enumeration is canceled. + continue; + } var enumerator = enumerable.GetAsyncEnumerator(cts.Token); try diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs index b5291469121..59046306598 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs @@ -19,7 +19,19 @@ public void GetPullRequestInstallArgs_ReturnsPrNumber() public void GetLocalArchiveInstallCommand_FormatsCorrectly() { var command = AspireCliShellCommandHelpers.GetLocalArchiveInstallCommand("/tmp/cli-archives", "/opt/aspire-scripts/get-aspire-cli-pr.sh"); - Assert.Equal("/opt/aspire-scripts/get-aspire-cli-pr.sh --local-dir '/tmp/cli-archives'", command); + Assert.Equal("/opt/aspire-scripts/get-aspire-cli-pr.sh --local-dir '/tmp/cli-archives' --hive-label local", command); + } + + [Fact] + public void GetLocalArchiveInstallCommandFromCurrentRef_UsesLocalHive() + { + using var environment = new EnvironmentVariableScope(("GITHUB_SHA", "0123456789abcdef0123456789abcdef01234567")); + + var command = AspireCliShellCommandHelpers.GetLocalArchiveInstallCommandFromCurrentRef("/tmp/cli-archives"); + + Assert.Equal( + "curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/0123456789abcdef0123456789abcdef01234567/eng/scripts/get-aspire-cli-pr.sh | bash -s -- --local-dir '/tmp/cli-archives' --hive-label local", + command); } [Fact] diff --git a/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs b/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs index 2d8c0685c06..8be76cccd4a 100644 --- a/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs +++ b/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs @@ -56,6 +56,64 @@ await Assert.ThrowsAnyAsync(async () => Assert.True(s_activeRunningEnumerables == 0, "expected all enumerables to be ended after cancellation"); } + [Fact] + public async Task FactoryIsRecreatedWhenRestartTokenExpires() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var secondFactoryCall = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var factoryCallCount = 0; + + async Task> InnerFactory(int? lastValue, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref factoryCallCount) == 2) + { + secondFactoryCall.SetResult(); + } + + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return CountingAsyncEnumerable(0, TimeSpan.Zero, cancellationToken); + } + + await using var enumerator = PeriodicRestartAsyncEnumerable + .CreateAsync(InnerFactory, restartInterval: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token) + .GetAsyncEnumerator(); + var moveNextTask = enumerator.MoveNextAsync().AsTask(); + + await secondFactoryCall.Task.WaitAsync(cts.Token); + cts.Cancel(); + + await Assert.ThrowsAnyAsync(() => moveNextTask); + } + + [Fact] + public async Task ClassFactoryIsRecreatedWhenRestartTokenExpires() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var secondFactoryCall = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var factoryCallCount = 0; + + async Task> InnerFactory(string? lastValue, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref factoryCallCount) == 2) + { + secondFactoryCall.SetResult(); + } + + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return EmptyStringAsyncEnumerable(); + } + + await using var enumerator = PeriodicRestartAsyncEnumerable + .CreateAsync(InnerFactory, restartInterval: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token) + .GetAsyncEnumerator(); + var moveNextTask = enumerator.MoveNextAsync().AsTask(); + + await secondFactoryCall.Task.WaitAsync(cts.Token); + cts.Cancel(); + + await Assert.ThrowsAnyAsync(() => moveNextTask); + } + static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) { var value = start; @@ -68,6 +126,12 @@ static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan d cancellationToken.ThrowIfCancellationRequested(); } + static async IAsyncEnumerable EmptyStringAsyncEnumerable() + { + await Task.Yield(); + yield break; + } + static async IAsyncEnumerable RefCountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) { Interlocked.Increment(ref s_totalEnumerablesRun); diff --git a/tests/Shared/CliInstallStrategy.cs b/tests/Shared/CliInstallStrategy.cs index 87f27c0d571..bb2ce4f7da3 100644 --- a/tests/Shared/CliInstallStrategy.cs +++ b/tests/Shared/CliInstallStrategy.cs @@ -128,7 +128,7 @@ internal static string GetPullRequestInstallArgs(int prNumber) internal static string GetLocalArchiveInstallCommand(string localDir, string commandPrefix) { - return $"{commandPrefix} --local-dir {QuoteBashArg(localDir)}"; + return $"{commandPrefix} --local-dir {QuoteBashArg(localDir)} --hive-label local"; } internal static string GetLocalArchiveInstallCommandFromCurrentRef(string localDir) @@ -140,7 +140,7 @@ internal static string GetLocalArchiveInstallCommandFromCurrentRef(string localD throw new InvalidOperationException($"GITHUB_SHA contains an unexpected value: '{sha}'. Expected a hex commit SHA or 'main'."); } - return $"curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/{sha}/eng/scripts/get-aspire-cli-pr.sh | bash -s -- --local-dir {QuoteBashArg(localDir)}"; + return $"curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/{sha}/eng/scripts/get-aspire-cli-pr.sh | bash -s -- --local-dir {QuoteBashArg(localDir)} --hive-label local"; } internal static string QuoteBashArg(string value) From aafa42d382a646ea5b0d733c2bbc5b0e2b31597e Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Thu, 24 Sep 2026 21:42:21 -0400 Subject: [PATCH 3/9] Preserve unrelated factory cancellation The periodic factory restart handler currently treats every cancellation as a restart while the outer token is active. A factory canceled for another reason would be silently retried instead of propagating its failure. Handle cancellation only when the periodic restart token fired, and verify that unrelated cancellation propagates for both enumerable overloads. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Utils/PeriodicRestartAsyncEnumerable.cs | 4 +- .../PeriodicRestartAsyncEnumerableTests.cs | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs index 32d1a5b44e9..3e3d02965f0 100644 --- a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs +++ b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs @@ -52,7 +52,7 @@ public static async IAsyncEnumerable CreateAsync(Func CreateAsync(Func> InnerFactory(string? lastValue, Cancellatio await Assert.ThrowsAnyAsync(() => moveNextTask); } + [Fact] + public async Task FactoryCancellationNotCausedByRestartIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var factoryCts = new CancellationTokenSource(); + factoryCts.Cancel(); + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + (_, _) => Task.FromCanceled>(factoryCts.Token), + restartInterval: TimeSpan.FromSeconds(1), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAnyAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(1))); + + Assert.Equal(factoryCts.Token, exception.CancellationToken); + } + + [Fact] + public async Task ClassFactoryCancellationNotCausedByRestartIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var factoryCts = new CancellationTokenSource(); + factoryCts.Cancel(); + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + (_, _) => Task.FromCanceled>(factoryCts.Token), + restartInterval: TimeSpan.FromSeconds(1), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAnyAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(1))); + + Assert.Equal(factoryCts.Token, exception.CancellationToken); + } + static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) { var value = start; From ec10136a1f4c2989ce2b6c8d25ea229f0c04bb85 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Thu, 24 Sep 2026 22:26:23 -0400 Subject: [PATCH 4/9] Fix PR archive hive selection and cancellation propagation PR archive tests install pre-downloaded packages through LocalArchive. Forcing those packages into the local hive breaks the CLI's baked pr-N channel, so generated AppHosts cannot resolve the PR AppHost SDK. Allow the installer to infer the hive from the package version and only configure the global local channel for non-PR archives. Cover both PR and CI package identities with focused tests. Periodic restart handling also retried independent cancellation in the struct factory and class enumerator paths. Require the periodic token to be canceled before restarting, and verify unrelated cancellation is propagated without retrying the factory. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Utils/PeriodicRestartAsyncEnumerable.cs | 4 +-- .../Helpers/CliE2EAutomatorHelpers.cs | 10 +++++-- .../Helpers/CliInstallStrategyTests.cs | 26 ++++++++++++++++--- .../NewChannelNuGetConfigTests.cs | 3 ++- .../Helpers/DeploymentE2EAutomatorHelpers.cs | 5 +++- .../PeriodicRestartAsyncEnumerableTests.cs | 22 +++++++++++----- tests/Shared/CliInstallStrategy.cs | 20 ++++++++++++-- tests/Shared/CliPackageDiscovery.cs | 13 ++++++++++ 8 files changed, 86 insertions(+), 17 deletions(-) diff --git a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs index 3e3d02965f0..c4f777031c4 100644 --- a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs +++ b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs @@ -31,7 +31,7 @@ public static async IAsyncEnumerable CreateAsync(Func CreateAsync(Func (string?)element.Attribute("value")) .OfType(); - Assert.Contains(packageSources, source => source.Replace('\\', '/').EndsWith("/hives/local/packages", StringComparison.Ordinal)); + Assert.Contains(packageSources, source => source.Replace('\\', '/').EndsWith($"/hives/{expectedHiveLabel}/packages", StringComparison.Ordinal)); } } else diff --git a/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs b/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs index e0ee11a3ace..6e3ce650107 100644 --- a/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs +++ b/tests/Aspire.Deployment.EndToEnd.Tests/Helpers/DeploymentE2EAutomatorHelpers.cs @@ -76,7 +76,10 @@ await auto.RunCommandAsync( counter, TimeSpan.FromSeconds(120)); await auto.SourceAspireEnvironmentAsync(counter, includeBundlePath); - await auto.ConfigureLocalHiveAsync(counter); + if (strategy.LocalArchiveHiveLabel == "local") + { + await auto.ConfigureLocalHiveAsync(counter); + } break; case CliInstallMode.InstallScript: diff --git a/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs b/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs index cdca54d8cef..1972ee3edb2 100644 --- a/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs +++ b/tests/Aspire.Hosting.Tests/Utils/PeriodicRestartAsyncEnumerableTests.cs @@ -120,17 +120,22 @@ public async Task FactoryCancellationNotCausedByRestartIsPropagated() using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); using var factoryCts = new CancellationTokenSource(); factoryCts.Cancel(); + var factoryCallCount = 0; var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( - (_, _) => Task.FromCanceled>(factoryCts.Token), + (_, _) => + { + Interlocked.Increment(ref factoryCallCount); + return Task.FromCanceled>(factoryCts.Token); + }, restartInterval: TimeSpan.FromSeconds(1), cancellationToken: cts.Token); await using var enumerator = enumerable.GetAsyncEnumerator(); - var exception = await Assert.ThrowsAnyAsync( + await Assert.ThrowsAnyAsync( async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(1))); - Assert.Equal(factoryCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); } [Fact] @@ -139,17 +144,22 @@ public async Task ClassFactoryCancellationNotCausedByRestartIsPropagated() using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); using var factoryCts = new CancellationTokenSource(); factoryCts.Cancel(); + var factoryCallCount = 0; var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( - (_, _) => Task.FromCanceled>(factoryCts.Token), + (_, _) => + { + Interlocked.Increment(ref factoryCallCount); + return Task.FromCanceled>(factoryCts.Token); + }, restartInterval: TimeSpan.FromSeconds(1), cancellationToken: cts.Token); await using var enumerator = enumerable.GetAsyncEnumerator(); - var exception = await Assert.ThrowsAnyAsync( + await Assert.ThrowsAnyAsync( async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(1))); - Assert.Equal(factoryCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); } static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) diff --git a/tests/Shared/CliInstallStrategy.cs b/tests/Shared/CliInstallStrategy.cs index bb2ce4f7da3..920bb6a56b1 100644 --- a/tests/Shared/CliInstallStrategy.cs +++ b/tests/Shared/CliInstallStrategy.cs @@ -128,7 +128,7 @@ internal static string GetPullRequestInstallArgs(int prNumber) internal static string GetLocalArchiveInstallCommand(string localDir, string commandPrefix) { - return $"{commandPrefix} --local-dir {QuoteBashArg(localDir)} --hive-label local"; + return $"{commandPrefix} --local-dir {QuoteBashArg(localDir)}"; } internal static string GetLocalArchiveInstallCommandFromCurrentRef(string localDir) @@ -140,7 +140,7 @@ internal static string GetLocalArchiveInstallCommandFromCurrentRef(string localD throw new InvalidOperationException($"GITHUB_SHA contains an unexpected value: '{sha}'. Expected a hex commit SHA or 'main'."); } - return $"curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/{sha}/eng/scripts/get-aspire-cli-pr.sh | bash -s -- --local-dir {QuoteBashArg(localDir)} --hive-label local"; + return $"curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/{sha}/eng/scripts/get-aspire-cli-pr.sh | bash -s -- --local-dir {QuoteBashArg(localDir)}"; } internal static string QuoteBashArg(string value) @@ -269,6 +269,22 @@ internal sealed class CliInstallStrategy /// public string? ExpectedVersion { get; } + /// + /// Gets the package hive label selected by the local-archive installer. + /// + public string LocalArchiveHiveLabel + { + get + { + if (Mode != CliInstallMode.LocalArchive) + { + throw new InvalidOperationException($"{nameof(LocalArchiveHiveLabel)} is only available for {nameof(CliInstallMode.LocalArchive)} strategies."); + } + + return CliPackageDiscovery.GetHiveLabel(ExpectedVersion); + } + } + /// /// Gets whether the Docker dotnet tool install command needs the generated NuGet.config for internal/prerelease feeds. /// diff --git a/tests/Shared/CliPackageDiscovery.cs b/tests/Shared/CliPackageDiscovery.cs index 8ef301a8502..35a0572f61e 100644 --- a/tests/Shared/CliPackageDiscovery.cs +++ b/tests/Shared/CliPackageDiscovery.cs @@ -19,6 +19,16 @@ internal static bool IsValidVersion(string version) return VersionPattern().IsMatch(version); } + internal static string GetHiveLabel(string? version) + { + if (version is not null && PullRequestVersionPattern().Match(version) is { Success: true } match) + { + return $"pr-{match.Groups[1].Value}"; + } + + return "local"; + } + internal static CliPackageInfo FindAspireCliPointerPackage(string packageDirectory) { return TryFindAspireCliPointerPackage(packageDirectory) @@ -96,6 +106,9 @@ private static string GetAvailableAspireCliPackageNames(string packageDirectory) [GeneratedRegex(@"^[0-9A-Za-z.\-]+$")] private static partial Regex VersionPattern(); + [GeneratedRegex(@"-pr\.([0-9]+)\.g[0-9a-f]+$", RegexOptions.IgnoreCase)] + private static partial Regex PullRequestVersionPattern(); + [GeneratedRegex(@"^Aspire\.Cli\.(win|linux|linux-musl|osx)-(x64|arm64)\.", RegexOptions.IgnoreCase)] private static partial Regex RidSpecificPackagePattern(); } From 8a3b2e2bbe9f6b5c94e8e35ac90d1d2212fff65e Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Fri, 25 Sep 2026 00:15:30 -0400 Subject: [PATCH 5/9] Fix local archive identity and watch connection retries LocalArchive CI builds retain a daily assembly identity even after user configuration selects the local channel. Generated projects therefore use daily feeds and cannot resolve CI SDK packages from the local hive. Kubernetes watches can also stall while establishing their initial HTTP response. Giving one attempt the periodic restart token prevents retries for five minutes and leaves template tests without resource updates. Override the CLI identity for non-PR local archives. Give each watch connection attempt the API timeout and retry timed-out attempts, while keeping established streams under the periodic restart token. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/Aspire.Hosting/Dcp/KubernetesService.cs | 78 +++++++++++-------- .../Helpers/CliInstallStrategyTests.cs | 11 +++ .../Dcp/KubernetesServiceTests.cs | 12 ++- tests/Shared/CliInstallStrategy.cs | 4 +- 4 files changed, 69 insertions(+), 36 deletions(-) diff --git a/src/Aspire.Hosting/Dcp/KubernetesService.cs b/src/Aspire.Hosting/Dcp/KubernetesService.cs index 0f98da505a3..91caebd1de4 100644 --- a/src/Aspire.Hosting/Dcp/KubernetesService.cs +++ b/src/Aspire.Hosting/Dcp/KubernetesService.cs @@ -271,25 +271,22 @@ public Task DeleteAsync(string name, string? namespaceParameter = null, Ca return ExecuteWithRetry( DcpApiOperationType.Watch, T.ObjectKind, - async (kubernetes, _) => + async (kubernetes, operationCancellationToken) => { - // The Kubernetes client buffers the streaming response body while this task is awaited. - // A healthy watch therefore lives until the periodic restart instead of completing within - // the shorter API retry budget used by non-streaming requests. var responseTask = string.IsNullOrEmpty(namespaceParameter) ? kubernetes.CustomObjects.ListClusterCustomObjectWithHttpMessagesAsync( GroupVersion.Group, GroupVersion.Version, resourceType, watch: true, - cancellationToken: restartCancellationToken) + cancellationToken: operationCancellationToken) : kubernetes.CustomObjects.ListNamespacedCustomObjectWithHttpMessagesAsync( GroupVersion.Group, GroupVersion.Version, namespaceParameter, resourceType, watch: true, - cancellationToken: restartCancellationToken); + cancellationToken: operationCancellationToken); // KubernetesClient's lazy WatchAsync does not await the HTTP response until enumeration starts. await responseTask.ConfigureAwait(false); @@ -302,7 +299,8 @@ public Task DeleteAsync(string name, string? namespaceParameter = null, Ca #pragma warning restore CS0618 // Type or member is obsolete }, RetryOnConnectivityAndConflictErrors, - restartCancellationToken); + restartCancellationToken, + timeoutEachAttempt: true); }; await foreach (var item in PeriodicRestartAsyncEnumerable.CreateAsync(innerWatchFactory, restartInterval: TimeSpan.FromMinutes(5), cancellationToken: cancellationToken).ConfigureAwait(false)) @@ -462,7 +460,8 @@ private async Task ExecuteWithRetry( string resourceType, Func> operation, Func isRetryable, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + bool timeoutEachAttempt = false) { using var activity = ProfilingTelemetry.StartDcpKubernetesApi(configuration, operationType, resourceType); var retryCount = 0; @@ -496,7 +495,12 @@ async ValueTask EnsureKubernetesClientAsync(CancellationToken cancellationToken) ? MaxRetryDuration : KubernetesInitializationTimeout; - var resiliencePipeline = CreateKubernetesCallResiliencePipeline(retryDuration, isRetryable, activity, () => retryCount++); + var resiliencePipeline = CreateKubernetesCallResiliencePipeline( + retryDuration, + isRetryable, + activity, + () => retryCount++, + timeoutEachAttempt); return await resiliencePipeline.ExecuteAsync(async (cancellationToken) => { // Keep connection establishment inside the retry loop so kubeconfig read failures remain retryable. @@ -523,34 +527,40 @@ private static ResiliencePipeline CreateKubernetesCallResiliencePipeline( TimeSpan retryDuration, Func isRetryable, ProfilingTelemetry.ActivityScope activity, - Action recordRetry) + Action recordRetry, + bool timeoutEachAttempt = false) { - var resiliencePipeline = new ResiliencePipelineBuilder() - .AddTimeout(new TimeoutStrategyOptions + var timeoutOptions = new TimeoutStrategyOptions + { + Timeout = retryDuration, + OnTimeout = (_) => { - Timeout = retryDuration, - OnTimeout = (_) => - { - activity.AddKubernetesApiTimeout(); - return ValueTask.CompletedTask; - } - }) - .AddRetry(new RetryStrategyOptions() + activity.AddKubernetesApiTimeout(); + return ValueTask.CompletedTask; + } + }; + var retryOptions = new RetryStrategyOptions + { + ShouldHandle = timeoutEachAttempt + ? new PredicateBuilder().Handle(isRetryable).Handle() + : new PredicateBuilder().Handle(isRetryable), + BackoffType = DelayBackoffType.Exponential, + MaxRetryAttempts = int.MaxValue, + Delay = s_initialRetryDelay, + MaxDelay = TimeSpan.FromSeconds(5), + OnRetry = (retry) => { - ShouldHandle = new PredicateBuilder().Handle(isRetryable), - BackoffType = DelayBackoffType.Exponential, - MaxRetryAttempts = int.MaxValue, - Delay = s_initialRetryDelay, - MaxDelay = TimeSpan.FromSeconds(5), - OnRetry = (retry) => - { - recordRetry(); - activity.AddKubernetesApiRetry(retry.AttemptNumber, retry.RetryDelay, retry.Outcome.Exception); - return ValueTask.CompletedTask; - } - }) - .Build(); - return resiliencePipeline; + recordRetry(); + activity.AddKubernetesApiRetry(retry.AttemptNumber, retry.RetryDelay, retry.Outcome.Exception); + return ValueTask.CompletedTask; + } + }; + + // Regular API calls have one total retry budget. Watches instead retry a stalled connection + // after each timeout until their outer periodic-restart token is canceled. + return timeoutEachAttempt + ? new ResiliencePipelineBuilder().AddRetry(retryOptions).AddTimeout(timeoutOptions).Build() + : new ResiliencePipelineBuilder().AddTimeout(timeoutOptions).AddRetry(retryOptions).Build(); } private ResiliencePipeline CreateReadKubeconfigResiliencePipeline() diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs index 641e41d9f19..158b99a0e29 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs @@ -34,6 +34,17 @@ public void GetLocalArchiveInstallCommandFromCurrentRef_AllowsHiveAutoDetection( command); } + [Fact] + public void GetConfigureLocalHiveCommands_OverridesCliIdentity() + { + Assert.Equal( + [ + "aspire config set channel local -g", + "SDK_VER=$(ls ~/.aspire/hives/local/packages/Aspire.Hosting.*.nupkg 2>/dev/null | head -1 | sed 's/.*Aspire\\.Hosting\\.//;s/\\.nupkg//') && aspire config set sdk.version \"$SDK_VER\" -g && export ASPIRE_CLI_CHANNEL=local ASPIRE_CLI_VERSION=\"$SDK_VER\" ASPIRE_CLI_PACKAGES=\"$HOME/.aspire/hives/local/packages\"" + ], + AspireCliShellCommandHelpers.GetConfigureLocalHiveCommands()); + } + [Fact] public void GetRecordAspireCliVersionCommand_IsBestEffort() { diff --git a/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs b/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs index 7edf14466a0..e69b449bd7d 100644 --- a/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs +++ b/tests/Aspire.Hosting.Tests/Dcp/KubernetesServiceTests.cs @@ -187,7 +187,7 @@ public async Task WatchAsync_RemainsActiveBeyondApiRetryTimeout() var watchTask = watchEnumerator.MoveNextAsync().AsTask(); await server.WaitForWatchRequestAsync(cts.Token); - await Task.Delay(TimeSpan.FromMilliseconds(500), cts.Token); + await server.WaitForWatchRequestCountAsync(2, cts.Token); Assert.False(watchTask.IsCompleted); watchCts.Cancel(); @@ -431,6 +431,14 @@ public Task WaitForWatchRequestAsync(CancellationToken cancellationToken) return _responseState.WatchRequestArrived.Task.WaitAsync(cancellationToken); } + public async Task WaitForWatchRequestCountAsync(int expectedCount, CancellationToken cancellationToken) + { + while (Volatile.Read(ref _responseState.WatchRequestCount) < expectedCount) + { + await Task.Delay(TimeSpan.FromMilliseconds(10), cancellationToken); + } + } + public Task WaitForRequestCancellationAsync(CancellationToken cancellationToken) { return _responseState.RequestCancellationObserved.Task.WaitAsync(cancellationToken); @@ -459,6 +467,7 @@ public static async Task StartAsync( && string.Equals(watchValues.ToString(), "true", StringComparison.OrdinalIgnoreCase); if (isWatchRequest && Volatile.Read(ref responseState.BlockWatchResponses)) { + Interlocked.Increment(ref responseState.WatchRequestCount); responseState.WatchRequestArrived.TrySetResult(true); try { @@ -515,6 +524,7 @@ private sealed class ResponseState { public bool BlockWatchResponses; public int RequestCount; + public int WatchRequestCount; public TaskCompletionSource RequestCancellationObserved { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public long ResponseDelayTicks; diff --git a/tests/Shared/CliInstallStrategy.cs b/tests/Shared/CliInstallStrategy.cs index 920bb6a56b1..a6c1ce2e511 100644 --- a/tests/Shared/CliInstallStrategy.cs +++ b/tests/Shared/CliInstallStrategy.cs @@ -67,7 +67,9 @@ internal static class AspireCliShellCommandHelpers private static readonly string[] s_configureLocalHiveCommands = [ "aspire config set channel local -g", - "SDK_VER=$(ls ~/.aspire/hives/local/packages/Aspire.Hosting.*.nupkg 2>/dev/null | head -1 | sed 's/.*Aspire\\.Hosting\\.//;s/\\.nupkg//') && aspire config set sdk.version \"$SDK_VER\" -g" + // The CLI identity takes precedence over user configuration. Override all identity fields so + // archive builds stamped as daily still scaffold projects from the local package directory. + "SDK_VER=$(ls ~/.aspire/hives/local/packages/Aspire.Hosting.*.nupkg 2>/dev/null | head -1 | sed 's/.*Aspire\\.Hosting\\.//;s/\\.nupkg//') && aspire config set sdk.version \"$SDK_VER\" -g && export ASPIRE_CLI_CHANNEL=local ASPIRE_CLI_VERSION=\"$SDK_VER\" ASPIRE_CLI_PACKAGES=\"$HOME/.aspire/hives/local/packages\"" ]; internal static string GetPrepareAspireEnvironmentCommand() From 60f325003082d11a42197c73318b90966ffea262 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Fri, 25 Sep 2026 01:16:37 -0400 Subject: [PATCH 6/9] Fix template resource row detection Template outerloop tests locate resource rows by an exact Fluent UI class string. Current rows render with the stable resource-row class, so visible resources are ignored until the tests time out. Use the dashboard's existing resource-row selector and scope grid-cell lookups to each matched row. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/Aspire.Templates.Tests/TemplateTestsBase.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs index 478c9866ccf..adabdbe7567 100644 --- a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs +++ b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs @@ -203,7 +203,7 @@ private static async Task CheckDashboardHasResourcesActualAsync(W await Task.Delay(500); // _testOutput.WriteLine($"Checking for rows again"); - var rowsLocator = dashboardPageWrapper.Page.Locator("//tr[@class='fluent-data-grid-row hover resource-row']"); + var rowsLocator = dashboardPageWrapper.Page.Locator(".main-grid .resource-row"); var allRows = await rowsLocator.AllAsync(); // _testOutput.WriteLine($"found rows#: {allRows.Count}"); if (allRows.Count == 0) @@ -215,7 +215,7 @@ private static async Task CheckDashboardHasResourcesActualAsync(W foreach (var rowLoc in allRows) { // get the cells - var cellLocs = await rowLoc.Locator("//td[@role='gridcell']").AllAsync(); + var cellLocs = await rowLoc.Locator("td[role='gridcell']").AllAsync(); // is the resource name expected? var resourceNameCell = cellLocs[0]; From d7ae8b4fab4d7f9657d012ef1175010b09ed99a4 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Fri, 25 Sep 2026 02:02:01 -0400 Subject: [PATCH 7/9] Fix template resource cell detection Fluent data-grid cells expose the gridcell role on custom elements rather than native td elements. The tag-qualified selector finds no cells after the resource-row locator succeeds. Select grid cells by role within each matched resource row. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/Aspire.Templates.Tests/TemplateTestsBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs index adabdbe7567..4d75aa437c9 100644 --- a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs +++ b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs @@ -215,7 +215,7 @@ private static async Task CheckDashboardHasResourcesActualAsync(W foreach (var rowLoc in allRows) { // get the cells - var cellLocs = await rowLoc.Locator("td[role='gridcell']").AllAsync(); + var cellLocs = await rowLoc.Locator("[role='gridcell']").AllAsync(); // is the resource name expected? var resourceNameCell = cellLocs[0]; From 7cec3cd5dcd1f551077579943eadfaa9a8efca27 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Fri, 25 Sep 2026 13:06:55 -0400 Subject: [PATCH 8/9] Restrict template resource locator to rows Fluent data-grid copies the configured row class onto each plain grid cell. Matching resource-row alone therefore returns both tr rows and td cells, and cell matches have no descendant grid cells. Restrict the resource locator to tr elements while keeping cell lookups scoped to each row. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/Aspire.Templates.Tests/TemplateTestsBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs index 4d75aa437c9..76f1a8b1802 100644 --- a/tests/Aspire.Templates.Tests/TemplateTestsBase.cs +++ b/tests/Aspire.Templates.Tests/TemplateTestsBase.cs @@ -203,7 +203,7 @@ private static async Task CheckDashboardHasResourcesActualAsync(W await Task.Delay(500); // _testOutput.WriteLine($"Checking for rows again"); - var rowsLocator = dashboardPageWrapper.Page.Locator(".main-grid .resource-row"); + var rowsLocator = dashboardPageWrapper.Page.Locator(".main-grid tr.resource-row"); var allRows = await rowsLocator.AllAsync(); // _testOutput.WriteLine($"found rows#: {allRows.Count}"); if (allRows.Count == 0) From 30b542f3abd32c631bcc3127d1fb1a48b6141686 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Fri, 25 Sep 2026 15:43:06 -0400 Subject: [PATCH 9/9] Fix restart cancellation attribution and PR hive matching Periodic restart filters treated any OperationCanceledException observed after the restart interval as restart cancellation, even when the exception belonged to an independent token. Require the exception token to match the restart token, and cover both overloads during factory creation and enumeration with deterministic cancellation synchronization. Match local archive PR package suffixes to the lowercase [0-9a-g]+ contract used by both installer scripts so hive selection behaves consistently. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Utils/PeriodicRestartAsyncEnumerable.cs | 8 +- .../Helpers/CliInstallStrategyTests.cs | 2 + .../PeriodicRestartAsyncEnumerableTests.cs | 121 ++++++++++++++++-- tests/Shared/CliPackageDiscovery.cs | 2 +- 4 files changed, 114 insertions(+), 19 deletions(-) diff --git a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs index c4f777031c4..5d3591904f2 100644 --- a/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs +++ b/src/Aspire.Hosting/Utils/PeriodicRestartAsyncEnumerable.cs @@ -31,7 +31,7 @@ public static async IAsyncEnumerable CreateAsync(Func CreateAsync(Func CreateAsync(Func CreateAsync(Func> InnerFactory(string? lastValue, Cancellatio } [Fact] - public async Task FactoryCancellationNotCausedByRestartIsPropagated() + public async Task FactoryCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); using var factoryCts = new CancellationTokenSource(); @@ -123,23 +123,30 @@ public async Task FactoryCancellationNotCausedByRestartIsPropagated() var factoryCallCount = 0; var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( - (_, _) => + async (_, restartToken) => { - Interlocked.Increment(ref factoryCallCount); - return Task.FromCanceled>(factoryCts.Token); + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + + var restartTokenCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = restartToken.Register(restartTokenCancelled.SetResult); + await restartTokenCancelled.Task.WaitAsync(cts.Token); + + factoryCts.Token.ThrowIfCancellationRequested(); + return CountingAsyncEnumerable(0, TimeSpan.Zero, restartToken); }, - restartInterval: TimeSpan.FromSeconds(1), + restartInterval: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token); await using var enumerator = enumerable.GetAsyncEnumerator(); - await Assert.ThrowsAnyAsync( - async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(1))); + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + Assert.Equal(factoryCts.Token, exception.CancellationToken); Assert.Equal(1, factoryCallCount); } [Fact] - public async Task ClassFactoryCancellationNotCausedByRestartIsPropagated() + public async Task ClassFactoryCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); using var factoryCts = new CancellationTokenSource(); @@ -147,19 +154,84 @@ public async Task ClassFactoryCancellationNotCausedByRestartIsPropagated() var factoryCallCount = 0; var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( - (_, _) => + async (_, restartToken) => { - Interlocked.Increment(ref factoryCallCount); - return Task.FromCanceled>(factoryCts.Token); + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + + var restartTokenCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = restartToken.Register(restartTokenCancelled.SetResult); + await restartTokenCancelled.Task.WaitAsync(cts.Token); + + factoryCts.Token.ThrowIfCancellationRequested(); + return EmptyStringAsyncEnumerable(); }, - restartInterval: TimeSpan.FromSeconds(1), + restartInterval: TimeSpan.FromMilliseconds(100), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + + Assert.Equal(factoryCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); + } + + [Fact] + public async Task EnumeratorCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var enumeratorCts = new CancellationTokenSource(); + enumeratorCts.Cancel(); + var factoryCallCount = 0; + var disposeCount = 0; + + Task> InnerFactory(int? lastValue, CancellationToken restartToken) + { + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + return Task.FromResult(ThrowAfterCancellationAsync(0, restartToken, enumeratorCts.Token, () => Interlocked.Increment(ref disposeCount))); + } + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + InnerFactory, + restartInterval: TimeSpan.FromMilliseconds(100), + cancellationToken: cts.Token); + await using var enumerator = enumerable.GetAsyncEnumerator(); + + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + + Assert.Equal(enumeratorCts.Token, exception.CancellationToken); + Assert.Equal(1, factoryCallCount); + Assert.Equal(1, disposeCount); + } + + [Fact] + public async Task ClassEnumeratorCancellationFromIndependentTokenAfterRestartExpirationIsPropagated() + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var enumeratorCts = new CancellationTokenSource(); + enumeratorCts.Cancel(); + var factoryCallCount = 0; + var disposeCount = 0; + + Task> InnerFactory(string? lastValue, CancellationToken restartToken) + { + Assert.Equal(1, Interlocked.Increment(ref factoryCallCount)); + return Task.FromResult(ThrowAfterCancellationAsync(string.Empty, restartToken, enumeratorCts.Token, () => Interlocked.Increment(ref disposeCount))); + } + + var enumerable = PeriodicRestartAsyncEnumerable.CreateAsync( + InnerFactory, + restartInterval: TimeSpan.FromMilliseconds(100), cancellationToken: cts.Token); await using var enumerator = enumerable.GetAsyncEnumerator(); - await Assert.ThrowsAnyAsync( - async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(1))); + var exception = await Assert.ThrowsAsync( + async () => await enumerator.MoveNextAsync().AsTask().WaitAsync(cts.Token)); + Assert.Equal(enumeratorCts.Token, exception.CancellationToken); Assert.Equal(1, factoryCallCount); + Assert.Equal(1, disposeCount); } static async IAsyncEnumerable CountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) @@ -180,6 +252,27 @@ static async IAsyncEnumerable EmptyStringAsyncEnumerable() yield break; } + static async IAsyncEnumerable ThrowAfterCancellationAsync( + T value, + [EnumeratorCancellation] CancellationToken restartToken, + CancellationToken exceptionToken, + Action onDispose) + { + var restartTokenCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = restartToken.Register(restartTokenCancelled.SetResult); + + try + { + await restartTokenCancelled.Task; + exceptionToken.ThrowIfCancellationRequested(); + yield return value; + } + finally + { + onDispose(); + } + } + static async IAsyncEnumerable RefCountingAsyncEnumerable(int start, TimeSpan delay, [EnumeratorCancellation] CancellationToken cancellationToken) { Interlocked.Increment(ref s_totalEnumerablesRun); diff --git a/tests/Shared/CliPackageDiscovery.cs b/tests/Shared/CliPackageDiscovery.cs index 35a0572f61e..b0684c4d208 100644 --- a/tests/Shared/CliPackageDiscovery.cs +++ b/tests/Shared/CliPackageDiscovery.cs @@ -106,7 +106,7 @@ private static string GetAvailableAspireCliPackageNames(string packageDirectory) [GeneratedRegex(@"^[0-9A-Za-z.\-]+$")] private static partial Regex VersionPattern(); - [GeneratedRegex(@"-pr\.([0-9]+)\.g[0-9a-f]+$", RegexOptions.IgnoreCase)] + [GeneratedRegex(@"-pr\.([0-9]+)\.[0-9a-g]+$")] private static partial Regex PullRequestVersionPattern(); [GeneratedRegex(@"^Aspire\.Cli\.(win|linux|linux-musl|osx)-(x64|arm64)\.", RegexOptions.IgnoreCase)]