Skip to content

Add memory leak tests for request handling and hot reload - #2170

Open
waldekmastykarz wants to merge 11 commits into
dotnet:mainfrom
waldekmastykarz:memory-leak-tests
Open

waldekmastykarz wants to merge 11 commits into
dotnet:mainfrom
waldekmastykarz:memory-leak-tests

Conversation

@waldekmastykarz

Copy link
Copy Markdown
Collaborator

Closes #2160

Adds MemoryRetentionTests to DevProxy.Integration.Tests, built on the existing harness (KestrelProxyHarness, FakeOrigin).

What the tests check

Test What it does On main
HotReload_ReleasesPreviousGenerations Builds the host with the same code Program.cs uses, loads MockResponsePlugin from its plugin DLL via a config file, proxies a mocked and a passed-through request, then rewrites the config file and waits for ConfigFileWatcher to stop the host. Repeats 20 times, then checks (with WeakReferences) that no previous generation's WebApplication, IServiceProvider, DevProxyCommand or plugins are still reachable. Skipped: all 20 generations are retained. Passes with #2153.
Requests_DoNotRetainMemory 1,000 warm-up + 10,000 measured requests through the Kestrel engine (mocked, passed-through, 64 KB request bodies, 256 KB response bodies; 8 concurrent), logged through the real ProxyConsoleFormatter. Checks that tracked proxy sessions are collected and the managed heap after a full GC grows by less than 8 MB. Passes (sessions retained: 0, growth 1.4–3.2 MB).
FailedAndCancelledRequests_DoNotRetainMemory Same, with requests the origin aborts (502) and requests the client cancels mid-flight. Skipped: all sessions are retained (about 160 MB over 1,000 requests). Passes with #2151.
HotReload_DetectsGenerationsHeldByALeak Canary: deliberately keeps each generation in a static list and asserts the hot-reload check sees every one retained. Passes
Requests_DetectSessionsHeldByALeak Canary: a plugin keeps every session in a static list; asserts the session check sees them all and the heap growth exceeds the bound (it's about 140 MB). Passes

The canaries make sure the checks can't silently pass by measuring nothing.

The skipped tests reference the PR that fixes the leak in their skip reason. I verified each by applying this branch onto the PR's head, un-skipping the test and running it 5 times: all passed. The other PR doesn't fix it (on #2153 the failed-requests test still fails, on #2151 the hot-reload test still fails). Once a fix merges, remove the Skip.

Heap bound

Heap snapshots (dotnet-gcdump, before vs after 30,000 requests) show the live growth is almost entirely 4 KB blocks in Kestrel's memory pool, which keeps growing towards its peak use long after warm-up (2k requests: 1.9 MB, 10k: ~2.8 MB, 30k: 3.8 MB). The bound is 8 MB. Leaks too small for it are covered by the per-session WeakReference tracking.

Other changes

  • The host-building functions (BuildApplication, IsJsonOutputRequested, etc.) move from Program.cs into a new ProxyHost class, unchanged, so the test can build hosts the same way the app does on every hot reload. Program.cs uses them through using static.
  • DevProxy gets InternalsVisibleTo for the integration tests, and the integration tests reference DevProxy. That required aligning the test project's OpenTelemetry packages with DevProxy (1.20.1 → 1.21.0, otherwise NU1605), and suppressing VSTHRD003/VSTHRD202 in the test project because the threading analyzers now flow in transitively and flag existing test code.
  • FakeOrigin can skip recording requests (so it doesn't hold the request bodies the tests measure) and gets /abort and /delay/{ms} endpoints.

Testing

  • CI only builds; tests don't run there. Locally on macOS: the memory tests ran 10 times in a row with no failures (about 25 s for the class, hot reload included). The full DevProxy.Integration.Tests (187 passed, 2 skipped) and DevProxy.Tests (179 passed) suites pass.
  • Not verified on Linux or Windows runners. The tests rely on forced full collections and WeakReferences rather than timing; the hot-reload test rewrites the config file until the watcher fires (up to 10 times, 3 s apart) to tolerate file-watcher differences.
  • dotnet restore DevProxy.sln --locked-mode passes.

Adds MemoryRetentionTests to DevProxy.Integration.Tests:

- Hot reload: runs 20 generations through the real host-building code and
  config file watcher and checks that previous generations' WebApplication,
  service provider, command and plugins are collected.
- Requests: proxies successful (mocked, passed-through, large bodies) and
  failed/cancelled requests through the Kestrel engine with the real console
  formatter, and checks proxy sessions are collected and the managed heap
  stays within a bound.
- Canary tests add a deliberate leak and assert both checks catch it.

The hot reload and failed/cancelled request checks are skipped until dotnet#2153
and dotnet#2151 fix the leaks they detect on main.

To build hosts like Program.cs does, the host-building functions move from
Program.cs into ProxyHost, unchanged.

Closes dotnet#2160

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@waldekmastykarz
waldekmastykarz requested a review from a team as a code owner November 23, 2026 13:24
Copilot AI balanced review requested due to automatic review settings November 23, 2026 13:24
@waldekmastykarz waldekmastykarz added the pr-performance Memory optimization, reduced allocations, and runtime or startup performance improvements label Nov 23, 2026

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

The memory-retention tests accept empty tracking samples, allowing collection checks and the canary to pass without validating session retention.

1 open issue
What changed in this PR

Adds memory-retention regression tests for Dev Proxy’s request handling and hot reload, addressing #2160 using the existing integration harness and shared production host setup.

Changes:

  • Adds heap-growth and weak-reference checks, plus deliberate-leak canaries. Known-leak tests remain skipped pending #2151 and #2153.
  • Extracts host-building helpers into ProxyHost for reuse by integration tests.
  • Extends the fake origin and aligns test dependencies with the application.
File Description
DevProxy/​ProxyHost.cs Houses the extracted host-building and logging helpers.
DevProxy/​Program.cs Uses the shared helpers through a static import.
DevProxy/​DevProxy.csproj Grants integration tests access to internal APIs.
DevProxy.Integration.Tests/​MemoryRetentionTests.cs Adds request and hot-reload retention checks and canaries.
DevProxy.Integration.Tests/​FakeOrigin.cs Adds optional recording and abort/delay endpoints.
DevProxy.Integration.Tests/​DevProxy.Integration.Tests.csproj References the application, aligns OpenTelemetry versions, and suppresses threading warnings.

Review effort: Balanced

Co-authored-by: Copilot App <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.

🔵 Needs a closer look

The GC-sensitive memory-retention assertions and file-watcher retry behavior were validated only on macOS, leaving the required repeated Linux and Windows stability checks outstanding.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

waldekmastykarz and others added 2 commits November 24, 2026 10:45
Co-authored-by: Copilot App <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.

🔵 Needs a closer look

Repeated Linux and Windows validation is still needed to establish cross-platform stability of the forced-GC, heap-growth, and hot-reload watcher checks, since supplied validation covers macOS only.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 25, 2026 14:09

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.

🔵 Needs a closer look

Only macOS repeated-run evidence is available, leaving GC-dependent heap bounds and file-watcher/connection teardown stability unverified on Linux and Windows.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 06:41

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.

🔵 Needs a closer look

The GC/heap-growth and file-watcher tests were validated only on macOS and do not run in CI, leaving the Linux and Windows stability and heap bounds required by #2160 unverified.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 13:08

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.

🔵 Needs a closer look

Only macOS validation is reported for the new heap-growth and file-watcher tests, leaving the required repeated Linux and Windows stability checks unverified.

No open issues 🎉

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Functional test results

  • PR: #2170
  • Tested commit: 3ad8d6c1733c6ac9ab1eb275ca723c939ea7da1f
  • Environment: macOS, .NET SDK 10.0.103, source Debug build, isolated local HTTP/1.1 upstream and configuration fixtures. Detached mode, system proxy disabled, OS-assigned proxy/API ports; no external API or credentials required.
Scenario or test command Expected Actual Result
dotnet restore DevProxy.sln --locked-mode then dotnet build DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj --no-restore Restore/build succeeds Passed, zero build warnings/errors. Initial no-restore attempt needed the missing assets restored. PASS
dotnet run --no-build --project DevProxy -- --detach --as-system-proxy false --port 0 --api-port 0 --config-file <fixture> --output json; PID-scoped status, authenticated GET /proxy, routed smoke requests Owned instance alive; API 200; mock 201; passthrough 200 PID 38179, initial proxy port 50357 and API port 50358; all assertions passed. PASS
1,000 warm-up + 10,000 mixed requests, concurrency 8, routed explicitly through the assigned proxy Mock GET 201 with exact generation JSON; passthrough GET 200 with exact body; POST echoes all 65,536 bytes; large GET returns all 262,144 bytes Every response matched. Warm-up 0.4 s; following 10,000 requests 6.2 s. This checks traffic correctness, not retained managed heap. PASS
8 upstream connection aborts + 8 client-cancelled delayed requests, followed by healthy traffic/API calls Abort returns 502; delayed client times out; proxy remains usable All eight 502s and eight client timeouts observed; subsequent passthrough and authenticated API returned 200. No claim that these sessions are collected. PASS
Rewrite config 20 times, selecting a new mock file for each generation; rediscover ports using the owned PID Same daemon PID applies each new configuration; mock returns corresponding generation; passthrough/API remain healthy Generations 1-20 each returned 201 with matching JSON, passthrough 200, and authenticated API 200. Same PID throughout. PASS
Inspect existing CI run 45826314287, associated with the tested head, rather than rerunning automated tests locally Active retention checks and intentional-leak canaries execute successfully on all three OSes Integration jobs passed: macOS 199 passed/2 skipped; Ubuntu 199 passed/2 skipped; Windows 191 passed/4 skipped. Logs explicitly show the two known-leak memory checks skipped. CI tested merge commit 4203acb containing this head and captured base. PASS
Prove collection across hot reloads and failed/cancelled requests Zero retained generation/session objects after forced GC HotReload_ReleasesPreviousGenerations and FailedAndCancelledRequests_DoNotRetainMemory remain intentionally skipped pending #2153 and #2151. Runtime recovery above does not establish collection. BLOCKED
#2160 repeated-run stability criterion: approximately 10 runs on Linux, macOS, Windows Repeated GC/heap/file-watcher checks pass without flakes Inspected current-head CI provides one successful integration run per OS, not repeated-run stability evidence. Automated tests were not rerun locally, per this testing workflow. BLOCKED

Requested changes

None. No reproducible functional defect attributable to this PR was established.

Outcome

Comment only, not approval or a change request. Source-build traffic and hot-reload scenarios passed, and current-head CI now does run the integration suite successfully on all three OSes (the PR description's CI statement is outdated). Full retention coverage and repeated cross-platform stability are not established by this run; the blocked rows are not passes. This report is functional testing, not code review.

All four proxy PIDs started during fixture development/testing were stopped with the matching source build and PID-specific stop, and verified absent; the owned upstream was stopped, fixtures removed, and the checkout left clean. Preliminary Python HTTP/1.0 fixture traffic hit an upstream reset/502; switching the fixture to HTTP/1.1 yielded the passing results above, so that preliminary result is inconclusive rather than a PR defect. The final run's log pathname disappeared during concurrent testing; structured assertion results were retained separately. Cleanup removed only exact owned log paths, never shared caches or other instances.

Copilot AI balanced review requested due to automatic review settings November 26, 2026 15:08

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.

🔵 Needs a closer look

The memory regression checks depend on process-wide GC/heap behavior and watcher shutdown, but repeated validation covers only macOS, leaving required Linux and Windows stability unverified.

No open issues 🎉

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Functional test results

  • PR: #2170
  • Tested commit: 8b27f09327c31d600550db409376aecb56a852d5
  • Captured base: e9ff612126b99a03b87715c259c49c6b43cf6a67
  • Environment: macOS, .NET SDK 10.0.103, source Debug build, local HTTP/1.1 upstream. Owned fixture home with both HOME and CFFIXED_USER_HOME, pre-created Application Support directory, unique certificate path; verified daemon log path resides under that home. System proxy disabled, random proxy/API ports. Other PR testers share this Mac, so elapsed times are descriptive only.

This retests the new head after its main-branch merge, including the merged #2151 request-log and #2154 body-copy changes. The six-file net PR scope and MemoryRetentionTests implementation are unchanged.

Scenario or test command Expected Actual Result
dotnet restore DevProxy.sln --locked-mode; dotnet build DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj --no-restore Current dependency graph restores and affected projects compile Both succeeded; zero build warnings/errors. PASS
dotnet run --no-build --project DevProxy -- --detach --as-system-proxy false --port 0 --api-port 0 --config-file <owned-config> --output json; PID-scoped status, authenticated API and routed smoke requests Owned process alive; API 200, mocked 201, passthrough/echo/large-body 200 PID 10762; initial proxy 59514, API 59515. API, status, exact smoke bodies and fixture-scoped log path verified. PASS
1,000 warm-up plus 10,000 mixed requests, concurrency 8 Mock GET 201 with exact generation JSON; passthrough GET 200 with exact body; 65,536-byte POST echo and 262,144-byte response exactly preserved Every assertion passed. Warm-up 0.31 s, following 10,000 requests 4.2 s. No speedup or managed-heap claim inferred from these timings. PASS
Eight upstream aborts and eight delayed requests cancelled by the client; then healthy request/API 502 on abort, client timeout on delay, healthy requests continue succeeding All eight 502s and eight timeouts observed; subsequent passthrough and authenticated API returned 200. PASS
Twenty config rewrites, each selecting a new generation-specific mock file; rediscover endpoints by owned PID Same daemon applies all generations; mock generation matches; passthrough/API healthy Generations 1-20 each returned matching JSON with 201, passthrough 200 and authenticated API 200. Same PID throughout. PASS
Inspect existing CI run 45846056249, associated with this head Active memory checks/canaries and other integration tests pass on all three platforms Linux/macOS each 310 passed, 2 skipped; Windows 302 passed, 4 skipped. CI logs identify merge commit d12320a combining the tested head and captured base. Automated tests were not rerun locally, per the testing workflow. PASS
Establish generation collection and failed/cancelled-session collection Relevant forced-GC/weak-reference checks execute and demonstrate collection Both HotReload_ReleasesPreviousGenerations and FailedAndCancelledRequests_DoNotRetainMemory remain skipped in source and all three CI logs. #2151 is now merged, but the latter skip was not removed. Runtime recovery above is not collection evidence. BLOCKED
#2160 repeated-run cross-platform stability criterion Approximately ten successful GC/heap/file-watcher runs on Linux, macOS and Windows Inspected current-head CI provides one successful suite run per platform, not the required repeated stability evidence. Local traffic/reload testing cannot substitute for it. BLOCKED

Requested changes

None based on reproduced functional defects. No PR-attributable runtime regression was established. The skipped failed/cancelled-request check should be revisited now that #2151 has merged; this retest did not edit or unskip tests.

Outcome

Comment only, scoped to the tested commit; neither approval nor a change request is justified while essential retention/stability evidence remains incomplete. Source-build scenarios and inspected current-head CI passed, but the blocked rows are not passes. This is functional testing, not code review.

The owned proxy was stopped gracefully using the matching source build with stop --pid 10762 and verified absent. The local upstream was stopped; all owned state, certificate, config and log fixtures were removed, with no shared state/cache cleanup. The original clean checkout was restored. Sanitized assertion evidence and the harness were retained outside the checkout.

waldekmastykarz and others added 3 commits November 27, 2026 09:47
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 08:49

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.

🔵 Needs a closer look

Memory thresholds, forced-GC assertions, and file-watcher synchronization have only been validated on macOS, leaving cross-platform stability unverified pending repeated Linux and Windows runs.

No open issues 🎉

Review effort: Balanced

@garrytrinder garrytrinder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Functional test results

  • PR: #2170
  • Tested commit: d37eb0668ab4016630f0bfdc0387cbcd7b82b05f
  • Captured base: b2a9cbfef9bd434ee3b10d761814aa25d83aba20
  • Environment: macOS, .NET SDK 10.0.103, source Debug build, local HTTP/1.1 upstream. Owned HOME/CFFIXED_USER_HOME with pre-created Application Support directory, unique certificate path, system proxy disabled, OS-assigned ports. Other testers share this Mac; timings are descriptive, not performance gates.
Scenario or test command Expected Actual Result
dotnet build DevProxy.Integration.Tests/DevProxy.Integration.Tests.csproj --no-restore Affected source projects compile Passed, zero warnings/errors. PASS
dotnet run --no-build --project DevProxy -- --detach --as-system-proxy false --port 0 --api-port 0 --config-file <owned-config> --output json; PID-scoped status, authenticated API and explicitly proxied smoke requests Owned instance alive; API 200, mock 201, passthrough/echo/large-body 200 PID 41571; initial proxy port 57894, API port 57895. Exact responses verified; daemon log path verified inside owned fixture home. PASS
1,000 warm-up + 10,000 mixed requests, concurrency 8 Mock 201 with matching JSON; passthrough 200 with exact body; 65,536-byte POST echo and 262,144-byte response preserved Every assertion passed. Warm-up 0.54 s; subsequent 10,000 requests 4.16 s. No managed-heap or speedup claim. PASS
Eight upstream aborts and eight client timeouts on delayed requests, then healthy traffic/API Abort 502, delayed client timeout, subsequent request/API 200 All expected errors and recovery responses observed. PASS
Twenty config rewrites selecting generation-specific mock files; rediscover assigned ports by owned PID Same daemon applies generations 1-20; matching mock JSON 201; passthrough/API 200 All twenty generations passed every assertion; same PID throughout, owned log still present after reloads. PASS
Inspect current-head CI run 45968694661, not rerun automated suites locally Active retention checks/canaries and integration suite pass on three platforms Linux/macOS: 456 passed, 2 skipped each. Windows: 448 passed, 4 skipped. CI logs identify merge commit dcdc568, combining tested head and captured base. PASS
Establish hot-reload and failed/cancelled-request collection Forced-GC/weak-reference release checks execute and demonstrate collection Both release facts remain skipped in current source and all three CI logs. Successful traffic/reload recovery is not collection evidence. BLOCKED
#2160 repeated cross-platform stability criterion Approximately ten successful GC/heap/watcher runs on Linux, macOS and Windows Current-head evidence inspected is one successful suite run per OS, not repeated-run stability. Previous-head runs do not prove this revision. BLOCKED

Requested changes

None based on reproduced functional defects. No PR-attributable runtime regression was established. The failed/cancelled-request retention skip still references the already-merged #2151 and needs revisiting; this workflow did not change or unskip tests.

Outcome

Comment only, bound to the tested commit. Runtime scenarios and inspected CI passed, but skipped retention checks and missing repeated cross-platform evidence prevent full functional approval. The blocked rows are not passes. This is functional testing, not code review.

Owned PID 41571 was stopped gracefully using the matching source build's PID-specific stop and verified absent. The upstream was stopped; exact owned config, state, certificate and log fixtures were removed, with no shared cleanup. The original clean checkout was restored. Sanitized results and harness are retained locally.

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

pr-performance Memory optimization, reduced allocations, and runtime or startup performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add memory leak tests for request handling and hot reload

3 participants