Skip to content

Defer dotnet restore in aspire update so channel switches don't trip NU1103#17017

Merged
mitchdenny merged 2 commits into
mainfrom
mitchdenny/fix-update-nuget-config-ordering
May 16, 2026
Merged

Defer dotnet restore in aspire update so channel switches don't trip NU1103#17017
mitchdenny merged 2 commits into
mainfrom
mitchdenny/fix-update-nuget-config-ordering

Conversation

@mitchdenny
Copy link
Copy Markdown
Member

Fixes #15891.

What the user sees

aspire update --channel daily (or any other Explicit channel — staging, PR
hives, local) on a file-based AppHost referencing several stable Aspire
integration packages fails partway through with:

error NU1103: Unable to find a stable package Aspire.Hosting.Python with version (>= 13.2.1)
  - Found 2552 version(s) in dotnet9 feed [ Nearest version: 13.3.0-preview.1.26111.5 ]
  - Versions from https://api.nuget.org/v3/index.json were not considered

The project is left in a broken intermediate state: new nuget.config (now
restricting Aspire* to the daily feed), only the first package bumped to a
daily version, the rest still on the stable version that no longer resolves.

Root cause

ProjectUpdater.UpdateProjectAsync ran in this order:

  1. (Explicit channels) merge the channel's feed mappings into nuget.config
    via NuGetConfigMerger.CreateOrUpdateAsync — adds the
    <packageSourceMapping> pinning Aspire* to the channel's feed.
  2. Iterate update steps; each non-CPM step called
    runner.AddPackageAsync(..., noRestore: false, ...) — i.e. each
    dotnet package add ran its own restore.

The first restore happened with nuget.config already in "channel-only" mode
but the rest of the PackageReferences still on stable versions. With
<packageSourceMapping> blocking nuget.org for Aspire*, NuGet emitted
NU1103 for the not-yet-bumped Aspire packages and the update aborted.

Fix

Defer the implicit restore until after every package version edit has been
applied:

  • UpdatePackageReferenceInProject now passes noRestore: true on every
    per-package AddPackageAsync so each dotnet package add only mutates the
    project / file-based AppHost.
  • After the existing "Applying updates" loop completes,
    UpdateProjectAsync runs a single runner.RestoreAsync(...) so users still
    get a clear failure surface if anything else is misconfigured.

By the time NuGet sees the new <packageSourceMapping>, every Aspire*
reference already points at a version that exists in the channel's feed, so
the mapping no longer causes NU1103.

Verified locally on .NET SDK 10.0.203 that dotnet restore <path-to-apphost.cs>
works for both .csproj and file-based AppHosts — the existing
IDotNetCliRunner.RestoreAsync shape covers both with no signature change.

New RestoringPackagesAfterUpdate / FailedToRestoreAfterUpdateFormat
resource strings carry the status and error messaging; xlf files regenerated
via dotnet build /t:UpdateXlf.

Tests

Three layers, each catching a different regression class:

  1. Unit (PR-time guard, fast)
    ProjectUpdaterTests.UpdateProjectFileAsync_AppliesAllPackageEditsBeforeFinalRestore
    wires AddPackageAsync and RestoreAsync to a shared call-order list and
    asserts every add carries noRestore: true, exactly one restore is
    invoked, and it runs last. If anyone flips noRestore back to false
    or moves the restore step before the loop, this fails immediately.

  2. Tightened existing tests — the five AddPackageAsync capture sites in
    ProjectUpdaterTests now also assert item.NoRestore == true (and the
    misleading "should be null because of --no-restore behavior" comment that
    actually referred to nugetSource is corrected). Catches regressions on
    every existing scenario — traditional PackageReference, multi-project,
    single-file AppHost, mixed paths.

  3. End-to-end CLI test (CI guard, real bug repro)
    UpdateChannelNuGetConfigOrderingTests.AspireUpdateAppliesAllPackageEditsBeforeRestoringWhenNuGetConfigGainsSourceMapping,
    in its own test class so CI's per-class job split (SplitTestsOnCI=true)
    puts it on its own runner. Exercises the bug end-to-end against LocalHive:
    writes an apphost.cs with three stable Aspire.Hosting.* references
    (Redis, PostgreSQL, Kafka at 13.2.1 — the same release used in the
    issue's repro) and a nuget.org-only nuget.config, runs
    aspire update --channel local, then asserts:

    • the merged <packageSourceMapping> actually landed (so we know the bug
      pre-condition was triggered, not silently bypassed), and
    • every #:package directive was bumped to the local SDK version (so we
      know the loop ran to completion rather than aborting after the first add).

    Skips on non-LocalHive strategies because reproducing against the public
    daily feed isn't deterministic.

