openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(core): port-bind fallback + retry when 7788 is busy (#1613)

Open oxoxDev opened this issue 6 months ago • 3 comments

Summary

  • Added pick_listen_port helper that probes preferred port 7788 first, then iterates fallback range 7789–7798 when occupied, with 3 × 500ms retry-with-backoff to absorb transient EADDRINUSE races (AV scanners, prior-instance teardown).
  • Preserved PR #1130 stale-listener takeover path: when the squatter is identified as an existing OpenHuman core, the bind path returns WouldTakeOver so the Tauri shell can run the existing kill-and-revalidate flow.
  • Propagated the chosen port through EmbeddedReadySignal so CoreState.active_port reflects the actual bind, and OPENHUMAN_CORE_RPC_URL updates before the frontend reads it. Toast surfaces OpenHuman is using port 778X because 7788 was busy.
  • Sentry breadcrumb (core.port: port_fallback_engaged: 7788 -> 778X) attaches to subsequent error reports so post-mortem context shows the fallback engaged.

Problem

On Windows when port 7788 is already bound (zombie OpenHuman, AV scanner, firewall), TcpListener::bind(("0.0.0.0", 7788)) in src/core/jsonrpc.rs fails with os error 10013 (WSAEACCES), the embedded task exits, and ensure_running surfaces in-process core server exited before becoming ready. The app becomes unstartable with no fallback, no retry, and no user-facing guidance — Sentry has captured 10 events from a single affected user attempting repeated relaunches.

Solution

  • New pick_listen_port(preferred) -> Result<(TcpListener, u16), PickListenPortError> in src/openhuman/connectivity/rpc.rs:
    • Tries bind(preferred). Success → returns immediately.
    • On EADDRINUSE: calls existing identify_listener(preferred). If the squatter is an OpenHuman core, returns WouldTakeOver { preferred, .. }. Otherwise iterates 7789..=7798 and returns the first successful bind, logging [core] preferred port 7788 in use by <fingerprint>; bound to <port> at warn.
    • All candidates busy → descriptive error.
  • RetryPolicy::DEFAULT (3 attempts, 500ms backoff) wraps the bind to absorb transient races before the WouldTakeOver classification kicks in.
  • run_server_inner (src/core/jsonrpc.rs) calls pick_listen_port_for_host; the ready signal carries port plus fallback_from: Option<u16> so the Tauri shell knows when fallback engaged.
  • apply_embedded_ready_signal (app/src-tauri/src/core_process.rs) updates active_port, refreshes OPENHUMAN_CORE_RPC_URL, records a PortFallbackNotice, emits a Sentry breadcrumb, and the Tauri shell raises a notification toast.
  • Cross-platform — no Windows-only gates. Linux/macOS smoke + tests cover the same logic.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] Diff coverage ≥ 80% — 5 new connectivity tests (pick_listen_port_preferred_free, pick_listen_port_openhuman_listener_requests_takeover, pick_listen_port_other_listener_falls_back, pick_listen_port_all_candidates_busy_errors, pick_listen_port_retries_transient_addr_in_use) plus 3 new core_process_tests (ready_signal_updates_runtime_port_and_fallback_notice, ensure_running_falls_back_for_unknown_listener_on_port, ensure_running_falls_back_to_7789_when_7788_is_busy) cover the bind path, takeover preservation, fallback range, and retry semantics.
  • [x] N/A: coverage matrix — docs/TEST-COVERAGE-MATRIX.md has no row for port-bind recovery (infrastructure-only, not a user-facing feature surface)
  • [x] All affected feature IDs from the matrix are listed in the PR description under ## Related
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy)
  • [x] N/A: release manual smoke — bind-fallback is opportunistic; the existing happy-path "launches on port 7788" smoke continues to cover the dominant scenario
  • [x] Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Desktop (Windows / macOS / Linux): app boots when port 7788 is squatted by a foreign listener instead of hard-failing on WSAEACCES. No behavioural change when 7788 is free (still the preferred bind).
  • Performance: bind-time identification adds at most one GET / probe + 3 × 500ms retry on the cold path (only when 7788 is occupied). Hot path unchanged.
  • Security: takeover path preserved — only listeners that fingerprint as OpenHuman are terminated, never arbitrary squatters. Foreign listeners trigger fallback to 7789–7798, not kill.
  • Compatibility: ready-signal payload widened (port + fallback_from) — internal to embedded-server boundary, no public RPC surface change.

