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.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Plugin singleton factories retain a logger from a disposed temporary provider, so later initialization failures are logged through disposed infrastructure instead of the live application logger.
The registration-time logger belongs to a temporary provider that's
disposed when AddPlugins returns, so resolve it from the factory's
service provider instead.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Other tests ran on this Mac. These results use per-process object counts after garbage collection, not elapsed-time or total-memory comparisons.
The system SDK 10.0.103 first rejected net11.0 with NETSDK1045. The private SDK removed that environment blocker.
The custom fixture built with two warnings: an unused DiagnosticSource reference was unavailable, and DllImport produced SYSLIB1054. Its managed and native responses passed.
No automated test suite ran locally. CI supplied the automated results for the tested commit.
Startup exceptions and cleanup
No proxy-startup defaults changed. Every proxy instance used these safety flags:
The reason will be displayed to describe this comment to others. Learn more.
Approved at the maintainer’s explicit direction after reassessing the scope of essential validation. The current head matches the latest functional test revision, and all eight reported current-head CI checks are successful.
The retention fix was verified against the exact base: after ten reloads, command/plugin/context counts stayed at one on this head versus eleven on base; provider counts remained bounded. Live-logger, forwarding, invalidation, telemetry, WebSocket and stdio scenarios passed. Dependency-only implementation replacement still fails on both head and base, with cold restart loading the replacement on both; this pre-existing limitation is disclosed, not treated as a blocker for the retention fix.
No new local tests were run for this approval; evidence comes from the previously published current-head functional report. This does not claim that untested or pre-existing behavior is fixed.
The retention fix passes on the current commit. Ten reloads retain one command and plugin generation on the head. The exact base retains eleven.
I inspected the changes since the previously tested commit, ea1de6e9650b4d7da929a25a6706a5a3f6986463.
The new merge includes command and logging changes from main. I repeated the affected retention, reload, plugin-error, and command checks.
Scenario or test command
Expected
Actual
Result
Locked restore; build DevProxy/DevProxy.csproj and DevProxy.Plugins/DevProxy.Plugins.csproj on head and base
Both products build on each revision.
All four builds passed with zero warnings and errors.
PASS
Detached startup; PID-scoped status; authenticated GET /proxy; explicit requests through the proxy
API returns 200. The mock and forwarded response retain their complete bodies.
Both revisions returned API 200, exactly 5,000,000 mock padding characters, and the exact local-server response.
PASS
Ten configuration edits on each revision; repeat API, mock, and forwarding requests after every reload
All edits apply in the same process. The head does not retain previous command or plugin generations.
Both processes completed ten reloads. All responses passed. Head command, plugin, and context counts remained 1; base counts reached 11.
PASS
Collect heap object counts before and after reloads with dotnet-gcdump
Head service-provider counts remain bounded. The base reproduces retention.
Head service providers remained 2; console providers remained 1. Base counts grew from 3 to 23 and 2 to 22.
PASS
Change only the copied plugin DLL timestamp; reload
A new context loads. Current plugins continue to serve requests.
Context count changed from 1 to 2. Command and plugin counts remained 1. Both response checks passed.
PASS
Start with LatencyPlugin bounds minMs: 10, maxMs: 0
Startup exits 1 and reports the plugin error through the live logger.
Exit 1. One Plugins error contained both bounds and the documentation URL. No ObjectDisposedException occurred.
PASS
Start with valid bounds; confirm readiness; change to the invalid bounds
The live logger reports the reload failure. The failed child exits and closes its listeners.
One error contained the plugin name, bounds, and documentation URL. The child exited. Both listeners closed.
PASS
stdio -c <fixture> /usr/bin/printf stdio-probe; repeat with a missing configuration
Exact child stdout and exit 0; missing configuration exits 2.
Exact stdout stdio-probe, exit 0; missing configuration exit 2 with the expected diagnostic.
The selected plugin command writes the parsed response and reports its work.
Exit 0; generated body {"generated":true}. File-count, processing, and completion messages were present.
PASS
Inspect CI for the tested commit
Automated tests and required checks pass on the same SHA.
All eight checks passed, including three-platform tests, build, smoke, and CodeQL.
PASS
Object counts after ten reloads:
Type
Head: before / after
Exact base: before / after
DevProxyCommand
1 / 1
1 / 11
LatencyPlugin
1 / 1
1 / 11
MockResponsePlugin
1 / 1
1 / 11
PluginLoadContext
1 / 1
1 / 11
ServiceProvider
2 / 2
3 / 23
ConsoleLoggerProvider
1 / 1
2 / 22
These are per-process object counts after garbage collection, not total-memory or elapsed-time comparisons. The results do not prove that all native-memory growth stops.
The first build found missing dependency assets. Locked restore resolved that setup failure.
The first mock-generation attempt used an absolute input pattern and returned No matching HTTP response files found.
The corrected relative pattern passed. No product code changed.
Current-commit build and platform tests, smoke, and CodeQL passed.
I checked their commit identifiers. I did not repeat automated test suites locally.
Startup exceptions and cleanup
None. Each proxy used the matching source-build executable with these flags:
Retention, forwarding, invalidation, and plugin errors
None
Not applicable
Private HOME and CFFIXED_USER_HOME; pre-created Library/Application Support; unique absolute DEV_PROXY_CERT_PATH
Random ports; bounded requests and launch deadlines; recorded launcher and child identities; private state, logs, and leaf certificates
All four proxy children exited. Checked listeners closed. Owned files were removed.
stdio and mock-generation commands
Not applicable
These commands do not start an HTTP proxy.
Same private paths
Separate output capture; finite deadlines; recorded command identities
Commands exited. Generated files were removed.
Build and heap tools
Not applicable
Not a proxy-startup scenario
Owned SDK, diagnostic tool, and comparison worktree
System SDK unchanged; build servers disabled for these builds
Owned SDK, tool, worktree, and heap dumps were removed. No process referenced the owned paths.
Before each explicit proxy stop, the test matched its PID and process start time. It used the matching build and private environment.
The local server stopped, and its listener closed. The checkout is clean at the tested SHA.
No native proxy settings or trust stores changed. Sanitized reports and test scripts remain in session artifacts.
No product edits, commits, pushes, or merges were made.
Requested changes
None attributable to this PR.
The previous tests found that dependency-only implementation replacement required a process restart on both head and base.
A cold restart loaded the replacement on both revisions. This limitation predates the retention fix.
The dependency loader, telemetry, and WebSocket code have no changes since the previous approval.
Their earlier runtime results remain historical evidence; I did not repeat those scenarios in this run.
This approval does not claim that dependency-only implementation replacement works.
It preserves the scope of the previous approval.
Outcome
Approve, limited to functional testing of the retention fix and affected regressions.
The current head reproduces the retention improvement against its exact base. The affected reload, logger, and command checks pass.
No essential scenario is blocked. Cleanup is verified. This approval does not replace code review.
The ASD-STE100 dictionary was unavailable. The language check is incomplete; this report does not claim verified conformance.
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.