Repository navigation
Keep system proxy registered across hot-reload restarts - #2149
waldekmastykarz merged 22 commits into
Conversation
Hot reload restarts the host in-process, which turned the system proxy off and on again for every reload. On macOS, each toggle runs networksetup for every network service, adding a noticeable delay and briefly letting other apps' traffic bypass the proxy. A process-wide SystemProxySession now tracks the applied endpoint across runs: it skips Disable() when the host stops for a restart, skips Enable() when the endpoint is unchanged, applies a new endpoint directly when it changed, releases the registration when a reload turns off asSystemProxy, and disables it after the restart loop ends (for example, a failed restart). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
The endpoint is cached even when proxy enablement fails, causing subsequent same-endpoint reloads to skip retries and leaving failed or partial configurations in place.
1 open issue
What changed in this PR
This PR adds process-wide system proxy tracking so Dev Proxy can retain registration across hot reloads, avoiding redundant OS proxy toggles and brief traffic bypasses.
Changes:
- Reuses unchanged proxy endpoints and updates changed endpoints without disabling first.
- Adds cleanup when system proxy use is turned off or the restart loop exits.
- Adds unit tests for endpoint reuse, port changes, configuration changes, and failed-restart cleanup.
| File | Description |
|---|---|
| DevProxy/Proxy/SystemProxySession.cs | Tracks registration and cleanup across host runs. |
| DevProxy/Program.cs | Owns the session across restarts and performs final cleanup. |
| DevProxy/Extensions/IServiceCollectionExtensions.cs | Routes proxy manager calls through the shared session. |
| DevProxy/Commands/DevProxyCommand.cs | Releases retained registration when the new run no longer uses it. |
| DevProxy.Tests/SystemProxyManagerTests.cs | Tests session registration and cleanup behavior. |
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 Needs a closer look
The change alters process-wide OS proxy ownership across listener restarts, but counting-fake tests cannot verify native macOS/Windows settings retention, endpoint replacement, or cleanup after failed startup or disabling asSystemProxy.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Hot-reload startup downloads that follow OS proxy settings can target the previous run’s stopped listener, causing schema-validation and version-check requests to fail or time out and delay rebinding.
1 open issue
Review effort: Balanced
There was a problem hiding this comment.
🟡 Changes recommended
Without proxy environment overrides on Windows, the retained proxy registration routes startup HTTP requests to a stopped listener, causing validation errors for valid configurations and preventing update checks.
2 open issues
Review effort: Balanced
Before the restarted run binds its listener, DI-created HttpClients (schema validation, update check) skip a system proxy registration kept from the previous run and go direct. Other proxies, such as a separately configured upstream proxy, are used as is. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
The endpoint comparison mismatches expanded and normalized IPv6 addresses, causing startup schema/update requests to use the stopped listener during reload; normalize both endpoints and add expanded-IPv6 test coverage.
1 open issue
2 resolved since last review
Review effort: Balanced
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
StartedAt changes when a config reload restarts the host, so stop missed the record and deleted it. Match PID and ProcessStartTime instead, the same identity DeleteStateAsync uses. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Combine dotnet#2100's snapshot restore with TryEnable/TryDisable. Track snapshot ownership per process so a manager created after a hot reload still leaves a 'system-proxy reset' or takeover alone. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Address review feedback on dotnet#2149: - Skip re-registering on a same-endpoint reload only while this process still owns the registration; after 'system-proxy reset' or a takeover, register again instead of reporting another owner's registration. - Clear the current-run claim when a restart keeps the registration so shutdown requests bypass the stopped listener. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
garrytrinder
left a comment
There was a problem hiding this comment.
Functional test results
- PR: #2149
- Tested commit:
f6f87dcea355b3b6ee4305915e66931966bc6520 - Environment: macOS 27.2.1, arm64, private .NET SDK 11.0.100.
The tests used the compiled PR application and plugins. No PR source files changed.
The cleanup tests used a simulated operating-system manager. A separate local server simulated a process that could not remove its proxy registration.
The tests did not change native proxy settings. These simulations do not prove native proxy behavior.
| Scenario or test command | Expected | Actual | Result |
|---|---|---|---|
Locked restore, then dotnet build DevProxy --no-restore --nologo -v quiet; corresponding plugin commands |
Both projects build | Both builds completed with zero warnings and errors, using SDK 11.0.100 | PASS |
| Check GitHub results for the tested commit | Automated tests and build checks succeed | Windows, macOS, Ubuntu, build, smoke, and CodeQL checks succeeded for the exact commit. Local automated test suites did not run | PASS |
Inject a failed removal into the compiled SystemProxySession, then call ReleaseUnclaimed and Release |
Keep cleanup ownership after both failures | HasRegistration stayed true. Final Release returned false. The endpoint remained available for a later attempt |
PASS |
Permit a later removal, then repeat Release |
Clear the registration after success. Do not remove it twice | The later attempt returned true and cleared the registration. The repeated call made no additional removal attempt | PASS |
| Simulate ownership transfer, then reload the same endpoint | Register the endpoint again | The manager received another enable call. The session did not use the same-endpoint shortcut | PASS |
Send real HTTP requests through the production language-model client. Stop its simulated listener for reload, before BeginRun |
Bypass the retained endpoint during shutdown | Model availability returned true. The completion returned PR2149_OK. Both requests reached the local origin, not the retained proxy |
PASS |
| Request a redirect through that client | Do not follow the redirect | The client returned HTTP 302. The redirect destination received no request | PASS |
| Claim the next listener; separately configure an unrelated upstream proxy | Resume normal proxy routing. Keep unrelated upstream routing | Both requests reached the configured local proxy and received its HTTP 503 response | PASS |
Run the actual stop --pid <owned PID> --output json command against an owned simulated API process. Change StartedAt before process exit |
Keep the failed-removal record despite the changed host start time | Stop returned 0 and reported failed proxy removal. The record remained, with asSystemProxy: true and unchanged ProcessStartTime |
PASS |
| Read orphan records after that simulated process exits | Find the retained cleanup record | The production orphan reader returned the same process identity. No native recovery operation ran | PASS |
Start the real proxy with safe flags. Send authenticated GET /proxy and an explicit-proxy request to http://pr2149.test/probe |
API 200 and an exact mock response | PID 92071; proxy 56990, API 56991. Mock HTTP 200, X-PR2149: 1, body {"revision":1} |
PASS |
| Change the main configuration to load the second mock file | Reload in the same process and apply the new response | Same PID; proxy 57020, API 57021. API 200, mock HTTP 201, revision header and body 2. Readiness took 1.04 seconds | PASS |
| Restore the first mock file through another configuration change | Apply the first response again | Same PID; proxy 57048, API 57049. API 200, mock HTTP 200, revision header and body 1. Readiness took 0.99 seconds | PASS |
| Stop PID 92071 through its API | Stop only the selected process | Stop returned 0. The process exited | PASS |
| Start another owned instance, then write invalid JSON to its configuration | Exit after the failed restart | PID 92255 exited. PID status returned 1. Its log contained JsonReaderException |
PASS |
| Test native registration, endpoint changes, removal failure, ownership transfer, and orphan recovery during real reloads | Preserve correct native settings and recovery records | No disposable environment with separate proxy settings was available. Shared-host safety requirements prohibit this test on this Mac | BLOCKED |
| Reproduce the reported race with real failed native removal during a host reload | Keep recovery state across the complete native sequence | The simulated process test kept the record. The complete native sequence remains untested | BLOCKED |
Startup exceptions and cleanup
The proxy launches used --detach --as-system-proxy false --install-cert false --port 0 --api-port 0. No safe startup default changed.
| Scenario | Changed default | Why the default prevents reproduction | Execution environment | Safety controls | Cleanup verification |
|---|---|---|---|---|---|
| Real proxy tests | None | Not applicable | Private HOME and CFFIXED_USER_HOME; pre-created Library/Application Support; unique DEV_PROXY_CERT_PATH |
Private state, logs, root and leaf certificates; bounded requests; recorded process identities | Both proxy processes exited. All eight assigned ports had no listener. Owned files were removed |
| Simulated cleanup and HTTP tests | No proxy startup default changed | A simulated manager supplies removal failures without changing native settings | Temporary executable using the compiled PR assemblies; private home and state | Local servers used random ports. The client proxy changed only inside the temporary process | Local servers and child processes exited. The retained synthetic state was removed after inspection |
| Native proxy tests | No exception executed | The safe flags prevent native registration. Only a disposable environment can permit this exception | No suitable environment available | Coordinator instructions and repository safety rules prohibit shared-host changes | Native settings remained unchanged |
Requested changes
None. This run did not reproduce a functional defect attributable to the PR.
Outcome
Comment only. The simulated failure tests and real HTTP tests passed. The five real proxy scenarios also passed.
Essential native lifecycle tests remain blocked. These results do not justify approval or a request for changes.
The initial build failed because the installed SDK supported .NET 10, not .NET 11. A private SDK resolved that problem.
Locked restores supplied the .NET 11 assets. The system SDK installation did not change.
Initial temporary-program attempts failed because of a NuGet connection error, a missing import, and an assertion against escaped JSON.
The final program used available packages, imported the required namespace, and parsed JSON before its assertions.
These were test setup errors, not reproduced PR defects.
All owned processes and listeners stopped. The temporary SDK, state, certificates, logs, and test files were removed.
The checkout is clean at the tested commit. No fixes, pushes, or merges were performed.
The ASD-STE100 dictionary was not available without an external request. The STE check is incomplete; verified conformance is not claimed.
When another running instance took over the system proxy, a hot reload now skips registering and stops reporting this instance as the system proxy, so stop --force on it leaves the other instance's settings alone. After 'system-proxy reset', a reload still registers again. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
garrytrinder
left a comment
There was a problem hiding this comment.
Functional test results
- PR: dotnet/dev-proxy#2149
- Tested commit:
59df68ae8ad543c3a9f1b943d4b2eebb2fab81df - Base commit:
5975ef034841771747dffc5d14b24a03867b043d - Environment: macOS 27.2.1, arm64, private .NET SDK
11.0.100.
The tests used the compiled PR application and plugins. No PR source files changed.
The controlled tests used simulated apply and removal operations. They used production snapshot storage and ownership checks with an actual, owned child process.
The HTTP tests used production clients and local servers. These tests do not prove native proxy registration or certificate trust.
This report replaces the earlier functional evidence for f6f87dce.
The expected transfer behavior has changed: a reload must not acquire another live process's registration.
The merged startup check can also reject that reload before the proxy engine starts.
| Scenario or test command | Expected | Actual | Result |
|---|---|---|---|
Locked restore, then dotnet build DevProxy --no-restore --nologo -v quiet; corresponding plugin commands |
Both projects build | Both builds completed with zero warnings and errors. The final restores used the existing package cache | PASS |
| Inspect GitHub checks for the tested commit | Automated tests and build checks succeed | Windows, macOS, Ubuntu, build, smoke, and CodeQL checks succeeded for this commit. Local automated test suites did not run | PASS |
| Retain a controlled registration, then construct the next host's manager | Skip another apply for the same endpoint | The new manager made zero apply calls. Reload made zero removal calls | PASS |
| Give a private snapshot to a live owned child. Reload with the same port, then with a changed port | Leave the other owner's registration alone | For both ports, YieldedToOtherOwner became true. The session cleared its registration. Reload and stop left the child's snapshot unchanged |
PASS |
Call production FindBlockingSystemProxyOwnerAsync with that snapshot |
Identify the other live owner. Permit a disabled system proxy | The check returned the child's PID when enabled. It returned null when disabled. It did not block the current owner | PASS |
| Delete the controlled snapshot to represent a reset, then reload | Permit registration again | The production manager reported Released. The session applied the endpoint and cleared its yielded state |
PASS |
Inject removal failures into ReleaseUnclaimed and final Release |
Keep cleanup ownership until removal succeeds | HasRegistration stayed true after failures. A later success cleared it. Another release made no additional removal call |
PASS |
Stop the controlled listener for reload, before BeginRun. Use production DI and language-model HTTP clients |
Bypass the retained, stopped endpoint | The schema request reached the local origin. Model availability returned true. Completion returned PR2149_OK |
PASS |
| Request a redirect through the language-model client | Do not follow the redirect | The client returned HTTP 302. The redirect destination received zero requests | PASS |
| Begin the next run, then claim the endpoint | Bypass before binding. Resume proxy routing after the claim | The unbound request succeeded directly. After the claim, the client attempted the selected, stopped proxy and reported a connection failure | PASS |
| Configure an unrelated local upstream proxy | Preserve upstream routing | The upstream received exactly one request and returned its distinctive HTTP 503 response | PASS |
Start the real proxy with safe flags. Request authenticated GET /proxy and explicit-proxy GET http://pr2149.test/probe |
Live API and exact mock response | PID 93577; proxy 51632, API 51633. API 200, mock 200, X-PR2149: 1, body {"revision":1} |
PASS |
| Change the main configuration to load the second mock file | Reload in the same process and apply the new response | Same PID; proxy 51642, API 51643. API 200, mock 201, revision header and body 2. Readiness took 0.25 seconds | PASS |
| Restore the first mock file through another configuration change | Apply the first response again | Same PID; proxy 51649, API 51650. API 200, mock 200, revision header and body 1. Readiness took 0.24 seconds | PASS |
Run stop --pid 93577 --output json through the PR build |
Stop only the selected process | Stop returned 0. The process exited and removed its state file | PASS |
Start another real instance, then replace its configuration with {"plugins":[INVALID |
Exit after the failed restart | PID 93611 exited. PID-scoped status returned 1. The owned log recorded JsonReaderException |
PASS |
Run actual stop --pid 93629 --output json against a controlled API process. Change StartedAt before exit |
Preserve the simulated failed-removal record across host start-time changes | Stop returned 0 and reported failed proxy removal. The record retained asSystemProxy: true and its original ProcessStartTime |
PASS |
| Read orphan records after the controlled API process exits | Find the retained cleanup record | The production orphan reader returned the same process identity. No native recovery operation ran | PASS |
| Test native registration during reload, endpoint changes, configuration opt-out, failed restart, ownership transfer, and final stop | Preserve or release the correct native registration | No disposable Windows or macOS environment was available. Shared-host safety requirements prohibit this test on this Mac | BLOCKED |
| Reproduce failed native removal across reload and stop, then recover the orphan | Preserve recovery state through the complete native sequence | Controlled tests preserved the record. The complete native sequence, including required certificate trust, remains untested | BLOCKED |
Startup exceptions and cleanup
Every real proxy launch used --detach --as-system-proxy false --install-cert false --port 0 --api-port 0.
No safe startup default changed.
| Scenario | Changed default | Why the default prevents reproduction | Execution environment | Safety controls | Cleanup verification |
|---|---|---|---|---|---|
| Real proxy tests | None | Not applicable | Private HOME and CFFIXED_USER_HOME; pre-created Library/Application Support; unique DEV_PROXY_CERT_PATH |
Private state, logs, and certificates. Bounded requests and recorded process identities | Both attempts stopped all owned application processes. All assigned ports had no listener |
| Controlled ownership and HTTP tests | No proxy startup default changed | Simulated operations avoid native settings changes | Temporary executable using compiled PR assemblies; private snapshot paths; local random-port servers | Only the temporary process changed HttpClient.DefaultProxy. Apply and removal callbacks did not call native operations |
Child processes and servers exited. Private snapshots and the synthetic recovery record were removed |
| Native lifecycle tests | No exception executed | The safe flags prevent native registration. Registration also requires certificate trust | No suitable disposable environment available | Coordinator instructions, .github/copilot-instructions.md, and the test-pr skill prohibit shared-host changes |
No native proxy or trust installation commands ran |
Cleanup checked 28 recorded process IDs and 22 assigned ports across both attempts and the controlled HTTP tests.
No owned process or listener remained. Private SDKs, fixtures, state, certificates, logs, and build outputs were removed.
The checkout is clean at the tested commit. No fixes, pushes, or merges were performed.
Requested changes
None. This run did not reproduce a functional defect attributable to the PR.
Outcome
Comment only. The controlled tests and safe runtime tests passed. Essential native lifecycle tests remain blocked.
These results do not justify approval or a request for changes. This report does not replace code review.
The first build lacked restore assets. A preview-SDK restore then failed with NuGet connection and lock-validation errors.
A private stable SDK and the existing package cache resolved these setup problems. Local package auditing was disabled for the offline restore.
The checked-in lock files did not change.
The temporary executable first failed to compile because of an incorrect namespace import.
Its corrected build completed with nine analyzer warnings in fixture code. The PR application and plugin builds had no warnings.
The first simulated stop timed out because the fixture parent did not collect its exited child process.
After the fixture collected child exit immediately, the repeated stop preserved the recovery record.
Both attempts verified process and listener cleanup. These setup failures did not establish PR defects.
The ASD-STE100 dictionary requires an external request and was unavailable.
Sentence lengths and the supplied writing checklist were checked. The STE check is incomplete; verified conformance is not claimed.
garrytrinder
left a comment
There was a problem hiding this comment.
Approved at the maintainer’s explicit direction to accept the remaining disposable-environment limitation. The head is unchanged from the latest functional report, and all reported current-head CI checks are successful.
Controlled tests passed for production snapshot storage and ownership checks, other-owner isolation across reloads, cleanup ownership preservation after removal failures, orphan recovery-record preservation, production HTTP-client bypass/routing, and safe detached lifecycle scenarios. No PR-attributable defect was reproduced.
Native Windows/macOS proxy registration, endpoint updates, restoration and crash recovery were not exercised because no suitable disposable environment was available. This approval accepts that disclosed validation risk; it does not claim those native scenarios passed. No new local tests were run for this approval. Functional report: #2149 (review)


Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
f6c87ead325206d10dacbc626ffdf67fbc921d35↑ Unit tests cover restart, port change, failed enable, failed port change followed by a reload, the pre-bind bypass, IPv6 normalization and DI wiring; the new failed-port-change test fails without the fix.
↑ All Copilot review threads are resolved, and garrytrinder's functional run found no defects in the scenarios it could exercise.
↓ CI for the latest commit hasn't been inspected yet.
↓ Hot reload with a real OS system proxy registration wasn't tested end to end on Windows or macOS; the functional run couldn't cover it either.
Hot reload restarts the host in-process. With
asSystemProxy: true(the default), every reload turned the system proxy off on shutdown and back on after binding. On macOS each toggle runstoggle-proxy.sh, which callsnetworksetupfor every network service, so each reload paid for an off + on cycle (at least ~0.6 s with 5 services) and other apps' traffic briefly bypassed the proxy.Changes
SystemProxySession, created once inProgram.csoutside the restart loop, which wraps each run'sISystemProxyManagerand tracks the applied endpoint:Enable()when the endpoint is unchanged, and applies a new endpoint directly (no "off" step) when the IP address or port changed (e.g.--port 0)asSystemProxychanged tofalse) releases it once the engine has startedHttpClients (plugin schema validation, update check) skip the retained registration and go direct (RetainedSystemProxyBypass); other proxies, such as an upstream proxy from env vars, are used as is.devproxy stop, Ctrl+C) still disables through the engine as before; orphan reconciliation and instance state are unchanged. Windows follows the same logic; Linux stays a no-op.asSystemProxyturned off, failed restart, and the pre-bind bypass (including a reload after a failed port change, IPv6 address normalization and DI wiring).Known limitations
These are documented in
SystemProxySessionand the Dev Proxy skill's hot reload best practices; fixing them is out of scope for this PR.HttpClients. Azure.Identity token requests (for example, from the API Center plugins) still follow the OS proxy and can reach the stopped listener until the restarted run binds.