From ff4052bd36ba0597ef5022aae16e304c1f00f360 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 22:23:27 -0600 Subject: [PATCH 1/2] fix(id): allow one half-open libsql probe --- pkgs/id/src/foreign_libsql.rs | 42 ++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/pkgs/id/src/foreign_libsql.rs b/pkgs/id/src/foreign_libsql.rs index 477f9e6459..1e5b2a370f 100644 --- a/pkgs/id/src/foreign_libsql.rs +++ b/pkgs/id/src/foreign_libsql.rs @@ -925,7 +925,8 @@ impl CircuitBreaker { pub fn allow(&self, now: Instant) -> bool { let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); match *state { - BreakerState::Closed { .. } | BreakerState::HalfOpen => true, + BreakerState::Closed { .. } => true, + BreakerState::HalfOpen => false, BreakerState::Open { since } => { if now.duration_since(since) >= BREAKER_HALF_OPEN_AFTER { *state = BreakerState::HalfOpen; @@ -959,6 +960,15 @@ impl CircuitBreaker { BreakerState::HalfOpen | BreakerState::Open { .. } => BreakerState::Open { since: now }, }; } + + /// Re-open after a half-open probe cannot establish recovery. Other + /// non-transient failures leave a closed breaker unchanged. + fn record_probe_failure(&self, now: Instant) { + let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner()); + if matches!(*state, BreakerState::HalfOpen) { + *state = BreakerState::Open { since: now }; + } + } } // --------------------------------------------------------------------------- @@ -1040,7 +1050,13 @@ impl LibsqlAdapter { return Err(AdapterError::CircuitOpen(alias.to_owned())); } // The token is resolved per attempt and never stored. - let token = self.credentials.resolve(&alias_config.credential_ref)?; + let token = match self.credentials.resolve(&alias_config.credential_ref) { + Ok(token) => token, + Err(error) => { + breaker.record_probe_failure(Instant::now()); + return Err(error); + } + }; let outcome = self .transport .post_pipeline( @@ -1072,11 +1088,15 @@ impl LibsqlAdapter { } Err(AdapterError::Auth { .. }) => { // Fatal and never retried; the token is not in the error. + breaker.record_probe_failure(Instant::now()); return Err(AdapterError::Auth { credential_ref: alias_config.credential_ref.clone(), }); } - Err(error) => return Err(error), + Err(error) => { + breaker.record_probe_failure(Instant::now()); + return Err(error); + } } } } @@ -1707,8 +1727,8 @@ mod tests { } /// Oracle: record item 7 — the breaker opens at the failure - /// threshold, refuses while open, half-opens after the timer, and - /// closes on a successful probe. + /// threshold, refuses while open, grants only one half-open probe, + /// reopens after a failed probe, and closes on a successful probe. #[test] fn test_circuit_breaker_opens_half_opens_and_closes() { let breaker = CircuitBreaker::new(); @@ -1719,7 +1739,17 @@ mod tests { } assert!(!breaker.allow(t0)); assert!(!breaker.allow(t0 + BREAKER_HALF_OPEN_AFTER - Duration::from_secs(1))); - assert!(breaker.allow(t0 + BREAKER_HALF_OPEN_AFTER)); + let probe_at = t0 + BREAKER_HALF_OPEN_AFTER; + assert!(breaker.allow(probe_at)); + assert!(!breaker.allow(probe_at)); + breaker.record_transient_failure(probe_at); + assert!(!breaker.allow(probe_at + BREAKER_HALF_OPEN_AFTER - Duration::from_secs(1))); + let retry_probe_at = probe_at + BREAKER_HALF_OPEN_AFTER; + assert!(breaker.allow(retry_probe_at)); + assert!(!breaker.allow(retry_probe_at)); + breaker.record_probe_failure(retry_probe_at); + assert!(!breaker.allow(retry_probe_at + BREAKER_HALF_OPEN_AFTER - Duration::from_secs(1))); + assert!(breaker.allow(retry_probe_at + BREAKER_HALF_OPEN_AFTER)); breaker.record_success(); assert!(breaker.allow(t0)); } From 48d1073a562639dc1c55200a9572221fbc167e49 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 14:38:24 -0600 Subject: [PATCH 2/2] fix(id): release the half-open probe reservation when a probe is cancelled Codex and CodeRabbit both flagged this on the PR: if the admitted half-open probe was cancelled while awaiting the transport, no outcome was recorded and the breaker stayed HalfOpen forever \u2014 HalfOpen has no timed exit, so every later call for the alias was refused permanently. query() now holds a HalfOpenProbeGuard for the rest of each admitted attempt; dropping the future unrecorded re-opens the breaker via record_probe_failure and restarts the cooldown. The drop is a no-op once an outcome has been recorded, and the guard is created only after the attempt own admission, so it cannot release another call probe. Tests: test_half_open_probe_guard_reopens_on_drop (breaker level, timed) and test_cancelled_half_open_probe_reopens_breaker (adapter level: never-completing transport, admitted probe task aborted mid-await, breaker Open with restarted cooldown). Full foreign_libsql module suite: 23 passed. --- pkgs/id/src/foreign_libsql.rs | 127 ++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/pkgs/id/src/foreign_libsql.rs b/pkgs/id/src/foreign_libsql.rs index 1e5b2a370f..d6de7e7dcd 100644 --- a/pkgs/id/src/foreign_libsql.rs +++ b/pkgs/id/src/foreign_libsql.rs @@ -971,6 +971,23 @@ impl CircuitBreaker { } } +/// Releases a half-open probe reservation when the admitted call ends +/// without recording an outcome — above all when its future is +/// cancelled while awaiting the transport: HalfOpen has no timed exit, +/// so a dropped probe would refuse every later call for the alias +/// forever. The guard re-opens the breaker on drop, which is a no-op +/// unless the state is still HalfOpen, so calls that did record an +/// outcome are unaffected. +struct HalfOpenProbeGuard<'a> { + breaker: &'a CircuitBreaker, +} + +impl Drop for HalfOpenProbeGuard<'_> { + fn drop(&mut self) { + self.breaker.record_probe_failure(Instant::now()); + } +} + // --------------------------------------------------------------------------- // The adapter // --------------------------------------------------------------------------- @@ -1049,6 +1066,12 @@ impl LibsqlAdapter { if !breaker.allow(Instant::now()) { return Err(AdapterError::CircuitOpen(alias.to_owned())); } + // Held for the rest of the attempt: if this future is + // dropped before the attempt records an outcome (caller + // cancellation while awaiting the transport), the guard + // re-opens the breaker instead of stranding the half-open + // probe reservation. + let _probe_guard = HalfOpenProbeGuard { breaker: &breaker }; // The token is resolved per attempt and never stored. let token = match self.credentials.resolve(&alias_config.credential_ref) { Ok(token) => token, @@ -1754,6 +1777,110 @@ mod tests { assert!(breaker.allow(t0)); } + /// Oracle: PR #8848 review finding (Codex and CodeRabbit) — a + /// half-open probe dropped before it records an outcome (a + /// cancelled query future) must not strand the breaker in + /// HalfOpen, which has no timed exit: the probe guard re-opens + /// the breaker and the restarted cooldown admits a later probe. + #[test] + fn test_half_open_probe_guard_reopens_on_drop() { + let breaker = CircuitBreaker::new(); + let t0 = Instant::now(); + for _ in 0..BREAKER_FAILURE_THRESHOLD { + breaker.record_transient_failure(t0); + } + let probe_at = t0 + BREAKER_HALF_OPEN_AFTER; + assert!(breaker.allow(probe_at)); + { + let _guard = HalfOpenProbeGuard { breaker: &breaker }; + // Dropped here with no outcome recorded, exactly as a + // cancelled query future drops it. + } + // The guard re-opened the breaker at drop time (about t0): + // the restarted cooldown refuses a probe until a full delay + // after the drop, then admits one. + assert!(!breaker.allow(probe_at - Duration::from_millis(1))); + assert!(breaker.allow(probe_at + BREAKER_HALF_OPEN_AFTER)); + breaker.record_success(); + // A guard dropped after an outcome was recorded is a no-op: + // the closed breaker stays closed. + drop(HalfOpenProbeGuard { breaker: &breaker }); + assert!(breaker.allow(t0)); + } + + /// Transport whose pipeline call never completes, so a test can + /// cancel a query while it is awaiting the transport. + #[derive(Debug, Default)] + struct PendingTransport { + attempts: StdMutex, + } + + impl PendingTransport { + fn attempts(&self) -> usize { + *self.attempts.lock().unwrap() + } + } + + impl Transport for PendingTransport { + fn post_pipeline<'a>( + &'a self, + base_url: &'a str, + token: &'a str, + body: &'a str, + _connect_timeout: Duration, + _deadline: Duration, + ) -> Pin> + Send + 'a>> + { + *self.attempts.lock().unwrap() += 1; + let _ = (base_url, token, body); + Box::pin(std::future::pending()) + } + } + + /// Oracle: PR #8848 review finding at the adapter level — + /// cancelling the admitted half-open probe while it awaits the + /// transport re-opens the breaker (restarted cooldown) instead of + /// stranding it in HalfOpen forever. + #[tokio::test] + async fn test_cancelled_half_open_probe_reopens_breaker() { + let adapter = LibsqlAdapter::with_parts( + test_config("https://example.invalid"), + PendingTransport::default(), + StaticCredentials, + ); + // Open the breaker with its cooldown already elapsed, so the + // first query is admitted as the half-open probe. + let breaker = adapter.breaker_for("main"); + let past = Instant::now() - BREAKER_HALF_OPEN_AFTER - Duration::from_secs(1); + for _ in 0..BREAKER_FAILURE_THRESHOLD { + breaker.record_transient_failure(past); + } + let adapter = Arc::new(adapter); + let probe = { + let adapter = Arc::clone(&adapter); + tokio::spawn(async move { adapter.query("main", &sample_query()).await }) + }; + // Wait until the probe is inside the transport, then cancel + // it the way a dropped caller future cancels it. + for _ in 0..10_000 { + if adapter.transport.attempts() > 0 { + break; + } + tokio::task::yield_now().await; + } + assert_eq!(adapter.transport.attempts(), 1); + probe.abort(); + let _ = probe.await; + // The guard re-opened the breaker: Open with a restarted + // cooldown, not HalfOpen with a stranded probe reservation. + { + let state = breaker.state.lock().unwrap(); + assert!(matches!(*state, BreakerState::Open { .. })); + } + let error = adapter.query("main", &sample_query()).await.unwrap_err(); + assert_eq!(error, AdapterError::CircuitOpen("main".to_owned())); + } + /// Oracle: record acceptance — the adapter queries a remote libsql /// database over live HTTP. A local TCP listener plays the sqld /// endpoint; the full stack (HttpTransport → pipeline → contract