Repository navigation
fix(stdio): retry same port on bind race instead of silent fallback (#1173) - #1198
Scriptwonder merged 2 commits into
Conversation
…oplayDev#1173) After a domain reload the previous TcpListener's OS socket is not always released by the time Start() rebinds, so listener.Start() throws AddressAlreadyInUse. The old catch silently switched to a new port via DiscoverNewPort(), which stranded the Python client (pinned to the configured port) on the orphan listener and returned busy/timeout indefinitely. Instead, keep the configured port and fail the start attempt WITHOUT blocking; the reload handler's async resume schedule and the editor-idle retry re-invoke Start() on the same port within ~1s, by which point the OS has released it. Only after the port stays busy past a short window (PortManager. ShouldAbandonBusyPort, 3s) is it treated as a foreign occupant and the bridge falls back to a new port — loudly (McpLog.Warn) instead of the previous debug-only switch. This keeps Stop()'s 500ms wait intact (no CoplayDev#787 backgrounded-stall regression) and is platform-agnostic (the race also reproduces on macOS, per CoplayDev#1173). Also classify ObjectDisposedException from a torn-down NetworkStream as a benign client disconnect so it no longer spams the Console as a red error (CoplayDev#1187).
📝 WalkthroughWalkthroughAdds a 3-second time-bounded retry window before ChangesBusy-port fallback window
Sequence Diagram(s)sequenceDiagram
rect rgba(173, 216, 230, 0.5)
note over StdioBridgeHost,EditorPrefs: Within BusyPortFallbackWindowSeconds (3s)
StdioBridgeHost->>PortManager: ShouldAbandonBusyPort(busyForSeconds)
PortManager-->>StdioBridgeHost: false
StdioBridgeHost->>StdioBridgeHost: dispose listener, send port_busy heartbeat (reloading=true)
StdioBridgeHost->>StdioBridgeHost: nextStartAt = now + 0.3s (retry same port)
end
rect rgba(255, 200, 150, 0.5)
note over StdioBridgeHost,EditorPrefs: After BusyPortFallbackWindowSeconds exceeded
StdioBridgeHost->>PortManager: ShouldAbandonBusyPort(busyForSeconds)
PortManager-->>StdioBridgeHost: true
StdioBridgeHost->>PortManager: DiscoverNewPort()
PortManager-->>StdioBridgeHost: newPort
StdioBridgeHost->>EditorPrefs: SetInt(newPort)
StdioBridgeHost->>StdioBridgeHost: start listener on newPort, clear _portBusySince
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR improves the stdio transport’s resilience across Unity domain reloads by avoiding an immediate silent port change on AddressAlreadyInUse, instead retrying the configured port for a short window and only then falling back to a new port with a warning. It also reduces console noise by treating ObjectDisposedException during client handling as a benign disconnect, and adds unit tests for the new “retry vs fallback” policy.
Changes:
- Update
StdioBridgeHost.Start()to retry the same port for a short “busy” window before falling back, and to warn loudly on fallback. - Add
PortManager.ShouldAbandonBusyPort(...)andBusyPortFallbackWindowSecondsto centralize the policy. - Extend EditMode tests to cover the retry/fallback threshold behavior.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs |
Same-port retry window on bind race; warning-only fallback; benign handling of disposed client stream errors. |
MCPForUnity/Editor/Helpers/PortManager.cs |
Adds a small policy API + constant to determine when to abandon a busy configured port. |
TestProjects/UnityMCPTests/Assets/Tests/EditMode/Services/PortManagerTests.cs |
Adds unit tests for the new retry-vs-fallback threshold logic. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if (!PortManager.ShouldAbandonBusyPort(now - _portBusySince)) | ||
| { | ||
| try { listener?.Server?.Dispose(); } catch { } | ||
| listener = null; | ||
| McpLog.Warn($"Port {currentUnityPort} not released yet after reload; retrying same port."); |
| double now = EditorApplication.timeSinceStartup; | ||
| // Start a fresh window on the first conflict, or if a stale timestamp | ||
| // survived a long idle gap (a real reload + retry resolves in seconds). | ||
| if (_portBusySince <= 0.0 || (now - _portBusySince) > 60.0) _portBusySince = now; |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs`:
- Around line 307-315: The busy-port early-return path in the listener
initialization block sets nextStartAt to throttle retries, but this only works
if EnsureStartedOnEditorIdle is already hooked. When Start() is called directly
(such as from StartAutoConnect), the function returns without activating a retry
loop, leaving the bridge stuck. Ensure the busy-port early-return path always
activates the retry mechanism by also calling or hooking
EnsureStartedOnEditorIdle when a port is detected as busy and we set
nextStartAt, so that retries are guaranteed to happen regardless of how Start()
was invoked.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f2820f62-6c2f-433c-a686-d86182b72b36
📒 Files selected for processing (3)
MCPForUnity/Editor/Helpers/PortManager.csMCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.csTestProjects/UnityMCPTests/Assets/Tests/EditMode/Services/PortManagerTests.cs
…+Dispose, name stale-reset const - Arm EnsureStartedOnEditorIdle in the same-port retry path so a transient AddressAlreadyInUse from a direct Start() caller (e.g. StartAutoConnect) cannot leave the bridge permanently stopped — the previous early-return assumed an already-hooked retry loop (CodeRabbit, CoplayDev#1198). - Call listener.Stop() before disposing the partially-started listener, matching Stop() (Copilot, CoplayDev#1198). - Name the 60s stale-reset magic number PortBusyStaleResetSeconds (Copilot, CoplayDev#1198).
|
Thanks for the review — addressed in b0fefe4:
|
…+Dispose, name stale-reset const - Arm EnsureStartedOnEditorIdle in the same-port retry path so a transient AddressAlreadyInUse from a direct Start() caller (e.g. StartAutoConnect) cannot leave the bridge permanently stopped — the previous early-return assumed an already-hooked retry loop (CodeRabbit, CoplayDev#1198). - Call listener.Stop() before disposing the partially-started listener, matching Stop() (Copilot, CoplayDev#1198). - Name the 60s stale-reset magic number PortBusyStaleResetSeconds (Copilot, CoplayDev#1198).
…dio-port-stability fix(stdio): retry same port on bind race instead of silent fallback (CoplayDev#1173)
Summary
After a domain reload, a transient
AddressAlreadyInUseon the configured stdio port no longer triggers a silent permanent port switch that strands the Python client on the orphan listener (the #1173 failure). The bridge now retries the same port and only falls back to a new port — loudly — when the port stays busy past a short window.Root cause (#1173)
Stop()/Dispose()run on the main thread duringbeforeAssemblyReload, but the OS frees the bound port a few hundred ms later (slower on Windows/macOS). When the post-reloadStart()rebinds too soon,listener.Start()throwsAddressAlreadyInUse. The previouscatchsilently switched to a new port viaDiscoverNewPort(), but the Python client stays pinned to the configured port → it talks to the orphan and returnsbusy/timeout indefinitely.What changed
StdioBridgeHost.Start()— onAddressAlreadyInUse, keep the configured port and fail the attempt without blocking. The reload handler's async resume schedule (0/1/3/5/10/30s) and the editor-idle retry re-invokeStart()on the same port within ~1s, by which point the OS has released it. Only after the port stays busy pastPortManager.BusyPortFallbackWindowSeconds(3s) does it fall back to a new port — viaMcpLog.Warninstead of the previous debug-only switch. The retry path also re-arms the editor-idle loop so a directStart()caller (e.g.StartAutoConnect) can't be left permanently stopped.PortManager—ShouldAbandonBusyPort(busyForSeconds)policy +BusyPortFallbackWindowSecondsconstant.HandleClientAsync— classifyObjectDisposedExceptionfrom a torn-downNetworkStreamas a benign disconnect (fixes the red Console spam in [Bug]: StdioBridgeHost logs repeated disposed NetworkStream errors on macOS with stdio reconnect/stale clients in 9.7.1 #1187).PortManagerTests— cover the retry-vs-fallback policy threshold.Why not just restore the 2000ms wait (the closed #1175 approach)
Bumping
Stop()'s wait back to 2000ms re-introduces the backgrounded-Unity stall that #787 deliberately fixed by reducing it to 500ms, and it doesn't address the silent port fallback that is the actual masking layer. This PR keeps the 500ms wait untouched, adds zero new main-thread blocking, and is platform-agnostic (the race also reproduces on macOS, per the #1173 thread).Test results
CI — full matrix green (
safe-to-test+full-matrix):UnityMCPTests EditMode on 2021.3.45f2: 886 passed, 0 failed, 46 skipped (all
Explicitside-effect / URP-gatedInconclusive).Live validation — the fix loaded into a running Unity 2021.3.45f2 editor:
BusyPortFallbackWindowSeconds = 3s;ShouldAbandonBusyPort(1.0s) = false(keep port),ShouldAbandonBusyPort(3.5s) = true(fall back).TcpListener+ realPortManager): an orphan holding a port triggersAddressAlreadyInUse; within the 3s window the port is kept; after the orphan releases, the same port rebinds — no silent switch.6400(no silent shift).Cannot access a disposed objecterrors.A/B — same runtime, same orphan-on-
6543scenario, before vs after the change:AddressAlreadyInUseRelated issues & regression sweep
NetworkStreamred errors) — primary symptom fixed by the benignObjectDisposedExceptionreclassification (0 red errors observed under reload churn). The secondary "clean up stale stdio processes" ask is largely client-side and out of scope here.HttpBridgeReloadHandler(ForceStopmay not kill the process, thenResumeHttpWithRetriesAsyncspawns a fresh one that collides), not stdio's socket-release timing. This PR does not address it (stdio-only) and the same-port-retry approach wouldn't fix it — tracked separately.ExecuteMenuItemretry path (StdioBridgeHost: long ExecuteMenuItem runs N times due to broker retry storm under 30s frame timeout #1130), stale-worker handling (Stale stdio workers persist across plugin updates → version drift between hub and worker (potential wire-protocol crashes) #1090), or multi-instance routing (BUG: MCP affects other projects when working in two or more editors #1023) — no regressions introduced in those areas.Summary by CodeRabbit