Repository navigation
Defer JavaScript installer when the app uses WithExplicitStart - #21504
David Fowler (davidfowl) wants to merge 3 commits into
Conversation
When a JavaScript app is configured with WithExplicitStart() and its package manager installs dependencies (install: true), the generated installer resource started automatically during AppHost startup. The installer now inherits the app's explicit start, and starting the app starts the deferred installer once so the app's WaitForCompletion dependency is satisfied. Fixes #20186 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21504Or
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21504" |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
A startup race can skip the installer and leave the parent blocked indefinitely, while the current tests bypass the runtime ordering needed to detect it.
2 open issues
What changed in this PR
This PR addresses #20186 by deferring JavaScript package installers alongside apps configured with WithExplicitStart(), then starting the installer when the parent app is explicitly started.
Changes:
- Evaluate the parent’s explicit-start configuration after builder calls finish.
- Start deferred installers on parent startup, with serialized state checks to avoid rerunning completed installers.
- Add tests for configuration order, parent startup and restart, and preservation of automatic-start and
install: falsebehavior.
| File | Description |
|---|---|
tests/Aspire.Hosting.JavaScript.Tests/PackageInstallationTests.cs |
Adds installer deferral and parent-start regression tests. |
src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs |
Propagates explicit-start behavior and starts deferred installers with their parent. |
Review effort: Balanced
Resources are initialized concurrently, so an explicit-start app can be started before its installer publishes its initial state. Wait for that state instead of skipping the installer, and add a deterministic regression test plus a real DCP/npm functional test covering deferral, start-on-demand and restart. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
|
CI notes for head ceaf0f2 (run 41146506214). All JavaScript and Hosting jobs passed on attempt 1. The only failures were in jobs this change doesn't touch:
The tree-actions spec uses a single-file .NET AppHost and never reaches 🤖 Posted by AspireAgent (AI Agent) |
…ction (#21519) ## Description Fixes the flaky `Cli.EndToEnd` test `TypeScriptCodegenValidationTests.UnAwaitedChainsCompileWithAutoResolvePromises`. The failure is a real product race in the polyglot AppHost server, not a test problem. ### Symptom On attempt 1 of run [41146506214](https://github.com/microsoft/aspire/actions/runs/41146506214) (PR #21504, job 124378846794), the test's AppHost failed with: ``` Flushing 4 pending promise(s). Consider awaiting fluent calls to avoid implicit flushing. ❌ Capability Error: Could not invoke 'run': A health check registration is missing. Check logs for more details. Code: INTERNAL_ERROR Capability: Aspire.Hosting/run ``` The test AppHost deliberately leaves `addPostgres`, `addDatabase` and `addContainer(...).withReference(db)` un-awaited before `addHealthCheck(...).build().run()`. ### Root cause #16110 set `jsonRpc.SynchronizationContext = null` in `JsonRpcServer` so that cross-connection calls don't deadlock. Before that change, StreamJsonRpc's default `NonConcurrentSynchronizationContext` serialized request handlers per connection. Now un-awaited guest calls such as `addPostgres`, `addContainer` and `addHealthCheck` run their exported methods at the same time on thread-pool threads. Those methods mutate non-thread-safe builder state: `IServiceCollection` (a `List<ServiceDescriptor>`) and the resource collection. A concurrent `List.Add` can drop an item: - If the `AddHealthChecks().AddNpgSql(...)` registration from `AddPostgres` is lost, `HealthCheckAnnotation` still references the key. `DistributedApplicationBuilder`'s `HealthCheckServiceOptions` validator then fails with "A health check registration is missing" when `run` starts. - If a resource add is lost, the resource silently disappears. The TS SDK's `flushPendingPromises` is not the problem. It awaits every un-awaited call before `build`. The calls themselves overlap on the server. ### Fix `CapabilityDispatcher` now has a per-connection `CapabilityInvocationGate` (the dispatcher is scoped per connection, like the old synchronization context): - The synchronous invocation of an exported method runs under the gate, so builder mutations from concurrent guest calls no longer overlap. - The gate is released when the invocation returns, including the synchronous prefix of async exports. It is also released when the invocation first calls a guest callback through `AtsCallbackProxyFactory`, because the guest may call back into the server before the callback completes. Re-entrant calls therefore cannot deadlock. The lease flows through `AsyncLocal`, so it is also released when the export offloads the callback to another thread (for example, `Task.Run(callback)`). - Exports that opt into `RunSyncOnBackgroundThread`, such as `run`, keep their existing ungated behavior. This matches how they bypassed the old synchronization context. - Cross-connection dispatch is unchanged. ## Evidence **Regression unit test, deterministic.** `InvokeAsync_ConcurrentCapabilityInvocations_DoNotOverlap` holds one invocation inside an export and then starts a second one. - On `main` it fails with `Assert.False() Failure — Expected: False, Actual: True`: the second invocation ran to completion while the first was still inside the export. - With this fix it passes. **Re-entry guard.** `InvokeAsync_CallbackFromSynchronousInvocation_CanReenterDispatcher` covers a synchronous export that blocks on a guest callback while the callback re-enters the dispatcher. It runs both inline and with the callback offloaded via `Task.Run`, and both pass without deadlocking. With a `[ThreadStatic]` lease, the offloaded case deadlocked (`TimeoutException`) until the lease moved to `AsyncLocal` after review. **Bounded stress on the real `Aspire.Hosting/addContainer` export** (temporary local test, not committed): 50 rounds × 32 concurrent un-awaited `addContainer` calls on one builder, through `CapabilityDispatcher`. | | Lost resources | Errors | |---|---|---| | `main` | 9 / 1600 | 0 | | This PR | 0 / 1600 | 0 | **E2E.** The flaky test itself, `Cli.EndToEnd-TypeScriptCodegenValidationTests`, exercises this path end to end in this PR's CI. On head ab6ec38 (CI run 41165837278, job 124435978766) it **passed** in 13m47s. After the AsyncLocal review fix, on head 17de5ac (CI run 41171583681, job 124453010234) it **passed** again, in 14m2s. **Failure rate:** attempt-1 `Cli.EndToEnd-TypeScriptCodegenValidationTests` jobs across the last 150 `ci.yml` runs (2026-10-30T10:39Z to 2026-10-31T03:47Z): | Outcome | Jobs | |---|---| | Completed | 63 | | Failed because of this test (run 41146506214, health check registration missing) | 1 (about 1.6%) | | Failed because of `RestoreGeneratesSdkFiles_WithConfiguredToolchain(pnpm)` (unrelated) | 1 | | Failed because of runner infrastructure (job died loading the Docker image, no logs) | 1 | The race is timing dependent, so it is rare in CI. It reproduces reliably under the stress run above. ## Validation - `Aspire.Hosting.RemoteHost.Tests` (full suite, local): 673 passed and 5 skipped. 15 failed, all `IntegrationHostProcessTests`, because their fixture build hits `NU1905` (NuGet audit can't reach nuget.org in this sandbox). Those failures are environmental and unrelated to this change. - New tests: fail before, pass after, as shown above. - CI on ab6ec38: all checks green. Attempt 1 lost three Windows VS Code extension E2E shards (coordinated-build, dynamic-debug-configuration, cli-path-rejection) to `The hosted runner lost communication with the server` after about 47 minutes. The same infrastructure failure, with the same shards and the same annotation, hit unrelated PRs (runs 41144696804, 41160826284). These shards exercise C# projects, not the polyglot RemoteHost. The automatic rerun (attempt 2) passed. - CI on 17de5ac (run 41171583681): attempt 1 failed only `Aspire.Cli.Tests` → `NuGetPackagePrefetcherTests.PrefetchingCancellationDueToShutdownLogsCleanMessage`, with a 30s timeout. This is known flake #20507 (fix in #21438). It's CLI NuGet prefetch code, which this PR doesn't touch. The automatic rerun (attempt 2) re-runs it once. ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - Did you add public API? - [x] No - Does the change make any security assumptions or guarantees? - [x] No **🤖 Posted by AspireAgent (AI Agent)** --------- Co-authored-by: davidfowl <95136+davidfowl@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
AspireAgent stopped: both review threads are addressed in 522f54c, and Final Results passed. 🤖 Posted by AspireAgent (AI Agent) |
Only auto-start an installer the integration deferred for an explicit-start parent, so WithNpm(install: false) plus WaitForCompletion stays manual. Decide deferral in a before-start pipeline step, which runs after every BeforeStartEvent subscriber, so WithExplicitStart applied in a later callback is honored. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Tests selector10 / 101 PR test projects · 4 PR jobs, from 3 changed files. Selected PR test projects (10 / 101)
Selected PR jobs (4)
How these were chosen — grouped by what changed
🔧 📦 affected project 🧪 🧪 Job reasons
Selection computed for commit |
| // WaitForCompletion dependency can be satisfied. Builder-time subscriptions run before the | ||
| // orchestrator's WaitFor handler, which is registered when the application starts. | ||
| var installerStartLock = new SemaphoreSlim(1, 1); | ||
| resource.OnBeforeResourceStarted(async (parent, e, cancellationToken) => |
There was a problem hiding this comment.
[automated] [P2] Start the installer independently of earlier start subscribers
If a global BeforeResourceStartedEvent subscriber is registered before AddJavaScriptApp and waits for this app's installer to finish, event dispatch blocks before reaching this callback. With an explicit-start app, the installer remains NotStarted and the parent Start remains pending; manually starting the installer releases it. Previously, the automatic installer could finish independently of the parent event. Can the deferred installer be started without depending on the order of user start-event subscribers?
|
|
||
| var commandService = e.Services.GetRequiredService<ResourceCommandService>(); | ||
| var result = await commandService.ExecuteCommandAsync(installer, KnownResourceCommands.StartCommand, cancellationToken).ConfigureAwait(false); | ||
| if (!result.Success) |
There was a problem hiding this comment.
[automated] [P2] Preserve cancellation from the installer Start
When the installer's Start is waiting on a prerequisite and the parent Start token is canceled, ExecuteCommandAsync returns a canceled result (Success=false, Canceled=true). This branch throws instead, so the parent command returns Canceled=false with an empty failure detail. An ordinary dependency-wait control preserves cancellation. Please propagate canceled results as cancellation before treating other unsuccessful results as errors.
|
David Fowler (@davidfowl) friendly ping: this PR has open review feedback from Ankit Jain (@radical) that's been waiting on an author response for a couple of weeks. Could you take a look when you get a chance? Thanks! |


Description
WithNpm(install: true)(likewise Yarn, pnpm, Bun and Deno) creates a<app>-installerresource, and the app waits for it to complete. If the app also usesWithExplicitStart(), the installer ignored that. It still started automatically during AppHost startup and rannpm install, even though the app itself was deferred.Root cause
In
JavaScriptHostingExtensions(AddInstaller), the generatedJavaScriptInstallerResourceonly gets anExplicitStartupAnnotationforinstall: false. Nothing looks at the parent'sExplicitStartupAnnotation. Simply copying the annotation when the installer is created isn't enough, for two reasons:WithExplicitStart()is commonly called afterWithNpm(...), as in the issue's repro.WaitForCompletion(installer)never completes, because no orchestrator mechanism starts explicit-start dependencies.Fix
before-startpipeline step,<installer>-defer-with-explicit-start-parent, marks the installer explicit-start when the parent is explicit-start and waits for the installer (install: true). The step runs after everyBeforeStartEventsubscriber and lifecycle hook, and before DCP creates resources, so it also catchesWithExplicitStart()applied from a laterOnBeforeStartcallback. The step also tags the installer with a private marker annotation.BeforeResourceStartedEventsubscription on the parent starts the deferred installer through the public start command (ResourceCommandService), but only if this integration deferred it (the marker is present) and it is stillNotStarted. An installer the app author made explicit-start, for exampleWithNpm(install: false)combined with a manualWaitForCompletion(installer), stays manual. Resources are initialized concurrently, so the handler first waits for the installer to publish its initial state rather than skipping it. A semaphore serializes the check and start across replicas. When the app is restarted, an installer that has already finished is not rerun. Builder-time subscriptions run before the orchestrator'sWaitForhandler, which is registered when the app starts, so the installer is started before the app begins waiting on it.install: falseand non-explicit apps keep their existing behavior.Repro / before-after evidence
New tests in
PackageInstallationTests:InstallerIsDeferredWhenParentUsesExplicitStart(explicitStartBeforePackageManager: True)Assert.True() Failure: installer has noExplicitStartupAnnotationInstallerIsDeferredWhenParentUsesExplicitStart(explicitStartBeforePackageManager: False)(issue's exact repro order)Assert.True() FailureStartingExplicitStartParentStartsDeferredInstallerOnceAssert.Equal() Failure(expected 1 installer start, got 0)StartingParentBeforeInstallerStateIsPublishedStillStartsInstaller(startup ordering race from review)Assert.False() Failure(also fails on this PR's first head, 6789435)ExplicitStartInstallerFunctionalTests.ExplicitStartAppDefersInstallerUntilAppIsStarted(real DCP + npm: the installer staysNotStarted, runs once when the app starts, and is not rerun on app restart)Expected: "NotStarted" Actual: "Starting"(the reported bug)StartingParentDoesNotStartManualInstallerTheParentWaitsFor(review: respectinstall: false+WaitForCompletion)Expected: 0, Actual: 1)InstallerIsDeferredWhenParentUsesExplicitStartInLaterBeforeStartCallback(review:WithExplicitStart()in a laterOnBeforeStart)Assert.True() FailureAssert.True() Failure)InstallerIsNotDeferredWhenParentStartsAutomaticallyStartingParentDoesNotStartInstallerDisabledWithInstallFalseE2E evidence (real DCP + npm)
ExplicitStartInstallerFunctionalTests.ExplicitStartAppDefersInstallerUntilAppIsStartedruns a real AppHost under DCP with a real npm project. The test:NotStartedand that thepostinstallmarker file doesn't exist.ResourceCommandService. The installer exits 0, and the app reachesRunningand serves HTTP.On main this test fails with
Expected: "NotStarted" Actual: "Starting", which is the bug reported in #20186. With this PR it passes locally and in CI on head ceaf0f2: the Hosting.JavaScript jobs on ubuntu-latest and windows-latest each passed 426/426 with 0 skipped.Local results:
PackageInstallationTests+ExplicitStartInstallerFunctionalTests+NodeFunctionalTests: 35/35 passed on 522f54c.Aspire.Hosting.JavaScript.Testson 522f54c: 414 of 433 passed. The 19 local failures are all environmental and also unaffected by this run-mode-only change:/root/is scrubbed to{UserProfile}. These run in publish mode.Fixes #20186
Checklist
<remarks />and<code />elements on your triple slash comments?🤖 Posted by AspireAgent (AI Agent)