Skip to content

fix(stdio): retry same port on bind race instead of silent fallback (#1173) - #1198

Merged
Scriptwonder merged 2 commits into
CoplayDev:betafrom
Scriptwonder:fix/issue-1173-stdio-port-stability
Jun 14, 2026
Merged

Scriptwonder merged 2 commits into
CoplayDev:betafrom
Scriptwonder:fix/issue-1173-stdio-port-stability

Conversation

@Scriptwonder

@Scriptwonder Scriptwonder commented Jun 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

After a domain reload, a transient AddressAlreadyInUse on 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 during beforeAssemblyReload, but the OS frees the bound port a few hundred ms later (slower on Windows/macOS). When the post-reload Start() rebinds too soon, listener.Start() throws AddressAlreadyInUse. The previous catch silently switched to a new port via DiscoverNewPort(), but the Python client stays pinned to the configured port → it talks to the orphan and returns busy/timeout indefinitely.

What changed

  • StdioBridgeHost.Start() — on AddressAlreadyInUse, 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-invoke Start() on the same port within ~1s, by which point the OS has released it. Only after the port stays busy past PortManager.BusyPortFallbackWindowSeconds (3s) does it fall back to a new port — via McpLog.Warn instead of the previous debug-only switch. The retry path also re-arms the editor-idle loop so a direct Start() caller (e.g. StartAutoConnect) can't be left permanently stopped.
  • PortManager — ShouldAbandonBusyPort(busyForSeconds) policy + BusyPortFallbackWindowSeconds constant.
  • HandleClientAsync — classify ObjectDisposedException from a torn-down NetworkStream as 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):

Unity EditMode
2021.3.45f2 ✅ pass
2022.3.62f1 ✅ pass
6000.0.75f1 ✅ pass
6000.4.8f1 ✅ pass

UnityMCPTests EditMode on 2021.3.45f2: 886 passed, 0 failed, 46 skipped (all Explicit side-effect / URP-gated Inconclusive).

Live validation — the fix loaded into a running Unity 2021.3.45f2 editor:

  • Fix code loads + policy correct in the real runtime: BusyPortFallbackWindowSeconds = 3s; ShouldAbandonBusyPort(1.0s) = false (keep port), ShouldAbandonBusyPort(3.5s) = true (fall back).
  • End-to-end retry (real TcpListener + real PortManager): an orphan holding a port triggers AddressAlreadyInUse; within the 3s window the port is kept; after the orphan releases, the same port rebinds — no silent switch.
  • A real domain reload tore down and rebound the bridge — it recovered and stayed on the configured port 6400 (no silent shift).
  • [Bug]: StdioBridgeHost logs repeated disposed NetworkStream errors on macOS with stdio reconnect/stale clients in 9.7.1 #1187: after reload churn, 0 red Cannot access a disposed object errors.

A/B — same runtime, same orphan-on-6543 scenario, before vs after the change:

port 6543 held → AddressAlreadyInUse Before (no fix) After (fix)
same-port retry policy absent present (3s window)
on conflict switches away to 6544 (silent — the #1173 bug) keeps 6543, retries; rebinds same port on release

Related issues & regression sweep

Summary by CodeRabbit

  • Bug Fixes
    • Improved TCP port fallback handling by retrying the configured port for up to 3 seconds when it’s temporarily busy, only switching to a newly discovered port after the window elapses.
    • Added clearer “port busy” signaling during reload-related race conditions and reduced log noise by treating expected disposal events as benign.
  • Tests
    • Added unit tests covering the abandon-vs-keep retry behavior within and beyond the 3-second window.

…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).
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a 3-second time-bounded retry window before StdioBridgeHost falls back to a new port on AddressAlreadyInUse. A new _portBusySince timestamp drives calls to the new PortManager.ShouldAbandonBusyPort helper; within the window, the host retries the configured port with a throttled delay and sends a port_busy heartbeat. ObjectDisposedException is reclassified as benign in the client handler. Two unit tests cover the new helper.

Changes

Busy-port fallback window