Notes for reviewers

  • TestDotNetCliRunner.RestoreAsync now defaults to returning 0 instead of
    throwing NotImplementedException, mirroring the existing
    AddProjectToSolutionAsync / GetNuGetConfigPathsAsync patterns. Required
    because UpdateProjectAsync always calls RestoreAsync now and most
    existing ProjectUpdater tests don't set the callback. No existing test
    relied on the throw behavior.
  • The CPM path (UpdatePackageVersionInDirectoryPackagesProps) edits
    Directory.Packages.props directly and never invoked restore on its own,
    so it was never part of the bug — but the new single deferred restore
    covers it too.
  • Existing UpdateProjectFileAsync_CanUpdateFromStableToDaily already
    exercises the Explicit channel path, so the production fix is hit by
    multiple tests, not just the new one.

Copilot AI review requested due to automatic review settings May 13, 2026 14:28
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 13, 2026

🚀 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 -- 17017

Or

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

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a failure mode in aspire update when switching to an Explicit channel (daily/staging/PR hives/local) where nuget.config is rewritten (including packageSourceMapping) before packages are updated. The update previously performed per-package restores, which could run NuGet against a half-updated reference graph and fail with NU1103, leaving the project in a broken intermediate state.

Changes:

  • Defers restore by switching per-package dotnet package add calls to --no-restore, then running a single final dotnet restore after all edits are applied.
  • Adds unit coverage to enforce call ordering (AddPackageAsync(... noRestore: true) for every package, and exactly one RestoreAsync executed last).
  • Adds an end-to-end regression test reproducing the original scenario against LocalHive, and introduces new localized resource strings for the final restore status/failure messaging.
Show a summary per file
File Description
tests/Aspire.Cli.Tests/TestServices/TestDotNetCliRunner.cs Makes RestoreAsync default to success so existing tests don’t start failing now that restore is always invoked.
tests/Aspire.Cli.Tests/Projects/ProjectUpdaterTests.cs Tightens existing assertions to require NoRestore == true and adds a dedicated regression test asserting restore ordering.
tests/Aspire.Cli.EndToEnd.Tests/UpdateChannelNuGetConfigOrderingTests.cs Adds an E2E regression test verifying nuget.config source mapping is applied and all #:package directives are updated before the single restore.
src/Aspire.Cli/Projects/ProjectUpdater.cs Implements deferred restore behavior: per-package AddPackageAsync uses noRestore: true, then performs one RestoreAsync at the end with status/error handling.
src/Aspire.Cli/Resources/UpdateCommandStrings.resx Adds new strings for “Restoring packages…” and restore-failure messaging.
src/Aspire.Cli/Resources/UpdateCommandStrings.Designer.cs Regenerates the strongly-typed resource accessors for the new strings.
src/Aspire.Cli/Resources/xlf/UpdateCommandStrings.*.xlf Updates localized XLF files with the new resource entries (state new).

Copilot's findings

Files not reviewed (1)
  • src/Aspire.Cli/Resources/UpdateCommandStrings.Designer.cs: Language not supported
  • Files reviewed: 18/19 changed files
  • Comments generated: 0

@github-actions
Copy link
Copy Markdown
Contributor

