Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(remote-access): restart a tunnel connector that exited on its own (#2455)
Call White3f4059b96366
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.mdindex ca6b1a123..9fbd123db 100644--- a/docs/plans/tunnel-quality-and-route-recovery.md+++ b/docs/plans/tunnel-quality-and-route-recovery.md@@ -605,6 +605,46 @@ Connector state writes are atomic. On startup:and- never clear shared logs or state belonging to the surviving connector.+### Exited-connector restart++A connector can exit on its own: after a reboot, when the network is not up yet+at UI start, cloudflared exits within about a second. `start()` records a+connector request (`remote-access-connector-requested` in the runtime+directory) and `stop()` withdraws it before stopping the process. The monitor+restarts a requested connector that is no longer running:++- only while remote access is enabled with a tunnel token, and never while+ recovery owns the connector lane: the restart checks+ `_connector_lane_reserved_locked()` under the recovery lock before it takes+ the connector lock, the same order settings and recovery use;+- one backoff delay after the exit is first seen, starting at one sample+ interval and doubling after each attempt up to two minutes; and+- the delay resets once a connector reports a ready connection.++The UI server, its monitor and recovery threads, and the `vibe remote` CLI all+read and rewrite the connector's pid, state, and request files. One+cross-process lifecycle lock, `runtime/remote-access-connector.lock`+(`storage.lock.MigrationFileLock`, never unlinked), serializes every+read-validate-mutate section: a start's status check, spawn, and publish; a+stop's withdrawal, kill, and record removal; the restart's request check,+spawn, and publish; status()'s removal of an exited connector's records; and+recovery's candidate spawn, promote, and drain record transitions. The lock+order is the lifecycle lock, then the recovery lock, then the connector lock.+User starts and stops wait up to 20 seconds, longer than a start's own+worst-case hold, and then report `remote_access_busy`; the monitor, the+restart, reconciliation, and status() only try the lock and skip when it is+busy, because a later tick repeats them, and a startup orphan-candidate+reconciliation that found it busy is retried on later ticks. Record cleanups+that nothing repeats (a discarded candidate, a drained connector, a cleared+tail rollback) wait up to 60 seconds, three times the longest hold, and+otherwise log an error and leave the records for reconciliation. Waits such as candidate warm-up and downloading a+missing cloudflared run outside it, and the OS releases it when its holder+dies. A request path that is not a regular file is no request.++So only an explicit `stop()` withdraws the request, and no stop or start in+any process interleaves with a restart. A tick that attempted a restart skips+quality evaluation, because its samples describe the exited connector.+## Doctor IntegrationDoctor gains a `Remote Access` group. It is read-only and never starts a@@ -912,6 +952,7 @@ the active Connector currently demonstrates QUIC. An unobserved UDP path stays| RA-TQ-030 | Connectivity diagnostics distinguish proven from unobserved paths | diagnostics contract test || RA-TQ-031 | Tunnel controls remain usable on desktop and mobile | browser/runtime proof || RA-TQ-033 | An unavailable route recovers over the other transport despite cooldown | supervisor scenario tests |+| RA-TQ-034 | A requested connector that exits on its own restarts with backoff; a stopped or disabled one stays down | supervisor scenario tests |## Implementation Boundaries@@ -956,5 +997,5 @@ changes must update the schema first.console is visible.- No secret or sensitive request data appears in local snapshots, logs, Doctor,status APIs, or cloud payloads.-- RA-TQ-001 through RA-TQ-030 and RA-TQ-033 pass in their required evidence+- RA-TQ-001 through RA-TQ-030, RA-TQ-033, and RA-TQ-034 pass in their required evidencelayers; RA-TQ-031 receives browser proof at desktop and mobile widths.diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yamlindex 2843fd263..e861b9f5e 100644--- a/tests/scenarios/tunnel_quality/catalog.yaml+++ b/tests/scenarios/tunnel_quality/catalog.yaml@@ -212,3 +212,9 @@ scenarios:kind: lifecyclelayer: scenariotest: tests/test_tunnel_recovery.py::test_ra_tq_033_availability_recovery_protocol_follows_route_outage+ - id: RA-TQ-034+ name: A requested Connector that exits on its own restarts with backoff; a stopped or disabled one stays down+ status: covered+ kind: resilience+ layer: scenario+ test: tests/test_tunnel_recovery.py::test_ra_tq_034_connector_exited_before_network_is_restarted_with_backoffdiff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.pyindex 557e2e732..f2020b571 100644--- a/tests/test_tunnel_recovery.py+++ b/tests/test_tunnel_recovery.py@@ -1,9 +1,14 @@from __future__ import annotationsimport json+import os+import subprocess+import sysimport threadingimport time+from pathlib import Path+import psutilimport pytestfrom config.v2_config import V2Config@@ -1483,3 +1488,556 @@ def test_ra_tq_009_restart_promotes_ready_candidate(monkeypatch, tmp_path) -> Noassert remote_access._read_pid() == candidate_pidassert reconciled["active"]["pid"] == candidate_pidassert reconciled["candidate"] is None+++def _setup_exiting_connector(monkeypatch, tmp_path) -> tuple[V2Config, Path]:+ """A real connector process that exits about half a second after start while the network is down."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ network_up = tmp_path / "network-up"+ binary = tmp_path / "bin" / "cloudflared"+ binary.parent.mkdir()+ binary.write_text(+ "#!/bin/sh\n"+ f'if [ -e "{network_up}" ]; then while :; do sleep 0.2; done; fi\n'+ 'echo "failed to dial to edge: lookup region1.v2.argotunnel.com: no such host" >&2\n'+ "sleep 0.5\n"+ "exit 1\n",+ encoding="utf-8",+ )+ binary.chmod(0o755)+ config = _config()+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"+ config.remote_access.vibe_cloud.cloudflared_path = str(binary)+ config.save()+ monkeypatch.setattr(remote_access, "_PREFERRED_PROTOCOL", None)+ monkeypatch.setattr(remote_access, "_version", lambda path: "cloudflared version test")+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)++ def process_command(pid: int) -> str | None:+ # The macOS fallback runs setuid ``ps``, which a sandboxed test cannot exec.+ try:+ return " ".join(psutil.Process(pid).cmdline()) or None+ except psutil.Error:+ return None++ monkeypatch.setattr(runtime, "get_process_command", process_command)+ return config, network_up+++def _wait_connector_exit(timeout: float = 5.0) -> None:+ deadline = time.monotonic() + timeout+ while remote_access._cloudflared_pid_state(remote_access._read_pid()) not in {"dead", "other"}:+ assert time.monotonic() < deadline, "connector did not exit"+ time.sleep(0.05)+++def test_ra_tq_034_connector_exited_before_network_is_restarted_with_backoff(monkeypatch, tmp_path) -> None:+ config, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ schedule = remote_access._ConnectorRestartSchedule()+ try:+ # UI start after a reboot: the network is down, so the connector exits within a second.+ remote_access.start()+ _wait_connector_exit()++ remote_access._restart_exited_connector(config, schedule, 1000.0)+ assert not remote_access._is_cloudflared_pid(remote_access._read_pid())+ remote_access._restart_exited_connector(config, schedule, 1000.0 + remote_access.QUALITY_SAMPLE_SECONDS)+ assert schedule.delay_seconds == 2 * remote_access.QUALITY_SAMPLE_SECONDS+ _wait_connector_exit()++ network_up.touch()+ now = 1100.0+ remote_access._restart_exited_connector(config, schedule, now)+ remote_access._restart_exited_connector(config, schedule, now + schedule.delay_seconds - 1)+ assert not remote_access._is_cloudflared_pid(remote_access._read_pid())+ remote_access._restart_exited_connector(config, schedule, now + schedule.delay_seconds)++ pid = remote_access._read_pid()+ time.sleep(1.0) # longer than the offline connector lives+ assert remote_access._is_cloudflared_pid(pid)+ remote_access._restart_exited_connector(config, schedule, now + 1000)+ assert remote_access._read_pid() == pid+ assert schedule.due_at is None+ finally:+ remote_access.stop()++[email protected]("withdrawal", ["user_stop", "remote_access_disabled"])+def test_ra_tq_034_withdrawn_connector_request_is_not_restarted(monkeypatch, tmp_path, withdrawal) -> None:+ config, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ schedule = remote_access._ConnectorRestartSchedule()+ real_start = remote_access._start+ started = []+ try:+ remote_access.start()+ _wait_connector_exit()+ network_up.touch()+ if withdrawal == "user_stop":+ remote_access.stop()+ else:+ config.remote_access.vibe_cloud.enabled = False+ config.save()++ def record_start(loaded, *, record_request, install_failure=None):+ started.append(record_request)+ return real_start(loaded, record_request=record_request, install_failure=install_failure)++ monkeypatch.setattr(remote_access, "_start", record_start)+ for now in (1000.0, 2000.0, 3000.0):+ remote_access._restart_exited_connector(config, schedule, now)++ assert started == []+ assert not remote_access._is_cloudflared_pid(remote_access._read_pid())+ finally:+ remote_access.stop()+++def test_ra_tq_034_restart_takes_recovery_lock_before_connector_lock(monkeypatch, tmp_path) -> None:+ config, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ schedule = remote_access._ConnectorRestartSchedule()+ recovery_holds_its_lock = threading.Event()+ connector_lock_acquired = []++ def reserve_recovery() -> None:+ # The order route recovery and settings use: _RECOVERY_LOCK, then _CONNECTOR_LOCK.+ with remote_access._RECOVERY_LOCK:+ recovery_holds_its_lock.set()+ acquired = remote_access._CONNECTOR_LOCK.acquire(timeout=5)+ connector_lock_acquired.append(acquired)+ if acquired:+ remote_access._CONNECTOR_LOCK.release()++ recovery = threading.Thread(target=reserve_recovery)+ real_read_pid = remote_access._read_pid++ def read_pid_while_recovery_reserves():+ # Recovery reserves the lane right after the restart takes the connector lock.+ if remote_access._CONNECTOR_LOCK._is_owned() and not recovery_holds_its_lock.is_set():+ recovery.start()+ recovery_holds_its_lock.wait(5)+ return real_read_pid()++ try:+ remote_access.start()+ _wait_connector_exit()+ network_up.touch()+ remote_access._restart_exited_connector(config, schedule, 1000.0)+ monkeypatch.setattr(remote_access, "_read_pid", read_pid_while_recovery_reserves)++ remote_access._restart_exited_connector(config, schedule, 1000.0 + schedule.delay_seconds)+ recovery.join(10)++ assert connector_lock_acquired == [True]+ finally:+ monkeypatch.setattr(remote_access, "_read_pid", real_read_pid)+ remote_access.stop()+++class _StopMonitor(Exception):+ pass+++def test_ra_tq_034_restart_tick_does_not_evaluate_the_exited_connector(monkeypatch, tmp_path) -> None:+ _, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ interval = remote_access.QUALITY_SAMPLE_SECONDS+ clock = {"now": 1000.0}++ def sleep(seconds: float) -> None:+ clock["now"] += seconds+ if clock["now"] >= 1000.0 + 2 * interval:+ raise _StopMonitor # end of the second tick++ monkeypatch.setattr(+ remote_access,+ "time",+ type("Clock", (), {"monotonic": staticmethod(lambda: clock["now"]), "sleep": staticmethod(sleep), "time": staticmethod(time.time)}),+ )+ monkeypatch.setattr(remote_access, "_public_health_url", lambda loaded: None)+ # Outage evidence left by the exited connector would fire availability recovery.+ monkeypatch.setattr(remote_access._QUALITY_EVALUATOR, "recovery_trigger", lambda snapshot, profile: "availability")+ optimized_while_running = []+ monkeypatch.setattr(+ remote_access,+ "optimize_route",+ lambda **kwargs: optimized_while_running.append(remote_access._is_cloudflared_pid(remote_access._read_pid())),+ )+ try:+ remote_access.start()+ _wait_connector_exit()+ network_up.touch()+ remote_access._quality_state_path().parent.mkdir(parents=True, exist_ok=True)++ # Tick 1 sees the exit and schedules the restart; tick 2 restarts.+ with pytest.raises(_StopMonitor):+ remote_access._quality_monitor_loop(interval, remote_access._quality_state_path())++ assert remote_access._is_cloudflared_pid(remote_access._read_pid())+ assert optimized_while_running == [False]+ finally:+ remote_access.stop()+++def test_ra_tq_034_failed_config_read_during_restart_keeps_the_request(monkeypatch, tmp_path) -> None:+ config, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ schedule = remote_access._ConnectorRestartSchedule()+ real_load = remote_access.V2Config.load+ reads_under_lock = []++ def load_failing_once_under_connector_lock(*args, **kwargs):+ if remote_access._CONNECTOR_LOCK._is_owned():+ reads_under_lock.append(True)+ # The restart's _start() reads the config twice under the lock;+ # the second read, after its fallback read, fails once.+ if len(reads_under_lock) == 2:+ raise OSError("transient config read failure")+ return real_load(*args, **kwargs)++ try:+ remote_access.start()+ _wait_connector_exit()+ network_up.touch()+ monkeypatch.setattr(remote_access.V2Config, "load", load_failing_once_under_connector_lock)+ remote_access._restart_exited_connector(config, schedule, 1000.0)+ remote_access._restart_exited_connector(config, schedule, 1000.0 + schedule.delay_seconds)+ assert len(reads_under_lock) == 2+ assert remote_access._connector_requested_path().exists()++ now = 2000.0+ remote_access._restart_exited_connector(config, schedule, now)+ remote_access._restart_exited_connector(config, schedule, now + schedule.delay_seconds)+ assert remote_access._is_cloudflared_pid(remote_access._read_pid())+ finally:+ monkeypatch.setattr(remote_access.V2Config, "load", real_load)+ remote_access.stop()+++def test_ra_tq_034_stop_still_stops_when_the_request_cannot_be_withdrawn(monkeypatch, tmp_path) -> None:+ config, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ network_up.touch()+ request = remote_access._connector_requested_path()+ try:+ remote_access.start()+ pid = remote_access._read_pid()+ assert remote_access._is_cloudflared_pid(pid)+ request.unlink()+ request.mkdir() # a corrupted request that unlink() cannot remove++ result = remote_access.stop()++ assert result["ok"] is False+ assert result["error"] == "remote_access_request_withdraw_failed"+ assert not remote_access._is_cloudflared_pid(pid)+ # What stop could not remove is no request, so the monitor keeps it down.+ schedule = remote_access._ConnectorRestartSchedule()+ for now in (1000.0, 2000.0, 3000.0):+ assert remote_access._restart_exited_connector(config, schedule, now) is False+ finally:+ if request.is_dir():+ request.rmdir()+ remote_access.stop()+++_LIFECYCLE_CHILD = """+import json, sys+from pathlib import Path++import psutil++from vibe import remote_access, runtime++runtime.get_process_command = lambda pid: (" ".join(psutil.Process(pid).cmdline()) or None) if psutil.pid_exists(pid) else None+remote_access._version = lambda path: "cloudflared version test"+remote_access._report_runtime_status_async = lambda *args, **kwargs: None++action, report = sys.argv[1], Path(sys.argv[2])+if action == "hold":+ with remote_access._connector_lifecycle():+ report.write_text("held", encoding="utf-8")+ sys.stdin.read() # held until the test kills this process+ sys.exit(0)+try:+ with remote_access._connector_lifecycle(timeout=0):+ probe = "free"+except remote_access._ConnectorLifecycleBusy:+ probe = "busy"+report.with_suffix(".probe").write_text(probe, encoding="utf-8")+result = remote_access.stop() if action == "stop" else remote_access.start()+report.write_text(json.dumps({"ok": result.get("ok"), "error": result.get("error")}), encoding="utf-8")+"""+++def _lifecycle_child(tmp_path: Path, action: str, name: str) -> tuple[subprocess.Popen, Path]:+ report = tmp_path / f"{name}.json"+ process = subprocess.Popen(+ [sys.executable, "-c", _LIFECYCLE_CHILD, action, str(report)],+ cwd=str(Path(remote_access.__file__).resolve().parents[1]),+ env={**os.environ, "AVIBE_HOME": str(tmp_path)},+ stdin=subprocess.PIPE,+ )+ return process, report+++def _wait_for_file(path: Path, timeout: float = 20.0) -> str:+ deadline = time.monotonic() + timeout+ while not path.exists() or not path.read_text(encoding="utf-8"):+ assert time.monotonic() < deadline, f"{path.name} never appeared"+ time.sleep(0.05)+ return path.read_text(encoding="utf-8")+++def _live_connectors(binary: Path) -> list[int]:+ live = []+ for process in psutil.process_iter(["pid", "cmdline", "status"]):+ cmdline = process.info.get("cmdline") or []+ if str(binary) in cmdline and process.info.get("status") != psutil.STATUS_ZOMBIE:+ live.append(process.info["pid"])+ return live++[email protected]("children", [("stop",), ("stop", "start")])+def test_ra_tq_034_cross_process_stop_and_start_serialize_with_the_restart(monkeypatch, tmp_path, children) -> None:+ config, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ binary = Path(config.remote_access.vibe_cloud.cloudflared_path)+ schedule = remote_access._ConnectorRestartSchedule()+ real_start = remote_access._start+ launched = []++ def start_while_other_processes_wait(loaded, *, record_request, install_failure=None):+ # The restart holds the lifecycle lock here, after its request check and+ # before its spawn: the round-8 ordering would have the stop read the+ # exited pid now. Each child finds the lock busy and must wait for it.+ for name in children:+ launched.append(_lifecycle_child(tmp_path, name, name))+ for _process, report in launched:+ assert _wait_for_file(report.with_suffix(".probe")) == "busy"+ return real_start(loaded, record_request=record_request, install_failure=install_failure)++ try:+ remote_access.start()+ _wait_connector_exit()+ network_up.touch()+ monkeypatch.setattr(remote_access, "_start", start_while_other_processes_wait)+ remote_access._restart_exited_connector(config, schedule, 1000.0)+ remote_access._restart_exited_connector(config, schedule, 1000.0 + schedule.delay_seconds)+ monkeypatch.setattr(remote_access, "_start", real_start)+ for process, report in launched:+ assert process.wait(timeout=60) == 0+ assert json.loads(_wait_for_file(report))["ok"] is True++ live = _live_connectors(binary)+ if remote_access._connector_requested_path().exists():+ # A start won the last word: exactly the recorded connector serves.+ assert live == [remote_access._read_pid()]+ else:+ # The stop won the last word: nothing serves, and the monitor keeps it down.+ assert live == []+ remote_access._restart_exited_connector(config, schedule, 5000.0)+ remote_access._restart_exited_connector(config, schedule, 9000.0)+ assert _live_connectors(binary) == []+ finally:+ for process, _report in launched:+ if process.poll() is None:+ process.kill()+ process.wait()+ monkeypatch.setattr(remote_access, "_start", real_start)+ remote_access.stop()+++def test_ra_tq_034_lifecycle_lock_frees_when_its_holder_dies_and_status_never_waits(monkeypatch, tmp_path) -> None:+ _setup_exiting_connector(monkeypatch, tmp_path)+ holder, report = _lifecycle_child(tmp_path, "hold", "holder")+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ try:+ assert _wait_for_file(report) == "held"+ remote_access._pid_path().parent.mkdir(parents=True, exist_ok=True)+ remote_access._pid_path().write_text(str(dead.pid), encoding="utf-8")+ with pytest.raises(remote_access._ConnectorLifecycleBusy):+ with remote_access._connector_lifecycle(timeout=0):+ pass++ started_at = time.monotonic()+ result = remote_access.status()+ assert time.monotonic() - started_at < remote_access.CONNECTOR_LIFECYCLE_WAIT_SECONDS / 3+ assert result["running"] is False+ # The holder owns the records, so status() left them for it.+ assert remote_access._read_pid() == dead.pid++ holder.kill()+ holder.wait()+ with remote_access._connector_lifecycle(timeout=0):+ pass+ remote_access.status()+ assert remote_access._read_pid() is None+ finally:+ if holder.poll() is None:+ holder.kill()+ holder.wait()+++def test_ra_tq_034_missing_cloudflared_downloads_outside_the_lifecycle_lock(monkeypatch, tmp_path) -> None:+ config, _ = _setup_exiting_connector(monkeypatch, tmp_path)+ config.remote_access.vibe_cloud.cloudflared_path = ""+ config.save()+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded=None: None)+ downloads = []++ def install_cloudflared():+ # Another thread can take the lock only if this download does not hold it.+ free = []++ def probe():+ try:+ with remote_access._connector_lifecycle(timeout=0):+ free.append(True)+ except remote_access._ConnectorLifecycleBusy:+ free.append(False)++ prober = threading.Thread(target=probe)+ prober.start()+ prober.join()+ downloads.append(free[0])+ return {"ok": False, "error": "cloudflared_install_failed", "detail": "offline"}++ monkeypatch.setattr(remote_access, "install_cloudflared", install_cloudflared)++ result = remote_access.start()+ remote_access._restart_exited_connector(config, remote_access._ConnectorRestartSchedule(due_at=0.0), 1.0)++ assert result["ok"] is False and result["detail"] == "offline"+ # One download per start or restart, each outside the lock; none under it.+ assert downloads == [True, True]+ assert remote_access._connector_requested_path().is_file()+++def test_ra_tq_034_orphan_candidate_reconcile_waits_for_the_lock_and_for_recovery(monkeypatch, tmp_path) -> None:+ _setup_exiting_connector(monkeypatch, tmp_path)+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ remote_access._state_path().parent.mkdir(parents=True, exist_ok=True)+ runtime.write_json(remote_access._state_path(), {"schema_version": 2, "candidate": {"pid": dead.pid}})+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)+ holder, report = _lifecycle_child(tmp_path, "hold", "holder")+ try:+ assert _wait_for_file(report) == "held"+ assert remote_access._reconcile_orphan_candidate_when_free() is False+ holder.kill()+ holder.wait()++ monkeypatch.setattr(remote_access, "_RECOVERY_THREAD", threading.current_thread())+ assert remote_access._reconcile_orphan_candidate_when_free() is False+ assert remote_access._state_connector("candidate") == {"pid": dead.pid}++ monkeypatch.setattr(remote_access, "_RECOVERY_THREAD", None)+ assert remote_access._reconcile_orphan_candidate_when_free() is True+ assert remote_access._state_connector("candidate") is None+ finally:+ if holder.poll() is None:+ holder.kill()+ holder.wait()+++def test_ra_tq_034_candidate_cleanup_waits_out_lifecycle_contention(monkeypatch, tmp_path) -> None:+ _setup_exiting_connector(monkeypatch, tmp_path)+ # A short user bound shows the cleanup does not give up when a user step would.+ monkeypatch.setattr(remote_access, "CONNECTOR_LIFECYCLE_WAIT_SECONDS", 0.2)+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ remote_access._state_path().parent.mkdir(parents=True, exist_ok=True)+ runtime.write_json(remote_access._state_path(), {"schema_version": 2, "candidate": {"pid": dead.pid}})+ holder, report = _lifecycle_child(tmp_path, "hold", "holder")+ errors = []++ def discard():+ try:+ remote_access._discard_candidate_connector(dead.pid)+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)++ cleaner = threading.Thread(target=discard)+ try:+ assert _wait_for_file(report) == "held"+ cleaner.start()+ cleaner.join(timeout=1.0)+ assert cleaner.is_alive() and errors == [] # still waiting, not failed+ holder.kill()+ holder.wait()+ cleaner.join(timeout=10)+ assert not cleaner.is_alive() and errors == []+ assert remote_access._state_connector("candidate") is None+ finally:+ if holder.poll() is None:+ holder.kill()+ holder.wait()+ cleaner.join(timeout=10)+++def test_ra_tq_034_start_survives_an_unwritable_request(monkeypatch, tmp_path) -> None:+ _, network_up = _setup_exiting_connector(monkeypatch, tmp_path)+ network_up.touch()+ blocker = tmp_path / "not-a-directory"+ blocker.write_text("", encoding="utf-8")+ # The request's parent is a file, so recording the request raises OSError.+ monkeypatch.setattr(remote_access, "_connector_requested_path", lambda: blocker / "request")+ try:+ result = remote_access.start()++ assert result["ok"] is True and result["started"] is True+ assert remote_access._is_cloudflared_pid(result["pid"])+ finally:+ remote_access.stop()+++def test_ra_tq_034_concurrent_starts_share_one_cloudflared_download(monkeypatch, tmp_path) -> None:+ config, _ = _setup_exiting_connector(monkeypatch, tmp_path)+ installed = threading.Event()+ both_checked = threading.Event()+ checks = []+ downloads = []++ def resolve_binary(loaded=None):+ checks.append(threading.current_thread().name)+ if len(checks) >= 2:+ both_checked.set()+ return "/fake/cloudflared" if installed.is_set() else None++ def install_cloudflared():+ downloads.append(threading.current_thread().name)+ both_checked.wait(5) # the other start has found cloudflared missing too+ installed.set()+ return {"ok": True, "path": "/fake/cloudflared"}++ monkeypatch.setattr(remote_access, "_resolve_binary", resolve_binary)+ monkeypatch.setattr(remote_access, "install_cloudflared", install_cloudflared)++ def download():+ remote_access._download_missing_cloudflared(config)++ threads = [threading.Thread(target=download, name=f"start-{i}") for i in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=10)++ assert len(downloads) == 1+++def test_ra_tq_034_candidate_cleanup_gives_up_only_after_its_long_bound(monkeypatch, tmp_path, caplog) -> None:+ _setup_exiting_connector(monkeypatch, tmp_path)+ monkeypatch.setattr(remote_access, "CLEANUP_LOCK_WAIT_SECONDS", 0.3)+ dead = subprocess.Popen([sys.executable, "-c", "pass"])+ dead.wait()+ remote_access._state_path().parent.mkdir(parents=True, exist_ok=True)+ runtime.write_json(remote_access._state_path(), {"schema_version": 2, "candidate": {"pid": dead.pid}})+ holder, report = _lifecycle_child(tmp_path, "hold", "holder")+ try:+ assert _wait_for_file(report) == "held"++ remote_access._discard_candidate_connector(dead.pid) # returns instead of hanging or raising++ assert remote_access._state_connector("candidate") == {"pid": dead.pid}+ assert "records stay after the lifecycle lock stayed busy" in caplog.text+ finally:+ holder.kill()+ holder.wait()diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 9ff237e28..dc4626118 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -71,6 +71,7 @@ _INSTANCE_ACCESS_SOURCES = frozenset(_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})_INSTANCE_KINDS = frozenset({"personal", "organization"})_CONNECTOR_LOCK = threading.RLock()+_CLOUDFLARED_DOWNLOAD_LOCK = threading.Lock()_STATUS_HEARTBEAT_LOCK = threading.Lock()_STATUS_HEARTBEAT_STARTED = False_STATUS_REPORT_LOCK = threading.Lock()@@ -122,6 +123,12 @@ STATUS_LOG_TAIL_BYTES = 64 * 1024STATUS_REPORT_DRAIN_SECONDS = 1.0RECOVERY_READY_TIMEOUT_SECONDS = 30.0START_PREFERRED_READY_TIMEOUT_SECONDS = 8.0+CONNECTOR_RESTART_MAX_DELAY_SECONDS = 120.0+# Outlasts a start's worst-case hold: 8 s readiness + 8 s stop_pid + the respawn.+CONNECTOR_LIFECYCLE_WAIT_SECONDS = 20.0+# Record cleanups that nothing repeats wait at least 3x the longest bounded hold+# (about 17 s) before giving up, so only a holder stuck for a minute leaves them.+CLEANUP_LOCK_WAIT_SECONDS = 60.0RECOVERY_EVALUATION_SECONDS = 45.0RECOVERY_DRAIN_SECONDS = 35.0QUALITY_COMPARISON_MAX_AGE_SECONDS = 2 * QUALITY_SAMPLE_SECONDS@@ -241,6 +248,59 @@ def _state_path() -> Path:return paths.get_runtime_dir() / "remote-access-cloudflared.json"+def _connector_requested_path() -> Path:+ return paths.get_runtime_dir() / "remote-access-connector-requested"+++def _connector_lifecycle_lock_path() -> Path:+ # Never unlinked: every waiter must lock the same inode.+ return paths.get_runtime_dir() / "remote-access-connector.lock"+++class _ConnectorLifecycleBusy(Exception):+ """Another thread or process holds the connector lifecycle lock."""+++_USER_WAIT = object()+++@contextmanager+def _connector_lifecycle(*, timeout: Any = _USER_WAIT):+ """Hold the cross-process connector lifecycle lock (L).++ The UI server, its monitor and recovery threads, and the ``vibe remote`` CLI+ all read and rewrite the connector's pid, state, and request files, so each+ read-validate-mutate section runs under one lock shared by every process.+ Lock order is L, then ``_RECOVERY_LOCK``, then ``_CONNECTOR_LOCK``: never+ acquire L fresh while holding either of them. L is re-entrant per thread,+ and the OS releases it when its holder dies. By default it waits as long as+ a user start or stop does; ``timeout=0`` is a try-lock for steps a later+ tick repeats, and record cleanups that nothing repeats wait+ ``CLEANUP_LOCK_WAIT_SECONDS``. A lock file that cannot be opened leaves+ only the per-process locks.+ """++ # Import lazily because storage's package initializer imports V2Config.+ from storage.lock import MigrationFileLock, MigrationLockTimeout++ lock = MigrationFileLock(+ _connector_lifecycle_lock_path(),+ timeout_seconds=CONNECTOR_LIFECYCLE_WAIT_SECONDS if timeout is _USER_WAIT else timeout,+ )+ try:+ lock.acquire()+ except MigrationLockTimeout as exc:+ raise _ConnectorLifecycleBusy(str(exc)) from exc+ except OSError:+ logger.warning("Tunnel connector lifecycle lock is unavailable", exc_info=True)+ yield+ return+ try:+ yield+ finally:+ lock.release()++def _active_hostnames_state_path() -> Path:return paths.get_state_dir() / "remote-access-active-hostnames.json"@@ -1031,21 +1091,31 @@ def _connector_lane_reserved_locked() -> bool:def _clear_pending_tail_rollback(*, force: bool = False) -> None:- with _CONNECTOR_LOCK:- state = _read_state() or {}- pending = state.get("pending_tail_rollback")- active = state.get("active")- if not isinstance(pending, dict):- return- if (- not force- and isinstance(active, dict)- and isinstance(pending.get("active_pid"), int)- and active.get("pid") != pending.get("active_pid")- ):- return- state["pending_tail_rollback"] = None- runtime.write_json(_state_path(), state)+ try:+ with _connector_lifecycle(timeout=CLEANUP_LOCK_WAIT_SECONDS), _CONNECTOR_LOCK:+ state = _read_state() or {}+ pending = state.get("pending_tail_rollback")+ active = state.get("active")+ if not isinstance(pending, dict):+ return+ if (+ not force+ and isinstance(active, dict)+ and isinstance(pending.get("active_pid"), int)+ and active.get("pid") != pending.get("active_pid")+ ):+ return+ state["pending_tail_rollback"] = None+ runtime.write_json(_state_path(), state)+ except _ConnectorLifecycleBusy:+ _log_stranded_records("pending tail rollback", None)+++def _log_stranded_records(kind: str, pid: int | None) -> None:+ # Needs a lifecycle holder stuck for CLEANUP_LOCK_WAIT_SECONDS. Monitor+ # reconciliation clears what remains: draining and rollback records on a later+ # tick, a candidate at the next monitor start.+ logger.error("Tunnel %s records stay after the lifecycle lock stayed busy pid=%s", kind, pid)def _replace_state_connector(name: str, record: dict[str, Any] | None) -> None:@@ -1152,14 +1222,7 @@ def status(pid_state = _cloudflared_pid_state(pid)running = pid_state == "cloudflared"if pid and pid_state in {"dead", "other"}:- _pid_path().unlink(missing_ok=True)- candidate = _state_connector("candidate") or {}- candidate_state = _cloudflared_pid_state(candidate.get("pid"))- if (- candidate_state not in {"cloudflared", "unknown"}- and _pending_tail_rollback() is None- ):- _state_path().unlink(missing_ok=True)+ _discard_exited_connector_records(pid)cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None) if config else Nonebinary = _resolve_binary(config)result = {@@ -1197,6 +1260,29 @@ def status(return result+def _discard_exited_connector_records(pid: int) -> None:+ """Remove an exited connector's records unless a lifecycle change owns them.++ Called from status(), which must never block: it only try-locks, and+ rechecks the records under the lock.+ """++ try:+ with _connector_lifecycle(timeout=0):+ if _read_pid() != pid or _cloudflared_pid_state(pid) not in {"dead", "other"}:+ return+ _pid_path().unlink(missing_ok=True)+ candidate = _state_connector("candidate") or {}+ candidate_state = _cloudflared_pid_state(candidate.get("pid"))+ if (+ candidate_state not in {"cloudflared", "unknown"}+ and _pending_tail_rollback() is None+ ):+ _state_path().unlink(missing_ok=True)+ except _ConnectorLifecycleBusy:+ return++def network_interfaces() -> dict[str, Any]:"""Return live, non-loopback source addresses that cloudflared can bind."""@@ -1466,7 +1552,7 @@ def apply_settings(payload: dict[str, Any]) -> dict[str, Any]:previous_runtime_signature = _runtime_signature(current_config, binary)def start_settings_candidate(protocol: str) -> tuple[int, str] | None:- with _RECOVERY_LOCK:+ with _connector_lifecycle(), _RECOVERY_LOCK:if _connector_lane_reserved_locked():return Nonewith _CONNECTOR_LOCK:@@ -1506,7 +1592,7 @@ def apply_settings(payload: dict[str, Any]) -> dict[str, Any]:candidate_pid, metrics_url = started_candidateif not _wait_candidate_ready(candidate_pid, metrics_url):raise RuntimeError("candidate_not_ready")- with _CONNECTOR_LOCK:+ with _connector_lifecycle(), _CONNECTOR_LOCK:with CONFIG_LOCK:live_config = V2Config.load()live_binary = _resolve_binary(live_config)@@ -3081,11 +3167,14 @@ def _discard_candidate_connector(pid: int) -> None:if state not in {"dead", "other"}:logger.warning("Preserving Tunnel candidate with unverified process identity pid=%s", pid)return- _candidate_pid_path().unlink(missing_ok=True)- with _CONNECTOR_LOCK:- candidate = _state_connector("candidate") or {}- if candidate.get("pid") == pid:- _replace_state_connector("candidate", None)+ try:+ with _connector_lifecycle(timeout=CLEANUP_LOCK_WAIT_SECONDS), _CONNECTOR_LOCK:+ _candidate_pid_path().unlink(missing_ok=True)+ candidate = _state_connector("candidate") or {}+ if candidate.get("pid") == pid:+ _replace_state_connector("candidate", None)+ except _ConnectorLifecycleBusy:+ _log_stranded_records("candidate", pid)def _promote_candidate_connector(@@ -3094,7 +3183,7 @@ def _promote_candidate_connector(pending_tail_rollback: dict[str, Any] | None = None,runtime_signature: dict[str, str] | None = None,) -> dict[str, Any]:- with _CONNECTOR_LOCK:+ with _connector_lifecycle(), _CONNECTOR_LOCK:state = _read_state() or {}active = state.get("active") if isinstance(state.get("active"), dict) else {"pid": _read_pid()}candidate = state.get("candidate")@@ -3129,12 +3218,15 @@ def _drain_tracked_connector(connector: dict[str, Any]) -> bool:if not drained:logger.warning("Old Tunnel connector remains tracked after drain failed pid=%s", pid)return False- with _CONNECTOR_LOCK:- current = _read_state() or {}- draining = current.get("draining")- if isinstance(draining, dict) and draining.get("pid") == pid:- current["draining"] = None- runtime.write_json(_state_path(), current)+ try:+ with _connector_lifecycle(timeout=CLEANUP_LOCK_WAIT_SECONDS), _CONNECTOR_LOCK:+ current = _read_state() or {}+ draining = current.get("draining")+ if isinstance(draining, dict) and draining.get("pid") == pid:+ current["draining"] = None+ runtime.write_json(_state_path(), current)+ except _ConnectorLifecycleBusy:+ _log_stranded_records("draining", pid)return True@@ -3237,7 +3329,7 @@ def _run_tail_protocol_recovery(candidate_pid: int | None = Nonepromoted = Falsetry:- with _CONNECTOR_LOCK:+ with _connector_lifecycle(), _CONNECTOR_LOCK:if _RECOVERY_CANCEL_EVENT.is_set():raise RuntimeError("route_optimization_cancelled")active = _state_connector("active") or {}@@ -3410,7 +3502,7 @@ def _run_route_optimization(result_p99=_request_path_metric(result_path, "p99"),)return- with _CONNECTOR_LOCK:+ with _connector_lifecycle(), _CONNECTOR_LOCK:if _RECOVERY_CANCEL_EVENT.is_set():raise RuntimeError("route_optimization_cancelled")active = _state_connector("active")@@ -3468,7 +3560,7 @@ def _run_route_optimization(result_rtt = candidate_snapshot.get("rtt_ms")result_median = float(result_rtt["median"]) if isinstance(result_rtt, dict) and result_rtt.get("median") is not None else None_set_recovery_state(state="draining")- with _CONNECTOR_LOCK:+ with _connector_lifecycle(), _CONNECTOR_LOCK:state = _read_state() or {}active = state.get("active") if isinstance(state.get("active"), dict) else {"pid": _read_pid()}old_pid = active.get("pid") if isinstance(active, dict) else None@@ -3505,12 +3597,15 @@ def _run_route_optimization(else:drained = old_pid_state in {"dead", "other"}if drained:- with _CONNECTOR_LOCK:- state = _read_state() or {}- draining = state.get("draining")- if isinstance(draining, dict) and draining.get("pid") == old_pid:- state["draining"] = None- runtime.write_json(_state_path(), state)+ try:+ with _connector_lifecycle(timeout=CLEANUP_LOCK_WAIT_SECONDS), _CONNECTOR_LOCK:+ state = _read_state() or {}+ draining = state.get("draining")+ if isinstance(draining, dict) and draining.get("pid") == old_pid:+ state["draining"] = None+ runtime.write_json(_state_path(), state)+ except _ConnectorLifecycleBusy:+ _log_stranded_records("draining", old_pid)else:logger.warning("Old Tunnel connector remains tracked after drain failed pid=%s", old_pid)_finish_recovery(@@ -3544,10 +3639,13 @@ def _run_route_optimization(candidate_state = _cloudflared_pid_state(candidate_pid)candidate_cleaned = candidate_state in {"dead", "other"}if not promoted and candidate_cleaned:- _candidate_pid_path().unlink(missing_ok=True)- with _CONNECTOR_LOCK:- if _state_path().exists():- _replace_state_connector("candidate", None)+ try:+ with _connector_lifecycle(timeout=CLEANUP_LOCK_WAIT_SECONDS), _CONNECTOR_LOCK:+ _candidate_pid_path().unlink(missing_ok=True)+ if _state_path().exists():+ _replace_state_connector("candidate", None)+ except _ConnectorLifecycleBusy:+ _log_stranded_records("candidate", candidate_pid)elif not promoted:logger.warning("Preserving Tunnel candidate with unverified process identity pid=%s", candidate_pid)with _RECOVERY_LOCK:@@ -3555,15 +3653,103 @@ def _run_route_optimization(_RECOVERY_THREAD = None-def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:+@dataclass+class _ConnectorRestartSchedule:+ """Backoff for restarting a requested connector that exited on its own."""++ delay_seconds: float = QUALITY_SAMPLE_SECONDS+ due_at: float | None = None+++def _exited_connector_requested(config: V2Config | None) -> bool:+ """Whether ``start()`` requested a connector that is no longer running.++ ``stop()`` withdraws the request, so a connector the user stopped stays+ down. A candidate, draining connector, or tail rollback means route+ recovery owns the connector lane. Reads only connector state, so callers+ may hold ``_CONNECTOR_LOCK``.+ """++ if config is None or config.remote_access.provider != "vibe_cloud":+ return False+ cloud = config.remote_access.vibe_cloud+ # A path that is not a regular file (one a stop could not remove) is no request.+ if not cloud.enabled or not cloud.tunnel_token or not _connector_requested_path().is_file():+ return False+ return (+ _cloudflared_pid_state(_read_pid()) in {"dead", "other"}+ and _state_connector("candidate") is None+ and _state_connector("draining") is None+ and _pending_tail_rollback() is None+ and _read_pid_file(_candidate_pid_path()) is None+ )+++def _restart_exited_connector(+ config: V2Config | None,+ schedule: _ConnectorRestartSchedule,+ now: float,+) -> bool:+ """Restart an exited connector once it has stayed down for the backoff delay.++ A connector that cannot connect at start, for example when the network is+ not up yet after a reboot, exits within seconds. The delay doubles after+ each attempt up to ``CONNECTOR_RESTART_MAX_DELAY_SECONDS``; the monitor+ resets it once a connector reports a ready connection. Returns whether a+ restart was attempted.+ """++ if not _exited_connector_requested(config):+ schedule.due_at = None+ return False+ with _RECOVERY_LOCK:+ recovery_owns_lane = _connector_lane_reserved_locked()+ if recovery_owns_lane:+ schedule.due_at = None+ return False+ if schedule.due_at is None:+ schedule.due_at = now + schedule.delay_seconds+ return False+ if now < schedule.due_at:+ return False+ install_failure = _download_missing_cloudflared(config)+ # Lock order is L, then _RECOVERY_LOCK, then _CONNECTOR_LOCK. The lane check+ # above released both before L. Under L no stop or start in any process+ # interleaves, so the request check, spawn, and publish below are one step.+ try:+ with _connector_lifecycle(timeout=0), _CONNECTOR_LOCK:+ if not _exited_connector_requested(config):+ return False+ schedule.due_at = None+ schedule.delay_seconds = min(2 * schedule.delay_seconds, CONNECTOR_RESTART_MAX_DELAY_SECONDS)+ logger.warning("Tunnel connector exited; restarting it")+ # Only explicit starts record the request and only stop() withdraws it.+ result = _start(None, record_request=False, install_failure=install_failure)+ except _ConnectorLifecycleBusy:+ return False # another lifecycle change is in progress; retry next tick+ if not result.get("ok"):+ logger.warning("Tunnel connector restart failed: %s", result.get("error"))+ return True+++def _quality_monitor_loop(+ interval_seconds: float,+ quality_path: Path,+ *,+ orphan_candidate_pending: bool = False,+) -> None:global _QUALITY_MONITOR_STARTED, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USEDlast_report_at = 0.0last_active_pid: int | None = Nonelast_effective_protocol = "unknown"+ restart_schedule = _ConnectorRestartSchedule()request_session = _public_probe_session()try:while quality_path == _quality_state_path() and quality_path.parent.exists():started_at = time.monotonic()+ if orphan_candidate_pending:+ # Startup found the lifecycle lock busy; retry until it runs.+ orphan_candidate_pending = not _reconcile_orphan_candidate_when_free()_reconcile_connector_lifecycle()active_pid = _read_pid()running = _is_cloudflared_pid(active_pid)@@ -3591,6 +3777,13 @@ def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:loaded = V2Config.load()except Exception:loaded = None+ if sample is not None and sample.ready:+ restart_schedule = _ConnectorRestartSchedule()+ if _restart_exited_connector(loaded, restart_schedule, started_at):+ # This tick's samples describe the exited connector. The next tick+ # samples the new one and resets the request window for its pid.+ time.sleep(max(0.1, interval_seconds - (time.monotonic() - started_at)))+ continueconfigured_protocol = _configured_protocol(loaded) if loaded is not None else "auto"effective_protocol = _effective_protocol(active, sample)if (@@ -3674,22 +3867,25 @@ def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:def _reconcile_draining_connector() -> None:- draining = _state_connector("draining")- if not draining or not isinstance(draining.get("pid"), int):+ if not _state_connector("draining"):return- draining_pid = int(draining["pid"])- active = _state_connector("active") or {}- if active.get("pid") == draining_pid:+ with _connector_lifecycle(timeout=0):+ draining = _state_connector("draining")+ if not draining or not isinstance(draining.get("pid"), int):+ return+ draining_pid = int(draining["pid"])+ active = _state_connector("active") or {}+ if active.get("pid") == draining_pid:+ _replace_state_connector("draining", None)+ return+ draining_state = _cloudflared_pid_state(draining_pid)+ if draining_state == "unknown":+ logger.warning("Preserving draining Tunnel connector with unknown identity pid=%s", draining_pid)+ return+ if draining_state == "cloudflared" and not runtime.stop_pid(draining_pid, timeout=8):+ logger.warning("Could not stop draining Tunnel connector pid=%s", draining_pid)+ return_replace_state_connector("draining", None)- return- draining_state = _cloudflared_pid_state(draining_pid)- if draining_state == "unknown":- logger.warning("Preserving draining Tunnel connector with unknown identity pid=%s", draining_pid)- return- if draining_state == "cloudflared" and not runtime.stop_pid(draining_pid, timeout=8):- logger.warning("Could not stop draining Tunnel connector pid=%s", draining_pid)- return- _replace_state_connector("draining", None)def _restore_tracked_rollback_connector(@@ -3704,7 +3900,7 @@ def _restore_tracked_rollback_connector(return Falseif not _connector_ready_now(rollback_pid, metrics_url):return False- with _CONNECTOR_LOCK:+ with _connector_lifecycle(timeout=0), _CONNECTOR_LOCK:state = _read_state() or {}current_pending = state.get("pending_tail_rollback")active = state.get("active")@@ -3742,7 +3938,7 @@ def _start_rollback_replacement(pending: dict[str, Any]) -> bool:or not binary):return False- with _CONNECTOR_LOCK:+ with _connector_lifecycle(timeout=0), _CONNECTOR_LOCK:active = _state_connector("active") or {}if (active.get("pid") != pending.get("active_pid")@@ -3776,7 +3972,7 @@ def _reconcile_pending_tail_rollback() -> None:pending = _pending_tail_rollback()if pending is None:if raw_pending is not None:- with _CONNECTOR_LOCK:+ with _connector_lifecycle(timeout=0), _CONNECTOR_LOCK:current = _read_state() or {}if current.get("pending_tail_rollback") == raw_pending:current["pending_tail_rollback"] = None@@ -3810,6 +4006,8 @@ def _reconcile_connector_lifecycle() -> None:_reconcile_pending_tail_rollback()if _pending_tail_rollback() is None:_reconcile_draining_connector()+ except _ConnectorLifecycleBusy:+ logger.debug("Tunnel connector lifecycle is busy; reconciling on a later tick")except Exception:logger.warning("Tunnel connector lifecycle reconciliation failed", exc_info=True)@@ -3844,71 +4042,92 @@ def _finish_reconciled_recovery(def _reconcile_orphan_candidate() -> None:"""Resolve a candidate left by a previous service process without risking the active route."""- candidate = _state_connector("candidate")- if not candidate or not isinstance(candidate.get("pid"), int):- candidate_pid = _read_pid_file(_candidate_pid_path())- if candidate_pid is None:- return- candidate = {"pid": candidate_pid}- else:- candidate_pid = int(candidate["pid"])- candidate_state = _cloudflared_pid_state(candidate_pid)- active = _state_connector("active") or {}- active_pid = active.get("pid") if isinstance(active.get("pid"), int) else _read_pid()- active_state = _cloudflared_pid_state(active_pid)-- if candidate_pid == active_pid:- with _CONNECTOR_LOCK:- state = _read_state() or {}- if isinstance(state.get("candidate"), dict) and state["candidate"].get("pid") == candidate_pid:- state["candidate"] = None- state["pid"] = candidate_pid- runtime.write_json(_state_path(), state)- _pid_path().write_text(str(candidate_pid), encoding="utf-8")- _candidate_pid_path().unlink(missing_ok=True)- _finish_reconciled_recovery("improved")- return+ with _connector_lifecycle(timeout=0):+ candidate = _state_connector("candidate")+ if not candidate or not isinstance(candidate.get("pid"), int):+ candidate_pid = _read_pid_file(_candidate_pid_path())+ if candidate_pid is None:+ return+ candidate = {"pid": candidate_pid}+ else:+ candidate_pid = int(candidate["pid"])+ candidate_state = _cloudflared_pid_state(candidate_pid)+ active = _state_connector("active") or {}+ active_pid = active.get("pid") if isinstance(active.get("pid"), int) else _read_pid()+ active_state = _cloudflared_pid_state(active_pid)- if candidate_state == "cloudflared" and active_state != "cloudflared":- if active_state == "unknown":- logger.warning("Preserving orphan Tunnel candidate because active process identity is unknown")- return- metrics_url = candidate.get("metrics_url")- try:- ready = isinstance(metrics_url, str) and requests.get(- f"{metrics_url.rstrip('/')}/ready",- timeout=0.5,- ).ok- except requests.RequestException:- ready = False- if ready:+ if candidate_pid == active_pid:with _CONNECTOR_LOCK:state = _read_state() or {}- state["active"] = candidate- state["candidate"] = None+ if isinstance(state.get("candidate"), dict) and state["candidate"].get("pid") == candidate_pid:+ state["candidate"] = Nonestate["pid"] = candidate_pidruntime.write_json(_state_path(), state)_pid_path().write_text(str(candidate_pid), encoding="utf-8")_candidate_pid_path().unlink(missing_ok=True)_finish_reconciled_recovery("improved")return- if not runtime.stop_pid(candidate_pid, timeout=8):- logger.warning("Could not stop unready orphan Tunnel candidate pid=%s", candidate_pid)- return- if candidate_state == "cloudflared" and active_state == "cloudflared":- if not runtime.stop_pid(candidate_pid, timeout=8):- logger.warning("Could not stop orphan Tunnel candidate pid=%s", candidate_pid)+ if candidate_state == "cloudflared" and active_state != "cloudflared":+ if active_state == "unknown":+ logger.warning("Preserving orphan Tunnel candidate because active process identity is unknown")+ return+ metrics_url = candidate.get("metrics_url")+ try:+ ready = isinstance(metrics_url, str) and requests.get(+ f"{metrics_url.rstrip('/')}/ready",+ timeout=0.5,+ ).ok+ except requests.RequestException:+ ready = False+ if ready:+ with _CONNECTOR_LOCK:+ state = _read_state() or {}+ state["active"] = candidate+ state["candidate"] = None+ state["pid"] = candidate_pid+ runtime.write_json(_state_path(), state)+ _pid_path().write_text(str(candidate_pid), encoding="utf-8")+ _candidate_pid_path().unlink(missing_ok=True)+ _finish_reconciled_recovery("improved")+ return+ if not runtime.stop_pid(candidate_pid, timeout=8):+ logger.warning("Could not stop unready orphan Tunnel candidate pid=%s", candidate_pid)+ return++ if candidate_state == "cloudflared" and active_state == "cloudflared":+ if not runtime.stop_pid(candidate_pid, timeout=8):+ logger.warning("Could not stop orphan Tunnel candidate pid=%s", candidate_pid)+ return+ elif candidate_state == "unknown":+ logger.warning("Preserving orphan Tunnel candidate with unknown process identity pid=%s", candidate_pid)return- elif candidate_state == "unknown":- logger.warning("Preserving orphan Tunnel candidate with unknown process identity pid=%s", candidate_pid)- return- with _CONNECTOR_LOCK:- if _state_path().exists():- _replace_state_connector("candidate", None)- _candidate_pid_path().unlink(missing_ok=True)- _finish_reconciled_recovery("failed")+ with _CONNECTOR_LOCK:+ if _state_path().exists():+ _replace_state_connector("candidate", None)+ _candidate_pid_path().unlink(missing_ok=True)+ _finish_reconciled_recovery("failed")+++def _reconcile_orphan_candidate_when_free() -> bool:+ """Run the startup orphan-candidate reconciliation; False to retry on a later tick.++ A candidate is spawned only under the lifecycle lock after recovery reserves+ the lane, so while this holds the lock with no recovery reserved, any+ recorded candidate is an orphan.+ """++ try:+ with _connector_lifecycle(timeout=0):+ with _RECOVERY_LOCK:+ recovery_running = _RECOVERY_THREAD is not None+ if recovery_running:+ return False+ _reconcile_orphan_candidate()+ except _ConnectorLifecycleBusy:+ return False+ return Truedef _normalize_orphaned_recovery_state() -> None:@@ -3955,7 +4174,7 @@ def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECOND_RECOVERY_EMERGENCY_BYPASS_USED = bool(persisted.get("emergency_bypass_used"))preferred_protocol = persisted.get("preferred_protocol")_PREFERRED_PROTOCOL = str(preferred_protocol) if preferred_protocol in {"quic", "http2"} else None- _reconcile_orphan_candidate()+ orphan_candidate_pending = not _reconcile_orphan_candidate_when_free()_reconcile_connector_lifecycle()_normalize_orphaned_recovery_state()quality_path = _quality_state_path()@@ -3963,6 +4182,7 @@ def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECONDthread = threading.Thread(target=_quality_monitor_loop,args=(interval_seconds, quality_path),+ kwargs={"orphan_candidate_pending": orphan_candidate_pending},name="vibe-tunnel-quality-monitor",daemon=True,)@@ -3986,6 +4206,22 @@ def start_runtime_monitoring(config: V2Config | None = None) -> None:def stop(config: V2Config | None = None) -> dict[str, Any]:+ """Stop the connector and withdraw the request that keeps one running."""++ try:+ with _connector_lifecycle():+ try:+ _connector_requested_path().unlink(missing_ok=True)+ except OSError as exc:+ logger.warning("Could not withdraw the tunnel connector request", exc_info=True)+ result = _stop_connector(config)+ return {**result, "ok": False, "error": "remote_access_request_withdraw_failed", "detail": str(exc)}+ return _stop_connector(config)+ except _ConnectorLifecycleBusy:+ return {"ok": False, "error": "remote_access_busy", "stopped": False}+++def _stop_connector(config: V2Config | None = None) -> dict[str, Any]:try:config = config or V2Config.load()except Exception:@@ -4053,32 +4289,88 @@ def rotate_session_secret(config: V2Config) -> None:def start(config: V2Config | None = None) -> dict[str, Any]:+ """Start the connector and record the request that keeps one running."""++ try:+ loaded = config or V2Config.load()+ except Exception:+ loaded = None+ install_failure = _download_missing_cloudflared(loaded)+ try:+ with _connector_lifecycle():+ return _start(loaded or config, record_request=True, install_failure=install_failure)+ except _ConnectorLifecycleBusy:+ return {"ok": False, "error": "remote_access_busy", "started": False}+++def _download_missing_cloudflared(config: V2Config | None) -> dict[str, Any] | None:+ """Download a missing cloudflared before the lifecycle lock; return the failure, if any.++ The lock is held only around short check, spawn, and publish sections, so+ _start() never downloads.+ """++ cloud = config.remote_access.vibe_cloud if config is not None else None+ if cloud is None or not cloud.enabled or not cloud.tunnel_token or _resolve_binary(config):+ return None+ # The installer writes one fixed temporary path, so concurrent starts share one download.+ with _CLOUDFLARED_DOWNLOAD_LOCK:+ if _resolve_binary(config):+ return None+ result = install_cloudflared()+ return None if result.get("ok") else result+++def _start(+ config: V2Config | None,+ *,+ record_request: bool,+ install_failure: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Start the connector; callers hold the connector lifecycle lock."""+fallback_config = configif fallback_config is None:try:fallback_config = V2Config.load()except Exception as exc:return {"ok": False, "error": "remote_access_config_load_failed", "detail": str(exc), "started": False}+ # Only an explicit stop() withdraws the request, so the automatic restart+ # (record_request=False) cleans up without it and the monitor keeps retrying.+ halt = stop if record_request else _stop_connectorwith _CONNECTOR_LOCK:try:config = V2Config.load()except Exception as exc:- stop_result = stop(fallback_config)+ stop_result = halt(fallback_config)return {**stop_result, "ok": False, "error": "remote_access_config_load_failed", "detail": str(exc)}cloud = config.remote_access.vibe_cloudif not cloud.enabled:- stop_result = stop(config)+ stop_result = halt(config)return {**stop_result, "ok": False, "error": "remote_access_disabled"}if not cloud.tunnel_token:- stop_result = stop(config)+ # Unreachable from the restart, whose request check requires a token.+ stop_result = halt(config)return {**stop_result, "ok": False, "error": "missing_tunnel_token"}+ if record_request:+ try:+ _connector_requested_path().parent.mkdir(parents=True, exist_ok=True)+ _connector_requested_path().touch()+ except OSError:+ # The connector still starts; without the request the monitor+ # just does not restart it if it exits.+ logger.warning("Could not record the tunnel connector request", exc_info=True)binary = _resolve_binary(config)if not binary:- install_result = install_cloudflared()- if install_result.get("ok") is False:- _report_runtime_status_async(config, event="start_failed", last_error=str(install_result.get("error") or "cloudflared_install_failed"))- return {**status(config), **install_result}- binary = str(install_result["path"])+ # Callers download before taking the lifecycle lock; a request recorded+ # above lets the monitor retry the download later.+ failure = install_failure or {+ "ok": False,+ "error": "cloudflared_install_failed",+ "detail": "cloudflared is not installed",+ }+ _report_runtime_status_async(config, event="start_failed", last_error=str(failure.get("error")))+ return {**status(config), **failure}current = status(config)if current.get("pid_state") == "unknown":_report_runtime_status_async(config, event="start_failed", last_error="cloudflared_process_unknown")@@ -4089,7 +4381,7 @@ def start(config: V2Config | None = None) -> dict[str, Any]:if running_sig == desired_sig and _running_connector_has_metrics(current.get("pid")):_report_runtime_status_async(config, event="start")return {**current, "ok": True, "started": False}- stop_result = stop(config)+ stop_result = _stop_connector(config)if stop_result.get("ok") is False or stop_result.get("running"):return {**stop_result,