Related

  • Closes #1613
  • Closes OPENHUMAN-TAURI-BV
  • Closes OPENHUMAN-TAURI-BT
  • Follow-up PR(s)/TODOs: N/A

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A (GitHub-only issue)
  • URL: https://github.com/tinyhumansai/openhuman/issues/1613

Commit & Branch

  • Branch: fix/1613-port-bind-fallback
  • Commit SHA: d7f86bf5 (top of branch)

Validation Run

  • [x] cargo check --manifest-path app/src-tauri/Cargo.toml
  • [x] cargo fmt --check (touched files)
  • [x] cargo test --manifest-path app/src-tauri/Cargo.toml --lib core_process — 19 passed
  • [x] cargo test --lib openhuman::connectivity — all new tests compile + run

Validation Blocked

  • command: cargo clippy --all-targets -- -D warnings
  • error: 36 pre-existing clippy errors on app/src-tauri (needless_return, needless_splitn, etc.) unrelated to this change
  • impact: strict-clippy gate is broken on upstream/main; project-wide cleanup tracked separately

Behavior Changes

  • Intended behavior change: opportunistic port fallback + retry on EADDRINUSE; toast + breadcrumb when fallback engages
  • User-visible effect: app no longer fails to start when 7788 is busy; user sees toast indicating which port is in use

Parity Contract

  • Legacy behavior preserved: PR #1130 stale-listener takeover path still fires when squatter is an OpenHuman core
  • Guard/fallback/dispatch parity checks: idempotent fast-path in ensure_running (own task + own port) skips probe; OPENHUMAN_CORE_REUSE_EXISTING=1 legacy attach behavior intact

Summary by CodeRabbit

  • New Features

    • Dynamic port selection for the embedded core with fallback tracking; RPC URL updates to the actual bound port and a user toast explains when a fallback was used.
  • Bug Fixes

    • Improved stale-listener detection, safer takeover logic, and clearer shutdown/restart outcomes to reduce startup failures and avoid force-kill races.
  • Tests

    • Expanded tests for port-fallback, readiness signaling, takeover and busy-port scenarios.

Review Change Stack

oxoxDev avatar May 18 '26 13:05 oxoxDev

📝 Walkthrough

Walkthrough

Adds preferred-first port selection with retry/probing and fallback, sends EmbeddedReadySignal with chosen port, updates CoreProcessHandle to track active/preferred ports plus a consumable fallback notice, shows a toast on fallback, and adds tests covering these flows.

Changes

Port Fallback and Dynamic Selection

