Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(remote-access): count only edge-registered Tunnel connections as ready (#2903)

Call Whitecc92744b0789
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.md
index 8d9adc942..16aa2ef23 100644
--- a/docs/plans/tunnel-quality-and-route-recovery.md
+++ b/docs/plans/tunnel-quality-and-route-recovery.md
@@ -379,7 +379,11 @@ timeouts are 500 ms and failures never block API or Doctor requests.
The active connector quality evaluator consumes:
-- `cloudflared_tunnel_ha_connections`;
+- `/ready` `readyConnections`, the edge-registered connection count that every
+ `ha_connections` check below means. The `cloudflared_tunnel_ha_connections`
+ gauge is only a fallback for a `/ready` body without that count: cloudflared
+ raises it when a connection starts dialing, so it can read four while the
+ edge has registered one;
- `cloudflared_tunnel_server_locations`;
- `cloudflared_tunnel_request_errors` counter delta;
- `quic_client_smoothed_rtt` per connection;
diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yaml
index e861b9f5e..28e0047ef 100644
--- a/tests/scenarios/tunnel_quality/catalog.yaml
+++ b/tests/scenarios/tunnel_quality/catalog.yaml
@@ -218,3 +218,9 @@ scenarios:
kind: resilience
layer: scenario
test: tests/test_tunnel_recovery.py::test_ra_tq_034_connector_exited_before_network_is_restarted_with_backoff
+ - id: RA-TQ-035
+ name: A Connector counts as ready only after the edge registers all four connections
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_tunnel_recovery.py::test_ra_tq_035_connector_readiness_counts_edge_registered_connections
diff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.py
index d6ced110a..93e09b5ed 100644
--- a/tests/test_tunnel_recovery.py
+++ b/tests/test_tunnel_recovery.py
@@ -898,15 +898,56 @@ def test_optimize_route_does_not_start_without_fresh_active_sample(monkeypatch)
assert result["error"] == "route_optimization_unavailable"
-def test_candidate_readiness_requires_four_ha_connections(monkeypatch) -> None:
- monkeypatch.setattr(remote_access, "_is_cloudflared_pid", lambda pid: True)
- monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", lambda url: _metrics_sample(connections=3))
-
- assert remote_access._connector_ready_now(222, "http://127.0.0.1:29002") is False
-
- monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", lambda url: _metrics_sample(connections=4))
+ ("ready_body", "expected"),
+ [
+ # cloudflared raises the HA gauge to 4 once the fourth connection starts
+ # dialing, while the edge has registered only the first one.
+ ({"status": 200, "readyConnections": 1}, False),
+ ({"status": 200, "readyConnections": 3}, False),
+ ({"status": 200, "readyConnections": 4}, True),
+ # A /ready body without the count falls back to the HA gauge.
+ ("OK", True),
+ ],
+)
+def test_ra_tq_035_connector_readiness_counts_edge_registered_connections(
+ monkeypatch,
+ ready_body: dict | str,
+ expected: bool,
+) -> None:
+ """RA-TQ-035: A Connector is ready only after the edge registers all four connections."""
+
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ class CloudflaredMetrics(BaseHTTPRequestHandler):
+ def do_GET(self) -> None: # noqa: N802 - http.server API
+ if self.path == "/ready":
+ body = json.dumps(ready_body) if isinstance(ready_body, dict) else ready_body
+ elif self.path == "/metrics":
+ body = "# TYPE cloudflared_tunnel_ha_connections gauge\ncloudflared_tunnel_ha_connections 4\n"
+ else:
+ self.send_error(404)
+ return
+ payload = body.encode()
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *args) -> None:
+ pass
- assert remote_access._connector_ready_now(222, "http://127.0.0.1:29002") is True
+ server = ThreadingHTTPServer(("127.0.0.1", 0), CloudflaredMetrics)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ monkeypatch.setattr(remote_access, "_is_cloudflared_pid", lambda pid: True)
+ try:
+ metrics_url = f"http://127.0.0.1:{server.server_address[1]}"
+ assert remote_access._connector_ready_now(222, metrics_url) is expected
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
def test_ra_tq_022_public_probe_session_honors_host_network_environment(
diff --git a/vibe/tunnel_quality.py b/vibe/tunnel_quality.py
index f6557b066..761f4a4e4 100644
--- a/vibe/tunnel_quality.py
+++ b/vibe/tunnel_quality.py
@@ -34,6 +34,7 @@ def utc_timestamp(now: float) -> str:
class MetricsSample:
sampled_at: float
ready: bool
+ # Connections the Cloudflare edge has registered, i.e. able to serve requests.
ha_connections: int
edge_locations: tuple[str, ...]
smoothed_rtt_ms: tuple[float, ...]
@@ -50,8 +51,20 @@ class RequestPathSample:
successes: tuple[bool, ...]
-def parse_metrics(text: str, *, ready: bool = True, now: float | None = None) -> MetricsSample:
- """Parse cloudflared Prometheus metrics without depending on sample order."""
+def parse_metrics(
+ text: str,
+ *,
+ ready: bool = True,
+ registered_connections: int | None = None,
+ now: float | None = None,
+) -> MetricsSample:
+ """Parse cloudflared Prometheus metrics without depending on sample order.
+
+ ``registered_connections`` is the edge-registered count from cloudflared's
+ ``/ready`` endpoint. The ``cloudflared_tunnel_ha_connections`` gauge is only
+ a fallback: cloudflared raises it when a connection starts dialing, so it
+ reports four while the edge may have registered just one.
+ """
values: dict[str, list[Any]] = {}
for family in text_string_to_metric_families(text):
@@ -88,7 +101,11 @@ def parse_metrics(text: str, *, ready: bool = True, now: float | None = None) ->
return MetricsSample(
sampled_at=now if now is not None else time.time(),
ready=ready,
- ha_connections=max(0, int(round(scalar("cloudflared_tunnel_ha_connections")))),
+ ha_connections=(
+ registered_connections
+ if registered_connections is not None
+ else max(0, int(round(scalar("cloudflared_tunnel_ha_connections"))))
+ ),
edge_locations=tuple(locations[:4]),
smoothed_rtt_ms=tuple(rtt_values[:4]),
request_errors_total=max(
@@ -109,7 +126,25 @@ def scrape_metrics(metrics_url: str, *, timeout: float = 0.5, now: float | None
ready_response = requests.get(f"{base_url}/ready", timeout=timeout)
metrics_response = requests.get(f"{base_url}/metrics", timeout=timeout)
metrics_response.raise_for_status()
- return parse_metrics(metrics_response.text, ready=ready_response.ok, now=now)
+ return parse_metrics(
+ metrics_response.text,
+ ready=ready_response.ok,
+ registered_connections=_ready_connections(ready_response),
+ now=now,
+ )
+
+
+def _ready_connections(response: requests.Response) -> int | None:
+ """Read ``readyConnections`` from cloudflared's ``/ready`` JSON body."""
+
+ try:
+ payload = response.json()
+ except ValueError:
+ return None
+ value = payload.get("readyConnections") if isinstance(payload, dict) else None
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+ return None
+ return value
def probe_request_path(