Repository navigation
Centralize temporary storage allocation behind an internal helper - #22553
Conversation
Centralize system temp allocation in a source-linked internal helper and enforce the boundary with development-only banned API analysis. Preserve allocation locations and Hosting filesystem behavior. Co-authored-by: Copilot App <[email protected]>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 22553Or
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 22553" |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
Public documentation references an internal helper unavailable to Hosting package consumers; both occurrences should describe system temporary directory APIs in plain text.
1 open issue
What changed in this PR
Centralizes Aspire’s temporary storage allocation behind a source-linked internal helper while preserving existing locations, allocation semantics, cleanup, and Hosting’s public API.
Changes:
- Routes production temporary storage calls through
TemporaryStorage. - Adds development-only analyzer enforcement against direct system temporary storage calls.
- Adds analyzer tests, shared-source wiring, and test-selection routing for the policy file.
| File | Description |
|---|---|
tests/Infrastructure.Tests/TemporaryStorageTests.cs |
Tests analyzer rejection of direct temporary storage calls. |
tests/Infrastructure.Tests/Infrastructure.Tests.csproj |
Supplies analyzer assemblies for policy tests. |
tests/Aspire.Tray.Tests/Aspire.Tray.Tests.csproj |
Links the helper into Tray tests. |
src/Shared/TemporaryStorage.cs |
Introduces the internal allocation helper. |
src/Shared/SocketPermissionHelper.cs |
Routes temporary-root lookup through the helper. |
src/Shared/MsBuildResponseFile.cs |
Routes response-file directory allocation through the helper. |
src/Shared/ChildProcess.cs |
Routes process-completion directory allocation through the helper. |
src/Directory.Build.targets |
Enables analyzer enforcement and links the helper into consumers. |
src/BannedSymbols.txt |
Defines prohibited direct system temporary storage calls. |
src/Aspire.Tray/Windows/NativeSmokeHarness.cs |
Migrates Windows smoke-test directory allocation. |
src/Aspire.Tray/Mac/NativeSmokeHarness.cs |
Migrates macOS smoke-test directory allocation. |
src/Aspire.Tray/Linux/LinuxTrayIcons.cs |
Migrates temporary icon directory allocation. |
src/Aspire.Hosting/Utils/IFileSystemService.cs |
Revises temporary storage documentation only. |
src/Aspire.Hosting/Utils/FileSystemService.cs |
Delegates allocation while retaining tracking and cleanup. |
src/Aspire.Hosting/IDistributedApplicationBuilder.cs |
Revises filesystem-service guidance only. |
src/Aspire.Hosting.RemoteHost/JsonRpcServer.cs |
Routes Windows socket temporary-root lookup through the helper. |
src/Aspire.Hosting.Radius/Publishing/RadiusDeploymentPipelineStep.cs |
Migrates kubeconfig and deployment-parameter directories. |
src/Aspire.Hosting.Native.Server/Dcp/DcpApiClient.cs |
Migrates the native DCP working directory. |
src/Aspire.Hosting.Kubernetes/KubernetesEnvironmentResource.cs |
Migrates patch, manifest, and TLS staging directories. |
src/Aspire.Hosting.Dotnet/DotnetProjectRunPropertiesResolver.cs |
Migrates the MSBuild results directory. |
src/Aspire.Hosting.Azure/AzureProvisioningResource.cs |
Migrates Bicep generation directory allocation. |
src/Aspire.Hosting.Azure/AzureBicepResource.cs |
Migrates temporary Bicep template allocation. |
src/Aspire.Dashboard/ServiceClient/DashboardRunStore.cs |
Migrates nonpersistent dashboard storage allocation. |
src/Aspire.Cli/Utils/EnvironmentChecker/GoAppHostToolingCheck.cs |
Migrates the isolated Go tooling probe directory. |
src/Aspire.Cli/Utils/EnvironmentChecker/DcpConnectionChecker.cs |
Migrates the DCP diagnostic session directory. |
src/Aspire.Cli/Utils/CliDownloader.cs |
Migrates CLI download staging. |
src/Aspire.Cli/Projects/NativeAppHostServerProject.cs |
Migrates native AppHost SDK generation storage. |
src/Aspire.Cli/Projects/GuestAppHostProject.cs |
Migrates integration-install result storage. |
src/Aspire.Cli/NuGet/TemporaryNuGetConfigFile.cs |
Migrates temporary NuGet configuration directories. |
src/Aspire.Cli/NuGet/NuGetClient.cs |
Migrates embedded trust-root staging. |
src/Aspire.Cli/NuGet/BundleNuGetService.cs |
Migrates temporary package acquisition storage. |
src/Aspire.Cli/Npm/NpmRunner.cs |
Migrates isolated npm temporary directories. |
src/Aspire.Cli/Configuration/ConfigSourceService.cs |
Migrates configuration-source version-check storage. |
src/Aspire.Cli/Commands/UpdateCommand.cs |
Migrates CLI update extraction storage. |
src/Aspire.Cli/Commands/RenderCommand.cs |
Migrates link-rendering smoke-test storage. |
src/Aspire.Cli/Certificates/CertificateGeneration/MacOSCertificateManager.cs |
Migrates temporary certificate files. |
src/Aspire.Cli/Certificates/CertificateGeneration/CertificateManager.cs |
Migrates certificate-export temporary files. |
src/Aspire.Cli/Agents/Playwright/PlaywrightCliInstaller.cs |
Migrates skill-generation and download staging. |
eng/github-ci/test-trigger-map.yml |
Routes analyzer policy changes to shared-build validation targets. |
Directory.Packages.props |
Pins the Banned API analyzer package. |
Review effort: Balanced
ChildProcess.cs now uses Aspire.Shared.TemporaryStorage, so the generated ProcessTestHost project must compile it alongside the other shared sources. Co-authored-by: Copilot App <[email protected]>
This comment has been minimized.
This comment has been minimized.
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
Co-authored-by: Copilot App <[email protected]>
This comment has been minimized.
This comment has been minimized.
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
There was a problem hiding this comment.
🟡 Changes recommended
The new preservation-dependent cleanup can leave exported kubeconfig credentials on disk after the version check, replacing the previous unconditional best-effort deletion of sensitive artifacts.
2 open issues
Review effort: Balanced
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
Co-authored-by: Copilot App <[email protected]>
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
Radius parameter cleanup still recursively deletes the tracked directory, ignoring ASPIRE_PRESERVE_TEMP_FILES and leaving it registered until shutdown rather than disposing its filesystem-service handle.
1 open issue
2 resolved since last review
Review effort: Balanced
Return a handle owning the TempDirectory from WriteDeployParametersFileAsync and dispose it after deployment and on write failure, so ASPIRE_PRESERVE_TEMP_FILES is honored and the directory stops being tracked once it is cleaned up. Co-authored-by: Copilot App <[email protected]>
Tests selectorSelects the full PR test matrix + all PR-gated jobs (ALL) — a rule matching 'Directory.Packages.props' selects ALL Selection computed for commit |
|
Pull request created: #2250
|
|
📝 Documentation has been drafted in microsoft/aspire.dev#2250 targeting Documented Note This draft PR needs human review before merging. |
#21919 added a test that predates the CertificateManager.Create and DcpConnectionChecker signature changes from #22553. Co-authored-by: Copilot App <[email protected]>
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `a4a7fdc6e14c767da40d1a8cac4598d40a29ed78` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ All 14 image-build harness scenarios pass on Linux (node 24), including new pre-deadline and cleanup Docker/plugin 255 cases, which fail without the fix.<br>↑ DcpConnectionHealthCheckTests builds; the repaired test passes locally.<br>↑ All 61 AzureAppServiceTests pass locally with updated snapshots.<br>↓ Two DcpConnectionHealthCheckTests string assertions fail locally only due to a Spanish UI culture.<br>↓ Post-push CI not yet inspected at time of assessment. | | Diagnosis confidence | 9/10 | ↑ docker/cli v28.0.4 propagates WaitStatus.ExitStatus() (-1 for signaled plugins, exit 255).<br>↑ CI log shows CS7036 at DcpConnectionHealthCheckTests.cs:208-209 matching the #22553 signatures. | | Evidence fit | 8.5/10 | ↑ Regression reproduces the reviewer's fallback-and-exit-0 symptom.<br>↓ Not validated against a real Buildx plugin kill. | <!-- /copilot-assessment --> ## Description Shared CLI E2E image builds can exhaust their 45-minute job downloading from a throttled Azure Ubuntu apt mirror without reaching the existing error-only fallback. Bound primary attempts so default-source fallback also runs for slow or stalled builds. Independent fix based on `main`; relates to #21828, which is unchanged and is not a dependency. No auto-merge or bypass requested. - Share orchestration across the reusable image workflow and cache warmer. Apply a five-minute primary limit to .NET, polyglot base, Java and Go. Four primary attempts plus four 30-second cleanup grace periods leave 23 minutes within the unchanged 45-minute cap for fallback, setup and artifact handling. - TERM the client's process group so Docker can cancel its BuildKit session. Retry exactly once after ordinary failure or deadline, preserving both attempts' output and fallback status. A dependency-free Node supervisor tracks deadline and external signals independently, including cancellation during cleanup. External cancellation and forced kills, including an independently killed client, fail without fallback. - Preserve original Ubuntu apt sources and restore them for empty mirror arguments, including inherited Java/Go layers. Leave third-party sources untouched. - Add behavioral regressions, test-selection routes, cache-warmer filters and docs. No action pins, package manifests or product code changed. - Treat Docker exit 255 (a CLI plugin such as Buildx killed by a signal) as unconfirmed cancellation, before or during deadline cleanup, so it fails without fallback. - Fix the `main` build break in `tests/Aspire.Cli.Tests/Utils/DcpConnectionHealthCheckTests.cs`: the test added by #21919 used the pre-#22553 `CertificateManager.Create` and `DcpConnectionChecker` signatures (CS7036). It now passes `TemporaryStorage` like neighboring tests. - Fix the `main` test break in `AzureAppServiceTests.UserDefinedSlotConfigNames_AreMergedWithGeneratedStickySettings`: the snapshots from #21457 predate the `resourceId`/`resourceLocation` outputs added by #21396. ### Two-attempt root-cause evidence Both jobs ran at #21828 head `1ab3ad1e302a110bdb4f69ad4e3ee2e05d646d9a` in [run 42151619597](https://github.com/microsoft/aspire/actions/runs/42151619597). Both have annotation `The job has exceeded the maximum execution time of 45m0s`. | Attempt | Image job | Started / completed (UTC, November 6) | Exact apt log | | --- | --- | --- | --- | | 1 | [127676748230](https://github.com/microsoft/aspire/actions/runs/42151619597/job/127676748230) | 02:41:00 / 03:26:22 | `#11 2272.6 Fetched 82.4 MB in 37min 49s (36.3 kB/s)` | | 2 | [127692798471](https://github.com/microsoft/aspire/actions/runs/42151619597/job/127692798471) | 03:29:03 / 04:14:24 | `#11 2492.6 Fetched 108 MB in 41min 29s (43.4 kB/s)` | Attempt 2 then downloaded from HTTPS GitHub at `#11 2497.2 Fetched 15.1 MB in 0s (80.1 MB/s)`, while another mirror download logged `#15 92.37 Fetched 4031 kB in 1min 29s (45.4 kB/s)`. Both also reported GHA cache-import HTTP 400, `Our services aren't available right now`. Cold apt downloads, not product tests, consumed the image job. Neither attempt reached product-test execution using these images. No third rerun was triggered. ### Local validation `.\restore.cmd`: passed, 0 errors and 18 dependency-advisory warnings. Original selector coverage passed across appropriate hosts: 299 Windows managed cases, 2 Windows native MSBuild graph cases and 79 Linux shell/Git cases: ```powershell dotnet test --project tests\Infrastructure.Tests\Infrastructure.Tests.csproj --no-launch-profile -- --filter-namespace "Infrastructure.Tests.TestTriggerMap" --filter-not-class "*.PrComparisonBaseTests" --filter-not-class "*.SelectTestsCliTests" --filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true" # Passed: 299 dotnet test --project tests\Infrastructure.Tests\Infrastructure.Tests.csproj --no-launch-profile -- --filter-method "*.NativeDashboardSharedHelpersSelectNativeValidationInEnforceMode" --filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true" # Passed: 2 dotnet test --project tests\Infrastructure.Tests\Infrastructure.Tests.csproj --no-launch-profile -- --filter-class "*.TestTriggerMapTests" --filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true" # Passed: 179 after the final routing change dotnet run --project tools\SelectTests -- --changed-files <generated-changed-files.txt> --explain # Passed: production graph/prefilter, 0 unattributed inputs. # Shared Docker shell helper correctly activates the existing ALL route. ``` Linux container, pinned .NET runtime, same built MTP assembly: ```bash /tmp/dotnet/dotnet /repo/artifacts/bin/Infrastructure.Tests/Debug/net11.0/Infrastructure.Tests.dll --filter-class "*.PrComparisonBaseTests" --filter-class "*.CliE2EImageBuildTests" --filter-class "*.SelectTestsCliTests" --filter-not-method "*.NativeDashboardSharedHelpersSelectNativeValidationInEnforceMode" --filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true" --results-directory /tmp/test-results # Original implementation: passed 88 (79 selector + 9 image cases). /tmp/dotnet/dotnet artifacts/bin/Infrastructure.Tests/Debug/net11.0/Infrastructure.Tests.dll --filter-class "*.CliE2EImageBuildTests" --filter-not-trait quarantined=true --filter-not-trait outerloop=true # Final b8274fc: passed all 13 expanded image cases. ``` The initial Windows run failed in 17 shell cases because it selected the broken System32 WSL bash shim, and 5 existing Git-fixture cleanup cases with `UnauthorizedAccessException`. The same cases passed on Linux. The 2 native graph cases passed on Windows; running the Windows SDK on Linux caused `BadImageFormatException`. Passing partitions cover every focused case without modifying unrelated tests. The 13 image cases cover success, ordinary failure, fallback failure, slow success, stall, forced kill, client cancellation, external cancellation before/during deadline cleanup, client SIGKILL during cleanup, all-image/.NET-only orchestration, and exact original apt-source restoration in real Ubuntu. Cleanup cancellation reproduces on 4bb054c as incorrect exit 0 plus fallback; the corrected supervisor exits 143 without fallback. Killed clients retain 137, never deadline 124. Real Docker/Buildx probe re-run after the supervisor change: ```bash build_with_mirror_retry 20s "real BuildKit cancellation probe" docker buildx build --progress plain --load -t mirror-fallback-probe ``` Passed: primary printed `PRIMARY_RUNNING`, then `#5 CANCELED` / `Canceled: context canceled`; fallback printed `FALLBACK_RUNNING` and loaded the image. BuildKit history recorded primary `Error` and fallback `Completed`. Process inspection before fallback and afterwards found only the BuildKit daemon, no surviving primary `RUN`/`sleep`. Temporary builder and image removed. `git diff --check`: passed. ### Actual final-head CI Head **b8274fc8e0377c70ada8aa9eecfbdbc4069c6ff7**, [run 42170803717](https://github.com/microsoft/aspire/actions/runs/42170803717): **image build and all four uploads passed; Infrastructure passed 2090/2090; all 116 selected CLI archive E2E jobs passed.** The downloaded Infrastructure TRX confirms all 13 new image cases passed. CLI unit tests passed on Linux, macOS and Windows. This is actual final-head evidence, not evidence from superseded runs. [Image job 127739541935](https://github.com/microsoft/aspire/actions/runs/42170803717/job/127739541935) ran 05:56:03–06:05:32 UTC. All four artifacts are present and unexpired: | Variant | Artifact ID | Size (bytes) | Uploaded UTC | | --- | --- | --- | --- | | .NET | 13481517063 | 696399767 | 06:04:42 | | Polyglot | 13480867983 | 391644472 | 06:04:54 | | Java | 13481671757 | 654944092 | 06:05:13 | | Go | 13481043964 | 583388699 | 06:05:30 | The primary mirror was healthy: `#11 4.388 Fetched 108 MB in 1s (114 MB/s)`. **No actual CI timeout/fallback occurred**; fallback evidence is deterministic/local BuildKit evidence, not a production CI claim. Representative actual consumers confirm all four artifacts load and execute tests: | Consumer job | Images loaded | Test outcome | | --- | --- | --- | | [Go starter 127743182589](https://github.com/microsoft/aspire/actions/runs/42170803717/job/127743182589) | .NET, polyglot, Go | 1 passed, 1 skipped | | [Java polyglot 127743185239](https://github.com/microsoft/aspire/actions/runs/42170803717/job/127743185239) | .NET, polyglot, Java | 1 passed | | [.NET smoke 127743188570](https://github.com/microsoft/aspire/actions/runs/42170803717/job/127743188570) | .NET, polyglot | 10 passed | **Required checks are not green; approval is still required.** Two failures outside the changed image infrastructure remain, with same-source main controls rather than blind reruns: - [Windows extension units 127739542026](https://github.com/microsoft/aspire/actions/runs/42170803717/job/127739542026): 4150 passed, 9 pending, 1 failed. `rejects when a POSIX process group remains alive after forced termination` passed its rejection/listener assertions but saw global fake-timer count 2 instead of 0. Test and process-helper blobs are identical to main 54b4929. [Main control 127718292677](https://github.com/microsoft/aspire/actions/runs/42164303520/job/127718292677) passed that exact case and all 4151 tests. The source of the two timers is not established; no extension edit or retry made. - [Windows Hosting-2 127739572340](https://github.com/microsoft/aspire/actions/runs/42170803717/job/127739572340): `ExecutableDoesNotExist` and `ExecutableWorkingDirectoryDoesNotExist` failed before scenario assertions because DCP's `docker.exe --version` dependency probe timed out. Test file and entire DCP source tree are identical to main 54b4929. [Main control 127718297752](https://github.com/microsoft/aspire/actions/runs/42164303520/job/127718297752) TRX passed the same cases in 6.005s and 2.854s. No product edit or retry made. All four review threads have been addressed. No merge or bypass performed; #21828 remains untouched and cannot consume this fix until integration. ### Security considerations The supervisor executes existing checked-in Docker commands, not new untrusted input. Separate-session process-group signaling avoids signaling the workflow shell and permits child cleanup. A forced kill cannot confirm remote BuildKit cancellation, so it fails closed without fallback. No threat model or separate security review has been performed. Fixes # (issue) ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - [ ] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [x] 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 - [x] No - Does the change make any security assumptions or guarantees? - [x] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [x] No - [ ] No --------- Co-authored-by: IEvangelist <[email protected]> Co-authored-by: Copilot App <[email protected]> Co-authored-by: Adam Ratzman <[email protected]>
Integrate pinned main b2baebe. Use TemporaryStorage.SystemTempPath for the two system-root safety guards, preserving behavior while satisfying the banned API analyzer introduced by #22553. Co-authored-by: Copilot App <[email protected]>
) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `a59c24f38ed49a18059c953b917e78e3883c0067` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8/10 | ↑ Current Release CLI build with banned-API analysis and 132 command/reporter tests passed after integrating pinned main and updating both system-temp guards.<br>↑ Historical hosting, generated SDK and packaged CLI evidence is recorded below.<br>↓ New-head cross-platform/native CI is pending; full local repository, security and API reviews remain unperformed. | <!-- /copilot-assessment --> ## Description Add experimental `aspire test`: keep supporting services available until every annotated resource/replica and its runtime result collector completes, report observed outcomes, then shut down orderly. `--keep-alive` retains the foreground CLI/AppHost for inspection after success or failure. `--format json` emits one summary object on stdout, with diagnostics on stderr. **Preview opt-in:** the command is disabled by default. Run `aspire config set features.testCommandEnabled true` to enable it. The flag only gates CLI command registration; it does not add hosting/runtime API gates or change ordinary `aspire run`. Both packaged C#/TypeScript CLI E2E scenarios explicitly enable it. **Current API:** `WithTesting()` marks a resource for process-based completion. `WithTesting(Func<ResourceTestingContext, Task>?)` registers one optional asynchronous runtime collector. The callback never executes during model construction, ordinary run, or publish. There is no public configuration wrapper or prelaunch output-path accessor. Repeating `WithTesting` replaces the callback; marker-only clears it. Both preserve the internally allocated resource output directory and containing context. The two context types are **`TestingContext`** for the invocation and **`ResourceTestingContext`** for an individual logical resource. The latter exposes its containing context through **`TestingContext`**, so `context.TestingContext.OutputPath` is the run directory and `context.OutputPath` is the resource directory. No compatibility aliases or obsolete wrappers are retained for these unshipped APIs. All new public hosting testing APIs carry `ASPIRETESTING001`. This foundation supplies framework-neutral orchestration/reporting; upper integrations own framework helpers, report parsing, and source-outcome mappings. **Run isolation:** `RunCommand.cs` and every `RunCommandStrings` localization file remain unchanged from the PR merge base. `TestCommand` deliberately owns launch/startup, cancellation/drain, reporting, and inspection while calling existing project/backchannel/secrets/logging services. Necessary startup bookkeeping is duplicated rather than extracting a shared runner that could alter ordinary development behavior. Run IDs, coordinator/reporter names, protocol DTOs, paths, lifetimes, cancellation, and seven-outcome policies are unaffected by the context naming revision. ### User-facing API and usage Marker-only execution works for any resource capable of reporting authoritative completion: ```csharp #pragma warning disable ASPIRETESTING001 builder.AddExecutable("smoke-tests", "custom-test-runner", ".") .WithTesting(); ``` Collectors run alongside resource execution. Runner arguments/environment and report locations must be configured independently, not from the callback or its synchronous prefix. This excerpt follows the [source playground](https://github.com/microsoft/aspire/tree/mitchdenny-aspire-test-lifetime/playground/AspireCliTesting): `service`/`serviceEndpoint` refer to its shared HTTP service, and the playground deletes the private runner-report directory in an AppHost shutdown `finally` block. ```csharp var reports = Directory.CreateTempSubdirectory("probe-reports-"); var tests = builder.AddDotnetProject("foundation-tests", "foundation-tests/tests.cs") .WithEnvironment("SERVICE_URL", serviceEndpoint) .WithEnvironment("TEST_OUTPUT_PATH", reports.FullName) .WaitFor(service); tests.WithTesting(async context => { var passed = await context.WaitForCompletionAsync(); if (passed) { var report = Path.Combine(reports.FullName, "probe.txt"); var actual = await File.ReadAllTextAsync(report, context.CancellationToken); passed = actual == "Aspire CLI testing"; File.Copy(report, Path.Combine(context.OutputPath, "probe.txt")); } context.PublishResult(new TestResult { Name = "shared-service-probe", Outcome = passed ? TestOutcome.Passed : TestOutcome.Failed }); }); ``` `ResourceTestingContext` exposes `TestingContext`, `ResourceName`, `OutputPath`, `CancellationToken`, `PublishResult(TestResult)`, and: ```csharp public TestingContext TestingContext { get; } public Task<bool> WaitForCompletionAsync(CancellationToken cancellationToken = default); ``` The completion helper describes resource execution independently of published results. Its default always observes run cancellation, including `--timeout-seconds` and Ctrl+C. A supplied token adds caller-local cancellation; it cannot disable run cancellation. Cancelling one wait does not cancel authoritative completion or other waiters. No separate timeout or hidden default is introduced. Generated TypeScript retains the resource context and projects the containing type as `TestingContext`, accessed through `context.testingContext()`: ```typescript await tests.withTesting(); await tests.withTesting({ callback: async context => { await context.waitForCompletionAsync(); const invocation = await context.testingContext(); // invocation.outputPath() identifies the containing run; // context.outputPath() identifies this resource's artifact destination. // Read independently configured reports, stage artifacts, and publish results. }, }); // Optional caller-local cancellation: // await context.waitForCompletionAsync({ cancellationToken: signal }); ``` `TestResult.Outcome` remains required; omitted or undefined outcomes are not silently fabricated. The enum uses implicit values with failure as its default: ```csharp public enum TestOutcome { Failed, Passed, Skipped, Inconclusive, Error, TimedOut, Cancelled } ``` Only `Passed` and `Skipped` are non-failing. All five other outcomes make testing unsuccessful even when resource processes exit zero. Individual JSON/streamed results preserve `failed`, `passed`, `skipped`, `inconclusive`, `error`, `timedOut`, or `cancelled`; generated TypeScript retains member names as string enum values. The shared host/CLI classifier rejects unknown outcomes rather than falling through to success. Published test `TimedOut`/`Cancelled` outcomes are normal test failures (exit `23`), not overall command deadline expiry (`17`) or user cancellation (`130`). They do not cancel peers, change deadlines, synthesize cancellation events, or fabricate unobserved tests. Process completion remains independent: a successful process can have unsuccessful results, and passing tests cannot override a failed process or collector exception. ### Lifetime, output, and deadlines - Exit `0` requires successful resource execution/collection and orderly shutdown. Nonzero/unknown terminal process status, startup failure, unsuccessful published outcomes, and collector exceptions cannot silently pass. Resource/test failure returns `23`; startup/RPC/configuration/shutdown errors have explicit nonzero diagnostics. User cancellation returns `130`. - All resources/replicas and current callbacks are joined without fail-fast behavior. Collection starts before CLI connection; events are retained/replayed. Already-terminal resources, notification races, late exit codes, and callback exceptions are covered. An early-returning callback cannot finish a running resource. Publication closes when its callback ends or cancellation occurs; noncooperative callbacks cannot change finalized output. - In guest testing mode, a successful guest exit explicitly requests server shutdown, waits for authoritative server completion, and preserves server failures/forced termination rather than discarding them during best-effort session disposal. Guest nonzero exits and caller cancellation remain failures; ordinary non-watch run behavior is unchanged. - The CLI creates a unique private `~/.aspire/testruns/<run-id>` before launching the AppHost, honoring configured Aspire home. The host internally allocates `<run-id>/<logical-resource-name>` before execution. No `resources` intermediary or resource GUID suffix. Replicas share their logical resource's directory; integrations coordinate replica-specific filenames. Invalid portable names, case collisions, existing paths, and unsafe links fail explicitly rather than being sanitized/adopted. Dashboard/test run-ID correlation remains deferred; the two roots use independent identifiers. - Text distinguishes `Resource` state transitions from `Test` results, displays exit codes only for terminal states, and emits accurate per-resource passed/failed/other totals after collection drains. All five unsuccessful outcomes count as **failed**; **other** counts skips only. Individual outcomes remain visible: unsuccessful test results red, passes green, skips yellow. Resource-only tests do not invent counts. Overall verdict, published totals, artifact links, and useful error/partial-run diagnostics remain; no duplicate final resource table. - Versioned `summary.json` records paths/timestamps/status/exit/error, actual resource observations, results, collection status, and totals. `publishedResults.failed` includes all five unsuccessful outcomes; `passed` and `skipped` count only their named outcomes. Every publication is counted once while retaining its specific outcome. No new result metadata fields. Exit codes never fabricate counts. - JSON stdout is one object without interactive output. During keep-alive it is emitted once at completion with `cliExitCode: null`; the final file later records inspection/shutdown outcome without another stdout object. - `--timeout-seconds` optionally bounds discovery/build, startup, execution, collection, and keep-alive using one monotonic deadline. It has no default and is distinct from startup-only timeout. Integers `1` through `4294967` are validated before artifacts/launch. Expiry returns `17` after at most five additional seconds of bounded teardown. Partial observations persist as `timedOut`; completed inspection results retain outcome/time while the final file records timeout exit/diagnostics. Explicit user cancellation takes precedence (`130`). ```bash aspire config set features.testCommandEnabled true aspire test --apphost ./AppHost/AppHost.csproj aspire test --apphost ./AppHost/AppHost.csproj --keep-alive aspire test --apphost ./AppHost/AppHost.csproj --timeout-seconds 120 --format json --non-interactive ``` The file-based playground resolves the hosting SDK and dashboard from repository source, without released experimental packages or private package hives. Later framework layers append scenarios to its shared AppHost; fixtures/report locations remain their responsibility. Development watch, detached testing, profile capture, and extension-managed test debug lifetimes are not supported. ### Screenshots / Recordings > **This PR includes UI changes.** Please add screenshots or screen recordings so reviewers can evaluate the visual changes without running locally. > > - For before/after comparisons, place them side-by-side or label them clearly. > - For interactive changes (animations, transitions, new flows), prefer a short screen recording (GIF or video). > - **TODO:** No text-rendering walkthrough was captured. Exercise multiple annotated resources/replicas and a failure; inspect resource/test distinction, terminal-only exit codes, collector-drained counts, overall totals/artifact links, keep-alive, and plain/no-color output. There is no final resource table. The new JSON CLI E2E cases produce diagnostic terminal recordings through the existing harness, not a visual-rendering demonstration. <!-- Add screenshots/recordings here --> ### Security considerations Threat modeling/security review remains pending. Dedicated run/resource directories use Unix `0700`; CLI-owned files use `0600` from creation. Windows directories use protected current-user ACLs with inherited file permissions. Dedicated `testruns` permissions are hardened without changing unrelated Aspire-home permissions. Unsafe links/reparse paths and writable Unix ancestors below trusted roots are rejected. Exclusive name reservations and private temporary files/atomic summary replacement avoid adopting or truncating existing destinations. Framework report permissions and container identity/mount access remain integration responsibilities. No new dependencies or external services; the optional playground starts a development HTTP service on a dynamic local endpoint. ### Validation **Latest CI compatibility correction:** integrated pinned main `b2baebe8864c718587bd7d13cfe5460a80f83062` and replaced both direct system-temp root probes in `TestRunReporter` with `TemporaryStorage.SystemTempPath`. The failed native archive, CLI, v2 RPC and TypeScript compatibility jobs all stopped at the same RS0030 compile errors after main's #22553 analyzer change; this is not a Homebrew recurrence. Console login-link behavior is unchanged. Current-head CI is pending. ```bash ./restore.sh # Passed: 0 warnings, 0 errors. dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --configuration Release --no-launch-profile -- --filter-class '*.Commands.TestCommandTests' --filter-class '*.TestRunReporterTests' --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 132 tests, including reporter path guards and console login-link/non-logging regressions; production banned-API analysis enabled. ``` **Current feature-flag revision:** `testCommandEnabled` defaults to false and gates only CLI command registration. Focused tests cover unset/false/true configuration, command availability, existing test-command behavior, configuration discovery, and ordinary run. The actual source CLI rejects `test` by default (exit `1`) and displays test help when `features__testCommandEnabled=true` (exit `0`). C#/TypeScript packaged E2E setup now explicitly enables the flag; that updated project was built, not rerun against a new native package locally. New-head CI is not yet verified. ```bash dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --no-launch-profile -- \ --filter-class '*.RootCommandTests' --filter-class '*.KnownFeaturesTests' \ --filter-class '*.TestCommandTests' --filter-class '*.ConfigCommandTests' \ --filter-class '*.RunCommandTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 356 tests. dotnet build tests/Aspire.Cli.EndToEnd.Tests/Aspire.Cli.EndToEnd.Tests.csproj --no-restore # Passed: 0 warnings, 0 errors. ``` **Earlier verified CI:** [run 41388552101, attempt 2](https://github.com/microsoft/aspire/actions/runs/41388552101/attempts/2) completed **successfully** for exact head `2f6dcc4a6e521e2e68e2e9dedef5462b676f0af5`, including final aggregation. This is historical evidence, not a green result for the subsequent preview-label, state-comparer, umask, or feature-flag revisions. The initial attempt had one unrelated unchanged Windows Managed terminal-host shutdown timeout; its single targeted rerun [passed](https://github.com/microsoft/aspire/actions/runs/41388552101/job/125106116188). No terminal-host source, assertions, timeouts, quarantine or skip settings were changed. CLI suites passed on Windows/Linux/macOS; Hosting-4 passed on Windows/Linux. Native hosting validation and the other PR checks also passed. **Earlier native CLI E2E passed:** [TestCommandTests job](https://github.com/microsoft/aspire/actions/runs/41388552101/job/125099931798), Linux x64, actual native CLI/packages at head `2f6dcc4a6e`, **2 tests passed in 2m28s**, exercising six real `aspire test` invocations. This validates the guest-shutdown source and corrected cross-UID fixture at that head, not merely an older archive or the current feature-flag revision. **Earlier review fixes:** guest testing now stops/drains the server and propagates completion (`b3a582dcf6`). A completion barrier proves it cannot return early; regression cases cover guest exit `0` with server `0`, `37`, `-1`, or `137`, guest exit `7`, cancellation during drain (`130`), ordinary non-watch run behavior, and cleanup. The replay regression (`2f6dcc4a6e`) pauses an actual notification replay predicate, publishes while paused, then checks the subscriber and multi-resource coordinator observe success/failure without a lost update or deadlock. Existing already-completed replay coverage remains separate; no public test hook or production instrumentation was added. ```bash export DOTNET_ROOT="$PWD/.dotnet" export PATH="$DOTNET_ROOT:$PATH" export MSBUILDTERMINALLOGGER=false dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --no-launch-profile -- \ --filter-class '*.GuestAppHostProjectTests' --filter-class '*.AppHostServerSessionTests' \ --filter-class '*.TestCommandTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 206 tests. dotnet test --project tests/Aspire.Hosting.Tests/Aspire.Hosting.Tests.csproj --no-launch-profile -- \ --filter-class '*.TestRunCoordinatorTests' --filter-class '*.TestRunStreamingTests' \ --filter-class '*.TestRunCoordinatorEndToEndTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 38 tests. ``` **Packaged CLI E2E:** `TestCommandTests.CSharpAppHost_TestResourcesCollectResultsAndStop` and `TestCommandTests.TypeScriptAppHost_TestResourcesCollectResultsAndStop` execute inside owned Linux Docker containers. Each language executes three real `aspire test` invocations: successful execution/result (exit `0`), process failure with a passing published result (exit `23`), and process success with a failing published result (exit `23`). Both AppHosts mark generic executable resources with `WithTesting`/`withTesting`, not a JavaScript testing integration. The runtime callback waits for authoritative completion, stages an artifact and publishes a result directly; TypeScript exercises real callback/context marshalling. A marker-only peer stays pending until publication completes and then probes the still-live HTTP dependency. Assertions cover the exact resource exit codes, collection state/counts, fresh flat artifact directory per invocation, artifact content, a single parseable JSON stdout object equal to persisted `summary.json`, and removal of all four recorded owned processes after return. AppHost construction explicitly checks that the collector has not run yet. Initial Linux CI exposed a fixture-only cross-UID permission issue: applying `umask 077` before scaffolding made root-owned bind-mounted source inaccessible to host fixture writes. `e1120ed4e8` retains harness shared-source permissions until host writes finish, then applies private runtime permissions and hardens only the owned container's Aspire home. Production artifact protections were not relaxed. ```bash ASPIRE_E2E_CLI_ARCHIVE_DIR="$PWD/artifacts/testing-cli-e2e-ci" \ ASPIRE_E2E_DOTNET_IMAGE=aspire-viteplus-e2e-runner:latest \ dotnet test --project tests/Aspire.Cli.EndToEnd.Tests/Aspire.Cli.EndToEnd.Tests.csproj --no-launch-profile -- \ --filter-class '*.TestCommandTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Local pass after permission fix: 2 tests, six real invocations, 1m55s. # Local driver: macOS arm64, owned Linux-arm64 containers. # Local native CLI/NuGet artifacts came from CI run 41382191517, product head f0d5b8f. # Head 2f6dcc4 Linux-x64 native execution separately passed in CI above. dotnet run --project tools/SelectTests -- --from 7b5825e^ --explain # Earlier added-file trace passed: new fixture attributed through ProjectGraph and convention # to Aspire.Cli.EndToEnd.Tests; one selected project and zero unattributed files. # CI admitted and passed a dedicated TestCommandTests class job. No routing-map edit required. ``` **CI fixes in `f0d5b8f6`:** refreshed Go/Java/Python/Rust generated snapshots for the current API; exercised `DisableExtensionLaunch` in the clone-property fixture; replaced Windows RPC fixture's inline `cmd /c` command with a batch file in a path containing spaces, and asserted actual terminal exit codes so error `99` cannot masquerade as an expected failure. The affected generator jobs and Windows Hosting-4 job passed in [CI run 41382191517](https://github.com/microsoft/aspire/actions/runs/41382191517); Linux/macOS CLI jobs passed. This run also hit an unrelated template SDK-download TLS handshake failure before test execution. The MongoDB failure on the earlier run matched existing flaky issue [#21593](#21593), and did not recur; no MongoDB changes were made. The superseded [run 41384739405](https://github.com/microsoft/aspire/actions/runs/41384739405) caught the E2E fixture permission issue fixed above and one unchanged Windows Git SSH verification theory failure after its five-second probe budget under runner contention. No SSH policy/timeout changes were made. That run was cancelled after the new fixes were pushed; the later head `2f6dcc4a6e` Windows CLI suite passed. Earlier context-naming revision validation, macOS arm64 with the restored repository SDK; quarantined/outerloop tests excluded. Generated TypeScript handle/getter/wrapper/registration changes were inspected and rerun successfully. The scanner explicitly checks the new getter capability and returned context type. ```bash dotnet test --project tests/Aspire.Hosting.Tests/Aspire.Hosting.Tests.csproj --no-launch-profile -- \ --filter-class '*.TestingCollectorTests' --filter-class '*.TestRunCoordinatorTests' \ --filter-class '*.TestRunStreamingTests' --filter-class '*.TestRunCoordinatorEndToEndTests' \ --filter-class '*.AppHostRpcTargetTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 96 tests. dotnet test --project tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests/Aspire.Hosting.CodeGeneration.TypeScript.Tests.csproj --no-launch-profile -- \ --filter-class '*.AtsTypeScriptCodeGeneratorTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 140 tests. dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --no-launch-profile -- \ --filter-class '*.TestRunReporterTests' --filter-class '*.TestCommandTests' --filter-class '*.RunCommandTests' \ --filter-not-trait 'quarantined=true' --filter-not-trait 'outerloop=true' # Passed: 247 tests. dotnet run --project src/Aspire.Cli/Aspire.Cli.csproj --no-launch-profile -- \ test --apphost playground/AspireCliTesting/apphost.cs --isolated \ --timeout-seconds 120 --format json --non-interactive # Earlier pass, before the default-off CLI gate: source AppHost built and executed; # exit 0; real shared-service-probe passed. New invocations require the opt-in above. # Directly verified one stdout JSON equals summary.json, current probe.txt content, # flat foundation-tests directory, and Unix 0700 directory/0600 artifact modes. base=$(git merge-base HEAD origin/main) git diff --exit-code "$base" -- src/Aspire.Cli/Commands/RunCommand.cs \ src/Aspire.Cli/Resources/RunCommandStrings.resx \ src/Aspire.Cli/Resources/RunCommandStrings.Designer.cs \ ':(glob)src/Aspire.Cli/Resources/xlf/RunCommandStrings.*.xlf' # Passed, including earlier review fixes: zero diff. git diff --check # Passed. ``` Coverage retains experimental context contracts, deferred runtime invocation, replacement/marker clearing with stable paths and containing context, default/run/caller cancellation and independent waiters, and all seven outcome policies. Real process/socket/RPC cases prove peers are awaited and per-test timeout/cancellation does not stop the host. CLI cases cover failure `23`, keep-alive, explicit cancellation/deadlines, truthful totals/specific outcomes, partial reporting, stdout purity, rendering/escaping/no-color, and ordinary-run regressions. Limits: the packaged CLI E2E cases do not exercise Ctrl+C, deadline expiry or keep-alive; those remain focused host/CLI test coverage. Local cross-OS native-AOT archive creation was blocked by missing native toolchain support, so local E2E validation used CI-built Linux artifacts rather than a fabricated local payload. No full local repository build, Windows packaged E2E execution, framework implementations/mappings, visual-rendering recording, API review, or threat-model/security review. The previous ordinary-run smoke remains historical evidence; this revision reran ordinary-run regression tests, not that manual scenario. ### Context and dependencies Informed by closed historical proposals [#18428](#18428) and [#13275](#13275), without claiming to fix them or implement their entire designs. The AppHost/CLI reporting contract remains `test-reporting.v1`; incompatible AppHosts fail explicitly. Framework integrations and dashboard work are separate stacked follow-ups. Fixes # (issue) ## Checklist - Is this feature complete? - [ ] Yes. Ready to ship. - [x] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - [ ] No - Did you add public API? - [x] Yes - If yes, did you have an API Review for it? - [ ] Yes - [x] No - Did you add `<remarks />` and `<code />` elements on your triple slash comments? - [x] Yes - [ ] No - [ ] No - Does the change make any security assumptions or guarantees? - [x] Yes - If yes, have you done a threat model and had a security review? - [ ] Yes - [x] No - [ ] No --------- Co-authored-by: Copilot App <[email protected]>


Description
Centralize temporary storage allocation behind a source-linked internal
ITemporaryStorageservice so the allocation boundary can be maintained consistently. Existing temporary locations and allocation semantics remain unchanged.IFileSystemService, so their temporary directories are tracked and cleaned up consistently and honorASPIRE_PRESERVE_TEMP_FILES.ASPIRE_PRESERVE_TEMP_FILESnow requires a truthy value (trueor a non-zero number); unset, empty,false, or0leave cleanup enabled.Follow-up PRs will build on this internal boundary.
Validation on macOS:
Fixes # (issue)
Checklist
<remarks />and<code />elements on your triple slash comments?