unity-mcp icon indicating copy to clipboard operation
unity-mcp copied to clipboard

fix: stop tearing down healthy HTTP sessions on transient probe misses (#1207)

Open Scriptwonder opened this issue 4 months ago • 4 comments

Addresses the dominant churn source in #1207, following the fix order @dsarno proposed from the evidence bundle.

Problem

Two amplifiers turned ordinary reload/test boundaries into no_unity_session wedges:

  1. Hair-trigger orphan detector. McpConnectionSection.UpdateConnectionStatus ends an active session the moment one cached reachability reading is false — and that reading is a lone TCP connect with a 50 ms wait, cached 0.75 s. On a machine busy with a test run or domain reload the probe times out against a perfectly healthy server; the detector then force-stops the bridge (13 teardowns / 147 socket closures in one session in the #1207 evidence bundle), feeding the reconnect churn that outruns the server's session-resolve window.
  2. Neutered escape hatch. UNITY_MCP_SESSION_RESOLVE_MAX_WAIT_S is documented as configurable but was clamped to a ceiling equal to its default (20 s), so users whose reloads legitimately exceed 20 s could not actually extend the window.

Fix

  • Orphan teardown now requires 3 consecutive failed polls at the 0.75 s cadence (~2.25 s of continuous unreachability); readings taken while the editor is compiling/importing don't count, and detection is skipped while busy. The decision is an internal static predicate with tests.
  • Probe connect wait raised 50 ms → 250 ms, implemented as an overall budget shared across candidate hosts so the worst-case main-thread wait cannot multiply (a refused connect still fails in ~1 ms; the budget only bites when packets are dropped or the stack is starved).
  • UNITY_MCP_SESSION_RESOLVE_MAX_WAIT_S ceiling raised to 120 s (default unchanged at 20 s); UNITY_MCP_SESSION_READY_WAIT_SECONDS likewise (default 6 s). Both now share one bounded env-read helper with tests.

What this deliberately does not do

  • No keepalive/reload-awareness changes in WebSocketTransportClient — #1234's resume rework already owns reload boundaries, and per the maintainer analysis the detector debounce removes the dominant churn source. If churn persists after both land, that's the next lever.
  • No change to ping/pong heartbeat semantics from #656.

Verification

  • cd Server && uv run pytest tests/ -q → 1313 passed, 3 skipped (5 new env-clamp tests).
  • 7 new EditMode tests covering the teardown predicate matrix (threshold, below-threshold, busy-editor deferral, toggle-in-progress, non-HTTP-local, not-running).
  • Compile-only matrix via tools/check-unity-versions.sh (2021.3 floor passes locally).

Summary by CodeRabbit

  • Bug Fixes
    • Improved local server detection so brief connection hiccups are less likely to interrupt an active session.
    • Prevented premature session shutdown while the editor is busy or when connection state is still fluctuating.
    • Increased the wait time for local connection checks, making startup and reconnect behavior more tolerant.
    • Expanded supported wait-time settings, with safer handling for invalid or out-of-range values.

Scriptwonder avatar Jul 04 '26 22:07 Scriptwonder

Review Change Stack

📝 Walkthrough

Walkthrough

Unity local HTTP reachability probing now uses a longer shared timeout budget, and orphaned session teardown waits for repeated down probes. Server-side wait-time environment parsing is centralized with a higher clamp ceiling and new tests.

Changes

Unity Editor: Reachability probing and orphan-session teardown

Layer / File(s) Summary
Local port reachability timeout budget
MCPForUnity/Editor/Services/ServerManagementService.cs
Increases the overall probe timeout from 50ms to 250ms and shares that budget across candidate hosts.
Orphan-session teardown policy
MCPForUnity/Editor/Windows/Components/Connection/McpConnectionSection.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Windows/McpConnectionSectionOrphanDetectionTests.cs, TestProjects/UnityMCPTests/Assets/Tests/EditMode/Windows/McpConnectionSectionOrphanDetectionTests.cs.meta
Adds consecutive down-poll tracking and threshold-based teardown checks, with NUnit coverage for session, editor, toggle, and transport states.

Server-side bounded wait-time environment handling

Layer / File(s) Summary
Bounded env wait-time helper and call sites
Server/src/transport/plugin_hub.py, Server/tests/test_plugin_hub_wait_env.py
Centralizes parsing and clamping for session resolve and readiness waits, raising the ceiling from 20s to 120s and testing default, override, invalid, negative, and ceiling cases.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Sequence Diagram(s)

sequenceDiagram
  participant UpdateStartHttpButtonState
  participant UpdateConnectionStatus
  participant ShouldEndOrphanedSession

  UpdateStartHttpButtonState->>UpdateStartHttpButtonState: probe local HTTP reachability
  UpdateStartHttpButtonState->>UpdateStartHttpButtonState: update consecutiveServerDownPolls
  UpdateConnectionStatus->>ShouldEndOrphanedSession: evaluate session and editor state
  ShouldEndOrphanedSession-->>UpdateConnectionStatus: return teardown decision
  UpdateConnectionStatus->>UpdateConnectionStatus: end orphaned session when allowed

Possibly related issues

  • CoplayDev/unity-mcp#1207: Extends configurable session-resolution waits beyond the previous 20-second ceiling, matching this PR’s server-side timeout changes.

Possibly related PRs

Suggested reviewers: dsarno

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the required template sections for type, changes made, compatibility, testing, and related issues. Add the missing template sections: Description, Type of Change, Changes Made, Compatibility/Package Source, Testing, Documentation Updates, Related Issues, and Additional Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main fix to HTTP session teardown behavior.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

coderabbitai[bot] avatar Jul 04 '26 22:07 coderabbitai[bot]

:warning: Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

:x: Patch coverage is 91.66667% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
Server/src/transport/plugin_hub.py 91.66% 1 Missing :warning:

:loudspeaker: Thoughts on this report? Let us know!

codecov-commenter avatar Jul 04 '26 22:07 codecov-commenter

@coderabbitai review

Scriptwonder avatar Jul 05 '26 00:07 Scriptwonder

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar Jul 05 '26 00:07 coderabbitai[bot]