Skip to content

Heartbeat.cs: Replace PowerShell process spawns with .NET APIs on Windows#15888

Merged
radical merged 3 commits intomainfrom
copilot/replace-powershell-spawns-with-dotnet-apis
Apr 6, 2026
Merged

Heartbeat.cs: Replace PowerShell process spawns with .NET APIs on Windows#15888
radical merged 3 commits intomainfrom
copilot/replace-powershell-spawns-with-dotnet-apis

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 4, 2026

On Windows CI runners, the heartbeat monitor spawned 5 separate powershell.exe processes per cycle — each loading the full PS runtime (~100MB, high CPU on init) — contributing to runner hangs on 2-core windows-latest agents.

Changes

All 5 Windows metric collection paths now use zero-spawn .NET equivalents:

Metric Before After
CPU % Get-CimInstance Win32_Processor GetSystemTimes P/Invoke — idle/kernel/user time deltas (same approach as Linux /proc/stat)
Memory Get-CimInstance Win32_OperatingSystem GlobalMemoryStatusEx P/Invoke — single syscall
DCP processes Get-Process -Name 'dcp*' Process.GetProcesses() filtered by name prefix
Top 10 processes Get-Process | Sort-Object CPU Same Process.GetProcesses() call, sorted by CPU%
Disk Get-PSDrive -PSProvider FileSystem DriveInfo.GetDrives()

Key optimizations:

  • Process.GetProcesses() is called once per cycle and shared between DCP and Top metrics, with process handles disposed after both reads complete.
  • DllImport is used over LibraryImport (the script's auto-generated project doesn't have AllowUnsafeBlocks); SYSLIB1054 suppressed via #pragma warning disable.
  • FILETIME.ToLong() explicitly casts both fields to long before bitwise OR to prevent sign-extension overflow.
  • Linux and macOS code paths are unchanged.

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
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
    • No
  • Does the change require an update in our Aspire docs?
    • Yes
    • No

…indows

- CPU: Use GetSystemTimes P/Invoke (kernel32.dll) instead of Get-CimInstance Win32_Processor
- Memory: Use GlobalMemoryStatusEx P/Invoke (kernel32.dll) instead of Get-CimInstance Win32_OperatingSystem
- DCP processes: Use Process.GetProcesses() filtered by name instead of PowerShell Get-Process
- Top processes: Use Process.GetProcesses() sorted by CPU instead of PowerShell Get-Process
- Disk: Use DriveInfo.GetDrives() instead of PowerShell Get-PSDrive
- Share single Process.GetProcesses() call per cycle between DCP and Top metrics
- Fix FILETIME.ToLong() to cast dwLowDateTime to long before bitwise OR (prevents overflow)
- Apply consistent Math.Round to CPU% in GetTopProcesses to match GetDcpProcesses behavior

Agent-Logs-Url: https://github.com/microsoft/aspire/sessions/980b8145-b029-436f-938b-b3f6da2078c7

Co-authored-by: radical <1472+radical@users.noreply.github.com>
Copilot AI changed the title [WIP] Replace PowerShell process spawns with .NET APIs on Windows Heartbeat.cs: Replace PowerShell process spawns with .NET APIs on Windows Apr 4, 2026
Copilot AI requested a review from radical April 4, 2026 02:16
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 6, 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 -- 15888

Or

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

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 optimizes the CI heartbeat diagnostics script on Windows by removing repeated PowerShell spawns and replacing them with zero-spawn .NET and Win32 API equivalents, reducing CPU/memory overhead on constrained windows-latest runners.

Changes:

  • Replaced Windows CPU and memory metric collection with GetSystemTimes and GlobalMemoryStatusEx P/Invokes.
  • Reworked Windows “DCP processes” and “Top processes” to use a shared Process.GetProcesses() snapshot per cycle (with explicit disposal).
  • Replaced Windows disk usage collection with DriveInfo.GetDrives().

Copy link
Copy Markdown
Contributor

@maddymontaquila maddymontaquila left a comment

Choose a reason for hiding this comment

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

Gorgeous!!

- Wrap ProcessName/Id reads inside try/catch in DCP process collection
  so a single exited process doesn't abort the entire cycle
- Return nullable tuple in Top processes LINQ, filter nulls afterward,
  so ProcessName/Id are never read outside the guarded block
- Remove unused prevCpu (TimeSpan) and prevDateTime (DateTime) params
  from GetCpuUsage and their caller-side variables

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@radical radical enabled auto-merge (squash) April 6, 2026 19:57
radical added a commit that referenced this pull request Apr 6, 2026
…lelization disable

- Cherry-pick Heartbeat.cs from PR #15888: replaces all 5 Windows PowerShell
  process spawns with .NET P/Invoke and BCL APIs (GetSystemTimes, GlobalMemoryStatusEx,
  Process.GetProcesses, DriveInfo.GetDrives)
- Remove DisableTestParallelization from run-tests.yml build steps
- Remove tests/Directory.Build.targets xunit.runner.json swap for DisableTestParallelization
- Remove tests/github-actions/xunit.runner.json
- Keep: VBCSCompiler shutdown, UseSharedCompilation=false, 60s heartbeat interval

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@radical radical merged commit f7d09af into main Apr 6, 2026
523 of 526 checks passed
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 6, 2026

🎬 CLI E2E Test Recordings — 56 recordings uploaded (commit 20a2130)

View recordings
Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View Recording
AddPackageWhileAppHostRunningDetached ▶️ View Recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View Recording
AgentInitCommand_DefaultSelection_InstallsSkillOnly ▶️ View Recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View Recording
AllPublishMethodsBuildDockerImages ▶️ View Recording
AspireAddPackageVersionToDirectoryPackagesProps ▶️ View Recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ 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
CreateStartAndStopAspireProject ▶️ View Recording
CreateTypeScriptAppHostWithViteApp ▶️ View Recording
DashboardRunWithOtelTracesReturnsNoTraces ▶️ View Recording
DescribeCommandResolvesReplicaNames ▶️ View Recording
DescribeCommandShowsRunningResources ▶️ View Recording
DetachFormatJsonProducesValidJson ▶️ View Recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ 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
InvalidAppHostPathWithComments_IsHealedOnRun ▶️ View Recording
LegacySettingsMigration_AdjustsRelativeAppHostPath ▶️ View Recording
LogsCommandShowsResourceLogs ▶️ View Recording
PsCommandListsRunningAppHost ▶️ View Recording
PsFormatJsonOutputsOnlyJsonToStdout ▶️ View Recording
PublishWithDockerComposeServiceCallbackSucceeds ▶️ View Recording
RestoreGeneratesSdkFiles ▶️ View Recording
RestoreSupportsConfigOnlyHelperPackageAndCrossPackageTypes ▶️ View Recording
RunFromParentDirectory_UsesExistingConfigNearAppHost ▶️ View Recording
RunWithMissingAwaitShowsHelpfulError ▶️ View Recording
SecretCrudOnDotNetAppHost ▶️ View Recording
SecretCrudOnTypeScriptAppHost ▶️ View Recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ▶️ View Recording
StopAllAppHostsFromAppHostDirectory ▶️ View Recording
StopAllAppHostsFromUnrelatedDirectory ▶️ View Recording
StopNonInteractiveMultipleAppHostsShowsError ▶️ View Recording
StopNonInteractiveSingleAppHost ▶️ View Recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View Recording

📹 Recordings uploaded automatically from CI run #24048287050

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.

Heartbeat.cs: Replace PowerShell process spawns with .NET APIs on Windows

5 participants