Re-running the failed jobs in the CI workflow for this pull request because 1 job was identified as retry-safe transient failures in the CI run attempt.
GitHub was asked to rerun all failed jobs for that attempt, and the rerun is being tracked in the rerun attempt.
The job links below point to the failed attempt jobs that matched the retry-safe transient failure rules.

…NU1103

Fixes #15891.

Before this change, `aspire update --channel daily` (or any other Explicit
channel) on an AppHost referencing several stable Aspire integration packages
would fail with NU1103 partway through. The CLI rewrote nuget.config to add
the channel's feed plus a `<packageSourceMapping>` pinning `Aspire*` to that
feed, then ran each per-package `dotnet package add` with restore enabled.
The first add's restore saw the still-stable references for the not-yet-bumped
packages, but the new mapping blocked the nuget.org fallback for them, so
NuGet emitted NU1103 and the update aborted halfway through — leaving the
project in a broken intermediate state (new nuget.config, only the first
package bumped).

Fix in `ProjectUpdater`:

- Pass `noRestore: true` on every per-package `AddPackageAsync` so each
  `dotnet package add` only mutates the project / file-based AppHost.
- After the existing "Applying updates" loop completes, run a single
  `runner.RestoreAsync(...)` so users still get a clear failure surface if
  anything else is misconfigured. Verified locally on .NET SDK 10.0.203 that
  `dotnet restore <path-to-apphost.cs>` works for both csproj and file-based
  AppHosts — no new runner abstraction needed. New
  `RestoringPackagesAfterUpdate` / `FailedToRestoreAfterUpdateFormat`
  resource strings carry the status and error messaging; xlf files
  regenerated via `dotnet build /t:UpdateXlf`.

Tests, in three layers so regressions are caught at PR time and in CI:

1. New unit test `UpdateProjectFileAsync_AppliesAllPackageEditsBeforeFinalRestore`
   in `ProjectUpdaterTests` wires `AddPackageAsync` and `RestoreAsync` to a
   shared call-order list and asserts every add carries `noRestore: true`,
   exactly one restore is invoked, and it runs last.

2. The five existing `AddPackageAsync` capture sites in
   `ProjectUpdaterTests` now also assert `item.NoRestore == true` (and the
   misleading "should be null because of --no-restore behavior" comment that
   actually referred to `nugetSource` is corrected). Catches regressions on
   every existing scenario — traditional PackageReference, multi-project,
   single-file AppHost, mixed paths.

   `TestDotNetCliRunner.RestoreAsync` now defaults to returning 0 instead of
   throwing `NotImplementedException`, mirroring the
   `AddProjectToSolutionAsync` / `GetNuGetConfigPathsAsync` pattern. Required
   because `UpdateProjectAsync` always calls `RestoreAsync` now.

3. New CLI E2E test
   `UpdateChannelNuGetConfigOrderingTests.AspireUpdateAppliesAllPackageEditsBeforeRestoringWhenNuGetConfigGainsSourceMapping`
   in its own test class so CI's per-class job split (`SplitTestsOnCI`) puts
   the regression on its own runner. Exercises the bug end-to-end against
   LocalHive: writes an `apphost.cs` with three stable `Aspire.Hosting.*`
   references and a nuget.org-only `nuget.config`, runs
   `aspire update --channel local`, and asserts the merged
   `packageSourceMapping` actually landed (so we know the bug pre-condition
   was triggered) and every `#:package` directive was bumped (so we know the
   loop ran to completion rather than aborting after the first add).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mitchdenny mitchdenny force-pushed the mitchdenny/fix-update-nuget-config-ordering branch from b4a0cb6 to 4a6bf4b Compare May 15, 2026 03:24
…file AppHosts

The Aspire.AppHost.Sdk pulls Aspire.Hosting.AppHost in implicitly, both
for the new csproj SDK format and for single-file (apphost.cs) AppHosts.
The csproj path already removes a redundant explicit PackageReference,
but the .cs path left an explicit '#:package Aspire.Hosting.AppHost@<ver>'
directive in place. After 'aspire update --channel daily' rewrites
nuget.config to pin Aspire* to the channel feed, the deferred restore
then fails with NU1103 because the channel does not carry the user's
stable version of Aspire.Hosting.AppHost.