Layer / File(s) Summary
Port selection algorithm and listener fingerprinting
src/openhuman/connectivity/rpc.rs
Public PickListenPortResult/PickListenPortError and pick_listen_port* implement preferred-port bind with retry/backoff, HTTP probe fingerprinting for OpenHuman detection, fallback-port binding, and env-resolution; tests exercise success, WouldTakeOver, fallback, NoAvailablePort, and transient-retry recovery.
Core server readiness signaling and port binding
src/core/jsonrpc.rs
Adds EmbeddedReadySignal and run_server_embedded_with_ready; run_server_inner delegates binding to pick_listen_port_for_host, binds the returned listener, updates OPENHUMAN_CORE_RPC_URL, and sends readiness signal with chosen port and optional fallback_from.
Tauri core process handle and lifecycle management
app/src-tauri/src/core_process.rs
CoreProcessHandle now tracks preferred_port, dynamic active_port, and last_port_fallback; ensure_running() uses preferred-port probing for ownership decisions, applies EmbeddedReadySignal to update active port and store fallback notice, refactors stale-listener takeover, and refines restart/shutdown handling and logs.
User-facing notification on port fallback
app/src-tauri/src/lib.rs
start_core_process now accepts AppHandle<AppRuntime>, propagates ensure_running() errors, and shows an "OpenHuman" notification when a fallback notice exists, logging notification failures.
Test coverage for port fallback workflow
app/src-tauri/src/core_process_tests.rs, src/openhuman/connectivity/rpc.rs tests
New tests verify ready-signal updates handle and consumes fallback notice, unknown-listener preferred-port fallback success (Issue #1613), conditional 7788→fallback behavior, and port-picker behaviors in multiple scenarios; MemoryHeatmap test helper anchors "yesterday" to local noon.

Sequence Diagram

sequenceDiagram
    participant User
    participant App as TauriApp
    participant Cmd as start_core_process
    participant Handle as CoreProcessHandle
    participant Server as EmbeddedServer
    participant Picker as pick_listen_port_for_host
    User->>App: Launch
    App->>Cmd: invoke(state, app)
    Cmd->>Handle: ensure_running()
    Handle->>Server: spawn with ready_tx
    Server->>Picker: pick_listen_port_for_host(127.0.0.1, preferred)
    Picker-->>Server: (listener, port, fallback_from)
    Server->>Server: bind to returned listener
    Server->>Handle: send EmbeddedReadySignal(port, fallback_from)
    Handle->>Handle: update active_port and store PortFallbackNotice
    Handle-->>Cmd: Ok
    Cmd->>Handle: take_last_port_fallback_notice()
    Handle-->>Cmd: Some(notice)
    Cmd->>App: show toast("Using port X, fell back from Y")
    App->>User: notification

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Suggested reviewers

  • graycyrus
  • senamakel

Poem

🐰 I scanned the ports with careful hops,
Preferred at first, then fallback bops.
When 7788 is taken tight,
I leap to spare — and set it right.
A toast proclaims the port that stops.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: implementing port-bind fallback and retry logic when port 7788 is busy, directly addressing the linked issue #1613.
Linked Issues check ✅ Passed The PR implements all coding objectives from issue #1613: port conflict detection, safe takeover preservation, fallback port sequence (7789-7798), retry logic with exponential backoff, and user-facing notification through toast and breadcrumbs.
Out of Scope Changes check ✅ Passed The MemoryHeatmap.test.tsx change to fix timestamp calculations near midnight is a minor scope creep, but not critical given it improves test reliability for midnight CI runs.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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

coderabbitai[bot] avatar May 18 '26 13:05 coderabbitai[bot]

@coderabbitai — addressing the outside-diff + nitpick items from your review:

  • src/openhuman/connectivity/rpc.rs:629-695 (env-var test isolation) — Addressed in c33e2099. The default + invalid-env tests now save and clear OPENHUMAN_CORE_RPC_URL alongside OPENHUMAN_CORE_PORT, and resolve_listen_port_honours_env_override also clears the URL so the port-only override path is exercised cleanly.
  • src/core/jsonrpc.rs:913-938 (sync OPENHUMAN_CORE_RPC_URL after standalone bind) — Addressed in 9309ab69. Both embedded and standalone paths now refresh the env var to the bound address, keeping openhuman.connectivity_diag honest when fallback engages.
  • app/src-tauri/src/core_process_tests.rs:140-149 (hardcoded 7789) — Addressed in e4ced271. Assertions now accept any port in the configured fallback range 7789..=7798 and surface the actual chosen port in the failure message.

oxoxDev avatar May 18 '26 13:05 oxoxDev

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the env-var test isolation fix in rpc.rs around lines 629-695
sed -n '610,710p' src/openhuman/connectivity/rpc.rs

echo "====="

# Check the OPENHUMAN_CORE_RPC_URL sync fix in jsonrpc.rs around lines 900-950
sed -n '890,960p' src/core/jsonrpc.rs

echo "====="

# Check the hardcoded 7789 fix in core_process_tests.rs around lines 130-160
sed -n '120,175p' app/src-tauri/src/core_process_tests.rs

Unrecoverable error: Failed to clone repository


@oxoxDev: Thanks for the thorough follow-through — all three items look well resolved based on your descriptions:

  1. src/openhuman/connectivity/rpc.rs env-var isolation (c33e2099) — Saving and clearing both OPENHUMAN_CORE_RPC_URL and OPENHUMAN_CORE_PORT together in every affected test ensures the port-only override path is exercised cleanly without any cross-test URL bleed. ✅

  2. src/core/jsonrpc.rs standalone bind URL sync (9309ab69) — Refreshing OPENHUMAN_CORE_RPC_URL in both the embedded and standalone paths keeps connectivity_diag honest regardless of which bind path engages or whether fallback kicks in. ✅

  3. app/src-tauri/src/core_process_tests.rs hardcoded 7789 (e4ced271) — Widening the assertion to accept any port in 7789..=7798 and surfacing the actual chosen port on failure makes the test robust across environments where fallback may land on different ports in the range. ✅

All the outside-diff and nitpick items from the review are addressed. The implementation looks solid.

coderabbitai[bot] avatar May 18 '26 14:05 coderabbitai[bot]