Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 163 additions & 6 deletions pkgs/id/src/foreign_libsql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release the half-open reservation when its query is cancelled

If a caller cancels a half-open query() while it awaits post_pipeline, the future is dropped before any success or failure recorder executes. The breaker consequently stays HalfOpen, and this branch rejects every subsequent query for that alias permanently—even after the cooldown or server recovery, since only Open has a timed transition. The transport's internal timeout cannot help once its future is dropped. Use a drop guard to reopen or release the half-open reservation when the admitted query is cancelled.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in this PR (task 17206, lane any-d) — thank you, the finding is correct.

query() now holds a HalfOpenProbeGuard for the rest of each admitted attempt: if the future is dropped before the attempt records an outcome — the cancellation case you describe, while awaiting post_pipeline — the guard's Drop calls record_probe_failure, re-opening the breaker and restarting the cooldown instead of stranding it in HalfOpen. The guard is a no-op when an outcome was recorded (every record_* path moves the state out of HalfOpen first), and it is only created after this attempt's own admission, so it cannot release another call's probe.

Tests (both levels, per the finding):

  • test_half_open_probe_guard_reopens_on_drop — breaker level: admit a probe, drop the guard unrecorded, assert the restarted cooldown refuses an immediate probe and admits one after the full delay; a guard dropped after a recorded success is a no-op.
  • test_cancelled_half_open_probe_reopens_breaker — adapter level: a never-completing transport, the admitted probe task is aborted mid-await; the breaker is Open (not HalfOpen) afterwards and the next call gets CircuitOpen from the restarted cooldown.

Verified: cargo test --manifest-path pkgs/id/Cargo.toml --lib -- circuit_breaker half_open probe — all matched tests pass, including the pre-existing state-machine test; rustfmt clean.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
BreakerState::Open { since } => {
if now.duration_since(since) >= BREAKER_HALF_OPEN_AFTER {
*state = BreakerState::HalfOpen;
Expand Down Expand Up @@ -959,6 +960,32 @@ 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 };
}
}
}

/// 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());
}
}

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -1039,8 +1066,20 @@ impl<T: Transport, C: CredentialResolver> LibsqlAdapter<T, C> {
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 = 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(
Expand Down Expand Up @@ -1072,11 +1111,15 @@ impl<T: Transport, C: CredentialResolver> LibsqlAdapter<T, C> {
}
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);
}
}
}
}
Expand Down Expand Up @@ -1707,8 +1750,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();
Expand All @@ -1719,11 +1762,125 @@ 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));
}

/// 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<usize>,
}

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<Box<dyn Future<Output = Result<TransportResponse, TransportError>> + 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
Expand Down