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): recover an unavailable QUIC route over HTTP/2 despite cooldown (#2367)
Call White7126cee35c59
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.mdindex 11b851e47..ca6b1a123 100644--- a/docs/plans/tunnel-quality-and-route-recovery.md+++ b/docs/plans/tunnel-quality-and-route-recovery.md@@ -51,7 +51,12 @@ continue to exchange that payload.1. `cloudflared` protocol `auto` is a connectivity fallback, not a performancepolicy. It prefers QUIC and falls back to HTTP/2 only when QUIC cannot connect.- Avibe owns performance-driven protocol selection.+ That fallback needs eight consecutive edge-address failures per connection+ (`max-edge-addr-retries`) plus backoff, and a process that has ever connected+ over QUIC never falls back. It therefore covers networks that block UDP from+ the start, not a QUIC path that dies later.+ Avibe owns performance-driven protocol selection and runtime transport+ recovery.2. The user-facing grade is request-path-first once enough request samples exist.Connector RTT remains visible diagnostic evidence, never a substitute forrequest latency.@@ -67,8 +72,12 @@ continue to exchange that payload.`auto` may remember the last verified protocol across service restarts, buta remembered explicit protocol that cannot establish four connectionswithin eight seconds is replaced by Cloudflare `auto`. Availability recovery- in `auto` mode also uses Cloudflare `auto`, preserving connectivity fallback- when network policy changes.+ in `auto` mode also uses Cloudflare `auto` for partial availability. When the+ route is unavailable (zero ready connections, or a high-confidence request+ window with no successful probe) on QUIC, the candidate uses explicit HTTP/2;+ a dead HTTP/2 route already gets QUIC first through Cloudflare `auto`.+ Promoting a candidate for an unavailable route persists the protocol it+ verified as the remembered preference before the old connector drains.6. No raw URL, response body, IP, connector identifier, or per-request sample isreported to avibe.bot. Only the bounded V2 aggregate is uploaded.@@ -95,7 +104,10 @@ does not replace the connector grade or trigger recovery.| Poor | P95 `< 1000 ms`, P99 `< 2000 ms`, and `< 10%` above 1 second || Critical | Any remaining measured window, or failure rate `>= 10%` |-Automatic tail-latency recovery requires high confidence and one of:+A high-confidence window with zero successful requests is an availability+episode, not tail latency, whatever connection count cloudflared reports; its+candidate is compared as though the active connector had no ready connections.+Otherwise, automatic tail-latency recovery requires high confidence and one of:- request failure rate `>= 10%`;- P95 `>= 750 ms`, or P95 at least twice the protocol-local baseline;@@ -444,6 +456,7 @@ three-minute rule; a single spike changes the displayed number but not health.| --- | --- | --- || No ready connections | `ha_connections == 0` | 15 seconds || Partial availability | `ha_connections < 4` | 60 seconds |+| No successful request | High-confidence request window with zero successes | Rolling request window || Request errors | `>= 3/minute` | 2 consecutive windows || Timeout packet loss | `>= 10/minute` across at least 2 connections | 2 consecutive windows || Metrics unavailable | State becomes `unknown`; never rotate from this alone | 45 seconds |@@ -511,8 +524,11 @@ Additional rules:- Thirty healthy minutes after the latest attempt reset the episode and attemptcount.- Service restart resumes persisted cooldown instead of immediately retrying.-- When the active connector has zero ready connections, availability restoration- takes priority over cooldown; one emergency candidate attempt is allowed.+- When the active route is unavailable, availability restoration takes priority+ over cooldown; one emergency candidate attempt is allowed. A route is+ unavailable when the connector reports zero ready connections or the+ high-confidence request window has no successful probe, because cloudflared+ can keep reporting a ready connection after its transport has died.## Make-Before-Break Recovery@@ -895,6 +911,7 @@ the active Connector currently demonstrates QUIC. An unobserved UDP path stays| RA-TQ-029 | Edge IP and source-address controls accept only live assigned addresses | config and network-policy tests || 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 |## Implementation Boundaries@@ -939,5 +956,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 pass in their required evidence layers; RA-TQ-031- receives browser proof at desktop and mobile widths.+- RA-TQ-001 through RA-TQ-030 and RA-TQ-033 pass in their required evidence+ layers; 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 94ea6d7d7..2843fd263 100644--- a/tests/scenarios/tunnel_quality/catalog.yaml+++ b/tests/scenarios/tunnel_quality/catalog.yaml@@ -206,3 +206,9 @@ scenarios:kind: network_policylayer: contracttest: tests/test_remote_access_vibe_cloud.py::test_ra_tq_032_remote_status_keeps_page_fields_and_drops_host_internals+ - id: RA-TQ-033+ name: A route that serves no public requests recovers over the other transport despite cooldown+ status: covered+ kind: lifecycle+ layer: scenario+ test: tests/test_tunnel_recovery.py::test_ra_tq_033_availability_recovery_protocol_follows_route_outagediff --git a/tests/scenarios/tunnel_quality/observations.yaml b/tests/scenarios/tunnel_quality/observations.yamlindex 595d51f1e..2345012ed 100644--- a/tests/scenarios/tunnel_quality/observations.yaml+++ b/tests/scenarios/tunnel_quality/observations.yaml@@ -13,3 +13,7 @@ observations:scenario_ids: [RA-TQ-010, RA-TQ-011, RA-TQ-012, RA-TQ-013, RA-TQ-015, RA-TQ-016, RA-TQ-017, RA-TQ-018, RA-TQ-019, RA-TQ-020]source: live_local_abnote: Healthy QUIC edge RTT hid 1.8-2.7 second request tails; HTTP2 reduced the persistent-path worst case, motivating request-failure recovery, connector-gated comparison, durable rollback, and drain convergence.+ - date: 2026-10-06+ scenario_ids: [RA-TQ-033]+ source: live_local_diagnosis+ note: Egress UDP to the edge failed for about ten minutes while TCP 7844 stayed reachable. All QUIC connections dropped, cloudflared still reported one ready connection, and every public probe failed. Cooldown from an earlier tail-latency attempt blocked recovery until the owner pinned HTTP/2, after which four connections registered within seconds.diff --git a/tests/test_tunnel_quality.py b/tests/test_tunnel_quality.pyindex 36e5b97c4..491b879af 100644--- a/tests/test_tunnel_quality.py+++ b/tests/test_tunnel_quality.py@@ -141,6 +141,29 @@ def test_partial_availability_triggers_recovery_after_four_samples() -> None:assert evaluator.recovery_trigger(snapshot) == "availability"+def test_ra_tq_033_unavailable_request_path_is_an_availability_episode() -> None:+ evaluator = tunnel_quality.QualityEvaluator()++ # cloudflared still reports four ready connections while no request succeeds.+ for index in range(12):+ sampled_at = 100 + index * 15+ snapshot = evaluator.update(+ _sample(sampled_at, (70, 75, 80, 85)),+ configured_protocol="auto",+ effective_protocol="quic",+ request_path_sample=tunnel_quality.RequestPathSample(+ sampled_at=sampled_at,+ latency_ms=(3500, 3500, 3500),+ successes=(False, False, False),+ ),+ )++ assert snapshot["ha_connections"] == 4+ assert snapshot["request_path"]["confidence"] == "high"+ assert snapshot["request_path"]["status"] == "unavailable"+ assert evaluator.recovery_trigger(snapshot) == "availability"++def test_ra_tq_003_metrics_failure_becomes_unknown_after_45_seconds() -> None:evaluator = tunnel_quality.QualityEvaluator()evaluator.update(_sample(100, (70, 75, 80, 85)))diff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.pyindex 1dd7ada3c..557e2e732 100644--- a/tests/test_tunnel_recovery.py+++ b/tests/test_tunnel_recovery.py@@ -663,17 +663,63 @@ def test_tail_recovery_rechecks_cancellation_before_next_protocol(monkeypatch, tassert results[0]["result"] == "failed"-def test_availability_recovery_uses_cloudflared_auto_fallback(monkeypatch, tmp_path) -> None:- config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(80))+_UNAVAILABLE_REQUEST_PATH = {+ **_request_path(3500, 3500, 3500, failure_rate=1.0),+ "status": "unavailable",+ "success_count": 0,+}+++ ("previous", "candidate_protocol", "expected_protocol", "expected_preference"),+ [+ # Partial availability keeps the existing edge-reselection behavior.+ ({"ha_connections": 2, "protocol": "quic"}, "quic", "auto", "quic"),+ # RA-TQ-033: a dead QUIC route is replaced over HTTP/2, whether the+ # connector admits it or still reports a stale ready connection.+ ({"ha_connections": 0, "protocol": "quic"}, "http2", "http2", "http2"),+ (+ {"ha_connections": 1, "protocol": "quic", "request_path": _UNAVAILABLE_REQUEST_PATH},+ "http2",+ "http2",+ "http2",+ ),+ (+ {"ha_connections": 4, "protocol": "quic", "request_path": _UNAVAILABLE_REQUEST_PATH},+ "http2",+ "http2",+ "http2",+ ),+ # Cloudflare auto already starts on QUIC, the alternative to a dead+ # HTTP/2 route; the transport it verified replaces the failed preference.+ ({"ha_connections": 0, "protocol": "http2"}, "quic", "auto", "quic"),+ ],+)+def test_ra_tq_033_availability_recovery_protocol_follows_route_outage(+ monkeypatch,+ tmp_path,+ previous,+ candidate_protocol,+ expected_protocol,+ expected_preference,+) -> None:+ config, active_pid, candidate_pid, alive = _setup_recovery(+ monkeypatch,+ tmp_path,+ {**_quality(80), "protocol": candidate_protocol},+ )remote_access._write_state(active_pid,config,"/usr/local/bin/cloudflared","http://127.0.0.1:29001",- requested_protocol="quic",+ requested_protocol=previous["protocol"],)+ monkeypatch.setattr(remote_access, "_PREFERRED_PROTOCOL", previous["protocol"])+ remote_access._set_preferred_protocol(previous["protocol"])spawned_protocols = []results = []+ drain_preferences = []def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):spawned_protocols.append(env["TUNNEL_TRANSPORT_PROTOCOL"])@@ -681,6 +727,8 @@ def test_availability_recovery_uses_cloudflared_auto_fallback(monkeypatch, tmp_preturn candidate_piddef stop_pid(pid, timeout=8):+ # The drain can outlive the process, so the preference must already be durable.+ drain_preferences.append(remote_access._stored_preferred_protocol())alive.discard(pid)return True@@ -691,11 +739,63 @@ def test_availability_recovery_uses_cloudflared_auto_fallback(monkeypatch, tmp_premote_access._run_route_optimization(config,"availability",- {**_quality(80), "ha_connections": 0, "protocol": "quic"},+ {**_quality(80), **previous},)- assert spawned_protocols == ["auto"]+ assert spawned_protocols == [expected_protocol]assert results[0]["result"] == "improved"+ assert drain_preferences == [expected_preference]+++ ("request_path", "expected_started"),+ [+ # RA-TQ-033: a route serving no public request overrides the cooldown+ # even though cloudflared still reports one ready connection.+ (_UNAVAILABLE_REQUEST_PATH, True),+ (_request_path(900, 1800, 2500, failure_rate=0.5), False),+ ],+)+def test_ra_tq_033_unavailable_route_bypasses_recovery_cooldown(+ monkeypatch,+ tmp_path,+ request_path,+ expected_started,+) -> None:+ started = []++ class FakeThread:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ def start(self):+ started.append(self)++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ now = time.time()+ previous = {**_quality(80), "ha_connections": 1, "protocol": "quic", "request_path": request_path}+ monkeypatch.setattr(remote_access, "status", lambda config=None: {"running": True})+ monkeypatch.setattr(remote_access, "_fresh_active_comparison_snapshot", lambda *args, **kwargs: previous)+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)+ monkeypatch.setattr(remote_access.threading, "Thread", FakeThread)+ with remote_access._RECOVERY_LOCK:+ remote_access._RECOVERY_THREAD = None+ remote_access._RECOVERY_ATTEMPTS[:] = [now - 600]+ remote_access._RECOVERY_STATE["next_attempt_at"] = remote_access.tunnel_quality.utc_timestamp(now + 3600)+ remote_access._RECOVERY_EMERGENCY_BYPASS_USED = False++ try:+ result = remote_access.optimize_route(trigger="availability")+ finally:+ with remote_access._RECOVERY_LOCK:+ remote_access._RECOVERY_THREAD = None+ remote_access._RECOVERY_ATTEMPTS.clear()+ remote_access._RECOVERY_STATE.clear()+ remote_access._RECOVERY_STATE.update(remote_access.tunnel_quality.empty_recovery())+ remote_access._RECOVERY_EMERGENCY_BYPASS_USED = False++ assert result["ok"] is expected_started+ assert len(started) == int(expected_started)def test_optimize_route_reserves_single_candidate_atomically(monkeypatch, tmp_path) -> None:diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 65ebd50d7..9ff237e28 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -2990,7 +2990,7 @@ def optimize_route(config: V2Config | None = None, *, trigger: str = "manual") -name="vibe-tunnel-route-optimization",daemon=True,)- emergency = effective_trigger == "availability" and int(previous.get("ha_connections") or 0) == 0+ emergency = tunnel_quality.route_unavailable(previous)if not _reserve_recovery(thread, manual=manual, emergency=emergency, now=now):return {**current, "ok": False, "error": "route_optimization_unavailable"}_RECOVERY_CANCEL_EVENT.clear()@@ -3381,6 +3381,7 @@ def _run_route_optimization(previous_path = previous.get("request_path") if isinstance(previous.get("request_path"), dict) else Noneprevious_p95 = _request_path_metric(previous_path, "p95")previous_p99 = _request_path_metric(previous_path, "p99")+ route_down = False_report_runtime_status_async(event="route_optimization_started")try:loaded = config or V2Config.load()@@ -3420,7 +3421,11 @@ def _run_route_optimization(if requested_protocol not in {"auto", "quic", "http2"}:requested_protocol = _initial_connector_protocol(loaded)if recovery_trigger == "availability" and _configured_protocol(loaded) == "auto":- requested_protocol = "auto"+ # cloudflared's auto mode starts on QUIC and falls back only after+ # repeated dial failures, so it cannot replace a dead QUIC route+ # within the candidate readiness window.+ route_down = tunnel_quality.route_unavailable(previous)+ requested_protocol = "http2" if route_down and previous_protocol == "quic" else "auto"candidate_pid, metrics_url = _start_candidate_connector(loaded,binary,@@ -3438,6 +3443,9 @@ def _run_route_optimization(if not isinstance(active_now_pid, int) or not _is_cloudflared_pid(active_now_pid):recovery_trigger = "availability"comparison_snapshot = {**previous, "ha_connections": 0}+ elif tunnel_quality.route_unavailable(previous):+ # Reported connections are not evidence of service when no request succeeds.+ comparison_snapshot = {**previous, "ha_connections": 0}if candidate_snapshot is None or not tunnel_quality.candidate_is_better(comparison_snapshot,candidate_snapshot,@@ -3481,6 +3489,15 @@ def _run_route_optimization(_pid_path().write_text(str(candidate_pid), encoding="utf-8")_candidate_pid_path().unlink(missing_ok=True)promoted = True+ if route_down:+ # The previous transport failed; restarts must use the one just verified.+ verified_protocol = (+ requested_protocol+ if requested_protocol in {"quic", "http2"}+ else candidate_snapshot.get("protocol")+ )+ if verified_protocol in {"quic", "http2"}:+ _set_preferred_protocol(verified_protocol)if isinstance(old_pid, int) and old_pid != candidate_pid:old_pid_state = _cloudflared_pid_state(old_pid)if old_pid_state == "cloudflared":diff --git a/vibe/tunnel_quality.py b/vibe/tunnel_quality.pyindex 819c478b3..f6557b066 100644--- a/vibe/tunnel_quality.py+++ b/vibe/tunnel_quality.py@@ -268,6 +268,24 @@ def request_path_needs_recovery(return request_path_is_degraded(request_path)+def route_unavailable(snapshot: dict[str, Any]) -> bool:+ """Whether the active route serves no traffic.++ cloudflared can keep reporting ready connections after its transport has+ silently died, so a high-confidence window with no successful public probe+ is treated as an outage alongside zero ready connections.+ """++ if int(snapshot.get("ha_connections") or 0) == 0:+ return True+ request_path = snapshot.get("request_path")+ return (+ isinstance(request_path, dict)+ and request_path.get("confidence") == "high"+ and request_path.get("status") == "unavailable"+ )++def request_path_has_usable_latency(request_path: dict[str, Any] | None) -> bool:if not request_path or request_path.get("confidence") == "low":return False@@ -682,7 +700,7 @@ class QualityEvaluator:return Noneif state not in {"healthy", "degraded"}:return None- if int(current.get("ha_connections") or 0) < 4:+ if int(current.get("ha_connections") or 0) < 4 or route_unavailable(current):return "availability"if float(current.get("request_errors_per_minute") or 0) >= 3 or float(current.get("packet_loss_per_minute") or 0) >= 10:return "errors"