Mirror the csproj cleanup for single-file AppHosts: strip the directive
inline during the SDK-bump path, and enqueue a cleanup step on the
SDK-already-current path so a re-run after a partial migration recovers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown
Contributor

🎬 CLI E2E Test Recordings — 82 recordings uploaded (commit b38cdee)

View all recordings
Status Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View Recording
AddPackageWhileAppHostRunningDetached ▶️ View Recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View Recording
AgentInitCommand_DefaultSelection_InstallsSkillOnly ▶️ View Recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View Recording
AspireAddPackageVersionToDirectoryPackagesProps ▶️ View Recording
AspireInitSingleFileAppHostRunsViaDotnetRunAppHost ▶️ View Recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ View Recording
AspireUpdateRemovesOrphanAppHostPackageVersionWhenSdkAlreadyCurrent ▶️ View Recording
Banner_DisplayedOnFirstRun ▶️ View Recording
Banner_DisplayedWithExplicitFlag ▶️ View Recording
Banner_NotDisplayedWithNoLogoFlag ▶️ View Recording
CertificatesClean_RemovesCertificates ▶️ View Recording
CertificatesTrust_WithNoCert_CreatesAndTrustsCertificate ▶️ View Recording
CertificatesTrust_WithUntrustedCert_TrustsCertificate ▶️ View Recording
ConfigSetGet_CreatesNestedJsonFormat ▶️ View Recording
CreateAndRunAspireStarterProject ▶️ View Recording
CreateAndRunAspireStarterProjectWithBundle ▶️ View Recording
CreateAndRunEmptyAppHostProject ▶️ View Recording
CreateAndRunJavaEmptyAppHostProject ▶️ View Recording
CreateAndRunJsReactProject ▶️ View Recording
CreateAndRunPythonReactProject ▶️ View Recording
CreateAndRunTypeScriptEmptyAppHostProject ▶️ View Recording
CreateAndRunTypeScriptStarterProject ▶️ View Recording
CreateJavaAppHostWithViteApp ▶️ View Recording
CreateTypeScriptAppHostWithViteApp_UsesConfiguredToolchain ▶️ View Recording
DashboardRunWithOtelTracesReturnsNoTraces ▶️ View Recording
DeployK8sBasicApiService ▶️ View Recording
DeployK8sWithExternalHelmChart ▶️ View Recording
DeployK8sWithGarnet ▶️ View Recording
DeployK8sWithMongoDB ▶️ View Recording
DeployK8sWithMySql ▶️ View Recording
DeployK8sWithPostgres ▶️ View Recording
DeployK8sWithRabbitMQ ▶️ View Recording
DeployK8sWithRedis ▶️ View Recording
DeployK8sWithSqlServer ▶️ View Recording
DeployK8sWithValkey ▶️ View Recording
DeployTypeScriptAppToKubernetes ▶️ View Recording
DescribeCommandResolvesReplicaNames ▶️ View Recording
DescribeCommandShowsRunningResources ▶️ View Recording
DetachFormatJsonProducesValidJson ▶️ View Recording
DetachFormatJsonProducesValidJsonWhenRestartingExistingInstance ▶️ View Recording
DoListStepsShowsPipelineSteps ▶️ View Recording
DocsCommand_RendersInteractiveMarkdownFromLocalSource ▶️ View Recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ View Recording
DoctorCommand_TypeScriptAppHostReportsMissingConfiguredToolchain ▶️ View Recording
DoctorCommand_WithSslCertDir_ShowsTrusted ▶️ View Recording
DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted ▶️ View Recording
GlobalMigration_HandlesCommentsAndTrailingCommas ▶️ View Recording
GlobalMigration_HandlesMalformedLegacyJson ▶️ View Recording
GlobalMigration_PreservesAllValueTypes ▶️ View Recording
GlobalMigration_SkipsWhenNewConfigExists ▶️ View Recording
GlobalSettings_MigratedFromLegacyFormat ▶️ View Recording
InitTypeScriptAppHost_AugmentsExistingViteRepoAtRoot ▶️ View Recording
InteractiveCSharpInitCreatesExpectedFiles ▶️ View Recording
InvalidAppHostPathWithComments_IsHealedOnRun ▶️ View Recording
LatestCliCanStartStableChannelAppHost ▶️ View Recording
LatestCliCanStartStableChannelTypeScriptAppHost ▶️ View Recording
LegacySettingsMigration_AdjustsRelativeAppHostPath ▶️ View Recording
LogLevelTrace_ProducesTraceEntriesInCliLogFile ▶️ View Recording
LogsCommandShowsResourceLogs ▶️ View Recording
OtelLogsReturnsStructuredLogsFromStarterAppCore ▶️ View Recording
PsCommandListsRunningAppHost ▶️ View Recording
PsFormatJsonOutputsOnlyJsonToStdout ▶️ View Recording
PublishWithConfigureEnvFileUpdatesEnvOutput ▶️ View Recording
PublishWithDockerComposeServiceCallbackSucceeds ▶️ View Recording
PublishWithoutOutputPathUsesAppHostDirectoryDefault ▶️ View Recording
ResourceCommand_FailsWhenInteractionServiceIsRequired ▶️ View Recording
RestoreGeneratesSdkFiles ▶️ View Recording
RestoreGeneratesSdkFiles_WithConfiguredToolchain ▶️ View Recording
RestoreRefreshesGeneratedSdkAfterAddingIntegration ▶️ View Recording
RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes ▶️ View Recording
RunFromParentDirectory_UsesExistingConfigNearAppHost ▶️ View Recording
SecretCrudOnDotNetAppHost ▶️ View Recording
SecretCrudOnTypeScriptAppHost ▶️ View Recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ▶️ View Recording
StartAndWaitForTypeScriptSqlServerAppHostWithNativeAssets ▶️ View Recording
StopAllAppHostsFromAppHostDirectory ▶️ View Recording
StopNonInteractiveSingleAppHost ▶️ View Recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View Recording
UnAwaitedChainsCompileWithAutoResolvePromises ▶️ View Recording
UpdateProjectChannelToStable_TypeScript_PicksUpStablePackages ▶️ View Recording