Layer / File(s) Summary
PortManager busy-port threshold and helper
MCPForUnity/Editor/Helpers/PortManager.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Services/PortManagerTests.cs
Adds BusyPortFallbackWindowSeconds (3.0) constant and ShouldAbandonBusyPort(double busyForSeconds) static method; two new NUnit tests assert the method returns false within the window and true at or beyond it.
StdioBridgeHost timed retry and benign-exception fix
MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs
Adds _portBusySince field and PortBusyStaleResetSeconds constant; reworks the AddressAlreadyInUse catch block in Start() to throttle retries on the configured port for up to 3 seconds before falling back to a discovered port and persisting it in EditorPrefs; adds ObjectDisposedException to the benign-exception filter in the client handler loop.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • CoplayDev/unity-mcp#428: Modifies the same AddressAlreadyInUse catch block in StdioBridgeHost.Start() and port fallback logic that this PR reworks with the time-bounded retry window.

Poem

🐇 A port was stuck, the socket clung tight,
So I watched and waited — three seconds just right.
If the old port freed, I'd hop back with cheer,
But past the window? I'd find a new pier.
No more lost clients on ports gone astray,
This rabbit now retries the smart way! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: retrying the same port on a bind race instead of silently falling back to a new port.
Linked Issues check ✅ Passed The PR successfully implements the retry-vs-fallback policy from #1173 and #1175, adds ShouldAbandonBusyPort helper, reclassifies ObjectDisposedException as benign per #1187, and includes unit test coverage.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the domain-reload port-binding race (#1173), implementing the retry policy (#1175 comparison), and eliminating error spam (#1187). No extraneous refactoring or unrelated functionality.
Description check ✅ Passed The pull request provides a comprehensive description covering the bug fix, root cause analysis, specific changes, test results, and related issues.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Scriptwonder Scriptwonder added safe-to-test Triggers CI checks full-matrix Enable full-matrix CI test labels Jun 14, 2026
@Scriptwonder
Scriptwonder marked this pull request as ready for review June 14, 2026 01:27
Copilot AI review requested due to automatic review settings June 14, 2026 01:27

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.

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(...) and BusyPortFallbackWindowSeconds to 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.

Comment on lines +307 to +311
if (!PortManager.ShouldAbandonBusyPort(now - _portBusySince))
{
try { listener?.Server?.Dispose(); } catch { }
listener = null;
McpLog.Warn($"Port {currentUnityPort} not released yet after reload; retrying same port.");
Comment on lines +302 to +305
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;

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c0908b8 and 6e1a87e.

📒 Files selected for processing (3)
  • MCPForUnity/Editor/Helpers/PortManager.cs
  • MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs
  • TestProjects/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).
@Scriptwonder

Copy link
Copy Markdown
Collaborator Author

Thanks for the review — addressed in b0fefe4:

  • CodeRabbit (early-return retry arming): valid — the previous early-return assumed EnsureStartedOnEditorIdle was already hooked, which isn't guaranteed for direct Start() callers like StartAutoConnect. The retry path now arms the editor-idle loop itself (if (!ensureUpdateHooked) { … EditorApplication.update += EnsureStartedOnEditorIdle; }), so a transient AddressAlreadyInUse can never leave the bridge permanently stopped.
  • Copilot (listener cleanup): now calls listener.Stop() before Server.Dispose(), matching Stop().
  • Copilot (magic number): 60.0 is now PortBusyStaleResetSeconds.

@Scriptwonder
Scriptwonder merged commit 4050f4d into CoplayDev:beta Jun 14, 2026
6 checks passed
@Scriptwonder
Scriptwonder deleted the fix/issue-1173-stdio-port-stability branch June 14, 2026 18:44
Serraya pushed a commit to Serraya/unity-mcp that referenced this pull request Jun 18, 2026
…+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).
Serraya pushed a commit to Serraya/unity-mcp that referenced this pull request Jun 18, 2026
…dio-port-stability

fix(stdio): retry same port on bind race instead of silent fallback (CoplayDev#1173)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-matrix Enable full-matrix CI test safe-to-test Triggers CI checks

Projects

None yet

2 participants