You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Stop hot reload from retaining every previous generation - #2153
Each config change (hot reload) builds a new host, but three independent roots kept every previous generation alive, along with its plugins, service provider, logger providers, and data. This PR breaks all three and reduces the per-reload native growth from loading plugin assemblies again.
Changes
Temporary service provider:AddPlugins built a container just to get a logger and never disposed it. It's now disposed after registration. The logger is only used synchronously during registration.
Static --config-file option: System.CommandLine records every command an option is added to as its parent, so the static option kept every DevProxyCommand and its WebApplication alive. The option (and its validator) is now created per DevProxyCommand instance and passed to StdioCommand.
HttpClientFactory timers: handler expiry timers rooted the factory, and through it the root service provider and its singletons. Handlers now never expire (SetHandlerLifetime(Timeout.InfiniteTimeSpan)), and the primary SocketsHttpHandler recycles pooled connections every 2 minutes, so DNS changes are still picked up. Proxy settings are unchanged: SocketsHttpHandler uses the same default system proxy as the previous default handler.
Plugin load contexts: the PluginLoadContext for a plugin path is reused across reloads as long as none of the files it loaded (the plugin DLL, its .deps.json, and any managed or native dependencies) changed timestamp or size. A rebuilt plugin or updated dependency still gets a new context. Plugin types are found by reading the assembly metadata instead of GetTypes(), so only the matching type and its dependencies load. If the file on disk no longer matches the loaded assembly's MVID, lookup falls back to the loaded assembly's types.
Plugin static state: since plugin assemblies now survive reloads, static state in built-in plugins does too. The DevTools WebSocket send semaphore is now per server instance and is released in a finally block, so a failed send can't block DevTools permanently. The OpenAI telemetry Meter and its instruments are now per plugin instance and disposed with it, so stale instruments (such as ones with an old currency in the description) don't carry over.
MSGraphDb.Dispose: no longer references SqliteConnection when no connection was opened, so disposing an unused instance doesn't load Microsoft.Data.Sqlite.
Because plugin assemblies are now reused across reloads, static state in a plugin assembly survives a reload while the DLL is unchanged.
Measurements
macOS arm64, Release build, LatencyPlugin only, 10 config edits, update check blocked. Object counts are from dotnet-gcdump after the last reload. Assembly counts are from dotnet-counters.
Before (main)
After
LatencyPlugin instances
11
1
DevProxyCommand instances
11
1
PluginLoadContext instances
11
1
ServiceProvider instances
23
2
ConsoleLoggerProvider instances
22
1
GC heap (gcdump)
7.9 MB / 115k objects
2.8 MB / 37k objects
Loaded assemblies, start → after 10 reloads
125 → 138
120 → 121
OS threads, start → after 10 reloads
30 → 41
30 → 29
Phys footprint, start → after 10 reloads
78 → 123 MB
78 → 116 MB
LatencyPlugin holds almost no data, so the footprint difference here is small. Retention scales with plugin data: in the earlier analysis, with a 5 MB mocks file over 5 reloads, gen2 after GC went from 56.5 MB to 10.8 MB with the first three fixes.
About 2.6 MB per reload of untagged runtime memory still grows in both builds. It isn't from plugin assemblies or retained generations, and is left for a follow-up.
Validation
dotnet test for DevProxy.Tests, DevProxy.Abstractions.Tests, and DevProxy.Integration.Tests pass. Added PluginLoadingTests for context reuse, invalidation on plugin and dependency changes, and metadata-based type lookup.
Hot reload run: 10 restarts, all applied. Touching the plugin DLL creates a new load context on the next reload.
- Dispose the temporary service provider used to get a logger while
registering plugins.
- Create the --config-file option per DevProxyCommand instance, so
System.CommandLine's parent tracking doesn't keep every command (and its
WebApplication) alive.
- Never expire HttpClientFactory handlers; recycle pooled connections every
2 minutes instead. The handler expiry timers kept each generation's root
service provider alive.
- Reuse a plugin's load context across reloads while the plugin file is
unchanged, find plugin types from metadata instead of GetTypes(), and
don't load Microsoft.Data.Sqlite when disposing an unused MSGraphDb.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The plugin cache can retain stale dependencies after dependency-only updates, and a DLL replacement race can mismatch type metadata with the loaded assembly and skip plugins.
This PR reduces memory retained across Dev Proxy configuration reloads by removing references to previous hosts and reusing unchanged plugin assemblies.
Changes:
Dispose the temporary service provider, make the config option instance-owned, and replace HTTP handler rotation with pooled-connection recycling.
Cache plugin load contexts and use metadata-based type lookup, with new regression tests. Plugin static state now survives reloads while the DLL is unchanged.
Avoid loading SQLite when disposing an unused database service.
File
Description
DevProxy/Plugins/PluginServiceExtensions.cs
Disposes the temporary provider and adds context caching and metadata lookup.
Track every file a PluginLoadContext loads (plus the plugin's .deps.json)
and only reuse the context when none changed. Fall back to the loaded
assembly's types when the plugin file on disk no longer matches its MVID.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Reusing the built-in plugin assembly preserves a static semaphore that is not released when a WebSocket send throws or is cancelled, blocking subsequent DevTools sends even after configuration reloads.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Release WebSocket send semaphore even when sends fail
DevProxy/Plugins/PluginServiceExtensions.cs:217
Reusing the built-in plugin assembly preserves the static WebSocketServer._webSocketSemaphore across reloads. If a WebSocket send throws or is cancelled after acquisition (DevProxy.Plugins/Inspection/WebSocketServer.cs:137–142), Release() is skipped, so subsequent DevTools sends remain blocked even after a config reload. Make the semaphore instance-scoped and release it in a finally block after successful acquisition.
… it on failure
Plugin assemblies are now reused across hot reloads, so the static semaphore
would survive reloads and a failed send would block DevTools permanently.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Semaphore disposal can race with outstanding sends, causing exceptions or stranded operations, and the DLL replacement test fails on Windows because the loaded file is locked.
On Windows, the DLL loaded on line 59 is locked against writes, so File.Copy(..., overwrite: true) throws IOException before the fallback is exercised. Skip this replacement test on Windows, following the platform guards in CertCommandTests.cs, so it does not fail the Windows test run.
Plugin assemblies are reused across hot reloads, so a static meter would keep
instruments (with stale currency descriptions) from previous generations.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Overwriting a loaded assembly in place corrupts the memory-mapped image on Linux.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Assembly reuse changes plugin state lifetime and cross-generation dependency loading, requiring human validation of single-file releases without .deps.json, especially native dependency updates not covered by the supplied managed-loader tests.
Environment: macOS 27.2.1 arm64, .NET SDK 10.0.103, Debug source builds. Detached instances used --as-system-proxy false --port 0 --api-port 0; isolated configuration, local upstream/OTLP collector, and owned certificate/state directories. Update requests were blocked locally.
Scenario or test command
Expected
Actual
Result
Locked restore and source builds of DevProxy and DevProxy.Plugins
Runnable PR artifacts
Both built with zero warnings/errors after restoring initially missing assets
PASS
Current-head CI, inspected rather than rerun locally
Required automated validation succeeds on tested SHA
Build, macOS/Linux/Windows tests, smoke and CodeQL all passed on tested SHA
PASS
Detached readiness, authenticated GET /proxy, explicit proxy requests
API 200, intact mocked body, preserved unmatched upstream response
API 200; complete 5,000,000-character mock payload; local upstream JSON preserved
PASS
Ten configuration edits with LatencyPlugin and 5 MB MockResponsePlugin fixture; forced-GC dotnet-gcdump snapshots
Old generations no longer retained; each edit applied
10/10 reloads served intact responses. HEAD retained 1 command, 1 latency plugin, 1 mock plugin, 1 load context, 2 service providers and 1 console provider, both before and after. Same base run ended with 11/11/11/11/23/22 respectively
PASS
Change only isolated plugin DLL timestamp, then reload
New load context without losing functionality
Contexts increased from 1 to 2; current command/plugin counts stayed at 1; mock response remained intact
Contexts increased from 1 to 2; custom plugin remained operational. Execution of updated dependency code is separately reported below
PASS
Touch only loaded native library, then change only .deps.json, with a reload after each
Both changes invalidate the cached context
Contexts increased 2 to 3 to 4; real native function continued returning its expected value
PASS
OpenAI completion through mocked response and local OTLP collector; change currency USD to EUR
New generation exports new metric descriptions, not old currency
Both completions returned 15 tokens; collector received USD initially, then EUR request-cost description without stale USD in the EUR payload
PASS
DevTools WebSocket client abort during traffic, reconnect, then config reload/reconnect
Failed send does not permanently hold semaphore or poison next generation
Induced send failure logged WebSocket ... invalid state ('Aborted') and returned HTTP 502 rather than hanging. A new connection received request/response CDP events in the same generation and again after reload
PASS
stdio -c <fixture> /usr/bin/printf stdio-probe; repeat with nonexistent config
End-to-end managed dependency implementation replacement, compared with exact base
Replacement changes response from managed-v1 to managed-v2 without process restart
Response remained managed-v1 after reload on both HEAD and base, despite new contexts. Observed twice on HEAD and once on base; not introduced by this PR
FAIL (pre-existing)
Requested changes
None attributable to this PR.
The dependency-only implementation replacement limitation is reproducible with a custom plugin whose response calls a separate managed dependency: request once, atomically replace only that dependency DLL with a build returning managed-v2, edit the config, and request through the new proxy port. Both tested revisions return managed-v1. This is not being presented as a PR regression or an inline change request. Cache invalidation itself is verified; successful in-process deployment of new dependency code is not.
Outcome
Comment only, not a change request. The reported generation-retention defect is reproduced on the exact base and fixed on this head; telemetry, invalidation, WebSocket recovery and CLI scenarios passed. Withholding blanket functional approval because the end-to-end dependency replacement experiment still fails, albeit identically on the base.
PR head was rechecked and remains the tested SHA. All owned proxy PIDs were stopped and verified absent; local services exited, exact owned fixtures/logs/certificates and the temporary base worktree were removed, and the original checkout is clean. No PR source changes, commits or merges were made.
Environment: macOS 27.2.1 arm64, .NET SDK 10.0.103, Debug source builds. Each launch used --detach --as-system-proxy false --port 0 --api-port 0. Configurations, HOME/CFFIXED_USER_HOME state, certificates, and logs were owned by this run; local upstream/OTLP collectors avoided external dependencies.
This supersedes my earlier functional report for 835af769. The refreshed head incorporates main; the nine-file PR-specific patch is unchanged. Current-head CI was inspected, not rerun locally.
Scenario or test command
Expected
Actual
Result
Locked restore and dotnet build for application and plugins
Matching runnable source artifacts
Both product builds passed with zero warnings/errors
PASS
CI at tested SHA
Automated validation passes
Build, smoke, macOS/Linux/Windows tests, CodeQL all successful at e38cf5e
PASS
Detached readiness and explicit proxy requests
Authenticated API 200, complete mock response, preserved forwarding
API 200; complete 5,000,000-character mocked payload; unmatched request returned exact local-upstream JSON
PASS
Ten config edits, LatencyPlugin + 5 MB MockResponsePlugin, forced-GC heap snapshots; repeat on current base
No accumulation of previous generations
HEAD before/after: 1 command, 1 latency plugin, 1 mock plugin, 1 context, 2 service providers, 1 console provider. Base after ten: 11/11/11/11/23/22. All ten reload responses intact on both revisions
PASS
Change only owned plugin DLL timestamp, then reload
Invalidate context; preserve current plugin behavior
Contexts 1 to 2; one current command/plugin; intact response
PASS
Atomically replace only managed dependency; touch only loaded native library; change only .deps.json, reloading after each
Each tracked change invalidates context
Contexts progressed 1 to 2 to 3 to 4; real native function and plugin responses remained available
PASS
Mock OpenAI completion, collect OTLP locally, change USD to EUR
New instrument description replaces old currency
Both completions returned 15 tokens; exported request-cost description changed USD to EUR without stale USD in EUR payload
PASS
Abort DevTools WebSocket client during traffic; reconnect in same generation, then reload/reconnect
Logged aborted-WebSocket send; induced request ended with curl exit 52/empty reply, not timeout. Reconnection received request/response CDP events both before and after reload
Previously inconclusive dependency implementation update, repeated on current HEAD and current base
Updated dependency returns managed-v2 after config reload
Both revisions still returned managed-v1 after reload, despite new contexts. Restarting each process against the same deployed files returned managed-v2, confirming the fixture/DLL replacement was valid
FAIL (pre-existing)
The disconnected-DevTools request now produces an empty reply rather than the older head's HTTP 502; the merged request-log cleanup changes affect error propagation. The targeted semaphore behavior is verified by successful same-generation reconnection after the exception. The first rerun stopped on the outdated HTTP-502 assertion; the subsequent run explicitly checked bounded transport failure plus actual reconnection.
Heap evidence above concerns retained generation object counts, not a claim that all heap/native growth is eliminated. Native dependency stamp invalidation was tested; live native implementation replacement was not established.
Requested changes
None attributable to this PR.
The remaining managed dependency behavior is reproduced on the exact current base, not only an older baseline. Minimal reproduction: custom plugin responds using a separate dependency returning managed-v1; request once; atomically replace only that dependency DLL with a build returning managed-v2; edit the configuration; request again. Both HEAD and base continue returning managed-v1; stopping and starting with identical deployed files returns managed-v2. This is not a PR regression or an inline change request.
Outcome
Comment only. Retention improvement, telemetry reset, tracked-file invalidation, WebSocket recovery and CLI regressions pass on the current head. End-to-end managed dependency implementation replacement still fails identically on the current base, so I am not issuing a change request or blanket functional approval.
Head was rechecked before publication. All owned proxies were stopped and verified absent; local servers exited; exact owned fixture/state/certificate/log directories, diagnostic binaries and the temporary base worktree were removed. The PR checkout is clean, with no source edits, commits, pushes or merges.
Environment: macOS 27.2.1 arm64, .NET SDK 10.0.103, Debug source builds; concurrent testers on the same Mac. Each proxy used --detach --as-system-proxy false --port 0 --api-port 0, an owned HOME/CFFIXED_USER_HOME with Application Support pre-created, and an owned certificate path.
Latest-batch retest, superseding my previous report on e38cf5e. The PR-specific nine-file patch is unchanged after merging main.
Scenario or test command
Expected
Actual
Result
Product builds and locked restore
Matching source artifacts and dependency locks
Application and plugins built with zero warnings/errors; locked restores passed
PASS
CI at tested SHA
Automated validation passes
Build, smoke, macOS/Linux/Windows tests and CodeQL successful; verified workflow head SHA
PASS
Detached API readiness; explicit proxied mock and unmatched local-upstream requests
API 200, intact response, forwarding preserved
Authenticated API 200; complete 5,000,000-character mock; exact local-upstream JSON
PASS
Ten config edits with LatencyPlugin + 5 MB MockResponsePlugin; forced-GC snapshots; identical current-base run
Old generations reclaimed
HEAD before/after: 1 command, 1 latency plugin, 1 mock plugin, 1 context, 2 service providers, 1 console provider. Base after ten reloads: 11/11/11/11/23/22. All ten reload responses intact
PASS
Plugin DLL timestamp change then config reload
New context, functioning plugin
Contexts 1 to 2; current command/plugin counts remain 1; intact mock
PASS
Managed dependency replacement, native-library timestamp change, .deps.json edit; reload after each
All tracked files invalidate contexts
Contexts 1 to 2 to 3 to 4; custom plugin and real native function remain operational
PASS
Mocked OpenAI completion; local OTLP collector; USD to EUR config reload
Replace currency descriptions
15-token completions; cost description changes from USD to EUR without stale USD in the EUR payload
PASS
DevTools client abort and send exception; reconnect; config reload/reconnect
Semaphore released; current and new generation usable
Logged aborted-WebSocket exception; induced curl request exits 52 with empty reply, not timeout; CDP request/response events received after both reconnections
Managed dependency implementation update on current HEAD and exact current base, with cold-start controls
Reload executes replacement returning managed-v2
Both revisions return managed-v1 after reload despite new contexts; restarting each against the same deployed files returns managed-v2
FAIL (pre-existing)
Concurrent machine load can affect elapsed time, pools and total memory. Retention findings use per-process forced-GC generation object counts, not wall-clock or footprint comparisons; no claim that all heap/native growth is fixed. Native file invalidation is verified, not live native implementation replacement. Automated tests were read from current-head CI, not rerun locally.
Requested changes
None attributable to this PR.
The dependency-only replacement limitation remains reproducible on the current base, with cold-start controls ruling out invalid fixture deployment. Minimal reproduction: load a custom plugin that calls a separate DLL returning managed-v1; atomically replace only that DLL with a build returning managed-v2; edit config and request again. Both HEAD and base still return managed-v1; process restart returns managed-v2. No inline change request is appropriate for this pre-existing behavior.
Outcome
Comment only. Retention, invalidation, telemetry, WebSocket recovery and CLI regressions passed again. End-to-end managed implementation replacement still fails identically on the base, so no PR-attributable change request or blanket functional approval.
No environment blockers. Head was rechecked before publication. All seven owned proxy PIDs were stopped and verified absent; local servers exited; exact owned fixtures, state, certificates, logs, diagnostic binaries, heap dumps and the comparison worktree were removed. Original PR checkout is clean; no source edits, fixes, commits, pushes or merges.
The reason will be displayed to describe this comment to others. Learn more.
🟢 Approval recommended
No active review issues are recorded for the changes aimed at reducing memory retained across configuration reloads.
No open issues 🎉
Review effort: Balanced
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pr-performanceMemory optimization, reduced allocations, and runtime or startup performance improvements
3 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Each config change (hot reload) builds a new host, but three independent roots kept every previous generation alive, along with its plugins, service provider, logger providers, and data. This PR breaks all three and reduces the per-reload native growth from loading plugin assemblies again.
Changes
AddPluginsbuilt a container just to get a logger and never disposed it. It's now disposed after registration. The logger is only used synchronously during registration.--config-fileoption: System.CommandLine records every command an option is added to as its parent, so the static option kept everyDevProxyCommandand itsWebApplicationalive. The option (and its validator) is now created perDevProxyCommandinstance and passed toStdioCommand.SetHandlerLifetime(Timeout.InfiniteTimeSpan)), and the primarySocketsHttpHandlerrecycles pooled connections every 2 minutes, so DNS changes are still picked up. Proxy settings are unchanged:SocketsHttpHandleruses the same default system proxy as the previous default handler.PluginLoadContextfor a plugin path is reused across reloads as long as none of the files it loaded (the plugin DLL, its.deps.json, and any managed or native dependencies) changed timestamp or size. A rebuilt plugin or updated dependency still gets a new context. Plugin types are found by reading the assembly metadata instead ofGetTypes(), so only the matching type and its dependencies load. If the file on disk no longer matches the loaded assembly's MVID, lookup falls back to the loaded assembly's types.finallyblock, so a failed send can't block DevTools permanently. The OpenAI telemetryMeterand its instruments are now per plugin instance and disposed with it, so stale instruments (such as ones with an old currency in the description) don't carry over.MSGraphDb.Dispose: no longer referencesSqliteConnectionwhen no connection was opened, so disposing an unused instance doesn't loadMicrosoft.Data.Sqlite.Because plugin assemblies are now reused across reloads, static state in a plugin assembly survives a reload while the DLL is unchanged.
Measurements
macOS arm64, Release build, LatencyPlugin only, 10 config edits, update check blocked. Object counts are from
dotnet-gcdumpafter the last reload. Assembly counts are fromdotnet-counters.main)LatencyPlugininstancesDevProxyCommandinstancesPluginLoadContextinstancesServiceProviderinstancesConsoleLoggerProviderinstancesLatencyPlugin holds almost no data, so the footprint difference here is small. Retention scales with plugin data: in the earlier analysis, with a 5 MB mocks file over 5 reloads, gen2 after GC went from 56.5 MB to 10.8 MB with the first three fixes.
About 2.6 MB per reload of untagged runtime memory still grows in both builds. It isn't from plugin assemblies or retained generations, and is left for a follow-up.
Validation
dotnet testforDevProxy.Tests,DevProxy.Abstractions.Tests, andDevProxy.Integration.Testspass. AddedPluginLoadingTestsfor context reuse, invalidation on plugin and dependency changes, and metadata-based type lookup.