📹 Recordings uploaded automatically from CI run #25899938835

@mitchdenny mitchdenny merged commit fa0cfa8 into main May 16, 2026
296 checks passed
@microsoft-github-policy-service microsoft-github-policy-service Bot added this to the 13.4 milestone May 16, 2026
aspire-repo-bot Bot added a commit to microsoft/aspire.dev that referenced this pull request May 16, 2026
The aspire update command now applies all package version edits before
running a single final dotnet restore, preventing NU1103 failures when
switching to channels that add NuGet source mappings (daily, staging, etc.)

Fixes microsoft/aspire#17017

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@aspire-repo-bot
Copy link
Copy Markdown
Contributor

Pull request created: #989

Generated by PR Documentation Check

@aspire-repo-bot
Copy link
Copy Markdown
Contributor

📝 Documentation has been drafted in microsoft/aspire.dev#989 targeting release/13.4.

Updated src/frontend/src/content/docs/reference/cli/commands/aspire-update.mdx to document the deferred-restore behavior introduced by this PR:

  • Expanded the Description bullet list to note that all package version edits are applied before a single final dotnet restore runs (preventing NU1103 on channel switches).
  • Expanded the --channel option entry with an explanation of how the deferred restore ensures NuGet source mappings are in place before restore.
  • Added a --channel daily example to the Examples section.

Note

This draft PR needs human review before merging.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

aspire update --channel daily fails because nuget.config is modified before packages are updated

3 participants