Skip to content

Defer JavaScript installer when the app uses WithExplicitStart - #21504

Open
David Fowler (davidfowl) wants to merge 3 commits into
mainfrom
fix/js-installer-explicit-start-20186
Open

David Fowler (davidfowl) wants to merge 3 commits into
mainfrom
fix/js-installer-explicit-start-20186

Conversation

@davidfowl

@davidfowl David Fowler (davidfowl) commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Description

WithNpm(install: true) (likewise Yarn, pnpm, Bun and Deno) creates a <app>-installer resource, and the app waits for it to complete. If the app also uses WithExplicitStart(), the installer ignored that. It still started automatically during AppHost startup and ran npm install, even though the app itself was deferred.

Root cause

In JavaScriptHostingExtensions (AddInstaller), the generated JavaScriptInstallerResource only gets an ExplicitStartupAnnotation for install: false. Nothing looks at the parent's ExplicitStartupAnnotation. Simply copying the annotation when the installer is created isn't enough, for two reasons:

  • WithExplicitStart() is commonly called after WithNpm(...), as in the issue's repro.
  • A deferred installer must still run when the user starts the app. Otherwise the app's WaitForCompletion(installer) never completes, because no orchestrator mechanism starts explicit-start dependencies.

Fix

  • A before-start pipeline 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 every BeforeStartEvent subscriber and lifecycle hook, and before DCP creates resources, so it also catches WithExplicitStart() applied from a later OnBeforeStart callback. The step also tags the installer with a private marker annotation.
  • A BeforeResourceStartedEvent subscription 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 still NotStarted. An installer the app author made explicit-start, for example WithNpm(install: false) combined with a manual WaitForCompletion(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's WaitFor handler, which is registered when the app starts, so the installer is started before the app begins waiting on it.
  • install: false and non-explicit apps keep their existing behavior.

Repro / before-after evidence

New tests in PackageInstallationTests:

Test main (13b2068) this PR
InstallerIsDeferredWhenParentUsesExplicitStart(explicitStartBeforePackageManager: True) ❌ Assert.True() Failure: installer has no ExplicitStartupAnnotation ✅
InstallerIsDeferredWhenParentUsesExplicitStart(explicitStartBeforePackageManager: False) (issue's exact repro order) ❌ Assert.True() Failure ✅
StartingExplicitStartParentStartsDeferredInstallerOnce ❌ Assert.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 stays NotStarted, runs once when the app starts, and is not rerun on app restart) ❌ Expected: "NotStarted" Actual: "Starting" (the reported bug) ✅
StartingParentDoesNotStartManualInstallerTheParentWaitsFor (review: respect install: false + WaitForCompletion) n/a (installer never started on main) ✅ (fails on ceaf0f2: Expected: 0, Actual: 1)
InstallerIsDeferredWhenParentUsesExplicitStartInLaterBeforeStartCallback (review: WithExplicitStart() in a later OnBeforeStart) ❌ Assert.True() Failure ✅ (also fails on ceaf0f2: Assert.True() Failure)
InstallerIsNotDeferredWhenParentStartsAutomatically ✅ ✅ (existing behavior preserved)
StartingParentDoesNotStartInstallerDisabledWithInstallFalse ✅ ✅ (existing behavior preserved)

E2E evidence (real DCP + npm)

ExplicitStartInstallerFunctionalTests.ExplicitStartAppDefersInstallerUntilAppIsStarted runs a real AppHost under DCP with a real npm project. The test:

  1. Checks that the installer starts as NotStarted and that the postinstall marker file doesn't exist.
  2. Starts the app through ResourceCommandService. The installer exits 0, and the app reaches Running and serves HTTP.
  3. Stops and restarts the app, and checks that the installer did not run again (the marker file is unchanged).

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.
  • Full Aspire.Hosting.JavaScript.Tests on 522f54c: 414 of 433 passed. The 19 local failures are all environmental and also unaffected by this run-mode-only change:
    • Dockerfile snapshot tests running as root, where /root/ is scrubbed to {UserProfile}. These run in publish mode.
    • Bun and Deno functional tests, because those runtimes aren't installed locally.

Fixes #20186

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
      • If yes, did you have an API Review for it?
        • Yes
        • No
      • Did you add <remarks /> and <code /> elements on your triple slash comments?
        • Yes
        • No
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
      • If yes, have you done a threat model and had a security review?
        • Yes
        • No
    • No

🤖 Posted by AspireAgent (AI Agent)

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>
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21504

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21504"

@aspire-repo-bot
aspire-repo-bot Bot requested a balanced review from Copilot October 30, 2026 22:53
@github-actions github-actions Bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label Oct 30, 2026
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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: false behavior.
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>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block the changes to installer startup behavior.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Collaborator Author

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:

  • Cli.EndToEnd TypeScriptCodegenValidationTests (ubuntu), attempt 1: UnAwaitedChainsCompileWithAutoResolvePromises failed with "aspire start failed". Its apphost uses only Postgres and nginx, with no JavaScript installer. The job passed on rerun (attempt 2).
  • VS Code extension E2E (Windows, tree-actions):
    • Attempt 1: hosted runner lost communication (infra).
    • Attempt 2: the test passed, but teardown failed with EBUSY: resource busy or locked, rmdir ...\AspireE2E.SecondaryActions. This job also failed on main in run 41136039061.
    • Attempt 3: hosted runner lost communication again.
    • A final rerun (attempt 4) is in progress.

The tree-actions spec uses a single-file .NET AppHost and never reaches Aspire.Hosting.JavaScript.

🤖 Posted by AspireAgent (AI Agent)

@davidfowl
David Fowler (davidfowl) marked this pull request as ready for review October 31, 2026 02:15
David Fowler (davidfowl) added a commit that referenced this pull request Nov 4, 2026
…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>
@davidfowl David Fowler (davidfowl) added the area-integrations Issues pertaining to Aspire Integrations packages label Nov 8, 2026 — with Copilot SWE Agent
@davidfowl David Fowler (davidfowl) added the agent:working An AI agent is actively working on this issue or PR label Nov 11, 2026 — with Copilot SWE Agent

David Fowler (davidfowl) commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

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>
@github-actions

Copy link
Copy Markdown
Contributor

Tests selector

10 / 101 PR test projects · 4 PR jobs, from 3 changed files.

Selected PR test projects (10 / 101)

Aspire.Cli.EndToEnd.Tests, Aspire.Hosting.Azure.Kubernetes.Tests, Aspire.Hosting.Azure.Tests, Aspire.Hosting.Blazor.Tests, Aspire.Hosting.CodeGeneration.TypeScript.Tests, Aspire.Hosting.Dotnet.Tests, Aspire.Hosting.JavaScript.Tests, Aspire.Hosting.Radius.Tests, Aspire.Hosting.Tests, Aspire.Playground.Tests

Selected PR jobs (4)

cli-starter-validation, extension-e2e, polyglot, typescript-api-compat


How these were chosen — grouped by what changed

⚠️ 9 of the 10 selected test projects come from a single change — src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs.

🔧 src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs (changed source)
→ 1 directly: Aspire.Hosting.JavaScript.Tests
→ 8 via the project graph: Aspire.Hosting.Azure.Kubernetes.Tests (2 hops), Aspire.Hosting.Azure.Tests, Aspire.Hosting.Blazor.Tests (2 hops), Aspire.Hosting.CodeGeneration.TypeScript.Tests, Aspire.Hosting.Dotnet.Tests (2 hops), Aspire.Hosting.Radius.Tests (2 hops), Aspire.Hosting.Tests, Aspire.Playground.Tests

📦 affected project Aspire.Hosting.JavaScript
→ 1 test: Aspire.Cli.EndToEnd.Tests

🧪 tests/Aspire.Hosting.JavaScript.Tests/ExplicitStartInstallerFunctionalTests.cs (changed test)
→ 1 directly: Aspire.Hosting.JavaScript.Tests

🧪 tests/Aspire.Hosting.JavaScript.Tests/PackageInstallationTests.cs (changed test)
→ 1 directly: Aspire.Hosting.JavaScript.Tests

Job reasons

Job Triggered by
cli-starter-validation affected project Aspire.Hosting.JavaScript
extension-e2e • src/Aspire.Hosting.JavaScript/JavaScriptHostingExtensions.cs
• affected project Aspire.Hosting.JavaScript
polyglot affected project Aspire.Hosting.JavaScript
typescript-api-compat affected project Aspire.Hosting.JavaScript

Selection computed for commit 522f54c.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the change aligning package installer startup with the parent app’s explicit-start setting.

No open issues 🎉

Review effort: Balanced

@davidfowl David Fowler (davidfowl) removed the agent:working An AI agent is actively working on this issue or PR label Nov 11, 2026
// 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) =>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@davidfowl David Fowler (davidfowl) added the pr-shepherd:fix PR shepherd: request an automated fix pass on this PR label Nov 13, 2026 — with Copilot SWE Agent
@davidfowl David Fowler (davidfowl) removed the pr-shepherd:fix PR shepherd: request an automated fix pass on this PR label Nov 20, 2026
@davidfowl David Fowler (davidfowl) added the pr-shepherd:fix PR shepherd: request an automated fix pass on this PR label Nov 20, 2026 — with Copilot SWE Agent
@davidfowl David Fowler (davidfowl) removed the pr-shepherd:fix PR shepherd: request an automated fix pass on this PR label Nov 20, 2026
@adamint

Copy link
Copy Markdown
Member

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!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-integrations Issues pertaining to Aspire Integrations packages needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JavaScript installer ignores parent WithExplicitStart()

5 participants