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.

feat(remote-access): recover request-path tail latency (#1152)

Call Whitebb44f8e0a41b
diff --git a/config/v2_config.py b/config/v2_config.py
index 1bb063c2a..ea4c65777 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -910,6 +910,7 @@ class VibeCloudRemoteAccessConfig:
instance_secret: str = ""
session_secret: str = ""
cloudflared_path: str = ""
+ transport_protocol: str = "auto"
dev_login_hint: str = ""
@@ -1190,6 +1191,13 @@ class V2Config:
**_filter_dataclass_fields(VibeCloudRemoteAccessConfig, vibe_cloud_payload)
),
)
+ remote_access.vibe_cloud.transport_protocol = str(
+ remote_access.vibe_cloud.transport_protocol or "auto"
+ ).strip().lower()
+ if remote_access.vibe_cloud.transport_protocol not in {"auto", "quic", "http2"}:
+ raise ValueError(
+ "Config 'remote_access.vibe_cloud.transport_protocol' must be 'auto', 'quic', or 'http2'"
+ )
audio_asr_payload = payload.get("audio_asr") or {}
if not isinstance(audio_asr_payload, dict):
diff --git a/docs/plans/contracts/tunnel-quality-runtime-status-v2.schema.json b/docs/plans/contracts/tunnel-quality-runtime-status-v2.schema.json
new file mode 100644
index 000000000..b0a6e7b83
--- /dev/null
+++ b/docs/plans/contracts/tunnel-quality-runtime-status-v2.schema.json
@@ -0,0 +1,169 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://avibe.bot/contracts/tunnel-quality-runtime-status-v2.schema.json",
+ "title": "Avibe Tunnel Quality Runtime Status v2",
+ "description": "Bounded connector and public request-path quality reported by a paired Avibe runtime.",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "schema_version",
+ "state",
+ "grade",
+ "sampled_at",
+ "protocol",
+ "transport",
+ "connector_count",
+ "ha_connections",
+ "rtt_ms",
+ "baseline_median_rtt_ms",
+ "edge_locations",
+ "window_seconds",
+ "request_errors_per_minute",
+ "packet_loss_per_minute",
+ "request_path",
+ "recovery"
+ ],
+ "properties": {
+ "schema_version": { "const": 2 },
+ "state": { "type": "string", "enum": ["healthy", "degraded", "recovering", "unknown"] },
+ "grade": { "type": "string", "enum": ["good", "fair", "poor", "critical", "unknown"] },
+ "sampled_at": { "type": "string", "format": "date-time" },
+ "protocol": { "type": "string", "enum": ["quic", "http2", "unknown"] },
+ "transport": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["configured", "effective"],
+ "properties": {
+ "configured": { "type": "string", "enum": ["auto", "quic", "http2"] },
+ "effective": { "type": "string", "enum": ["quic", "http2", "unknown"] }
+ }
+ },
+ "connector_count": { "type": "integer", "minimum": 0, "maximum": 25 },
+ "ha_connections": { "type": "integer", "minimum": 0, "maximum": 4 },
+ "rtt_ms": { "$ref": "#/$defs/latencyRange" },
+ "baseline_median_rtt_ms": { "type": ["number", "null"], "minimum": 0 },
+ "edge_locations": {
+ "type": "array",
+ "maxItems": 4,
+ "uniqueItems": true,
+ "items": { "type": "string", "pattern": "^[a-z0-9-]{2,32}$" }
+ },
+ "window_seconds": { "type": "integer", "minimum": 15, "maximum": 600 },
+ "request_errors_per_minute": { "type": "number", "minimum": 0 },
+ "packet_loss_per_minute": { "type": "number", "minimum": 0 },
+ "request_path": {
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "source",
+ "status",
+ "confidence",
+ "window_seconds",
+ "sample_count",
+ "success_count",
+ "latency_ms",
+ "failure_rate",
+ "slow_request_rate",
+ "baseline_p95_ms"
+ ],
+ "properties": {
+ "source": { "const": "synthetic_local" },
+ "status": { "type": "string", "enum": ["healthy", "degraded", "unavailable", "insufficient"] },
+ "confidence": { "type": "string", "enum": ["low", "medium", "high"] },
+ "window_seconds": { "type": "integer", "minimum": 30, "maximum": 600 },
+ "sample_count": { "type": "integer", "minimum": 1, "maximum": 100 },
+ "success_count": { "type": "integer", "minimum": 0, "maximum": 100 },
+ "latency_ms": { "$ref": "#/$defs/requestLatency" },
+ "failure_rate": { "$ref": "#/$defs/rate" },
+ "slow_request_rate": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["over_500_ms", "over_1000_ms", "over_2000_ms"],
+ "properties": {
+ "over_500_ms": { "$ref": "#/$defs/rate" },
+ "over_1000_ms": { "$ref": "#/$defs/rate" },
+ "over_2000_ms": { "$ref": "#/$defs/rate" }
+ }
+ },
+ "baseline_p95_ms": { "type": ["number", "null"], "minimum": 0 }
+ }
+ }
+ ]
+ },
+ "recovery": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "state",
+ "last_attempt_at",
+ "last_trigger",
+ "last_result",
+ "previous_median_rtt_ms",
+ "result_median_rtt_ms",
+ "previous_protocol",
+ "result_protocol",
+ "previous_p95_ms",
+ "result_p95_ms",
+ "previous_p99_ms",
+ "result_p99_ms",
+ "next_attempt_at",
+ "attempt_count_window"
+ ],
+ "properties": {
+ "state": { "type": "string", "enum": ["idle", "evaluating", "draining", "cooldown"] },
+ "last_attempt_at": { "$ref": "#/$defs/nullableDateTime" },
+ "last_trigger": { "type": ["string", "null"], "enum": ["availability", "latency", "tail_latency", "errors", "manual", null] },
+ "last_result": { "type": ["string", "null"], "enum": ["improved", "no_improvement", "failed", null] },
+ "previous_median_rtt_ms": { "$ref": "#/$defs/nullableMetric" },
+ "result_median_rtt_ms": { "$ref": "#/$defs/nullableMetric" },
+ "previous_protocol": { "type": ["string", "null"], "enum": ["quic", "http2", null] },
+ "result_protocol": { "type": ["string", "null"], "enum": ["quic", "http2", null] },
+ "previous_p95_ms": { "$ref": "#/$defs/nullableMetric" },
+ "result_p95_ms": { "$ref": "#/$defs/nullableMetric" },
+ "previous_p99_ms": { "$ref": "#/$defs/nullableMetric" },
+ "result_p99_ms": { "$ref": "#/$defs/nullableMetric" },
+ "next_attempt_at": { "$ref": "#/$defs/nullableDateTime" },
+ "attempt_count_window": { "type": "integer", "minimum": 0 }
+ }
+ }
+ },
+ "$defs": {
+ "nullableDateTime": { "type": ["string", "null"], "format": "date-time" },
+ "nullableMetric": { "type": ["number", "null"], "minimum": 0 },
+ "rate": { "type": "number", "minimum": 0, "maximum": 1 },
+ "latencyRange": {
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["min", "median", "max"],
+ "properties": {
+ "min": { "type": "number", "minimum": 0 },
+ "median": { "type": "number", "minimum": 0 },
+ "max": { "type": "number", "minimum": 0 }
+ }
+ }
+ ]
+ },
+ "requestLatency": {
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["p50", "p95", "p99", "max"],
+ "properties": {
+ "p50": { "type": "number", "minimum": 0 },
+ "p95": { "type": "number", "minimum": 0 },
+ "p99": { "type": "number", "minimum": 0 },
+ "max": { "type": "number", "minimum": 0 }
+ }
+ }
+ ]
+ }
+ }
+}
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.md
index ae0c5e040..86c181a4f 100644
--- a/docs/plans/tunnel-quality-and-route-recovery.md
+++ b/docs/plans/tunnel-quality-and-route-recovery.md
@@ -30,8 +30,163 @@ Affected repositories:
- `avibe-bot-backend`: additive runtime-status contract, latest-snapshot
persistence, and current health display.
-The cross-repository payload contract is frozen in
-`docs/plans/contracts/tunnel-quality-runtime-status-v1.schema.json`.
+The cross-repository payload contracts are frozen in
+`docs/plans/contracts/tunnel-quality-runtime-status-v1.schema.json` and
+`docs/plans/contracts/tunnel-quality-runtime-status-v2.schema.json`.
+
+## V2 Amendment: Request-Path Quality and Protocol Recovery
+
+The landed V1 implementation correctly detects connector availability, errors,
+loss, and QUIC edge RTT. The August 3 incident exposed a missing layer: four
+healthy QUIC connections reported about 73 ms edge RTT while persistent public
+requests intermittently took 1.8 seconds and fresh connections reached 2.7
+seconds. Switching the connector to HTTP/2 reduced the persistent-request worst
+case to about 620 ms, even though connector-level metrics remained healthy.
+
+This amendment is normative for V2 and overrides the V1 sections below where
+they conflict. V1 remains documented because older Avibe and avibe.bot versions
+continue to exchange that payload.
+
+### Decisions
+
+1. `cloudflared` protocol `auto` is a connectivity fallback, not a performance
+ policy. It prefers QUIC and falls back to HTTP/2 only when QUIC cannot connect.
+ Avibe owns performance-driven protocol selection.
+2. The user-facing grade is request-path-first once enough request samples exist.
+ Connector RTT remains visible diagnostic evidence, never a substitute for
+ request latency.
+3. Request-path measurements use an unauthenticated public `/health` request from
+ the Avibe host with one persistent HTTP session. This includes a local
+ client-to-Cloudflare leg, so absolute numbers are diagnostic; before/after
+ measurements on the same host are the recovery decision signal.
+4. A same-tunnel replica cannot be targeted through the public hostname.
+ Protocol evaluation therefore happens after promotion and old-connector
+ drain, with make-before-break rollback when the new path is not better.
+5. `transport_protocol` is persisted as `auto`, `quic`, or `http2`. Pinned
+ `quic`/`http2` modes permit route reselection but never change protocol.
+ `auto` may remember the last verified protocol across service restarts, but
+ a remembered explicit protocol that cannot establish four connections
+ within eight seconds is replaced by Cloudflare `auto`. Availability recovery
+ in `auto` mode also uses Cloudflare `auto`, preserving connectivity fallback
+ when network policy changes.
+6. No raw URL, response body, IP, connector identifier, or per-request sample is
+ reported to avibe.bot. Only the bounded V2 aggregate is uploaded.
+
+### Request-path sampling and grading
+
+The quality monitor performs three sequential `/health` requests during each
+15-second connector sample. Requests share a session so the metric models the
+steady-state API path rather than repeated DNS/TLS setup. Each request has a
+3.5-second timeout. The rolling window is 180 seconds and retains at most 48
+samples. Public probes use Requests' normal host environment, including
+`HTTPS_PROXY`, `NO_PROXY`, `REQUESTS_CA_BUNDLE`, and `CURL_CA_BUNDLE`, so the
+monitor measures the same network policy that ordinary host traffic uses.
+
+The V2 aggregate contains sample and success counts, P50/P95/P99/maximum,
+failure rate, rates above 500/1000/2000 ms, confidence, and the protocol-local
+healthy P95 baseline. Confidence is `low` below 12 samples, `medium` from 12 to
+29, and `high` from 30 samples. A low-confidence request window is displayed but
+does not replace the connector grade or trigger recovery.
+
+| Request-path grade | Required properties |
+| --- | --- |
+| Good | P95 `< 350 ms`, P99 `< 750 ms`, and `< 2%` above 1 second |
+| Fair | P95 `< 600 ms`, P99 `< 1200 ms`, and `< 5%` above 1 second |
+| 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:
+
+- request failure rate `>= 10%`;
+- P95 `>= 750 ms`, or P95 at least twice the protocol-local baseline;
+- at least 5 percent of requests above 1 second; or
+- P99 `>= 1500 ms` with at least 3 percent of requests above 1 second.
+
+The rolling high-confidence window is the persistence gate; a single short
+measurement cannot trigger rotation. Healthy minute-level P95 aggregates feed a
+24-hour p20 baseline independently for QUIC and HTTP/2.
+
+### Protocol-aware recovery
+
+Availability, connector error/loss, and QUIC RTT recovery continue to use the V1
+same-protocol candidate comparison. A `tail_latency` episode uses a staged
+request-path comparison:
+
+1. Capture the active request-path aggregate before creating a candidate.
+2. First start a new connector with the current explicit protocol to request a
+ new edge route. This preserves the cheaper V1 route-reselection behavior.
+3. Wait for four ready connections, atomically promote the candidate, and drain
+ the old connector. Public probes are not evaluated while both replicas are
+ eligible because Cloudflare cannot attribute them to one connector.
+4. Reset only the rolling request window, then collect 20 persistent public
+ probes over at least 30 seconds.
+5. During the same evaluation window, collect both request-path probes and the
+ promoted connector's availability, request-error, and packet-loss metrics.
+ Accept only when those connector gates pass and either P95 improves by 20
+ percent, P99 improves by 40 percent without P95 worsening by more than 25
+ percent, the over-one-second rate is materially reduced, or a failure rate
+ of at least 10 percent is reduced by at least half and five percentage
+ points. Maximum latency is displayed but never decides a switch by itself.
+6. When same-protocol reselection is not materially better and the mode is
+ `auto`, repeat steps 2-5 with the opposite explicit protocol.
+7. If neither candidate is materially better, start a replacement using the
+ previous explicit protocol, promote it make-before-break, drain the rejected
+ connector, and record `no_improvement`.
+8. The existing cooldown and attempt budget apply to protocol attempts. A
+ successful `auto` attempt persists the verified protocol preference; pinned
+ modes never rewrite it.
+
+Promotion persists a local-only `pending_tail_rollback` transition before the
+old connector is drained. The live recovery thread remains the sole owner of
+that marker while it is evaluating; lifecycle reconciliation treats it as a
+crash orphan only when no live recovery thread exists. The marker is cleared
+only after the promoted route
+passes both request-path and connector gates, or after the previous protocol is
+restored. If Avibe restarts while the marker exists, the supervisor reuses a
+still-ready draining connector when possible; otherwise it starts a replacement
+with the previous explicit protocol and drains the unverified route. The monitor
+also retries any retained drain on every lifecycle reconciliation cycle, so a
+single failed stop cannot suppress public probes indefinitely. This transition
+state stays in the local connector aggregate and is never reported to avibe.bot.
+
+Recovery history adds previous/result protocol, P95, and P99. This makes a
+decision explainable when connector RTT is absent under HTTP/2 or unchanged
+under QUIC.
+
+### V2 surfaces
+
+Local Remote Access shows two independent lines:
+
+```text
+Connector: QUIC - 4/4 - RTT 79 ms
+Remote requests: P95 1.1 s - P99 2.3 s - 6% above 1 s
+```
+
+The overall badge follows request-path grade at medium/high confidence, while
+the connector line remains available for diagnosis. avibe.bot uses the same V2
+request-path grade and P95 in its latest-status card. Unsupported future schema
+versions remain ignorable, and the V2 parser continues accepting V1 during
+rolling deployment.
+
+### V2 acceptance scenarios
+
+| ID | Scenario | Required evidence |
+| --- | --- | --- |
+| RA-TQ-010 | Request-path tails override a healthy connector RTT grade | evaluator contract test |
+| RA-TQ-011 | HTTP/2 receives a request-path grade without QUIC RTT | evaluator contract test |
+| RA-TQ-012 | Auto mode evaluates the opposite protocol and keeps a material improvement | supervisor scenario test |
+| RA-TQ-013 | A non-improving protocol switch rolls back make-before-break | supervisor rollback test |
+| RA-TQ-014 | Avibe and avibe.bot exchange and display the bounded V2 aggregate | cross-repo contract and UI tests |
+| RA-TQ-015 | Sustained public request failures degrade the path and trigger recovery | evaluator contract test |
+| RA-TQ-016 | A failed old-connector drain is retried without disabling probes forever | supervisor lifecycle test |
+| RA-TQ-017 | Restart rolls back a promoted route that was never verified | crash-recovery scenario test |
+| RA-TQ-018 | A faster tail candidate is rejected when connector error gates fail | supervisor candidate-policy test |
+| RA-TQ-019 | A live tail recovery retains ownership of its pending rollback marker | supervisor ownership test |
+| RA-TQ-020 | A candidate that materially eliminates request failures is accepted | candidate-policy contract test |
+| RA-TQ-021 | A rollback replacement that loses readiness remains pending for reconciliation | supervisor rollback test |
+| RA-TQ-022 | Public probes honor the host proxy and CA environment | network-policy test |
+| RA-TQ-023 | Status cleanup preserves rollback after a promoted process exits | supervisor lifecycle test |
+| RA-TQ-024 | Pinned transport rejects comparison evidence from another protocol | protocol-evidence contract test |
## Product Decisions
@@ -449,8 +604,10 @@ The current endpoint remains additive and backward compatible:
POST /api/v1/instances/{instance_id}/runtime-status
```
-Avibe adds an optional `tunnel_quality` property whose exact schema is
-`contracts/tunnel-quality-runtime-status-v1.schema.json`. Example:
+Avibe adds an optional `tunnel_quality` property. Its supported exact shapes
+are `contracts/tunnel-quality-runtime-status-v1.schema.json` and
+`contracts/tunnel-quality-runtime-status-v2.schema.json`. V1 remains valid
+during rolling deployment. Example V1 payload:
```json
{
@@ -498,9 +655,9 @@ All runtime-status sends go through one serialized, coalescing reporter. A
scheduled heartbeat must not race a newer recovery event and overwrite it with
an older snapshot.
-The backend validates the nested V1 object, stores it as an additive JSONB
-column on the existing latest-status row, and returns it in serialized instance
-status. It does not create a time-series table in V1.
+The backend validates each supported nested object, stores it as an additive
+JSONB column on the existing latest-status row, and returns it in serialized
+instance status. It does not create a time-series table.
### avibe.bot receiving behavior
@@ -509,14 +666,26 @@ parses the required core heartbeat first, then handles `tunnel_quality`
independently:
- missing quality means an older Avibe and remains valid;
-- a supported, valid V1 object is stored;
+- a supported, valid V1 or V2 object is stored;
- malformed or oversized quality is discarded while the core heartbeat still
returns `200` and updates last-seen state;
- an unsupported future `schema_version` is ignored, not rejected; and
-- a V1 sample more than five minutes ahead of backend time is discarded as
+- a supported sample more than five minutes ahead of backend time is discarded as
unreasonable clock skew;
- validation failures are rate-limited in logs/Sentry without echoing payloads.
+V2 validation also preserves the producer's correlated semantics rather than
+accepting each field independently. A non-null request path contains at least
+one probe attempt; zero attempts are represented by `request_path: null`.
+Failure and slow-request rates must be four-decimal rounded ratios of integer
+counts in that sample window, and the slow counts must agree with every reported
+nearest-rank percentile and maximum. Confidence is derived from `sample_count`;
+low confidence is `insufficient`; a successful medium-confidence path is
+`healthy`; and high-confidence `healthy`/`degraded` status is derived from the
+documented recovery thresholds. At medium/high confidence, `grade` is derived
+from the request-path grading table. A high-confidence degraded or unavailable
+path requires the aggregate state to be `degraded` or `recovering`.
+
The backend rejects an older quality sample when its `sampled_at` predates the
stored sample, while still accepting the core heartbeat. The comparison and
coalesce happen atomically in the database conflict update so overlapping
@@ -645,4 +814,4 @@ 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-009 pass in their required evidence layers.
+- RA-TQ-001 through RA-TQ-024 pass in their required evidence layers.
diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yaml
index 30afa66bc..0e896dc11 100644
--- a/tests/scenarios/tunnel_quality/catalog.yaml
+++ b/tests/scenarios/tunnel_quality/catalog.yaml
@@ -1,4 +1,4 @@
-version: 1
+version: 2
capability:
id: tunnel_quality
name: remote-access tunnel quality and smooth route recovery
@@ -65,3 +65,93 @@ scenarios:
kind: crash_recovery
layer: scenario
test: tests/test_tunnel_recovery.py::test_ra_tq_009_restart_promotes_ready_candidate
+ - id: RA-TQ-010
+ name: Request-path tails override a healthy connector RTT grade
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_tunnel_quality.py::test_ra_tq_010_request_path_tail_overrides_good_connector_rtt
+ - id: RA-TQ-011
+ name: HTTP2 receives a request-path grade without QUIC RTT
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_tunnel_quality.py::test_ra_tq_011_http2_uses_request_path_grade_without_rtt
+ - id: RA-TQ-012
+ name: Auto mode keeps a materially better alternate protocol
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_012_tail_recovery_keeps_better_alternate_protocol
+ - id: RA-TQ-013
+ name: Non-improving protocol switch rolls back make-before-break
+ status: covered
+ kind: rollback
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_013_tail_recovery_rolls_back_protocol
+ - id: RA-TQ-014
+ name: Local and cloud surfaces consume the bounded V2 aggregate
+ status: partial
+ kind: cross_repo_contract
+ layer: contract
+ test: tests/test_remote_access_vibe_cloud.py::test_ra_tq_014_runtime_status_payload_includes_v2_request_path
+ - id: RA-TQ-015
+ name: Sustained public request failures degrade the path and trigger recovery
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_tunnel_quality.py::test_ra_tq_015_sustained_request_failures_trigger_recovery
+ - id: RA-TQ-016
+ name: Failed old-connector drains are retried during monitor lifecycle reconciliation
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_016_monitor_lifecycle_retries_failed_drain
+ - id: RA-TQ-017
+ name: Restart rolls back a promoted tail route that was never verified
+ status: covered
+ kind: crash_recovery
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_017_restart_rolls_back_unverified_tail_candidate
+ - id: RA-TQ-018
+ name: Tail candidates must pass connector availability and error gates
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_018_tail_candidate_must_pass_connector_error_gates
+ - id: RA-TQ-019
+ name: Live tail recovery retains ownership of its pending rollback marker
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_019_live_tail_recovery_owns_pending_rollback
+ - id: RA-TQ-020
+ name: Material request-failure reduction can accept a healthy candidate
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_tunnel_quality.py::test_ra_tq_020_request_path_candidate_accepts_material_failure_reduction
+ - id: RA-TQ-021
+ name: A rollback replacement that loses readiness remains pending for reconciliation
+ status: covered
+ kind: rollback
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_021_tail_rollback_stays_pending_if_replacement_loses_readiness
+ - id: RA-TQ-022
+ name: Public probes honor the host proxy and CA environment
+ status: covered
+ kind: network_policy
+ layer: unit
+ test: tests/test_tunnel_recovery.py::test_ra_tq_022_public_probe_session_honors_host_network_environment
+ - id: RA-TQ-023
+ name: Status cleanup preserves rollback after a promoted process exits
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_023_status_preserves_rollback_after_promoted_process_exit
+ - id: RA-TQ-024
+ name: Pinned transport rejects stale comparison evidence from another protocol
+ status: covered
+ kind: contract
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_024_pinned_protocol_rejects_stale_tail_evidence
diff --git a/tests/scenarios/tunnel_quality/observations.yaml b/tests/scenarios/tunnel_quality/observations.yaml
index bbefdeb13..595d51f1e 100644
--- a/tests/scenarios/tunnel_quality/observations.yaml
+++ b/tests/scenarios/tunnel_quality/observations.yaml
@@ -1,4 +1,4 @@
-version: 1
+version: 2
capability: tunnel_quality
observations:
- date: 2026-07-15
@@ -9,3 +9,7 @@ observations:
scenario_ids: [RA-TQ-004, RA-TQ-005]
source: cloudflare_replica_contract
note: Candidate evaluation uses a supported same-tunnel replica; hostname and tunnel identity remain unchanged during overlap and drain.
+ - date: 2026-08-03
+ 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_ab
+ note: 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.
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index 995171c87..dcdd88511 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -5,6 +5,8 @@ import sys
from dataclasses import fields
from pathlib import Path
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config.v2_config import UiConfig, V2Config
@@ -170,6 +172,19 @@ def test_save_config_accepts_typing_ack_mode(monkeypatch, tmp_path):
assert updated.ack_mode == "typing"
+def test_remote_access_transport_protocol_is_normalized_and_validated() -> None:
+ payload = _full_config_payload()
+ payload["remote_access"] = {"vibe_cloud": {"transport_protocol": " HTTP2 "}}
+
+ config = V2Config.from_payload(payload)
+
+ assert config.remote_access.vibe_cloud.transport_protocol == "http2"
+
+ payload["remote_access"]["vibe_cloud"]["transport_protocol"] = "tcp"
+ with pytest.raises(ValueError, match="transport_protocol"):
+ V2Config.from_payload(payload)
+
+
def test_save_config_merges_audio_asr_settings(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index ce5257c0e..0a2734d6a 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -803,6 +803,38 @@ def test_ra_tq_007_runtime_status_payload_includes_tunnel_quality(monkeypatch, t
assert payload["tunnel_quality"]["grade"] == "good"
+def test_ra_tq_014_runtime_status_payload_includes_v2_request_path(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.save()
+ monkeypatch.setattr(remote_access, "_local_ui_healthy", lambda cfg: True)
+ monkeypatch.setattr(remote_access, "_observed_cloudflared_origin_service", lambda: "http://127.0.0.1:5123")
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda cfg=None: {
+ "ok": True,
+ "running": True,
+ "binary_found": True,
+ "tunnel_quality": {
+ "schema_version": 2,
+ "state": "degraded",
+ "grade": "critical",
+ "sampled_at": "2026-08-03T12:45:00Z",
+ "request_path": {
+ "confidence": "high",
+ "latency_ms": {"p50": 202, "p95": 1100, "p99": 2300, "max": 2700},
+ },
+ },
+ },
+ )
+
+ payload = remote_access.runtime_status_payload(config, event="tunnel_quality")
+
+ assert payload["tunnel_quality"]["schema_version"] == 2
+ assert payload["tunnel_quality"]["request_path"]["latency_ms"]["p95"] == 1100
+
+
def test_observed_cloudflared_origin_service_reads_only_log_tail(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
remote_access._cloudflared_stderr_path().parent.mkdir(parents=True, exist_ok=True)
@@ -1612,6 +1644,53 @@ def test_start_clears_previous_cloudflared_logs_before_spawn(monkeypatch, tmp_pa
assert spawn_args == [[binary, "tunnel", "--metrics", "127.0.0.1:29999", "--no-autoupdate", "run"]]
+def test_start_falls_back_to_auto_when_preferred_protocol_is_not_ready(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ binary = "/usr/local/bin/cloudflared"
+ preferred_pid = 222
+ fallback_pid = 333
+ alive = {preferred_pid, fallback_pid}
+ spawned_protocols = []
+ spawned_pids = iter([preferred_pid, fallback_pid])
+ metrics_urls = iter(["http://127.0.0.1:29998", "http://127.0.0.1:29999"])
+
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda cfg: binary)
+ monkeypatch.setattr(remote_access, "_version", lambda path: "cloudflared test")
+ monkeypatch.setattr(remote_access, "_allocate_metrics_url", lambda: next(metrics_urls))
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in alive)
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: f"{binary} tunnel run")
+ monkeypatch.setattr(remote_access, "_wait_connector_ready", lambda *args, **kwargs: False)
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ pid = next(spawned_pids)
+ spawned_protocols.append(env["TUNNEL_TRANSPORT_PROTOCOL"])
+ pid_path.write_text(str(pid), encoding="utf-8")
+ return pid
+
+ def stop_pid(pid, timeout=8):
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ previous_preference = remote_access._PREFERRED_PROTOCOL
+ remote_access._PREFERRED_PROTOCOL = "http2"
+ try:
+ result = remote_access.start(config)
+ finally:
+ remote_access._PREFERRED_PROTOCOL = previous_preference
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert result["ok"] is True
+ assert result["pid"] == fallback_pid
+ assert spawned_protocols == ["http2", "auto"]
+ assert preferred_pid not in alive
+ assert state["active"]["requested_protocol"] == "auto"
+
+
def test_effective_ui_bind_host_uses_setup_host_when_tunnel_disabled() -> None:
config = _config()
config.remote_access.vibe_cloud.enabled = False
diff --git a/tests/test_tunnel_quality.py b/tests/test_tunnel_quality.py
index 57caae2a2..5284e1f32 100644
--- a/tests/test_tunnel_quality.py
+++ b/tests/test_tunnel_quality.py
@@ -23,6 +23,29 @@ def _sample(
)
+def test_request_path_probe_rejects_redirects() -> None:
+ class RedirectResponse:
+ status_code = 302
+
+ def close(self) -> None:
+ pass
+
+ class RedirectSession:
+ def get(self, *args, **kwargs):
+ assert kwargs["allow_redirects"] is False
+ return RedirectResponse()
+
+ sample = tunnel_quality.probe_request_path(
+ RedirectSession(),
+ "https://example.avibe.bot/health",
+ attempts=1,
+ now=100,
+ )
+
+ assert sample.sampled_at == 100
+ assert sample.successes == (False,)
+
+
def test_ra_tq_001_parse_cloudflared_metrics_extracts_quality_inputs() -> None:
sample = tunnel_quality.parse_metrics(
"""
@@ -220,3 +243,186 @@ def test_baseline_state_round_trips_without_raw_samples() -> None:
restored.load_state(evaluator.export_state(), now=10_000 + 15 * 60)
assert restored.baseline(10_000 + 15 * 60) == 77.5
+
+
+def test_ra_tq_010_request_path_tail_overrides_good_connector_rtt() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ snapshot = None
+
+ for index in range(10):
+ sampled_at = 10_000 + 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=(120, 140, 1600),
+ successes=(True, True, True),
+ ),
+ )
+
+ assert snapshot is not None
+ assert snapshot["schema_version"] == 2
+ assert snapshot["rtt_ms"]["median"] == 77.5
+ assert snapshot["request_path"]["confidence"] == "high"
+ assert snapshot["request_path"]["latency_ms"]["p95"] == 1600
+ assert snapshot["grade"] == "critical"
+ assert snapshot["state"] == "degraded"
+ assert evaluator.recovery_trigger(snapshot) == "tail_latency"
+
+
+def test_request_path_twofold_baseline_regression_has_no_absolute_floor() -> None:
+ request_path = tunnel_quality.summarize_request_path_samples(
+ [
+ tunnel_quality.RequestPathSample(
+ sampled_at=1,
+ latency_ms=tuple([220.0] * 30),
+ successes=tuple([True] * 30),
+ )
+ ],
+ baseline_p95_ms=100.0,
+ )
+
+ assert request_path is not None
+ assert request_path["latency_ms"]["p95"] == 220.0
+ assert request_path["status"] == "degraded"
+
+
+def test_request_path_degradation_controls_state_when_connector_metrics_are_missing() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ snapshot = None
+
+ for index in range(10):
+ snapshot = evaluator.update(
+ None,
+ effective_protocol="quic",
+ request_path_sample=tunnel_quality.RequestPathSample(
+ sampled_at=1_000 + index * 15,
+ latency_ms=(120, 140, 1600),
+ successes=(True, True, True),
+ ),
+ now=1_000 + index * 15,
+ )
+
+ assert snapshot is not None
+ assert snapshot["request_path"]["confidence"] == "high"
+ assert snapshot["request_path"]["status"] == "degraded"
+ assert snapshot["state"] == "degraded"
+
+
+def test_ra_tq_015_sustained_request_failures_trigger_recovery() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ snapshot = None
+
+ for index in range(10):
+ sampled_at = 15_000 + 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=(80, 90, 100),
+ successes=(True, True, index % 3 != 0),
+ ),
+ )
+
+ assert snapshot is not None
+ assert snapshot["request_path"]["confidence"] == "high"
+ assert snapshot["request_path"]["failure_rate"] >= 0.10
+ assert snapshot["request_path"]["status"] == "degraded"
+ assert snapshot["state"] == "degraded"
+ assert evaluator.recovery_trigger(snapshot) == "tail_latency"
+
+
+def test_ra_tq_011_http2_uses_request_path_grade_without_rtt() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ snapshot = None
+
+ for index in range(4):
+ sampled_at = 20_000 + index * 15
+ snapshot = evaluator.update(
+ _sample(sampled_at, (), connections=4),
+ configured_protocol="auto",
+ effective_protocol="http2",
+ request_path_sample=tunnel_quality.RequestPathSample(
+ sampled_at=sampled_at,
+ latency_ms=(180, 200, 220),
+ successes=(True, True, True),
+ ),
+ )
+
+ assert snapshot is not None
+ assert snapshot["protocol"] == "http2"
+ assert snapshot["transport"] == {"configured": "auto", "effective": "http2"}
+ assert snapshot["rtt_ms"] is None
+ assert snapshot["request_path"]["confidence"] == "medium"
+ assert snapshot["grade"] == "good"
+ assert snapshot["state"] == "healthy"
+
+
+def test_request_path_candidate_accepts_tail_improvement_despite_p50_regression() -> None:
+ active = tunnel_quality.summarize_request_path_samples(
+ [
+ tunnel_quality.RequestPathSample(
+ sampled_at=1,
+ latency_ms=tuple([100.0] * 93 + [324.0] * 5 + [1840.0] * 2),
+ successes=tuple([True] * 100),
+ )
+ ]
+ )
+ candidate = tunnel_quality.summarize_request_path_samples(
+ [
+ tunnel_quality.RequestPathSample(
+ sampled_at=2,
+ latency_ms=tuple([170.0] * 93 + [386.0] * 5 + [621.0] * 2),
+ successes=tuple([True] * 100),
+ )
+ ]
+ )
+
+ assert active is not None
+ assert candidate is not None
+ assert tunnel_quality.request_path_is_better(active, candidate) is True
+
+
+def test_ra_tq_020_request_path_candidate_accepts_material_failure_reduction() -> None:
+ active = tunnel_quality.summarize_request_path_samples(
+ [
+ tunnel_quality.RequestPathSample(
+ sampled_at=1,
+ latency_ms=tuple([100.0] * 100),
+ successes=tuple([True] * 90 + [False] * 10),
+ )
+ ]
+ )
+ candidate = tunnel_quality.summarize_request_path_samples(
+ [
+ tunnel_quality.RequestPathSample(
+ sampled_at=2,
+ latency_ms=tuple([500.0] * 100),
+ successes=tuple([True] * 100),
+ )
+ ]
+ )
+
+ assert active is not None
+ assert candidate is not None
+ assert tunnel_quality.request_path_is_better(active, candidate) is True
+
+
+def test_unavailable_request_path_does_not_expose_latency_as_usable() -> None:
+ request_path = tunnel_quality.summarize_request_path_samples(
+ [
+ tunnel_quality.RequestPathSample(
+ sampled_at=1,
+ latency_ms=tuple([20.0] * 12),
+ successes=tuple([False] * 12),
+ )
+ ]
+ )
+
+ assert request_path is not None
+ assert request_path["status"] == "unavailable"
+ assert tunnel_quality.request_path_has_usable_latency(request_path) is False
diff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.py
index 52a057584..653e43c79 100644
--- a/tests/test_tunnel_recovery.py
+++ b/tests/test_tunnel_recovery.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import json
import time
+import pytest
+
from tests.test_remote_access_vibe_cloud import _config
from vibe import remote_access, runtime
@@ -16,6 +18,32 @@ def _quality(median: float) -> dict:
}
+def _request_path(
+ p50: float,
+ p95: float,
+ p99: float,
+ *,
+ slow_rate: float = 0.0,
+ failure_rate: float = 0.0,
+) -> dict:
+ return {
+ "source": "synthetic_local",
+ "status": "degraded" if p95 >= 750 or slow_rate >= 0.05 else "healthy",
+ "confidence": "high",
+ "window_seconds": 180,
+ "sample_count": 100,
+ "success_count": round(100 * (1 - failure_rate)),
+ "latency_ms": {"p50": p50, "p95": p95, "p99": p99, "max": p99},
+ "failure_rate": failure_rate,
+ "slow_request_rate": {
+ "over_500_ms": slow_rate,
+ "over_1000_ms": slow_rate,
+ "over_2000_ms": 0.0,
+ },
+ "baseline_p95_ms": 250.0,
+ }
+
+
def _metrics_sample(*, connections: int = 4) -> remote_access.tunnel_quality.MetricsSample:
return remote_access.tunnel_quality.MetricsSample(
sampled_at=time.time(),
@@ -114,6 +142,278 @@ def test_ra_tq_005_non_improving_candidate_keeps_active(monkeypatch, tmp_path) -
assert results[0]["result"] == "no_improvement"
+def test_ra_tq_012_tail_recovery_keeps_better_alternate_protocol(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ alternate_pid = 333
+ alive.add(alternate_pid)
+ previous = {
+ **_quality(80),
+ "protocol": "quic",
+ "request_path": _request_path(202, 900, 1840, slow_rate=0.08),
+ }
+ candidate_path = _request_path(170, 386, 621)
+ spawned_protocols = []
+ spawned_pids = iter([candidate_pid, alternate_pid])
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ spawned_protocols.append(env["TUNNEL_TRANSPORT_PROTOCOL"])
+ pid = next(spawned_pids)
+ pid_path.write_text(str(pid), encoding="utf-8")
+ return pid
+
+ def stop_pid(pid, timeout=8):
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(
+ remote_access,
+ "_measure_promoted_route",
+ lambda cfg, protocol, metrics_url: (
+ candidate_path if protocol == "http2" else _request_path(250, 950, 1900, slow_rate=0.08),
+ _quality(80),
+ ),
+ )
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+ monkeypatch.setattr(remote_access, "_set_preferred_protocol", lambda protocol: None)
+
+ remote_access._run_route_optimization(config, "tail_latency", previous)
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == alternate_pid
+ assert state["active"]["requested_protocol"] == "http2"
+ assert state["draining"] is None
+ assert active_pid not in alive
+ assert spawned_protocols == ["quic", "http2"]
+ assert results[0]["result"] == "improved"
+ assert results[0]["previous_protocol"] == "quic"
+ assert results[0]["result_protocol"] == "http2"
+ assert results[0]["result_p99"] == 621
+
+
+def test_ra_tq_013_tail_recovery_rolls_back_protocol(monkeypatch, tmp_path) -> None:
+ config, active_pid, first_candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ alternate_pid = 333
+ rollback_pid = 444
+ alive.add(alternate_pid)
+ alive.add(rollback_pid)
+ previous_path = _request_path(202, 900, 1840, slow_rate=0.08)
+ previous = {**_quality(80), "protocol": "quic", "request_path": previous_path}
+ worse_path = _request_path(300, 1200, 2400, slow_rate=0.12)
+ spawned_pids = iter([first_candidate_pid, alternate_pid, rollback_pid])
+ spawned_protocols = []
+ drained = []
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ pid = next(spawned_pids)
+ spawned_protocols.append(env["TUNNEL_TRANSPORT_PROTOCOL"])
+ pid_path.write_text(str(pid), encoding="utf-8")
+ return pid
+
+ def stop_pid(pid, timeout=8):
+ drained.append(pid)
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(
+ remote_access,
+ "_measure_promoted_route",
+ lambda cfg, protocol, metrics_url: (worse_path, _quality(80)),
+ )
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+ monkeypatch.setattr(remote_access, "_set_preferred_protocol", lambda protocol: None)
+
+ remote_access._run_route_optimization(config, "tail_latency", previous)
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == rollback_pid
+ assert state["active"]["requested_protocol"] == "quic"
+ assert state["candidate"] is None
+ assert state["draining"] is None
+ assert spawned_protocols == ["quic", "http2", "quic"]
+ assert drained == [active_pid, first_candidate_pid, alternate_pid]
+ assert results[0]["result"] == "no_improvement"
+ assert results[0]["result_protocol"] == "quic"
+
+
+def test_ra_tq_021_tail_rollback_stays_pending_if_replacement_loses_readiness(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ config, _active_pid, first_candidate_pid, alive = _setup_recovery(
+ monkeypatch,
+ tmp_path,
+ _quality(180),
+ )
+ alternate_pid = 333
+ rollback_pid = 444
+ alive.update({alternate_pid, rollback_pid})
+ previous_path = _request_path(202, 900, 1840, slow_rate=0.08)
+ previous = {**_quality(80), "protocol": "quic", "request_path": previous_path}
+ worse_path = _request_path(300, 1200, 2400, slow_rate=0.12)
+ spawned_pids = iter([first_candidate_pid, alternate_pid, rollback_pid])
+ measurement_count = 0
+ rollback_lost_readiness = False
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ pid = next(spawned_pids)
+ pid_path.write_text(str(pid), encoding="utf-8")
+ return pid
+
+ def measure_promoted_route(cfg, protocol, metrics_url):
+ nonlocal measurement_count, rollback_lost_readiness
+ measurement_count += 1
+ if measurement_count == 3:
+ rollback_lost_readiness = True
+ return worse_path, _quality(80)
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=8: alive.discard(pid) is None)
+ monkeypatch.setattr(remote_access, "_measure_promoted_route", measure_promoted_route)
+ monkeypatch.setattr(
+ remote_access,
+ "_connector_ready_now",
+ lambda pid, url: not (pid == rollback_pid and rollback_lost_readiness),
+ )
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "tail_latency", previous)
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == rollback_pid
+ assert state["active"]["requested_protocol"] == "quic"
+ assert state["pending_tail_rollback"] == {
+ "active_pid": rollback_pid,
+ "previous_protocol": "quic",
+ }
+ assert results[0]["result"] == "failed"
+
+
+def test_ra_tq_018_tail_candidate_must_pass_connector_error_gates(monkeypatch, tmp_path) -> None:
+ config, active_pid, first_candidate_pid, alive = _setup_recovery(
+ monkeypatch,
+ tmp_path,
+ _quality(180),
+ )
+ config.remote_access.vibe_cloud.transport_protocol = "quic"
+ config.save()
+ remote_access._write_state(
+ active_pid,
+ config,
+ "/usr/local/bin/cloudflared",
+ "http://127.0.0.1:29001",
+ requested_protocol="quic",
+ )
+ rollback_pid = 333
+ alive.add(rollback_pid)
+ previous_path = _request_path(202, 900, 1840, slow_rate=0.08)
+ previous = {**_quality(80), "protocol": "quic", "request_path": previous_path}
+ better_path = _request_path(170, 386, 621)
+ bad_connector = {**_quality(80), "request_errors_per_minute": 1}
+ measurements = iter([(better_path, bad_connector), (previous_path, _quality(80))])
+ spawned_pids = iter([first_candidate_pid, rollback_pid])
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ pid = next(spawned_pids)
+ pid_path.write_text(str(pid), encoding="utf-8")
+ return pid
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=8: alive.discard(pid) is None)
+ monkeypatch.setattr(
+ remote_access,
+ "_measure_promoted_route",
+ lambda cfg, protocol, metrics_url: next(measurements),
+ )
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "tail_latency", previous)
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == rollback_pid
+ assert state["active"]["requested_protocol"] == "quic"
+ assert state["pending_tail_rollback"] is None
+ assert active_pid not in alive
+ assert results[0]["result"] == "no_improvement"
+
+
+def test_tail_recovery_rechecks_cancellation_before_next_protocol(monkeypatch, tmp_path) -> None:
+ config, _active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ previous_path = _request_path(202, 900, 1840, slow_rate=0.08)
+ previous = {**_quality(80), "protocol": "quic", "request_path": previous_path}
+ spawned_protocols = []
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ spawned_protocols.append(env["TUNNEL_TRANSPORT_PROTOCOL"])
+ pid_path.write_text(str(candidate_pid), encoding="utf-8")
+ return candidate_pid
+
+ def stop_pid(pid, timeout=8):
+ alive.discard(pid)
+ return True
+
+ def stop_during_measurement(cfg, protocol, metrics_url):
+ assert remote_access.stop(cfg)["ok"] is True
+ return _request_path(250, 950, 1900, slow_rate=0.08), _quality(80)
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(remote_access, "_measure_promoted_route", stop_during_measurement)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ try:
+ remote_access._run_route_optimization(config, "tail_latency", previous)
+ finally:
+ remote_access._RECOVERY_CANCEL_EVENT.clear()
+
+ assert spawned_protocols == ["quic"]
+ assert remote_access._read_pid() is None
+ assert 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))
+ remote_access._write_state(
+ active_pid,
+ config,
+ "/usr/local/bin/cloudflared",
+ "http://127.0.0.1:29001",
+ requested_protocol="quic",
+ )
+ spawned_protocols = []
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ spawned_protocols.append(env["TUNNEL_TRANSPORT_PROTOCOL"])
+ pid_path.write_text(str(candidate_pid), encoding="utf-8")
+ return candidate_pid
+
+ def stop_pid(pid, timeout=8):
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(
+ config,
+ "availability",
+ {**_quality(80), "ha_connections": 0, "protocol": "quic"},
+ )
+
+ assert spawned_protocols == ["auto"]
+ assert results[0]["result"] == "improved"
+
+
def test_optimize_route_reserves_single_candidate_atomically(monkeypatch, tmp_path) -> None:
started = []
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -200,6 +500,35 @@ def test_candidate_readiness_requires_four_ha_connections(monkeypatch) -> None:
assert remote_access._connector_ready_now(222, "http://127.0.0.1:29002") is True
+def test_ra_tq_022_public_probe_session_honors_host_network_environment(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ ca_bundle = tmp_path / "host-ca.pem"
+ ca_bundle.write_text("test CA", encoding="utf-8")
+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.test:8080")
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")
+ monkeypatch.setenv("REQUESTS_CA_BUNDLE", str(ca_bundle))
+ monkeypatch.delenv("ALL_PROXY", raising=False)
+ monkeypatch.delenv("all_proxy", raising=False)
+
+ session = remote_access._public_probe_session()
+ try:
+ settings = session.merge_environment_settings(
+ "https://alex.avibe.bot/health",
+ {},
+ None,
+ None,
+ None,
+ )
+ finally:
+ session.close()
+
+ assert session.trust_env is True
+ assert settings["proxies"]["https"] == "http://proxy.test:8080"
+ assert settings["verify"] == str(ca_bundle)
+
+
def test_manual_optimization_uses_active_availability_trigger(monkeypatch) -> None:
now = time.time()
quality = {
@@ -353,6 +682,58 @@ def test_failed_drain_remains_tracked_for_reconcile(monkeypatch, tmp_path) -> No
assert active_pid not in alive
+def test_ra_tq_016_monitor_lifecycle_retries_failed_drain(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ state["active"] = remote_access._connector_record(
+ candidate_pid,
+ "http://127.0.0.1:29002",
+ stdout_path=remote_access._candidate_cloudflared_stdout_path(),
+ stderr_path=remote_access._candidate_cloudflared_stderr_path(),
+ )
+ state["draining"] = state["active"] | {
+ "pid": active_pid,
+ "metrics_url": "http://127.0.0.1:29001",
+ }
+ state["pid"] = candidate_pid
+ runtime.write_json(remote_access._state_path(), state)
+ remote_access._pid_path().write_text(str(candidate_pid), encoding="utf-8")
+ attempts = iter([False, True])
+
+ def stop_pid(pid, timeout=8):
+ stopped = next(attempts)
+ if stopped:
+ alive.discard(pid)
+ return stopped
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+
+ remote_access._reconcile_connector_lifecycle()
+ assert remote_access._state_connector("draining")["pid"] == active_pid
+
+ remote_access._reconcile_connector_lifecycle()
+ assert remote_access._state_connector("draining") is None
+ assert active_pid not in alive
+
+
+def test_monitor_lifecycle_preserves_pending_work_after_transient_error(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ calls = []
+ monkeypatch.setattr(
+ remote_access,
+ "_reconcile_pending_tail_rollback",
+ lambda: (_ for _ in ()).throw(OSError("transient state read")),
+ )
+ monkeypatch.setattr(remote_access, "_reconcile_draining_connector", lambda: calls.append("drain"))
+
+ remote_access._reconcile_connector_lifecycle()
+
+ assert calls == []
+
+
def test_ra_tq_008_restart_removes_orphan_candidate(monkeypatch, tmp_path) -> None:
_, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
@@ -382,6 +763,195 @@ def test_ra_tq_008_restart_removes_orphan_candidate(monkeypatch, tmp_path) -> No
assert stopped == [candidate_pid]
+def test_ra_tq_017_restart_rolls_back_unverified_tail_candidate(monkeypatch, tmp_path) -> None:
+ config, previous_pid, unverified_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ rollback_pid = 333
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ state["active"] = remote_access._connector_record(
+ unverified_pid,
+ "http://127.0.0.1:29002",
+ stdout_path=remote_access._candidate_cloudflared_stdout_path(),
+ stderr_path=remote_access._candidate_cloudflared_stderr_path(),
+ requested_protocol="http2",
+ )
+ state["candidate"] = None
+ state["draining"] = None
+ state["pending_tail_rollback"] = {
+ "active_pid": unverified_pid,
+ "previous_protocol": "quic",
+ }
+ state["pid"] = unverified_pid
+ runtime.write_json(remote_access._state_path(), state)
+ remote_access._pid_path().write_text(str(unverified_pid), encoding="utf-8")
+ alive.discard(previous_pid)
+ stopped = []
+ results = []
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ assert env["TUNNEL_TRANSPORT_PROTOCOL"] == "quic"
+ alive.add(rollback_pid)
+ pid_path.write_text(str(rollback_pid), encoding="utf-8")
+ return rollback_pid
+
+ def stop_pid(pid, timeout=8):
+ stopped.append(pid)
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(
+ remote_access,
+ "_finish_reconciled_recovery",
+ lambda result, **kwargs: results.append((result, kwargs)),
+ )
+ monkeypatch.setattr(remote_access, "_set_preferred_protocol", lambda protocol: None)
+
+ remote_access._reconcile_pending_tail_rollback()
+
+ reconciled = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == rollback_pid
+ assert reconciled["active"]["requested_protocol"] == "quic"
+ assert reconciled["pending_tail_rollback"] is None
+ assert reconciled["draining"] is None
+ assert stopped == [unverified_pid]
+ assert results == [("failed", {"result_protocol": "quic"})]
+
+
+def test_ra_tq_019_live_tail_recovery_owns_pending_rollback(monkeypatch, tmp_path) -> None:
+ _, previous_pid, candidate_pid, _alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ state["active"] = remote_access._connector_record(
+ candidate_pid,
+ "http://127.0.0.1:29002",
+ stdout_path=remote_access._candidate_cloudflared_stdout_path(),
+ stderr_path=remote_access._candidate_cloudflared_stderr_path(),
+ requested_protocol="http2",
+ )
+ state["draining"] = None
+ state["pending_tail_rollback"] = {
+ "active_pid": candidate_pid,
+ "previous_protocol": "quic",
+ }
+ state["pid"] = candidate_pid
+ runtime.write_json(remote_access._state_path(), state)
+ remote_access._pid_path().write_text(str(candidate_pid), encoding="utf-8")
+ calls = []
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = object()
+ monkeypatch.setattr(
+ remote_access,
+ "_start_rollback_replacement",
+ lambda pending: calls.append(pending) or True,
+ )
+
+ try:
+ remote_access._reconcile_pending_tail_rollback()
+ finally:
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ current = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert current["active"]["pid"] == candidate_pid
+ assert current["pending_tail_rollback"]["active_pid"] == candidate_pid
+ assert previous_pid != candidate_pid
+ assert calls == []
+
+
+def test_ra_tq_023_status_preserves_rollback_after_promoted_process_exit(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ config, _previous_pid, promoted_pid, alive = _setup_recovery(
+ monkeypatch,
+ tmp_path,
+ _quality(180),
+ )
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ state["active"] = remote_access._connector_record(
+ promoted_pid,
+ "http://127.0.0.1:29002",
+ stdout_path=remote_access._candidate_cloudflared_stdout_path(),
+ stderr_path=remote_access._candidate_cloudflared_stderr_path(),
+ requested_protocol="http2",
+ )
+ state["candidate"] = None
+ state["draining"] = None
+ state["pending_tail_rollback"] = {
+ "active_pid": promoted_pid,
+ "previous_protocol": "quic",
+ }
+ state["pid"] = promoted_pid
+ runtime.write_json(remote_access._state_path(), state)
+ remote_access._pid_path().write_text(str(promoted_pid), encoding="utf-8")
+ alive.discard(promoted_pid)
+ rollback_attempts = []
+ monkeypatch.setattr(
+ remote_access,
+ "_start_rollback_replacement",
+ lambda pending: rollback_attempts.append(pending) or False,
+ )
+
+ current = remote_access.status(config)
+ remote_access._reconcile_pending_tail_rollback()
+
+ preserved = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert current["running"] is False
+ assert current["pid"] is None
+ assert preserved["active"]["pid"] == promoted_pid
+ assert preserved["pending_tail_rollback"] == {
+ "active_pid": promoted_pid,
+ "previous_protocol": "quic",
+ }
+ assert rollback_attempts == [preserved["pending_tail_rollback"]]
+
+
+def test_ra_tq_024_pinned_protocol_rejects_stale_tail_evidence(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ config, active_pid, _candidate_pid, _alive = _setup_recovery(
+ monkeypatch,
+ tmp_path,
+ _quality(180),
+ )
+ config.remote_access.vibe_cloud.transport_protocol = "http2"
+ config.save()
+ remote_access._write_state(
+ active_pid,
+ config,
+ "/usr/local/bin/cloudflared",
+ "http://127.0.0.1:29001",
+ requested_protocol="http2",
+ )
+ now = time.time()
+ stale = {
+ **_quality(80),
+ "protocol": "quic",
+ "sampled_at": remote_access.tunnel_quality.utc_timestamp(now),
+ "request_path": _request_path(202, 900, 1840, slow_rate=0.08),
+ }
+ current = {
+ "transport_protocol": "http2",
+ "tunnel_quality": stale,
+ }
+
+ assert (
+ remote_access._fresh_active_comparison_snapshot(
+ current,
+ trigger="tail_latency",
+ now=now,
+ )
+ is None
+ )
+ with pytest.raises(RuntimeError, match="request_path_comparison_unavailable"):
+ remote_access._run_tail_protocol_recovery(
+ config,
+ "/usr/local/bin/cloudflared",
+ stale,
+ )
+
+
def test_restart_removes_candidate_recorded_only_in_pid_file(monkeypatch, tmp_path) -> None:
_, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
remote_access._candidate_pid_path().write_text(str(candidate_pid), encoding="utf-8")
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index cbca50c9a..eee7af259 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -3,7 +3,7 @@ import { CheckCircle2, Cloud, ExternalLink, Link2, RefreshCcw, Route } from 'luc
import { Trans, useTranslation } from 'react-i18next';
import { type RemoteAccessStatus, useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
-import { getTunnelQualityDisplayState } from '../lib/tunnelQuality';
+import { getTunnelQualityDisplayState, getTunnelRequestPathDisplayState } from '../lib/tunnelQuality';
import { CompactField } from './settings/SettingsPrimitives';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
@@ -11,6 +11,12 @@ import { Badge } from './ui/badge';
const VIBE_CLOUD_URL = 'https://avibe.bot';
const VIBE_CLOUD_APP_URL = 'https://avibe.bot/app';
+const formatLatency = (milliseconds: number) => (
+ milliseconds >= 1000
+ ? `${(milliseconds / 1000).toFixed(milliseconds >= 10_000 ? 0 : 1)} s`
+ : `${Math.round(milliseconds)} ms`
+);
+
export const RemoteAccess: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
@@ -175,6 +181,20 @@ export const RemoteAccess: React.FC = () => {
? 'destructive'
: 'secondary';
const qualityLabel = t(`remoteAccess.quality${qualityGrade.charAt(0).toUpperCase()}${qualityGrade.slice(1)}`);
+ const requestPath = quality?.request_path;
+ const requestPathDisplayState = getTunnelRequestPathDisplayState(requestPath);
+ const requestPathUnavailable = requestPathDisplayState === 'unavailable';
+ const requestLatency = requestPathDisplayState === 'latency' ? requestPath?.latency_ms : null;
+ const effectiveProtocol = quality?.transport?.effective || quality?.protocol || 'unknown';
+ const protocolLabel = effectiveProtocol === 'http2'
+ ? 'HTTP/2'
+ : effectiveProtocol === 'quic'
+ ? 'QUIC'
+ : t('remoteAccess.protocolUnknown');
+ const configuredProtocol = quality?.transport?.configured || status?.transport_protocol;
+ const protocolDisplay = configuredProtocol === 'auto' && effectiveProtocol !== 'unknown'
+ ? t('remoteAccess.protocolAutomatic', { protocol: protocolLabel })
+ : protocolLabel;
return (
<section
@@ -248,15 +268,41 @@ export const RemoteAccess: React.FC = () => {
<div className="text-[12px] text-muted">{t('remoteAccess.quality')}</div>
<div className="mt-1 flex min-h-5 items-center gap-2">
<Badge variant={qualityVariant}>{qualityLabel}</Badge>
- {qualityFresh && quality?.rtt_ms && (
+ {qualityFresh && (requestLatency || quality?.rtt_ms) && (
<span className="font-mono text-[11px] text-foreground">
- {Math.round(quality.rtt_ms.median)} ms
+ {requestLatency
+ ? `P95 ${formatLatency(requestLatency.p95)}`
+ : formatLatency(quality!.rtt_ms!.median)}
</span>
)}
</div>
- {qualityFresh && quality?.edge_locations?.length ? (
- <div className="mt-1 truncate font-mono text-[10px] uppercase text-muted" title={quality.edge_locations.join(', ')}>
- {quality.edge_locations.join(' · ')}
+ {qualityFresh && quality ? (
+ <div className="mt-1 space-y-0.5 text-[10px] leading-4 text-muted">
+ <div className="truncate" title={quality.edge_locations?.join(', ')}>
+ {t('remoteAccess.connectorPath', {
+ protocol: protocolDisplay,
+ connections: quality.ha_connections,
+ rtt: quality.rtt_ms ? formatLatency(quality.rtt_ms.median) : t('remoteAccess.rttUnavailable'),
+ })}
+ </div>
+ {requestPathUnavailable ? (
+ <div className="truncate font-medium text-destructive">
+ {t('remoteAccess.requestPathUnavailable', {
+ success: requestPath?.success_count || 0,
+ count: requestPath?.sample_count || 0,
+ })}
+ </div>
+ ) : requestLatency ? (
+ <div className="truncate font-mono text-foreground/80">
+ {t('remoteAccess.requestPath', {
+ p95: formatLatency(requestLatency.p95),
+ p99: formatLatency(requestLatency.p99),
+ slow: Math.round((requestPath?.slow_request_rate.over_1000_ms || 0) * 100),
+ })}
+ </div>
+ ) : requestPath ? (
+ <div>{t('remoteAccess.requestPathMeasuring', { count: requestPath.sample_count })}</div>
+ ) : null}
</div>
) : null}
</div>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d037cac9a..6898addf6 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -356,11 +356,15 @@ export type VaultMetadataUpdatePayload = {
};
export type TunnelQualitySnapshot = {
- schema_version: 1;
+ schema_version: 1 | 2;
state: 'healthy' | 'degraded' | 'recovering' | 'unknown';
grade: 'good' | 'fair' | 'poor' | 'critical' | 'unknown';
sampled_at: string;
protocol: 'quic' | 'http2' | 'unknown';
+ transport?: {
+ configured: 'auto' | 'quic' | 'http2';
+ effective: 'quic' | 'http2' | 'unknown';
+ };
connector_count: number;
ha_connections: number;
rtt_ms: { min: number; median: number; max: number } | null;
@@ -369,13 +373,35 @@ export type TunnelQualitySnapshot = {
window_seconds: number;
request_errors_per_minute: number;
packet_loss_per_minute: number;
+ request_path?: {
+ source: 'synthetic_local';
+ status: 'healthy' | 'degraded' | 'unavailable' | 'insufficient';
+ confidence: 'low' | 'medium' | 'high';
+ window_seconds: number;
+ sample_count: number;
+ success_count: number;
+ latency_ms: { p50: number; p95: number; p99: number; max: number } | null;
+ failure_rate: number;
+ slow_request_rate: {
+ over_500_ms: number;
+ over_1000_ms: number;
+ over_2000_ms: number;
+ };
+ baseline_p95_ms: number | null;
+ } | null;
recovery: {
state: 'idle' | 'evaluating' | 'draining' | 'cooldown';
last_attempt_at: string | null;
- last_trigger: 'availability' | 'latency' | 'errors' | 'manual' | null;
+ last_trigger: 'availability' | 'latency' | 'tail_latency' | 'errors' | 'manual' | null;
last_result: 'improved' | 'no_improvement' | 'failed' | null;
previous_median_rtt_ms: number | null;
result_median_rtt_ms: number | null;
+ previous_protocol?: 'quic' | 'http2' | null;
+ result_protocol?: 'quic' | 'http2' | null;
+ previous_p95_ms?: number | null;
+ result_p95_ms?: number | null;
+ previous_p99_ms?: number | null;
+ result_p99_ms?: number | null;
next_attempt_at: string | null;
attempt_count_window: number;
};
@@ -388,6 +414,7 @@ export type RemoteAccessStatus = {
running: boolean;
public_url?: string;
pid_state?: string;
+ transport_protocol?: 'auto' | 'quic' | 'http2';
tunnel_quality?: TunnelQualitySnapshot;
error?: string;
optimization_started?: boolean;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 25da541be..3d89b133f 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1125,6 +1125,13 @@
"qualityUnknown": "Measuring",
"qualityRecovering": "Optimizing",
"qualityDegraded": "Degraded",
+ "protocolAutomatic": "{{protocol}} (Auto)",
+ "protocolUnknown": "Detecting",
+ "connectorPath": "Connector · {{protocol}} · {{connections}}/4 · RTT {{rtt}}",
+ "rttUnavailable": "Unavailable",
+ "requestPath": "Requests · P95 {{p95}} · P99 {{p99}} · {{slow}}% > 1 s",
+ "requestPathUnavailable": "Requests unavailable · {{success}}/{{count}} succeeded",
+ "requestPathMeasuring": "Measuring requests · {{count}} samples",
"optimizeRoute": "Optimize route",
"optimizingRoute": "Optimizing...",
"optimizeStarted": "A second Connector is evaluating a better route"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 546146c00..2d42e87ff 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1125,6 +1125,13 @@
"qualityUnknown": "测量中",
"qualityRecovering": "正在优化",
"qualityDegraded": "异常",
+ "protocolAutomatic": "{{protocol}}(自动)",
+ "protocolUnknown": "检测中",
+ "connectorPath": "连接器 · {{protocol}} · {{connections}}/4 · 往返 {{rtt}}",
+ "rttUnavailable": "不可用",
+ "requestPath": "远程请求 · P95 {{p95}} · P99 {{p99}} · {{slow}}% 超过 1 秒",
+ "requestPathUnavailable": "远程请求不可用 · {{success}}/{{count}} 成功",
+ "requestPathMeasuring": "正在测量远程请求 · {{count}} 个样本",
"optimizeRoute": "优化线路",
"optimizingRoute": "优化中...",
"optimizeStarted": "第二条 Connector 正在评估更优线路"
diff --git a/ui/src/lib/tunnelQuality.test.ts b/ui/src/lib/tunnelQuality.test.ts
index 48b64c206..ee1d62063 100644
--- a/ui/src/lib/tunnelQuality.test.ts
+++ b/ui/src/lib/tunnelQuality.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { getTunnelQualityDisplayState } from './tunnelQuality';
+import { getTunnelQualityDisplayState, getTunnelRequestPathDisplayState } from './tunnelQuality';
describe('getTunnelQualityDisplayState', () => {
it('lets degraded health override a good latency grade', () => {
@@ -12,3 +12,30 @@ describe('getTunnelQualityDisplayState', () => {
expect(getTunnelQualityDisplayState({ state: 'degraded', grade: 'good' }, false)).toBe('unknown');
});
});
+
+describe('getTunnelRequestPathDisplayState', () => {
+ const requestPath = {
+ source: 'synthetic_local' as const,
+ status: 'healthy' as const,
+ confidence: 'high' as const,
+ window_seconds: 180,
+ sample_count: 36,
+ success_count: 36,
+ latency_ms: { p50: 120, p95: 180, p99: 220, max: 240 },
+ failure_rate: 0,
+ slow_request_rate: { over_500_ms: 0, over_1000_ms: 0, over_2000_ms: 0 },
+ baseline_p95_ms: null,
+ };
+
+ it('renders failed request windows as unavailable instead of latency', () => {
+ expect(getTunnelRequestPathDisplayState({
+ ...requestPath,
+ status: 'unavailable',
+ success_count: 0,
+ })).toBe('unavailable');
+ });
+
+ it('renders usable high-confidence request latency', () => {
+ expect(getTunnelRequestPathDisplayState(requestPath)).toBe('latency');
+ });
+});
diff --git a/ui/src/lib/tunnelQuality.ts b/ui/src/lib/tunnelQuality.ts
index 328570869..8181f52d8 100644
--- a/ui/src/lib/tunnelQuality.ts
+++ b/ui/src/lib/tunnelQuality.ts
@@ -9,3 +9,17 @@ export const getTunnelQualityDisplayState = (
if (quality.state === 'degraded') return 'degraded';
return quality.grade;
};
+
+export const getTunnelRequestPathDisplayState = (
+ requestPath: TunnelQualitySnapshot['request_path'],
+): 'absent' | 'measuring' | 'latency' | 'unavailable' => {
+ if (!requestPath) return 'absent';
+ if (
+ requestPath.confidence !== 'low'
+ && (requestPath.status === 'unavailable' || requestPath.success_count === 0)
+ ) {
+ return 'unavailable';
+ }
+ if (requestPath.confidence !== 'low' && requestPath.latency_ms) return 'latency';
+ return 'measuring';
+};
diff --git a/vibe/cli.py b/vibe/cli.py
index ed33f4a48..2c1a97e18 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -9803,7 +9803,40 @@ def _doctor(*, deep: bool = False):
)
else:
rtt = quality.get("rtt_ms") if isinstance(quality.get("rtt_ms"), dict) else None
- if rtt is None:
+ request_path = (
+ quality.get("request_path")
+ if isinstance(quality.get("request_path"), dict)
+ else None
+ )
+ request_latency = (
+ request_path.get("latency_ms")
+ if remote_access.tunnel_quality.request_path_has_usable_latency(request_path)
+ else None
+ )
+ request_path_unavailable = bool(
+ request_path
+ and request_path.get("confidence") != "low"
+ and (
+ request_path.get("status") == "unavailable"
+ or int(request_path.get("success_count") or 0) == 0
+ )
+ )
+ if request_path_unavailable:
+ quality_message = (
+ f"Tunnel quality: {state}/{grade}; remote requests unavailable, "
+ f"{int(request_path.get('success_count') or 0)}/"
+ f"{int(request_path.get('sample_count') or 0)} succeeded; "
+ f"connector {quality.get('protocol') or 'unknown'}"
+ )
+ elif request_latency is not None:
+ slow_rate = request_path.get("slow_request_rate") or {}
+ quality_message = (
+ f"Tunnel quality: {state}/{grade}; remote requests P95 "
+ f"{request_latency.get('p95')} ms, P99 {request_latency.get('p99')} ms, "
+ f"{round(float(slow_rate.get('over_1000_ms') or 0) * 100)}% above 1 second; "
+ f"connector {quality.get('protocol') or 'unknown'}"
+ )
+ elif rtt is None:
quality_message = (
f"Tunnel quality: {state}; edge RTT unavailable for "
f"{quality.get('protocol') or 'unknown'} transport"
@@ -9814,7 +9847,9 @@ def _doctor(*, deep: bool = False):
f"maximum {rtt.get('max')} ms"
)
quality_status = "pass" if state == "healthy" and grade in {"good", "fair", "unknown"} else "warn"
- if state == "degraded" and int(quality.get("ha_connections") or 0) == 0:
+ if request_path_unavailable or (
+ state == "degraded" and int(quality.get("ha_connections") or 0) == 0
+ ):
quality_status = "fail"
_add_doctor_item(
remote_access_items,
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index cd24c37e0..ecfbcd725 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -59,9 +59,14 @@ QUALITY_SAMPLE_SECONDS = tunnel_quality.SAMPLE_INTERVAL_SECONDS
STATUS_LOG_TAIL_BYTES = 64 * 1024
STATUS_REPORT_DRAIN_SECONDS = 1.0
RECOVERY_READY_TIMEOUT_SECONDS = 30.0
+START_PREFERRED_READY_TIMEOUT_SECONDS = 8.0
RECOVERY_EVALUATION_SECONDS = 45.0
RECOVERY_DRAIN_SECONDS = 35.0
QUALITY_COMPARISON_MAX_AGE_SECONDS = 2 * QUALITY_SAMPLE_SECONDS
+REQUEST_PATH_PROBE_ATTEMPTS = 3
+REQUEST_PATH_PROBE_TIMEOUT_SECONDS = 3.5
+PROTOCOL_EVALUATION_ATTEMPTS = 20
+PROTOCOL_EVALUATION_INTERVAL_SECONDS = 1.6
_QUALITY_MONITOR_LOCK = threading.Lock()
_QUALITY_MONITOR_STARTED = False
_QUALITY_EVALUATOR = tunnel_quality.QualityEvaluator()
@@ -75,6 +80,7 @@ _RECOVERY_ATTEMPTS: list[float] = []
_RECOVERY_CANCEL_EVENT = threading.Event()
_RECOVERY_MANUAL_BYPASS_USED = False
_RECOVERY_EMERGENCY_BYPASS_USED = False
+_PREFERRED_PROTOCOL: str | None = None
_BLOCKED_PAIRING_BACKEND_HOSTS = {
"localhost",
"localhost.localdomain",
@@ -327,6 +333,34 @@ def _allocate_metrics_url() -> str:
return f"http://{host}:{port}"
+def _configured_protocol(config: V2Config) -> str:
+ protocol = str(getattr(config.remote_access.vibe_cloud, "transport_protocol", "auto") or "auto").lower()
+ return protocol if protocol in {"auto", "quic", "http2"} else "auto"
+
+
+def _stored_preferred_protocol() -> str | None:
+ payload = runtime.read_json(_quality_history_path())
+ if not isinstance(payload, dict):
+ return None
+ protocol = payload.get("preferred_protocol")
+ return str(protocol) if protocol in {"quic", "http2"} else None
+
+
+def _initial_connector_protocol(config: V2Config) -> str:
+ configured = _configured_protocol(config)
+ if configured != "auto":
+ return configured
+ return _PREFERRED_PROTOCOL or _stored_preferred_protocol() or "auto"
+
+
+def _connector_environment(token: str, protocol: str) -> dict[str, str]:
+ return {
+ **os.environ,
+ "TUNNEL_TOKEN": token,
+ "TUNNEL_TRANSPORT_PROTOCOL": protocol,
+ }
+
+
def _connector_command(binary: str, metrics_url: str) -> list[str]:
parsed = urllib.parse.urlsplit(metrics_url)
host = parsed.hostname or "127.0.0.1"
@@ -340,6 +374,7 @@ def _connector_record(
*,
stdout_path: Path,
stderr_path: Path,
+ requested_protocol: str = "auto",
) -> dict[str, Any]:
return {
"pid": pid,
@@ -347,10 +382,17 @@ def _connector_record(
"metrics_url": metrics_url,
"stdout_path": str(stdout_path),
"stderr_path": str(stderr_path),
+ "requested_protocol": requested_protocol,
}
-def _write_state(pid: int, config: V2Config, binary: str, metrics_url: str) -> None:
+def _write_state(
+ pid: int,
+ config: V2Config,
+ binary: str,
+ metrics_url: str,
+ requested_protocol: str | None = None,
+) -> None:
signature = _runtime_signature(config, binary)
runtime.write_json(
_state_path(),
@@ -363,9 +405,11 @@ def _write_state(pid: int, config: V2Config, binary: str, metrics_url: str) -> N
metrics_url,
stdout_path=_cloudflared_stdout_path(),
stderr_path=_cloudflared_stderr_path(),
+ requested_protocol=requested_protocol or _initial_connector_protocol(config),
),
"candidate": None,
"draining": None,
+ "pending_tail_rollback": None,
},
)
@@ -377,6 +421,7 @@ def _runtime_signature(config: V2Config, binary: str) -> dict[str, str]:
"binary_path": binary,
"public_url": cloud.public_url,
"tunnel_token_sha256": hashlib.sha256((cloud.tunnel_token or "").encode("utf-8")).hexdigest(),
+ "transport_protocol": _configured_protocol(config),
}
@@ -400,6 +445,36 @@ def _state_connector(name: str) -> dict[str, Any] | None:
return None
+def _pending_tail_rollback() -> dict[str, Any] | None:
+ state = _read_state() or {}
+ pending = state.get("pending_tail_rollback")
+ if not isinstance(pending, dict):
+ return None
+ active_pid = pending.get("active_pid")
+ previous_protocol = pending.get("previous_protocol")
+ if not isinstance(active_pid, int) or previous_protocol not in {"quic", "http2"}:
+ return None
+ return pending
+
+
+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)
+
+
def _replace_state_connector(name: str, record: dict[str, Any] | None) -> None:
state = _read_state() or {}
state["schema_version"] = 2
@@ -448,6 +523,7 @@ def _running_signature(pid: int | None) -> dict[str, str] | None:
"binary_path": str(state.get("binary_path") or ""),
"public_url": str(state.get("public_url") or ""),
"tunnel_token_sha256": str(state.get("tunnel_token_sha256") or ""),
+ "transport_protocol": str(state.get("transport_protocol") or ""),
}
@@ -469,7 +545,7 @@ def tunnel_quality_snapshot() -> dict[str, Any] | None:
if _QUALITY_SNAPSHOT is not None and _QUALITY_SNAPSHOT_PATH == _quality_state_path():
return json.loads(json.dumps(_QUALITY_SNAPSHOT))
payload = runtime.read_json(_quality_state_path())
- if isinstance(payload, dict) and payload.get("schema_version") == 1:
+ if isinstance(payload, dict) and payload.get("schema_version") in {1, 2}:
return payload
return None
@@ -486,7 +562,10 @@ def status(config: V2Config | None = None) -> dict[str, Any]:
_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"}:
+ if (
+ candidate_state not in {"cloudflared", "unknown"}
+ and _pending_tail_rollback() is None
+ ):
_state_path().unlink(missing_ok=True)
cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None) if config else None
binary = _resolve_binary(config)
@@ -502,6 +581,7 @@ def status(config: V2Config | None = None) -> dict[str, Any]:
"binary_found": bool(binary),
"binary_path": binary,
"binary_version": _version(binary) if binary else None,
+ "transport_protocol": _configured_protocol(config) if config is not None else "auto",
}
quality = tunnel_quality_snapshot()
if quality is not None:
@@ -530,7 +610,7 @@ def runtime_status_payload(config: V2Config | None = None, event: str = "heartbe
"observed_origin_service": _observed_cloudflared_origin_service(),
}
quality = current.get("tunnel_quality")
- if isinstance(quality, dict) and quality.get("schema_version") == 1:
+ if isinstance(quality, dict) and quality.get("schema_version") in {1, 2}:
payload["tunnel_quality"] = quality
error = last_error or current.get("error")
if error:
@@ -702,12 +782,19 @@ def _snapshot_change_key(snapshot: dict[str, Any] | None) -> tuple[Any, ...]:
return ()
rtt = snapshot.get("rtt_ms") if isinstance(snapshot.get("rtt_ms"), dict) else {}
recovery = snapshot.get("recovery") if isinstance(snapshot.get("recovery"), dict) else {}
+ request_path = snapshot.get("request_path") if isinstance(snapshot.get("request_path"), dict) else {}
+ request_latency = request_path.get("latency_ms") if isinstance(request_path.get("latency_ms"), dict) else {}
return (
snapshot.get("state"),
snapshot.get("grade"),
snapshot.get("ha_connections"),
rtt.get("median"),
rtt.get("max"),
+ snapshot.get("protocol"),
+ request_path.get("status"),
+ request_path.get("confidence"),
+ request_latency.get("p95"),
+ request_latency.get("p99"),
tuple(snapshot.get("edge_locations") or []),
recovery.get("state"),
recovery.get("last_result"),
@@ -731,12 +818,13 @@ def _persist_quality_snapshot(
runtime.write_json(quality_path, snapshot)
with _RECOVERY_LOCK:
monitor_state = {
- "schema_version": 1,
+ "schema_version": 2,
"evaluator": _QUALITY_EVALUATOR.export_state(),
"recovery": json.loads(json.dumps(_RECOVERY_STATE)),
"attempts": list(_RECOVERY_ATTEMPTS[-100:]),
"manual_bypass_used": _RECOVERY_MANUAL_BYPASS_USED,
"emergency_bypass_used": _RECOVERY_EMERGENCY_BYPASS_USED,
+ "preferred_protocol": _PREFERRED_PROTOCOL,
}
runtime.write_json(quality_path.with_name(_quality_history_path().name), monitor_state)
if publish and _snapshot_change_key(previous) != _snapshot_change_key(snapshot):
@@ -783,6 +871,7 @@ def _reserve_recovery(thread: threading.Thread, *, manual: bool, emergency: bool
_RECOVERY_THREAD is not None
or _state_connector("candidate") is not None
or _state_connector("draining") is not None
+ or _pending_tail_rollback() is not None
or _read_pid_file(_candidate_pid_path()) is not None
):
return False
@@ -817,6 +906,65 @@ def _automatic_recovery_enabled() -> bool:
return os.environ.get("AVIBE_TUNNEL_AUTO_RECOVERY", "1").strip().lower() not in {"0", "false", "no", "off"}
+def _public_health_url(config: V2Config) -> str | None:
+ public_url = str(config.remote_access.vibe_cloud.public_url or "").strip()
+ try:
+ parsed = urllib.parse.urlsplit(public_url)
+ except ValueError:
+ return None
+ if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
+ return None
+ return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, "/health", "", ""))
+
+
+def _effective_protocol(
+ active: dict[str, Any] | None,
+ sample: tunnel_quality.MetricsSample | None,
+) -> str:
+ requested = str((active or {}).get("requested_protocol") or "auto")
+ if requested in {"quic", "http2"}:
+ return requested
+ if sample is not None and sample.smoothed_rtt_ms:
+ return "quic"
+ if sample is not None and sample.ready:
+ return "http2"
+ snapshot = tunnel_quality_snapshot() or {}
+ observed = snapshot.get("protocol")
+ return str(observed) if observed in {"quic", "http2"} else "unknown"
+
+
+def _request_path_metric(request_path: dict[str, Any] | None, name: str) -> float | None:
+ latency = request_path.get("latency_ms") if isinstance(request_path, dict) else None
+ value = latency.get(name) if isinstance(latency, dict) else None
+ return float(value) if isinstance(value, (int, float)) else None
+
+
+def _set_preferred_protocol(protocol: str | None) -> None:
+ global _PREFERRED_PROTOCOL
+ if protocol not in {"quic", "http2", None}:
+ return
+ _PREFERRED_PROTOCOL = protocol
+ snapshot = tunnel_quality_snapshot()
+ if snapshot is not None:
+ _persist_quality_snapshot(snapshot, publish=False)
+
+
+def _tail_snapshot_matches_active_protocol(
+ current: dict[str, Any],
+ quality: dict[str, Any],
+) -> bool:
+ observed = quality.get("protocol")
+ if observed not in {"quic", "http2"}:
+ return False
+ configured = current.get("transport_protocol")
+ requested = (_state_connector("active") or {}).get("requested_protocol")
+ if configured in {"quic", "http2"}:
+ return requested == configured and observed == configured
+ if requested in {"quic", "http2"}:
+ return observed == requested
+ return True
+
+
def _fresh_active_comparison_snapshot(
current: dict[str, Any],
*,
@@ -828,10 +976,22 @@ def _fresh_active_comparison_snapshot(
sampled_at = _parse_timestamp(quality.get("sampled_at"))
age = now - sampled_at if sampled_at is not None else None
rtt = quality.get("rtt_ms")
+ tail_evidence_valid = (
+ trigger != "tail_latency"
+ or (
+ isinstance(quality.get("request_path"), dict)
+ and _tail_snapshot_matches_active_protocol(current, quality)
+ )
+ )
if (
age is not None
and -5 <= age <= QUALITY_COMPARISON_MAX_AGE_SECONDS
- and (trigger in {"availability", "errors", "manual"} or isinstance(rtt, dict))
+ and tail_evidence_valid
+ and (
+ trigger in {"availability", "errors", "manual"}
+ or isinstance(rtt, dict)
+ or trigger == "tail_latency"
+ )
):
return json.loads(json.dumps(quality))
@@ -849,6 +1009,8 @@ def _fresh_active_comparison_snapshot(
connector_count=1,
recovery=_recovery_payload(),
)
+ if trigger == "tail_latency":
+ return None
if trigger not in {"availability", "errors", "manual"} and not isinstance(snapshot.get("rtt_ms"), dict):
return None
return snapshot
@@ -870,7 +1032,11 @@ def optimize_route(config: V2Config | None = None, *, trigger: str = "manual") -
if manual:
effective_trigger = _QUALITY_EVALUATOR.recovery_trigger(previous) or "manual"
if effective_trigger == "manual" and not isinstance(previous.get("rtt_ms"), dict):
- return {**current, "ok": False, "error": "route_optimization_unavailable"}
+ request_path = previous.get("request_path")
+ if isinstance(request_path, dict) and request_path.get("confidence") in {"medium", "high"}:
+ effective_trigger = "tail_latency"
+ else:
+ return {**current, "ok": False, "error": "route_optimization_unavailable"}
try:
thread = threading.Thread(
target=_run_route_optimization,
@@ -908,8 +1074,8 @@ def _candidate_average_snapshot(metrics_url: str) -> dict[str, Any] | None:
return tunnel_quality.summarize_candidate_snapshots(snapshots)
-def _wait_candidate_ready(pid: int, metrics_url: str) -> bool:
- deadline = time.monotonic() + RECOVERY_READY_TIMEOUT_SECONDS
+def _wait_connector_ready(pid: int, metrics_url: str, *, timeout_seconds: float) -> bool:
+ deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
if _connector_ready_now(pid, metrics_url):
return True
@@ -919,6 +1085,14 @@ def _wait_candidate_ready(pid: int, metrics_url: str) -> bool:
return False
+def _wait_candidate_ready(pid: int, metrics_url: str) -> bool:
+ return _wait_connector_ready(
+ pid,
+ metrics_url,
+ timeout_seconds=RECOVERY_READY_TIMEOUT_SECONDS,
+ )
+
+
def _connector_ready_now(pid: int, metrics_url: str) -> bool:
if not _is_cloudflared_pid(pid):
return False
@@ -929,12 +1103,291 @@ def _connector_ready_now(pid: int, metrics_url: str) -> bool:
return False
+def _start_candidate_connector(
+ config: V2Config,
+ binary: str,
+ requested_protocol: str,
+) -> tuple[int, str]:
+ metrics_url = _allocate_metrics_url()
+ candidate_pid = runtime.spawn_background(
+ _connector_command(binary, metrics_url),
+ _candidate_pid_path(),
+ _candidate_cloudflared_stdout_path().name,
+ _candidate_cloudflared_stderr_path().name,
+ env=_connector_environment(config.remote_access.vibe_cloud.tunnel_token, requested_protocol),
+ )
+ candidate = _connector_record(
+ candidate_pid,
+ metrics_url,
+ stdout_path=_candidate_cloudflared_stdout_path(),
+ stderr_path=_candidate_cloudflared_stderr_path(),
+ requested_protocol=requested_protocol,
+ )
+ _replace_state_connector("candidate", candidate)
+ return candidate_pid, metrics_url
+
+
+def _discard_candidate_connector(pid: int) -> None:
+ state = _cloudflared_pid_state(pid)
+ if state == "cloudflared":
+ runtime.stop_pid(pid, timeout=8)
+ state = _cloudflared_pid_state(pid)
+ 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)
+
+
+def _promote_candidate_connector(
+ pid: int,
+ *,
+ pending_tail_rollback: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ with _CONNECTOR_LOCK:
+ state = _read_state() or {}
+ active = state.get("active") if isinstance(state.get("active"), dict) else {"pid": _read_pid()}
+ candidate = state.get("candidate")
+ if not isinstance(candidate, dict) or candidate.get("pid") != pid:
+ raise RuntimeError("candidate_state_changed")
+ metrics_url = candidate.get("metrics_url")
+ if not isinstance(metrics_url, str) or not _connector_ready_now(pid, metrics_url):
+ raise RuntimeError("candidate_no_longer_ready")
+ old_pid = active.get("pid") if isinstance(active, dict) else None
+ state["active"] = candidate
+ state["candidate"] = None
+ state["draining"] = active if isinstance(old_pid, int) and old_pid != pid else None
+ state["pending_tail_rollback"] = pending_tail_rollback
+ state["pid"] = pid
+ runtime.write_json(_state_path(), state)
+ _pid_path().write_text(str(pid), encoding="utf-8")
+ _candidate_pid_path().unlink(missing_ok=True)
+ return active if isinstance(active, dict) else {}
+
+
+def _drain_tracked_connector(connector: dict[str, Any]) -> bool:
+ pid = connector.get("pid")
+ if not isinstance(pid, int):
+ return True
+ state = _cloudflared_pid_state(pid)
+ if state == "cloudflared":
+ drained = runtime.stop_pid(pid, timeout=RECOVERY_DRAIN_SECONDS)
+ else:
+ drained = state in {"dead", "other"}
+ 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)
+ return True
+
+
+def _public_probe_session() -> requests.Session:
+ """Use the host's effective proxy and CA environment for public probes."""
+
+ return requests.Session()
+
+
+def _measure_promoted_route(
+ config: V2Config,
+ protocol: str,
+ metrics_url: str,
+) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
+ url = _public_health_url(config)
+ if url is None:
+ return None, None
+ session = _public_probe_session()
+ request_samples: list[tunnel_quality.RequestPathSample] = []
+ connector_evaluator = tunnel_quality.QualityEvaluator()
+ connector_snapshots: list[dict[str, Any]] = []
+ try:
+ for index in range(PROTOCOL_EVALUATION_ATTEMPTS):
+ if _RECOVERY_CANCEL_EVENT.is_set():
+ raise RuntimeError("route_optimization_cancelled")
+ request_samples.append(
+ tunnel_quality.probe_request_path(
+ session,
+ url,
+ attempts=1,
+ timeout=REQUEST_PATH_PROBE_TIMEOUT_SECONDS,
+ )
+ )
+ try:
+ sample = tunnel_quality.scrape_metrics(metrics_url)
+ except Exception:
+ logger.debug("Tunnel candidate metrics scrape failed", exc_info=True)
+ else:
+ connector_snapshots.append(
+ connector_evaluator.update(
+ sample,
+ connector_count=1,
+ configured_protocol=_configured_protocol(config),
+ effective_protocol=protocol,
+ )
+ )
+ if index + 1 < PROTOCOL_EVALUATION_ATTEMPTS:
+ time.sleep(PROTOCOL_EVALUATION_INTERVAL_SECONDS)
+ finally:
+ session.close()
+ return (
+ tunnel_quality.summarize_request_path_samples(
+ request_samples,
+ baseline_p95_ms=_QUALITY_EVALUATOR.request_baseline(protocol),
+ ),
+ tunnel_quality.summarize_candidate_snapshots(connector_snapshots),
+ )
+
+
+def _tail_candidate_protocol(config: V2Config, previous_protocol: str) -> str:
+ configured = _configured_protocol(config)
+ if configured != "auto":
+ return configured
+ if previous_protocol == "quic":
+ return "http2"
+ if previous_protocol == "http2":
+ return "quic"
+ raise RuntimeError("active_protocol_unknown")
+
+
+def _run_tail_protocol_recovery(
+ config: V2Config,
+ binary: str,
+ previous: dict[str, Any],
+) -> tuple[str, str, dict[str, Any] | None]:
+ previous_path = previous.get("request_path")
+ previous_protocol = str(previous.get("protocol") or "unknown")
+ if not isinstance(previous_path, dict) or previous_protocol not in {"quic", "http2"}:
+ raise RuntimeError("request_path_comparison_unavailable")
+ configured_protocol = _configured_protocol(config)
+ active_requested_protocol = str(
+ (_state_connector("active") or {}).get("requested_protocol") or "auto"
+ )
+ if configured_protocol in {"quic", "http2"}:
+ if (
+ active_requested_protocol != configured_protocol
+ or previous_protocol != configured_protocol
+ ):
+ raise RuntimeError("request_path_comparison_unavailable")
+ previous_protocol = configured_protocol
+ elif (
+ active_requested_protocol in {"quic", "http2"}
+ and previous_protocol != active_requested_protocol
+ ):
+ raise RuntimeError("request_path_comparison_unavailable")
+
+ def activate_and_measure(
+ protocol: str,
+ ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
+ candidate_pid: int | None = None
+ promoted = False
+ try:
+ with _CONNECTOR_LOCK:
+ if _RECOVERY_CANCEL_EVENT.is_set():
+ raise RuntimeError("route_optimization_cancelled")
+ active = _state_connector("active") or {}
+ active_pid = active.get("pid")
+ if not isinstance(active_pid, int) or not _is_cloudflared_pid(active_pid):
+ raise RuntimeError("active_connector_unavailable")
+ live_config = V2Config.load()
+ if (
+ not live_config.remote_access.vibe_cloud.enabled
+ or not live_config.remote_access.vibe_cloud.tunnel_token
+ or _configured_protocol(live_config) != configured_protocol
+ or (
+ configured_protocol in {"quic", "http2"}
+ and protocol != configured_protocol
+ )
+ ):
+ raise RuntimeError("route_optimization_cancelled")
+ candidate_pid, metrics_url = _start_candidate_connector(
+ live_config,
+ binary,
+ protocol,
+ )
+ if not _wait_candidate_ready(candidate_pid, metrics_url):
+ raise RuntimeError("candidate_not_ready")
+ _set_recovery_state(
+ state="draining",
+ previous_protocol=previous_protocol,
+ result_protocol=protocol,
+ )
+ replaced = _promote_candidate_connector(
+ candidate_pid,
+ pending_tail_rollback={
+ "active_pid": candidate_pid,
+ "previous_protocol": previous_protocol,
+ },
+ )
+ promoted = True
+ if not _drain_tracked_connector(replaced):
+ raise RuntimeError("old_connector_not_drained")
+ _set_recovery_state(state="evaluating")
+ candidate_path, candidate_connector = _measure_promoted_route(
+ config,
+ protocol,
+ metrics_url,
+ )
+ active = _state_connector("active") or {}
+ active_metrics_url = active.get("metrics_url")
+ if not isinstance(active_metrics_url, str) or not _connector_ready_now(
+ candidate_pid,
+ active_metrics_url,
+ ):
+ raise RuntimeError("promoted_connector_no_longer_ready")
+ return candidate_path, candidate_connector
+ finally:
+ if candidate_pid is not None and not promoted:
+ _discard_candidate_connector(candidate_pid)
+
+ candidate_protocols = [previous_protocol]
+ if configured_protocol == "auto":
+ candidate_protocols.append(_tail_candidate_protocol(config, previous_protocol))
+ for candidate_protocol in candidate_protocols:
+ candidate_path, candidate_connector = activate_and_measure(candidate_protocol)
+ candidate_snapshot = (
+ {**candidate_connector, "request_path": candidate_path}
+ if isinstance(candidate_path, dict) and isinstance(candidate_connector, dict)
+ else None
+ )
+ if (
+ isinstance(candidate_snapshot, dict)
+ and tunnel_quality.candidate_is_better(
+ previous,
+ candidate_snapshot,
+ trigger="tail_latency",
+ )
+ ):
+ _clear_pending_tail_rollback()
+ if configured_protocol == "auto":
+ _set_preferred_protocol(candidate_protocol)
+ return "improved", candidate_protocol, candidate_path
+
+ rollback_path, _rollback_connector = activate_and_measure(previous_protocol)
+ _clear_pending_tail_rollback()
+ if configured_protocol == "auto":
+ _set_preferred_protocol(previous_protocol)
+ return "no_improvement", previous_protocol, rollback_path or previous_path
+
+
def _finish_recovery(
*,
trigger: str | None,
result: str,
previous_median: float | None,
result_median: float | None,
+ previous_protocol: str | None = None,
+ result_protocol: str | None = None,
+ previous_p95: float | None = None,
+ result_p95: float | None = None,
+ previous_p99: float | None = None,
+ result_p99: float | None = None,
) -> None:
now = time.time()
_QUALITY_EVALUATOR.reset_healthy_samples()
@@ -950,6 +1403,12 @@ def _finish_recovery(
last_result=result,
previous_median_rtt_ms=previous_median,
result_median_rtt_ms=result_median,
+ previous_protocol=previous_protocol,
+ result_protocol=result_protocol,
+ previous_p95_ms=previous_p95,
+ result_p95_ms=result_p95,
+ previous_p99_ms=previous_p99,
+ result_p99_ms=result_p99,
next_attempt_at=tunnel_quality.utc_timestamp(next_attempt),
attempt_count_window=attempt_count,
)
@@ -969,33 +1428,55 @@ def _run_route_optimization(
previous = previous or tunnel_quality_snapshot() or {}
previous_rtt = previous.get("rtt_ms") if isinstance(previous.get("rtt_ms"), dict) else {}
previous_median = float(previous_rtt["median"]) if previous_rtt.get("median") is not None else None
+ previous_protocol = str(previous.get("protocol")) if previous.get("protocol") in {"quic", "http2"} else None
+ previous_path = previous.get("request_path") if isinstance(previous.get("request_path"), dict) else None
+ previous_p95 = _request_path_metric(previous_path, "p95")
+ previous_p99 = _request_path_metric(previous_path, "p99")
_report_runtime_status_async(event="route_optimization_started")
try:
+ loaded = config or V2Config.load()
+ cloud = loaded.remote_access.vibe_cloud
+ binary = _resolve_binary(loaded)
+ active = _state_connector("active")
+ active_pid = int(active.get("pid")) if active and isinstance(active.get("pid"), int) else _read_pid()
+ if not binary or not cloud.tunnel_token or not _is_cloudflared_pid(active_pid):
+ raise RuntimeError("active_connector_unavailable")
+ if trigger == "tail_latency":
+ result, result_protocol, result_path = _run_tail_protocol_recovery(
+ loaded,
+ binary,
+ previous,
+ )
+ _finish_recovery(
+ trigger=recovery_trigger,
+ result=result,
+ previous_median=previous_median,
+ result_median=None,
+ previous_protocol=previous_protocol,
+ result_protocol=result_protocol,
+ previous_p95=previous_p95,
+ result_p95=_request_path_metric(result_path, "p95"),
+ previous_p99=previous_p99,
+ result_p99=_request_path_metric(result_path, "p99"),
+ )
+ return
with _CONNECTOR_LOCK:
if _RECOVERY_CANCEL_EVENT.is_set():
raise RuntimeError("route_optimization_cancelled")
- loaded = config or V2Config.load()
- cloud = loaded.remote_access.vibe_cloud
- binary = _resolve_binary(loaded)
active = _state_connector("active")
active_pid = int(active.get("pid")) if active and isinstance(active.get("pid"), int) else _read_pid()
if not binary or not cloud.tunnel_token or not _is_cloudflared_pid(active_pid):
raise RuntimeError("active_connector_unavailable")
- metrics_url = _allocate_metrics_url()
- candidate_pid = runtime.spawn_background(
- _connector_command(binary, metrics_url),
- _candidate_pid_path(),
- _candidate_cloudflared_stdout_path().name,
- _candidate_cloudflared_stderr_path().name,
- env={**os.environ, "TUNNEL_TOKEN": cloud.tunnel_token},
+ requested_protocol = str((active or {}).get("requested_protocol") or _initial_connector_protocol(loaded))
+ 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"
+ candidate_pid, metrics_url = _start_candidate_connector(
+ loaded,
+ binary,
+ requested_protocol,
)
- candidate = _connector_record(
- candidate_pid,
- metrics_url,
- stdout_path=_candidate_cloudflared_stdout_path(),
- stderr_path=_candidate_cloudflared_stderr_path(),
- )
- _replace_state_connector("candidate", candidate)
if not _wait_candidate_ready(candidate_pid, metrics_url):
raise RuntimeError("candidate_not_ready")
@@ -1020,6 +1501,10 @@ def _run_route_optimization(
result="no_improvement",
previous_median=previous_median,
result_median=result_median,
+ previous_protocol=previous_protocol,
+ result_protocol=(candidate_snapshot or {}).get("protocol"),
+ previous_p95=previous_p95,
+ previous_p99=previous_p99,
)
return
@@ -1067,6 +1552,10 @@ def _run_route_optimization(
result="improved",
previous_median=previous_median,
result_median=result_median,
+ previous_protocol=previous_protocol,
+ result_protocol=candidate_snapshot.get("protocol"),
+ previous_p95=previous_p95,
+ previous_p99=previous_p99,
)
except Exception:
logger.warning("Tunnel route optimization failed", exc_info=True)
@@ -1075,6 +1564,10 @@ def _run_route_optimization(
result="failed",
previous_median=previous_median,
result_median=None,
+ previous_protocol=previous_protocol,
+ result_protocol=None,
+ previous_p95=previous_p95,
+ previous_p99=previous_p99,
)
finally:
candidate_cleaned = promoted or candidate_pid is None
@@ -1099,9 +1592,13 @@ def _run_route_optimization(
def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:
global _QUALITY_MONITOR_STARTED, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USED
last_report_at = 0.0
+ last_active_pid: int | None = None
+ last_effective_protocol = "unknown"
+ request_session = _public_probe_session()
try:
while quality_path == _quality_state_path() and quality_path.parent.exists():
started_at = time.monotonic()
+ _reconcile_connector_lifecycle()
active_pid = _read_pid()
running = _is_cloudflared_pid(active_pid)
active = _state_connector("active") or {}
@@ -1121,11 +1618,50 @@ def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:
sample = tunnel_quality.scrape_metrics(metrics_url)
except Exception:
logger.debug("Tunnel metrics scrape failed", exc_info=True)
+ if active_pid != last_active_pid:
+ _QUALITY_EVALUATOR.reset_request_window()
+ last_active_pid = active_pid
+ try:
+ loaded = V2Config.load()
+ except Exception:
+ loaded = None
+ configured_protocol = _configured_protocol(loaded) if loaded is not None else "auto"
+ effective_protocol = _effective_protocol(active, sample)
+ if (
+ last_effective_protocol in {"quic", "http2"}
+ and effective_protocol in {"quic", "http2"}
+ and effective_protocol != last_effective_protocol
+ ):
+ _QUALITY_EVALUATOR.reset_request_window()
+ last_effective_protocol = effective_protocol
+ request_path_sample = None
+ recovery_state = _recovery_payload().get("state")
+ public_health_url = _public_health_url(loaded) if loaded is not None else None
+ if (
+ running
+ and public_health_url is not None
+ and not _is_cloudflared_pid(candidate.get("pid"))
+ and not _is_cloudflared_pid(draining.get("pid"))
+ and _pending_tail_rollback() is None
+ and recovery_state not in {"evaluating", "draining"}
+ ):
+ try:
+ request_path_sample = tunnel_quality.probe_request_path(
+ request_session,
+ public_health_url,
+ attempts=REQUEST_PATH_PROBE_ATTEMPTS,
+ timeout=REQUEST_PATH_PROBE_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ logger.debug("Tunnel request-path probe failed", exc_info=True)
previous_snapshot = tunnel_quality_snapshot()
snapshot = _QUALITY_EVALUATOR.update(
sample,
connector_count=connector_count,
recovery=_recovery_payload(),
+ configured_protocol=configured_protocol,
+ effective_protocol=effective_protocol,
+ request_path_sample=request_path_sample,
)
try:
if not _persist_quality_snapshot(snapshot, expected_path=quality_path):
@@ -1158,6 +1694,7 @@ def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:
last_report_at = now
time.sleep(max(0.1, interval_seconds - (time.monotonic() - started_at)))
finally:
+ request_session.close()
with _QUALITY_MONITOR_LOCK:
_QUALITY_MONITOR_STARTED = False
@@ -1181,17 +1718,152 @@ def _reconcile_draining_connector() -> None:
_replace_state_connector("draining", None)
-def _finish_reconciled_recovery(result: str) -> None:
+def _restore_tracked_rollback_connector(
+ pending: dict[str, Any],
+ draining: dict[str, Any],
+) -> bool:
+ rollback_pid = draining.get("pid")
+ metrics_url = draining.get("metrics_url")
+ if not isinstance(rollback_pid, int) or not isinstance(metrics_url, str):
+ return False
+ if draining.get("requested_protocol") != pending.get("previous_protocol"):
+ return False
+ if not _connector_ready_now(rollback_pid, metrics_url):
+ return False
+ with _CONNECTOR_LOCK:
+ state = _read_state() or {}
+ current_pending = state.get("pending_tail_rollback")
+ active = state.get("active")
+ current_draining = state.get("draining")
+ if (
+ current_pending != pending
+ or not isinstance(active, dict)
+ or active.get("pid") != pending.get("active_pid")
+ or not isinstance(current_draining, dict)
+ or current_draining.get("pid") != rollback_pid
+ or _RECOVERY_CANCEL_EVENT.is_set()
+ ):
+ return False
+ state["active"] = current_draining
+ state["draining"] = active
+ state["pending_tail_rollback"] = None
+ state["pid"] = rollback_pid
+ runtime.write_json(_state_path(), state)
+ _pid_path().write_text(str(rollback_pid), encoding="utf-8")
+ _drain_tracked_connector(active)
+ return True
+
+
+def _start_rollback_replacement(pending: dict[str, Any]) -> bool:
+ candidate_pid: int | None = None
+ promoted = False
+ try:
+ loaded = V2Config.load()
+ cloud = loaded.remote_access.vibe_cloud
+ binary = _resolve_binary(loaded)
+ if (
+ _RECOVERY_CANCEL_EVENT.is_set()
+ or not cloud.enabled
+ or not cloud.tunnel_token
+ or not binary
+ ):
+ return False
+ with _CONNECTOR_LOCK:
+ active = _state_connector("active") or {}
+ if (
+ active.get("pid") != pending.get("active_pid")
+ or _state_connector("draining") is not None
+ or _state_connector("candidate") is not None
+ or _RECOVERY_CANCEL_EVENT.is_set()
+ ):
+ return False
+ candidate_pid, metrics_url = _start_candidate_connector(
+ loaded,
+ binary,
+ str(pending["previous_protocol"]),
+ )
+ if not _wait_candidate_ready(candidate_pid, metrics_url):
+ return False
+ replaced = _promote_candidate_connector(candidate_pid)
+ promoted = True
+ _drain_tracked_connector(replaced)
+ return True
+ finally:
+ if candidate_pid is not None and not promoted:
+ _discard_candidate_connector(candidate_pid)
+
+
+def _reconcile_pending_tail_rollback() -> None:
+ with _RECOVERY_LOCK:
+ if _RECOVERY_THREAD is not None:
+ return
+ state = _read_state() or {}
+ raw_pending = state.get("pending_tail_rollback")
+ pending = _pending_tail_rollback()
+ if pending is None:
+ if raw_pending is not None:
+ with _CONNECTOR_LOCK:
+ current = _read_state() or {}
+ if current.get("pending_tail_rollback") == raw_pending:
+ current["pending_tail_rollback"] = None
+ runtime.write_json(_state_path(), current)
+ return
+ active = _state_connector("active") or {}
+ if active.get("pid") != pending.get("active_pid"):
+ _clear_pending_tail_rollback(force=True)
+ return
+ draining = _state_connector("draining")
+ restored = isinstance(draining, dict) and _restore_tracked_rollback_connector(pending, draining)
+ if not restored and isinstance(draining, dict):
+ _reconcile_draining_connector()
+ if _state_connector("draining") is not None:
+ return
+ if not restored:
+ restored = _start_rollback_replacement(pending)
+ if not restored:
+ logger.warning(
+ "Could not yet roll back unverified Tunnel route pid=%s",
+ pending.get("active_pid"),
+ )
+ return
+ previous_protocol = str(pending["previous_protocol"])
+ _set_preferred_protocol(previous_protocol)
+ _finish_reconciled_recovery("failed", result_protocol=previous_protocol)
+
+
+def _reconcile_connector_lifecycle() -> None:
+ try:
+ _reconcile_pending_tail_rollback()
+ if _pending_tail_rollback() is None:
+ _reconcile_draining_connector()
+ except Exception:
+ logger.warning("Tunnel connector lifecycle reconciliation failed", exc_info=True)
+
+
+def _finish_reconciled_recovery(
+ result: str,
+ *,
+ result_protocol: str | None = None,
+) -> None:
recovery = _recovery_payload()
previous_median = recovery.get("previous_median_rtt_ms")
+ previous_protocol = recovery.get("previous_protocol")
+ previous_p95 = recovery.get("previous_p95_ms")
+ previous_p99 = recovery.get("previous_p99_ms")
trigger = recovery.get("last_trigger")
- if trigger not in {"availability", "latency", "errors", "manual"}:
+ if trigger not in {"availability", "latency", "tail_latency", "errors", "manual"}:
trigger = None
_finish_recovery(
trigger=trigger,
result=result,
previous_median=float(previous_median) if isinstance(previous_median, (int, float)) else None,
result_median=None,
+ previous_protocol=(
+ str(previous_protocol) if previous_protocol in {"quic", "http2"} else None
+ ),
+ result_protocol=result_protocol,
+ previous_p95=float(previous_p95) if isinstance(previous_p95, (int, float)) else None,
+ previous_p99=float(previous_p99) if isinstance(previous_p99, (int, float)) else None,
)
@@ -1272,6 +1944,7 @@ def _normalize_orphaned_recovery_state() -> None:
if (
_state_connector("candidate") is not None
or _state_connector("draining") is not None
+ or _pending_tail_rollback() is not None
or _read_pid_file(_candidate_pid_path()) is not None
):
return
@@ -1279,7 +1952,7 @@ def _normalize_orphaned_recovery_state() -> None:
def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECONDS) -> None:
- global _QUALITY_EVALUATOR, _QUALITY_MONITOR_STARTED, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USED
+ global _PREFERRED_PROTOCOL, _QUALITY_EVALUATOR, _QUALITY_MONITOR_STARTED, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USED
with _QUALITY_MONITOR_LOCK:
if _QUALITY_MONITOR_STARTED:
return
@@ -1291,7 +1964,7 @@ def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECOND
_RECOVERY_MANUAL_BYPASS_USED = False
_RECOVERY_EMERGENCY_BYPASS_USED = False
persisted = runtime.read_json(_quality_history_path())
- if isinstance(persisted, dict) and persisted.get("schema_version") == 1:
+ if isinstance(persisted, dict) and persisted.get("schema_version") in {1, 2}:
evaluator_state = persisted.get("evaluator")
if isinstance(evaluator_state, dict):
_QUALITY_EVALUATOR.load_state(evaluator_state)
@@ -1306,8 +1979,10 @@ def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECOND
_RECOVERY_ATTEMPTS[:] = [float(item) for item in attempts if isinstance(item, (int, float))][-100:]
_RECOVERY_MANUAL_BYPASS_USED = bool(persisted.get("manual_bypass_used"))
_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()
- _reconcile_draining_connector()
+ _reconcile_connector_lifecycle()
_normalize_orphaned_recovery_state()
quality_path = _quality_state_path()
try:
@@ -1432,8 +2107,9 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
"error": stop_result.get("error") or "cloudflared_stop_failed",
"restarted": False,
}
- env = {**os.environ, "TUNNEL_TOKEN": cloud.tunnel_token}
- try:
+ requested_protocol = _initial_connector_protocol(config)
+
+ def spawn_connector(protocol: str) -> tuple[int, str, dict[str, Any]]:
_clear_cloudflared_logs()
metrics_url = _allocate_metrics_url()
pid = runtime.spawn_background(
@@ -1441,14 +2117,62 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
_pid_path(),
"remote_access_cloudflared_stdout.log",
"remote_access_cloudflared_stderr.log",
- env=env,
+ env=_connector_environment(cloud.tunnel_token, protocol),
+ )
+ _write_state(
+ pid,
+ config,
+ binary,
+ metrics_url,
+ requested_protocol=protocol,
)
- _write_state(pid, config, binary, metrics_url)
+ time.sleep(0.2)
+ return pid, metrics_url, status(config)
+
+ try:
+ pid, metrics_url, current = spawn_connector(requested_protocol)
+ preferred_needs_fallback = (
+ _configured_protocol(config) == "auto"
+ and requested_protocol in {"quic", "http2"}
+ and not _wait_connector_ready(
+ pid,
+ metrics_url,
+ timeout_seconds=START_PREFERRED_READY_TIMEOUT_SECONDS,
+ )
+ )
+ if preferred_needs_fallback:
+ preferred_state = _cloudflared_pid_state(pid)
+ if preferred_state == "unknown":
+ _report_runtime_status_async(
+ config,
+ event="start_failed",
+ last_error="cloudflared_process_unknown",
+ )
+ return {
+ **current,
+ "ok": False,
+ "error": "cloudflared_process_unknown",
+ "started": False,
+ }
+ if preferred_state == "cloudflared" and not runtime.stop_pid(pid, timeout=8):
+ _report_runtime_status_async(
+ config,
+ event="start_failed",
+ last_error="cloudflared_stop_failed",
+ )
+ return {
+ **status(config),
+ "ok": False,
+ "error": "cloudflared_stop_failed",
+ "started": False,
+ }
+ _pid_path().unlink(missing_ok=True)
+ _state_path().unlink(missing_ok=True)
+ requested_protocol = "auto"
+ pid, metrics_url, current = spawn_connector(requested_protocol)
except Exception as exc:
_report_runtime_status_async(config, event="start_failed", last_error="cloudflared_spawn_failed")
return {**status(config), "ok": False, "error": "cloudflared_spawn_failed", "detail": str(exc)}
- time.sleep(0.2)
- current = status(config)
if not current.get("running"):
_report_runtime_status_async(config, event="start_failed", last_error="cloudflared_exited")
return {**current, "ok": False, "error": "cloudflared_exited"}
diff --git a/vibe/tunnel_quality.py b/vibe/tunnel_quality.py
index 857753c8e..14424b8f8 100644
--- a/vibe/tunnel_quality.py
+++ b/vibe/tunnel_quality.py
@@ -19,6 +19,11 @@ RATE_WINDOW_SECONDS = 60
BASELINE_MINUTE_SAMPLES = 15
BASELINE_RETENTION_SAMPLES = 24 * 60
CANDIDATE_MIN_SAMPLES = 4
+REQUEST_PATH_WINDOW_SECONDS = 180
+REQUEST_PATH_MAX_SAMPLES = 48
+REQUEST_PATH_MIN_SAMPLES = 12
+REQUEST_PATH_HIGH_CONFIDENCE_SAMPLES = 30
+REQUEST_BASELINE_RETENTION_SAMPLES = 2 * 24 * 60
def utc_timestamp(now: float) -> str:
@@ -38,6 +43,13 @@ class MetricsSample:
timeout_packet_loss_by_connection: tuple[tuple[str, float], ...] = ()
+@dataclass(frozen=True)
+class RequestPathSample:
+ sampled_at: float
+ latency_ms: tuple[float, ...]
+ 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."""
@@ -100,6 +112,41 @@ def scrape_metrics(metrics_url: str, *, timeout: float = 0.5, now: float | None
return parse_metrics(metrics_response.text, ready=ready_response.ok, now=now)
+def probe_request_path(
+ session: requests.Session,
+ url: str,
+ *,
+ attempts: int = 3,
+ timeout: float = 3.5,
+ now: float | None = None,
+) -> RequestPathSample:
+ """Measure a bounded public health window through one persistent session."""
+
+ latency_values: list[float] = []
+ successes: list[bool] = []
+ for _ in range(max(1, attempts)):
+ started_at = time.perf_counter()
+ success = False
+ try:
+ response = session.get(
+ url,
+ timeout=timeout,
+ allow_redirects=False,
+ headers={"Accept": "application/json", "Cache-Control": "no-cache"},
+ )
+ success = 200 <= response.status_code < 300
+ response.close()
+ except requests.RequestException:
+ pass
+ latency_values.append(round((time.perf_counter() - started_at) * 1000, 1))
+ successes.append(success)
+ return RequestPathSample(
+ sampled_at=now if now is not None else time.time(),
+ latency_ms=tuple(latency_values),
+ successes=tuple(successes),
+ )
+
+
def rtt_stats(values: tuple[float, ...] | list[float]) -> dict[str, float] | None:
if not values:
return None
@@ -132,13 +179,165 @@ def _percentile(values: list[float], percentile: float) -> float | None:
return round(ordered[index], 1)
+def request_path_grade(request_path: dict[str, Any] | None) -> str:
+ if not request_path or request_path.get("confidence") == "low":
+ return "unknown"
+ latency = request_path.get("latency_ms")
+ if not isinstance(latency, dict):
+ return "critical" if request_path.get("status") == "unavailable" else "unknown"
+ p95 = float(latency.get("p95") or 0)
+ p99 = float(latency.get("p99") or 0)
+ slow = request_path.get("slow_request_rate") or {}
+ over_one_second = float(slow.get("over_1000_ms") or 0)
+ failure_rate = float(request_path.get("failure_rate") or 0)
+ if failure_rate >= 0.10:
+ return "critical"
+ if p95 < 350 and p99 < 750 and over_one_second < 0.02:
+ return "good"
+ if p95 < 600 and p99 < 1200 and over_one_second < 0.05:
+ return "fair"
+ if p95 < 1000 and p99 < 2000 and over_one_second < 0.10:
+ return "poor"
+ return "critical"
+
+
+def request_path_is_degraded(request_path: dict[str, Any] | None) -> bool:
+ if not request_path or request_path.get("confidence") != "high":
+ return False
+ if request_path.get("status") == "unavailable":
+ return True
+ latency = request_path.get("latency_ms")
+ if not isinstance(latency, dict):
+ return False
+ p95 = float(latency.get("p95") or 0)
+ p99 = float(latency.get("p99") or 0)
+ slow = request_path.get("slow_request_rate") or {}
+ over_one_second = float(slow.get("over_1000_ms") or 0)
+ failure_rate = float(request_path.get("failure_rate") or 0)
+ baseline = request_path.get("baseline_p95_ms")
+ baseline_regression = baseline is not None and p95 >= 2 * float(baseline)
+ return (
+ failure_rate >= 0.10
+ or p95 >= 750
+ or baseline_regression
+ or over_one_second >= 0.05
+ or (p99 >= 1500 and over_one_second >= 0.03)
+ )
+
+
+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
+ if request_path.get("status") == "unavailable" or int(request_path.get("success_count") or 0) == 0:
+ return False
+ return isinstance(request_path.get("latency_ms"), dict)
+
+
+def summarize_request_path_samples(
+ samples: list[RequestPathSample] | tuple[RequestPathSample, ...],
+ *,
+ baseline_p95_ms: float | None = None,
+) -> dict[str, Any] | None:
+ latencies: list[float] = []
+ successes: list[bool] = []
+ for sample in samples:
+ count = min(len(sample.latency_ms), len(sample.successes))
+ for index in range(count):
+ latency = float(sample.latency_ms[index])
+ if not math.isfinite(latency) or latency < 0:
+ continue
+ latencies.append(latency)
+ successes.append(bool(sample.successes[index]))
+ sample_count = len(latencies)
+ if sample_count == 0:
+ return None
+ success_count = sum(successes)
+ confidence = (
+ "high"
+ if sample_count >= REQUEST_PATH_HIGH_CONFIDENCE_SAMPLES
+ else "medium"
+ if sample_count >= REQUEST_PATH_MIN_SAMPLES
+ else "low"
+ )
+ latency = {
+ "p50": _percentile(latencies, 0.50),
+ "p95": _percentile(latencies, 0.95),
+ "p99": _percentile(latencies, 0.99),
+ "max": round(max(latencies), 1),
+ }
+ failure_rate = round((sample_count - success_count) / sample_count, 4)
+ slow_request_rate = {
+ "over_500_ms": round(sum(value > 500 for value in latencies) / sample_count, 4),
+ "over_1000_ms": round(sum(value > 1000 for value in latencies) / sample_count, 4),
+ "over_2000_ms": round(sum(value > 2000 for value in latencies) / sample_count, 4),
+ }
+ payload: dict[str, Any] = {
+ "source": "synthetic_local",
+ "status": "insufficient",
+ "confidence": confidence,
+ "window_seconds": REQUEST_PATH_WINDOW_SECONDS,
+ "sample_count": sample_count,
+ "success_count": success_count,
+ "latency_ms": latency,
+ "failure_rate": failure_rate,
+ "slow_request_rate": slow_request_rate,
+ "baseline_p95_ms": baseline_p95_ms,
+ }
+ if confidence != "low":
+ if success_count == 0:
+ payload["status"] = "unavailable"
+ else:
+ payload["status"] = "degraded" if request_path_is_degraded(payload) else "healthy"
+ return payload
+
+
+def request_path_is_better(active: dict[str, Any], candidate: dict[str, Any]) -> bool:
+ active_latency = active.get("latency_ms")
+ candidate_latency = candidate.get("latency_ms")
+ if not isinstance(active_latency, dict) or not isinstance(candidate_latency, dict):
+ return False
+ candidate_count = int(candidate.get("sample_count") or 0)
+ candidate_success = int(candidate.get("success_count") or 0)
+ if candidate_count < REQUEST_PATH_MIN_SAMPLES or candidate_success / candidate_count < 0.95:
+ return False
+ active_p95 = float(active_latency.get("p95") or 0)
+ active_p99 = float(active_latency.get("p99") or 0)
+ candidate_p95 = float(candidate_latency.get("p95") or 0)
+ candidate_p99 = float(candidate_latency.get("p99") or 0)
+ active_slow = float((active.get("slow_request_rate") or {}).get("over_1000_ms") or 0)
+ candidate_slow = float((candidate.get("slow_request_rate") or {}).get("over_1000_ms") or 0)
+ active_failure = float(active.get("failure_rate") or 0)
+ candidate_failure = float(candidate.get("failure_rate") or 0)
+ p95_improved = active_p95 > 0 and candidate_p95 <= active_p95 * 0.80
+ tail_improved = (
+ active_p95 > 0
+ and candidate_p95 <= active_p95 * 1.25
+ and active_p99 > 0
+ and candidate_p99 <= active_p99 * 0.60
+ )
+ slow_rate_improved = (
+ active_slow >= 0.03
+ and candidate_slow <= min(active_slow - 0.02, active_slow * 0.50)
+ )
+ failure_rate_improved = (
+ active_failure >= 0.10
+ and candidate_failure <= min(active_failure - 0.05, active_failure * 0.50)
+ )
+ return p95_improved or tail_improved or slow_rate_improved or failure_rate_improved
+
+
class QualityEvaluator:
"""Stateful evaluator shared by status, Doctor, reporting, and recovery."""
def __init__(self) -> None:
self._counter_samples: deque[MetricsSample] = deque(maxlen=8)
self._baseline_samples: deque[tuple[float, float]] = deque(maxlen=BASELINE_RETENTION_SAMPLES)
+ self._request_samples: deque[RequestPathSample] = deque(maxlen=REQUEST_PATH_MAX_SAMPLES)
+ self._request_baseline_samples: deque[tuple[float, str, float]] = deque(
+ maxlen=REQUEST_BASELINE_RETENTION_SAMPLES
+ )
self._last_baseline_minute: int | None = None
+ self._last_request_baseline_minute: dict[str, int] = {}
self._last_snapshot: dict[str, Any] | None = None
self._latency_bad_samples = 0
self._partial_samples = 0
@@ -158,10 +357,18 @@ class QualityEvaluator:
def reset_healthy_samples(self) -> None:
self._healthy_samples = 0
+ def reset_request_window(self) -> None:
+ self._request_samples.clear()
+
def export_state(self) -> dict[str, Any]:
return {
"baseline_samples": [[timestamp, value] for timestamp, value in self._baseline_samples],
"last_baseline_minute": self._last_baseline_minute,
+ "request_baseline_samples": [
+ [timestamp, protocol, value]
+ for timestamp, protocol, value in self._request_baseline_samples
+ ],
+ "last_request_baseline_minute": dict(self._last_request_baseline_minute),
}
def load_state(self, payload: dict[str, Any], *, now: float | None = None) -> None:
@@ -183,6 +390,30 @@ class QualityEvaluator:
self._baseline_samples = deque(restored, maxlen=BASELINE_RETENTION_SAMPLES)
last_minute = payload.get("last_baseline_minute")
self._last_baseline_minute = int(last_minute) if isinstance(last_minute, int) else None
+ request_samples = payload.get("request_baseline_samples")
+ restored_request_samples: list[tuple[float, str, float]] = []
+ if isinstance(request_samples, list):
+ for item in request_samples[-REQUEST_BASELINE_RETENTION_SAMPLES:]:
+ if not isinstance(item, list) or len(item) != 3 or item[1] not in {"quic", "http2"}:
+ continue
+ try:
+ timestamp = float(item[0])
+ value = float(item[2])
+ except (TypeError, ValueError):
+ continue
+ if timestamp >= cutoff and value >= 0 and math.isfinite(value):
+ restored_request_samples.append((timestamp, str(item[1]), value))
+ self._request_baseline_samples = deque(
+ restored_request_samples,
+ maxlen=REQUEST_BASELINE_RETENTION_SAMPLES,
+ )
+ request_minutes = payload.get("last_request_baseline_minute")
+ if isinstance(request_minutes, dict):
+ self._last_request_baseline_minute = {
+ protocol: int(value)
+ for protocol, value in request_minutes.items()
+ if protocol in {"quic", "http2"} and isinstance(value, int)
+ }
def baseline(self, now: float | None = None) -> float | None:
cutoff = (now if now is not None else time.time()) - 24 * 60 * 60
@@ -192,6 +423,59 @@ class QualityEvaluator:
return None
return _percentile([value for _, value in self._baseline_samples], 0.20)
+ def request_baseline(self, protocol: str, now: float | None = None) -> float | None:
+ cutoff = (now if now is not None else time.time()) - 24 * 60 * 60
+ while self._request_baseline_samples and self._request_baseline_samples[0][0] < cutoff:
+ self._request_baseline_samples.popleft()
+ values = [
+ value
+ for _, sample_protocol, value in self._request_baseline_samples
+ if sample_protocol == protocol
+ ]
+ if len(values) < BASELINE_MINUTE_SAMPLES:
+ return None
+ return _percentile(values, 0.20)
+
+ def _request_path(
+ self,
+ sample: RequestPathSample | None,
+ *,
+ protocol: str,
+ now: float,
+ ) -> dict[str, Any] | None:
+ if sample is not None:
+ self._request_samples.append(sample)
+ cutoff = now - REQUEST_PATH_WINDOW_SECONDS
+ while self._request_samples and self._request_samples[0].sampled_at < cutoff:
+ self._request_samples.popleft()
+ return summarize_request_path_samples(
+ list(self._request_samples),
+ baseline_p95_ms=self.request_baseline(protocol, now) if protocol in {"quic", "http2"} else None,
+ )
+
+ def _record_request_baseline(
+ self,
+ request_path: dict[str, Any] | None,
+ *,
+ protocol: str,
+ now: float,
+ ) -> None:
+ if (
+ protocol not in {"quic", "http2"}
+ or not request_path
+ or request_path.get("status") != "healthy"
+ or request_path.get("confidence") == "low"
+ ):
+ return
+ latency = request_path.get("latency_ms")
+ if not isinstance(latency, dict) or latency.get("p95") is None:
+ return
+ minute = int(now // 60)
+ if self._last_request_baseline_minute.get(protocol) == minute:
+ return
+ self._request_baseline_samples.append((now, protocol, float(latency["p95"])))
+ self._last_request_baseline_minute[protocol] = minute
+
def _rates(self, sample: MetricsSample) -> tuple[float, float]:
self._counter_samples.append(sample)
cutoff = sample.sampled_at - RATE_WINDOW_SECONDS
@@ -216,11 +500,20 @@ class QualityEvaluator:
*,
connector_count: int = 1,
recovery: dict[str, Any] | None = None,
+ configured_protocol: str = "auto",
+ effective_protocol: str | None = None,
+ request_path_sample: RequestPathSample | None = None,
now: float | None = None,
) -> dict[str, Any]:
current_time = now if now is not None else (sample.sampled_at if sample else time.time())
recovery_payload = recovery or empty_recovery()
previous_state = str((self._last_snapshot or {}).get("state") or "unknown")
+ previous_protocol = str((self._last_snapshot or {}).get("protocol") or "unknown")
+ protocol = effective_protocol if effective_protocol in {"quic", "http2"} else previous_protocol
+ if sample is not None:
+ if effective_protocol not in {"quic", "http2"}:
+ protocol = "quic" if sample.smoothed_rtt_ms else "http2" if sample.ready else "unknown"
+ request_path = self._request_path(request_path_sample, protocol=protocol, now=current_time)
if sample is None:
self._metrics_failures += 1
@@ -229,12 +522,16 @@ class QualityEvaluator:
state = "unknown"
previous_connections = int((self._last_snapshot or {}).get("ha_connections") or 0)
previous_locations = list((self._last_snapshot or {}).get("edge_locations") or [])
+ request_grade = request_path_grade(request_path)
+ if request_path_is_degraded(request_path):
+ state = "degraded"
snapshot = {
- "schema_version": 1,
+ "schema_version": 2,
"state": "recovering" if recovery_payload["state"] in {"evaluating", "draining"} else state,
- "grade": "unknown",
+ "grade": request_grade,
"sampled_at": utc_timestamp(current_time),
- "protocol": "unknown",
+ "protocol": protocol,
+ "transport": {"configured": configured_protocol, "effective": protocol},
"connector_count": max(0, connector_count),
"ha_connections": previous_connections,
"rtt_ms": None,
@@ -243,6 +540,7 @@ class QualityEvaluator:
"window_seconds": RATE_WINDOW_SECONDS,
"request_errors_per_minute": 0.0,
"packet_loss_per_minute": 0.0,
+ "request_path": request_path,
"recovery": recovery_payload,
}
self._last_snapshot = snapshot
@@ -250,10 +548,12 @@ class QualityEvaluator:
self._metrics_failures = 0
rtt = rtt_stats(sample.smoothed_rtt_ms)
- grade = latency_grade(rtt)
+ connector_grade = latency_grade(rtt)
+ request_grade = request_path_grade(request_path)
+ grade = request_grade if request_grade != "unknown" else connector_grade
errors_per_minute, loss_per_minute = self._rates(sample)
- self._latency_bad_samples = self._latency_bad_samples + 1 if grade in {"poor", "critical"} else 0
+ self._latency_bad_samples = self._latency_bad_samples + 1 if connector_grade in {"poor", "critical"} else 0
self._partial_samples = self._partial_samples + 1 if sample.ha_connections < 4 else 0
self._error_windows = self._error_windows + 1 if errors_per_minute >= 3 else 0
self._loss_windows = self._loss_windows + 1 if loss_per_minute >= 10 else 0
@@ -265,6 +565,7 @@ class QualityEvaluator:
or self._error_windows >= 2
or self._loss_windows >= 2
or self._latency_bad_samples >= 12
+ or request_path_is_degraded(request_path)
)
baseline = self.baseline(current_time)
recovery_state = recovery_payload["state"]
@@ -277,9 +578,10 @@ class QualityEvaluator:
healthy_rtt = (
rtt is None or rtt["median"] < max(160.0, 1.5 * baseline)
if baseline is not None
- else grade in {"good", "fair", "unknown"}
+ else connector_grade in {"good", "fair", "unknown"}
)
- self._healthy_samples = self._healthy_samples + 1 if sample.ha_connections == 4 and errors_per_minute < 3 and loss_per_minute < 10 and healthy_rtt else 0
+ healthy_request_path = not request_path_is_degraded(request_path)
+ self._healthy_samples = self._healthy_samples + 1 if sample.ha_connections == 4 and errors_per_minute < 3 and loss_per_minute < 10 and healthy_rtt and healthy_request_path else 0
state = "healthy" if self._healthy_samples >= 20 else "degraded"
else:
state = "healthy"
@@ -288,7 +590,7 @@ class QualityEvaluator:
minute = int(current_time // 60)
if (
state == "healthy"
- and grade in {"good", "fair"}
+ and connector_grade in {"good", "fair"}
and sample.ha_connections == 4
and errors_per_minute < 3
and loss_per_minute < 10
@@ -299,12 +601,16 @@ class QualityEvaluator:
self._last_baseline_minute = minute
baseline = self.baseline(current_time)
+ if state == "healthy":
+ self._record_request_baseline(request_path, protocol=protocol, now=current_time)
+
snapshot = {
- "schema_version": 1,
+ "schema_version": 2,
"state": state,
"grade": grade,
"sampled_at": utc_timestamp(current_time),
- "protocol": "quic" if rtt is not None else "http2" if sample.ready else "unknown",
+ "protocol": protocol,
+ "transport": {"configured": configured_protocol, "effective": protocol},
"connector_count": max(0, connector_count),
"ha_connections": min(4, sample.ha_connections),
"rtt_ms": rtt,
@@ -313,6 +619,7 @@ class QualityEvaluator:
"window_seconds": RATE_WINDOW_SECONDS,
"request_errors_per_minute": errors_per_minute,
"packet_loss_per_minute": loss_per_minute,
+ "request_path": request_path,
"recovery": recovery_payload,
}
self._last_snapshot = snapshot
@@ -326,6 +633,8 @@ class QualityEvaluator:
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"
+ if request_path_is_degraded(current.get("request_path")):
+ return "tail_latency"
rtt = current.get("rtt_ms")
if not isinstance(rtt, dict):
return None
@@ -350,6 +659,12 @@ def empty_recovery() -> dict[str, Any]:
"last_result": None,
"previous_median_rtt_ms": None,
"result_median_rtt_ms": None,
+ "previous_protocol": None,
+ "result_protocol": None,
+ "previous_p95_ms": None,
+ "result_p95_ms": None,
+ "previous_p99_ms": None,
+ "result_p99_ms": None,
"next_attempt_at": None,
"attempt_count_window": 0,
}
@@ -364,6 +679,14 @@ def candidate_is_better(active: dict[str, Any], candidate: dict[str, Any], *, tr
return False
if trigger == "availability" and int(active.get("ha_connections") or 0) < 4:
return True
+ if trigger == "tail_latency":
+ active_path = active.get("request_path")
+ candidate_path = candidate.get("request_path")
+ return (
+ isinstance(active_path, dict)
+ and isinstance(candidate_path, dict)
+ and request_path_is_better(active_path, candidate_path)
+ )
active_rtt = active.get("rtt_ms")
candidate_rtt = candidate.get("rtt_ms")
if trigger == "errors":