Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(socket): stop the reconnect counter reporting past its own maximum

M3gA-Mindacb28e50d1d2
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop.rs b/crates/openhuman-core/src/platform/socket/ws_loop.rs
index 418f1bf237..816833192c 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop.rs
@@ -26,8 +26,8 @@ use connect::{
use dispatch::{handle_eio_message, handle_sio_packet, parse_sio_ack};
#[cfg(test)]
use reconnect::{
- decide_after_invalid_token, drain_pending_emits, log_connection_failure, InvalidTokenAction,
- FAIL_ESCALATE_THRESHOLD,
+ decide_after_invalid_token, drain_pending_emits, log_connection_failure, render_attempt_line,
+ InvalidTokenAction, FAIL_ESCALATE_THRESHOLD,
};
#[cfg(test)]
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
index b58bb7c05f..4f98e3c20f 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/connect.rs
@@ -62,6 +62,12 @@ pub(super) struct ReconnectContext {
pub(super) lost_previous: bool,
/// Attempts that ended in `ConnectionOutcome::Failed` since the outage began.
pub(super) failed_attempts: u32,
+ /// Whether this outage already fired the one-shot sustained-outage
+ /// escalation (`FAIL_ESCALATE_THRESHOLD`). The escalation fires while the
+ /// socket is still down, so it cannot know how long the outage lasted;
+ /// this flag is what lets the recovery report that duration, and only for
+ /// an outage that actually paged (#6417).
+ pub(super) escalated: bool,
}
// ---------------------------------------------------------------------------
@@ -159,7 +165,7 @@ pub(super) async fn run_connection(
*emit_ready.lock() = true;
emit_state_change(shared);
if let Some(started) = reconnect.outage_started {
- log::info!(
+ let line = format!(
"[socket] {} after {:.1}s ({} failed attempt(s))",
if reconnect.lost_previous {
"Reconnected"
@@ -169,6 +175,35 @@ pub(super) async fn run_connection(
started.elapsed().as_secs_f64(),
reconnect.failed_attempts
);
+ if reconnect.escalated {
+ // This outage already paged (one `error` at
+ // `FAIL_ESCALATE_THRESHOLD`), and that event could not carry a
+ // duration because the socket was still down when it fired. Close
+ // it out with the duration now that it is known — the missing half
+ // of #6417. Gated on `escalated` so the volume stays bounded: an
+ // outage that never crossed the threshold stays at `info`, and one
+ // that did produces exactly two events, never one per retry (the
+ // OPENHUMAN-TAURI-8M storm this threshold exists to prevent).
+ //
+ // An offline user never reaches here at all: their escalation was
+ // demoted to a breadcrumb, so `escalated` stayed false. Still
+ // routed through the classifier rather than `report_error` so a
+ // future expected-shape added there applies to both halves of the
+ // pair, instead of silently reporting only the recovery.
+ let attempts = reconnect.failed_attempts.to_string();
+ let outage_secs = format!("{:.0}", started.elapsed().as_secs_f64());
+ crate::core::observability::report_error_or_expected(
+ line.as_str(),
+ "socket",
+ "ws_reconnect",
+ &[
+ ("attempts", attempts.as_str()),
+ ("outage_s", outage_secs.as_str()),
+ ],
+ );
+ } else {
+ log::info!("{line}");
+ }
}
// 7. Main event loop
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
index 4183675b44..29d01520d2 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop/reconnect.rs
@@ -221,6 +221,7 @@ pub(crate) async fn ws_loop(
outage_started: Some(Instant::now()),
lost_previous: true,
failed_attempts: 0,
+ escalated: false,
};
}
ConnectionOutcome::Failed(_) => {
@@ -287,7 +288,11 @@ pub(crate) async fn ws_loop(
retried once this cycle — escalating to normal backoff path"
);
consecutive_failures = consecutive_failures.saturating_add(1);
- log_connection_failure(consecutive_failures, &reason);
+ reconnect.escalated |= log_connection_failure(
+ consecutive_failures,
+ reconnect.outage_started.map(|t| t.elapsed()),
+ &reason,
+ );
// Fall through to the backoff sleep below.
// Intentionally drop `fresh` here: the bounded
// path now demands a backoff sleep, after which
@@ -338,7 +343,11 @@ pub(crate) async fn ws_loop(
}
ConnectionOutcome::Failed(reason) => {
consecutive_failures = consecutive_failures.saturating_add(1);
- log_connection_failure(consecutive_failures, &reason);
+ reconnect.escalated |= log_connection_failure(
+ consecutive_failures,
+ reconnect.outage_started.map(|t| t.elapsed()),
+ &reason,
+ );
// keep growing backoff
}
}
@@ -392,9 +401,16 @@ pub(crate) async fn ws_loop(
/// - Above the threshold: `warn` — already paged once; avoid unbounded events
/// during a long outage.
///
+/// Returns whether this call fired the one-shot escalation, so the caller can
+/// remember that the outage paged and report its duration on recovery (#6417).
+///
/// Extracted as a pure function so it can be unit-tested without running an
/// async event loop or touching the WS stack.
-pub(super) fn log_connection_failure(consecutive: u32, reason: &str) {
+pub(super) fn log_connection_failure(
+ consecutive: u32,
+ outage: Option<Duration>,
+ reason: &str,
+) -> bool {
if consecutive == FAIL_ESCALATE_THRESHOLD {
// Route the one-shot sustained-outage escalation through the
// observability classifier so an offline user (no wifi / airplane mode
@@ -414,16 +430,57 @@ pub(super) fn log_connection_failure(consecutive: u32, reason: &str) {
"ws_connect",
&[("attempts", attempts.as_str())],
);
+ // Report the outage as "paged" only if the classifier actually let the
+ // event through. An offline user (`Network is unreachable`, airplane
+ // mode — OPENHUMAN-TAURI-BH) is demoted to a warn breadcrumb here, and
+ // claiming otherwise would make the recovery report in
+ // `run_connection` fire a Sentry event on the way back up — the same
+ // noise, moved one step later. Pairing on the *reported* escalation
+ // keeps it at exactly two events for a genuine outage and zero for a
+ // user who simply closed their laptop lid.
+ crate::core::observability::expected_error_kind(&detailed).is_none()
} else {
// Below threshold (transient blips) or above threshold (already fired
// the one-shot error): stay at `warn` so subsequent retries don't pile
// up additional Sentry events.
- log::warn!(
- "[socket] Connection failed (attempt {}/{}): {}",
- consecutive,
- FAIL_ESCALATE_THRESHOLD,
- reason
- );
+ log::warn!("{}", render_attempt_line(consecutive, outage, reason));
+ false
+ }
+}
+
+/// Render the `warn`-level line for a failed attempt.
+///
+/// `FAIL_ESCALATE_THRESHOLD` is the point at which the loop *pages*, not a cap
+/// on retries — the loop retries forever by design. Printing it as the
+/// denominator of every attempt is what produced `attempt 32/5` in #6417: a
+/// counter apparently past its own maximum, which reads as a bug in the loop
+/// rather than the intended behaviour.
+///
+/// So the denominator is only shown while it is still true. Past the threshold
+/// the line drops it and reports what actually matters during a long outage —
+/// how long the socket has been down — which is also what the reporter asked
+/// for. Duration is in seconds to match the `Connected after …` line that
+/// closes the outage out in `run_connection`.
+///
+/// A pure `String` so the wording is directly assertable without a tracing
+/// capture layer.
+pub(super) fn render_attempt_line(
+ consecutive: u32,
+ outage: Option<Duration>,
+ reason: &str,
+) -> String {
+ if consecutive <= FAIL_ESCALATE_THRESHOLD {
+ format!("[socket] Connection failed (attempt {consecutive}/{FAIL_ESCALATE_THRESHOLD}): {reason}")
+ } else {
+ match outage {
+ Some(down) => format!(
+ "[socket] Connection failed (attempt {consecutive}, still retrying after {:.0}s down): {reason}",
+ down.as_secs_f64()
+ ),
+ None => format!(
+ "[socket] Connection failed (attempt {consecutive}, still retrying): {reason}"
+ ),
+ }
}
}
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs b/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs
index e0a0fcec14..3b9d74ccad 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop_dispatch_and_redirect_tests.rs
@@ -306,7 +306,7 @@ fn handle_sio_packet_unknown_type_is_noop() {
fn log_connection_failure_does_not_panic_below_threshold() {
// Calls 1 through threshold-1 stay at warn — must complete without panic.
for i in 1..FAIL_ESCALATE_THRESHOLD {
- log_connection_failure(i, "simulated transient failure");
+ log_connection_failure(i, None, "simulated transient failure");
}
}
@@ -314,7 +314,7 @@ fn log_connection_failure_does_not_panic_below_threshold() {
fn log_connection_failure_does_not_panic_at_and_above_threshold() {
// Calls at and above threshold escalate to error — must also not panic.
for i in FAIL_ESCALATE_THRESHOLD..=FAIL_ESCALATE_THRESHOLD + 3 {
- log_connection_failure(i, "simulated sustained failure");
+ log_connection_failure(i, None, "simulated sustained failure");
}
}
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_reconnect_tests.rs b/crates/openhuman-core/src/platform/socket/ws_loop_reconnect_tests.rs
index 50555f40fe..75428c8d7f 100644
--- a/crates/openhuman-core/src/platform/socket/ws_loop_reconnect_tests.rs
+++ b/crates/openhuman-core/src/platform/socket/ws_loop_reconnect_tests.rs
@@ -4,6 +4,7 @@ use crate::platform::socket::token_provider::TokenProvider;
use crate::platform::socket::types::ConnectionStatus;
use futures_util::StreamExt;
use std::sync::Arc;
+use std::time::Duration;
use tokio::sync::mpsc;
use tokio::sync::watch;
use tokio_tungstenite::tungstenite::Error as WsError;
@@ -540,3 +541,198 @@ fn draining_an_empty_channel_reports_nothing_dropped() {
let (_tx, mut rx) = mpsc::unbounded_channel::<String>();
assert_eq!(drain_pending_emits(&mut rx), 0);
}
+
+// ── #6417: the attempt counter and the one-shot outage escalation ──────────
+
+/// Pull the `N` and `M` out of an `attempt N/M` fragment, if the line has one.
+///
+/// `None` means the line carries no `N/M` fraction at all, which is the
+/// post-fix shape past the threshold.
+fn parsed_attempt_fraction(line: &str) -> Option<(u32, u32)> {
+ let rest = line.split_once("(attempt ")?.1;
+ let fraction = rest.split_once(')')?.0;
+ let (n, m) = fraction.split_once('/')?;
+ Some((n.trim().parse().ok()?, m.trim().parse().ok()?))
+}
+
+/// Guard on the guard: `parsed_attempt_fraction` must actually parse the shape
+/// the bug produced, so the assertion in
+/// `attempt_line_never_reports_more_attempts_than_its_maximum` cannot pass
+/// vacuously by returning `None` for every line it is handed.
+#[test]
+fn attempt_fraction_parser_reads_the_reported_bug_shape() {
+ assert_eq!(
+ parsed_attempt_fraction("[socket] Connection failed (attempt 32/5): boom"),
+ Some((32, 5)),
+ "the parser must recognise the `attempt 32/5` shape from #6417, or the \
+ counter assertion silently tests nothing"
+ );
+ assert_eq!(
+ parsed_attempt_fraction("[socket] Connection failed (attempt 3/5): boom"),
+ Some((3, 5))
+ );
+ assert_eq!(
+ parsed_attempt_fraction(
+ "[socket] Connection failed (attempt 32, still retrying after 844s down): boom"
+ ),
+ None,
+ "a line with no fraction has nothing to compare"
+ );
+}
+
+/// #6417 acceptance criterion 1: `attempt N/M` never shows N > M.
+///
+/// `FAIL_ESCALATE_THRESHOLD` is a paging threshold, not a retry cap — the loop
+/// retries forever — so printing it as a denominator produced the reported
+/// `attempt 32/5`. Past the threshold the line must stop claiming a maximum
+/// it does not honour.
+#[test]
+fn attempt_line_never_reports_more_attempts_than_its_maximum() {
+ // Alan's log reached attempt 32 over a 14-minute outage; go well past it.
+ for consecutive in 1..=40u32 {
+ let line = render_attempt_line(
+ consecutive,
+ Some(Duration::from_secs(u64::from(consecutive) * 30)),
+ "WebSocket connect: IO error: Network is unreachable (os error 51)",
+ );
+ if let Some((n, m)) = parsed_attempt_fraction(&line) {
+ assert!(
+ n <= m,
+ "attempt {n}/{m} reports more attempts than its own maximum \
+ (#6417) — rendered line: {line}"
+ );
+ }
+ }
+}
+
+/// The reported `attempt 32/5` shape specifically: once the streak is past the
+/// threshold the line carries the bare attempt count and how long the socket
+/// has been down, which is the diagnostic the reporter actually wanted.
+#[test]
+fn attempt_line_past_the_threshold_drops_the_denominator_for_the_outage() {
+ let line = render_attempt_line(32, Some(Duration::from_secs(844)), "connection refused");
+ assert!(
+ !line.contains(&format!("32/{FAIL_ESCALATE_THRESHOLD}")),
+ "line still prints the paging threshold as a retry cap (#6417): {line}"
+ );
+ assert!(
+ line.contains("attempt 32") && line.contains("844s"),
+ "line should report the attempt count and the outage duration: {line}"
+ );
+
+ // Inside the threshold the fraction is still true, so it stays.
+ let early = render_attempt_line(3, None, "connection refused");
+ assert!(
+ early.contains(&format!("attempt 3/{FAIL_ESCALATE_THRESHOLD}")),
+ "within the threshold the fraction is accurate and should remain: {early}"
+ );
+}
+
+/// #6417 second symptom: one sustained-outage escalation per outage, however
+/// long the outage runs. The equality test against the threshold is deliberate
+/// (OPENHUMAN-TAURI-8M: 549 Sentry events from one gateway 503) — this pins
+/// that it fires exactly once across a streak far past the threshold, so a
+/// later change to `>=` cannot silently reintroduce the storm.
+#[test]
+fn sustained_outage_escalates_exactly_once_across_a_long_streak() {
+ let escalations = (1..=40u32)
+ .filter(|&consecutive| {
+ log_connection_failure(
+ consecutive,
+ Some(Duration::from_secs(u64::from(consecutive) * 30)),
+ "WebSocket connect: HTTP 503 Service Unavailable",
+ )
+ })
+ .count();
+
+ assert_eq!(
+ escalations, 1,
+ "a 40-attempt outage must page exactly once, not {escalations} times \
+ (OPENHUMAN-TAURI-8M)"
+ );
+}
+
+/// The escalation is only reported as "paged" when the observability
+/// classifier actually lets it through. An offline user's outage demotes to a
+/// warn breadcrumb, so their *recovery* must not report either — otherwise the
+/// OPENHUMAN-TAURI-BH noise returns through the recovery path instead of the
+/// failure path.
+#[test]
+fn offline_user_outage_does_not_arm_the_recovery_report() {
+ let offline = "WebSocket connect: IO error: Network is unreachable (os error 51)";
+ assert!(
+ !log_connection_failure(
+ FAIL_ESCALATE_THRESHOLD,
+ Some(Duration::from_secs(60)),
+ offline
+ ),
+ "an offline user's escalation is demoted to a breadcrumb, so it must not \
+ arm the recovery Sentry report (OPENHUMAN-TAURI-BH)"
+ );
+
+ let genuine = "WebSocket connect: HTTP 503 Service Unavailable";
+ assert!(
+ log_connection_failure(
+ FAIL_ESCALATE_THRESHOLD,
+ Some(Duration::from_secs(60)),
+ genuine
+ ),
+ "a genuine outage escalation reaches Sentry and must arm the recovery report"
+ );
+}
+
+/// End-to-end reproduction of the log excerpt in #6417.
+///
+/// Alan's report is a 14-minute Wi-Fi outage that produced, every 30 s:
+///
+/// ```text
+/// 12:24:42 WRN [socket] Connection failed (attempt 1/5) …
+/// 12:25:37 ERR socket.ws_connect failed: … (sustained outage after 5 attempts)
+/// 12:26:07 WRN [socket] Connection failed (attempt 6/5) …
+/// 12:39:07 WRN [socket] Connection failed (attempt 32/5) …
+/// ```
+///
+/// This replays that streak through the two functions that actually emit it
+/// and asserts the reported symptoms are gone: no line claims more attempts
+/// than its maximum, and the 32-attempt outage pages exactly once. Run with
+/// `--nocapture` to read the rendered lines directly.
+#[test]
+fn reproduces_the_6417_outage_without_either_reported_symptom() {
+ let reason = "WebSocket connect: IO error: Network is unreachable (os error 51)";
+ let mut escalations = 0usize;
+ let mut rendered = Vec::new();
+
+ // 32 attempts, one every 30 s — the shape and duration Alan reported.
+ for attempt in 1..=32u32 {
+ let outage = Duration::from_secs(u64::from(attempt) * 30);
+ if log_connection_failure(attempt, Some(outage), reason) {
+ escalations += 1;
+ println!("attempt {attempt:>2}: ESCALATED (one-shot sustained-outage report)");
+ } else {
+ let line = render_attempt_line(attempt, Some(outage), reason);
+ println!("attempt {attempt:>2}: {line}");
+ rendered.push(line);
+ }
+ }
+
+ // Symptom 1: `attempt 32/5`. No rendered line may claim a maximum it has
+ // already exceeded.
+ for line in &rendered {
+ if let Some((n, m)) = parsed_attempt_fraction(line) {
+ assert!(n <= m, "#6417 symptom 1 still present: {line}");
+ }
+ }
+ assert!(
+ !rendered.iter().any(|l| l.contains("attempt 32/5")),
+ "#6417 symptom 1 still present: a line reads `attempt 32/5`"
+ );
+
+ // Symptom 2: the offline shape is demoted, so this outage must page zero
+ // times. `sustained_outage_escalates_exactly_once_across_a_long_streak`
+ // covers the genuine-outage case that pages exactly once.
+ assert_eq!(
+ escalations, 0,
+ "an offline user's outage must not page at all (OPENHUMAN-TAURI-BH), \
+ got {escalations} escalation(s)"
+ );
+}