Repository navigation
feat(cache): add per-origin half-open circuit-breaker for pull-through (#963) - #986
Conversation
#963) When an origin was fully unavailable, every cache miss ran the full retry cycle (up to 3 retries, exponential backoff to 10s), serializing that backoff cost across all concurrent misses with no way to fast-fail until the origin recovered. Add a per-origin half-open circuit-breaker fronting each origin's pull-through retry loop: - CLOSED: requests flow; consecutive origin-unavailable failures counted. - OPEN: after `failure_threshold` failures, fast-fail every miss for `cooldown_ms` BEFORE the retry/backoff loop runs — no backoff incurred, origin not even called. - HALF-OPEN: after the cooldown, admit `half_open_max_calls` trial pulls; a trial success closes the breaker, a failure re-opens it. Only transient/origin-unavailable failures (transient exhausting the retry budget) trip the breaker; permanent per-object errors (404 -> NotFound, other 4xx/decode/cap) are recorded as "available" and never trip it. Keyed per-origin by index, parallel to the fallback chain. Config surfaced via `cache.circuit_breaker` (CircuitBreakerPolicy in the config-types leaf crate), defaults: enabled, threshold 5, 30s cooldown, 1 half-open trial. Three new metrics: circuit_breaker_{trips,recoveries, short_circuits}. Clock is injected (SystemClock prod / ManualClock tests) so the cooldown state machine is tested deterministically without sleeps. cache stays a leaf crate (no mode branching). Tests cover closed->open, fast-fail-with-no-backoff (call-counter + paused-clock + timeout), half-open recovery and re-open, 404-does-not-trip, and concurrency. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a per-origin half-open circuit-breaker mechanism to prevent retry-backoff storms during sustained origin outages. It adds the circuit_breaker module, integrates it into the CacheEngine pull-through path, exposes new OpenMetrics counters, and updates configuration types and validation. A critical feedback item highlights an async cancellation vulnerability where half_open_in_flight slots can leak if a future is cancelled before record is called, recommending an RAII guard to ensure cancellation safety.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
Adds a per-origin half-open circuit-breaker to the cache pull-through path to fast-fail cache misses during sustained origin outages (avoiding retry/backoff storms), with config wiring, metrics, and integration/unit tests.
Changes:
- Introduces
OriginBreakerstate machine (CLOSED/OPEN/HALF-OPEN) and wires it intoCacheEnginepull-through across fallback origins. - Adds
CircuitBreakerPolicyto the config-types vocabulary and resolves it through common/node configuration into cache engine construction. - Adds new OpenMetrics counters for breaker trips/recoveries/short-circuits plus extensive unit + integration test coverage.
Reviewed changes
Copilot reviewed 18 out of 18 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/tests/sighup_signal.rs | Updates resolved config seeding to include circuit_breaker default. |
| crates/node/src/runtime/reload.rs | Includes circuit_breaker default in runtime reload seed + tests. |
| crates/node/src/runtime/mod.rs | Passes resolved circuit_breaker policy into cache engine construction. |
| crates/node/src/metrics.rs | Pins exported circuit-breaker metric names in metrics tests; updates cache open call signature. |
| crates/config-types/src/lib.rs | Adds circuit breaker module and re-exports CircuitBreakerPolicy. |
| crates/config-types/src/circuit_breaker.rs | Implements operator-facing CircuitBreakerPolicy value type + serde defaults and tests. |
| crates/common/src/config/types.rs | Adds optional cache.circuit_breaker to file config schema with docs. |
| crates/common/src/config/resolved.rs | Adds resolved circuit_breaker policy to ResolvedCache. |
| crates/common/src/config/mod.rs | Resolves circuit breaker defaults + validates half-open invariant; adds resolver tests. |
| crates/cli/tests/config_validate.rs | Updates sample resolved config to include circuit_breaker default. |
| crates/cache/tests/s3_origin.rs | Updates engine construction to pass circuit breaker policy. |
| crates/cache/tests/pull_through.rs | Updates engine construction helper calls to pass circuit breaker policy. |
| crates/cache/tests/circuit_breaker.rs | New integration tests proving fast-fail avoids origin fetch/backoff and validates recovery + concurrency behavior. |
| crates/cache/src/retry.rs | Adds TerminalFailure classification via run_with_retry_classified to drive breaker decisions. |
| crates/cache/src/metrics.rs | Adds circuit-breaker counters to CacheMetrics and updates module docs. |
| crates/cache/src/lib.rs | Exposes new circuit-breaker module and re-exports policy/types needed by callers/tests. |
| crates/cache/src/engine.rs | Stores per-origin breakers, short-circuits pull-through when OPEN, and records breaker outcomes. |
| crates/cache/src/circuit_breaker.rs | New circuit-breaker state machine with injectable clock and unit tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…safe (#963) Address PR #986 review: - Async cancellation slot leak: `acquire` now returns a `TrialGuard` RAII handle that owns any reserved HALF-OPEN trial slot. The guard is held across the pull-through `.await`; if the future is cancelled (client disconnect / timeout) the guard's `Drop` releases the slot without recording a transition, so a cancelled trial reclaims its budget instead of leaking it and wedging the breaker HALF-OPEN forever. `TrialGuard::record` commits the success/failure transition and defuses the guard so there is no double-release. CLOSED admissions carry an owns-no-slot guard; disabled policies an inert one. Adds two tests: one drops an in-flight trial guard and asserts a subsequent trial is admitted (slot reclaimed); one mixes recorded and cancelled trials and asserts the full budget is reclaimed without underflow. - Short-circuit path now bumps `origin_fallback` when it advances the chain (`idx + 1 < total`), matching the non-breaker fallback advance so `decdn_cache_origin_fallback_total` no longer undercounts. - Rewrote the `record_breaker_outcome` doc comment (was a copy/paste mix describing log emission) to describe what it actually does. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Coverage reportTotal: 83.67% (was 83.55%, ▲ +0.12%) — 41393/49470 lines
History
|
…it-breaker # Conflicts: # crates/cache/src/engine.rs
The paused-clock test wrapped the OPEN-breaker miss in a `tokio::time::timeout`. Under `start_paused = true` on a current-thread runtime, `engine.get`'s cross-thread iroh-blobs store I/O momentarily idles the runtime, which then auto-advances the paused clock straight to the timeout deadline and fires it spuriously — even when the breaker correctly short-circuits with no backoff timer. The test failed ~6/8 times in isolation (it passed in full-suite CI only because concurrent tests kept the runtime busy; it surfaced once the merge re-ran it under coverage instrumentation). Replace the `timeout` guard with a paused-clock delta measurement: with no pending timer, an idle runtime has nothing to auto-advance to, so the clock moves only if a retry backoff sleep actually leaks. A short-circuit keeps the delta ~zero; a leaked 60s retry would push it past a backoff interval. Same guarantee (fast-fail incurs no backoff), now deterministic — 20/20 plain and 8/8 under coverage instrumentation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Closes #963
Problem
When an origin is fully unavailable, every cache miss runs the full retry cycle (up to 3 retries with exponential backoff to 10s), serializing that backoff cost across all concurrent misses with no way to fast-fail until the origin recovers.
State machine
A per-origin half-open circuit-breaker (
OriginBreaker) fronts each origin's pull-through retry loop. One breaker per origin in the fallback chain, keyed by index.failure_threshold, trips to OPEN. Any success (or a permanent per-object answer like 404) resets the count.cooldown_mselapses, then the next acquire transitions to HALF-OPEN.half_open_max_callstrial pulls (each running its normal retry budget). A trial success closes the breaker; a trial failure re-opens it and resets the cooldown. Trials beyond the budget fast-fail like OPEN.Failure classification
Only origin-unavailable outcomes (transient failures that exhausted the retry budget) count toward the threshold. Permanent per-object errors — HTTP 404 →
NotFound, other 4xx / decode / cap breaches — are recorded as available (the origin responded, it just can't serve this object) and never trip the breaker. This is derived from the existingOriginPullErrorPermanent-vs-Transient taxonomy via a newTerminalFailureclassification on the retry loop.If an OPEN breaker short-circuits every eligible origin, the miss surfaces a fast
CacheError::OriginError("circuit-breaker open") rather than a spuriousNotFound.Defaults chosen
enabledtruefailure_threshold5cooldown_ms30_000(30s)half_open_max_calls1enabled = false(orfailure_threshold = 0) opts out and reproduces pre-#963 behaviour exactly. Surfaced viacache.circuit_breakerin the config schema (CircuitBreakerPolicyin theconfig-typesleaf crate), with#[serde(default)]partial sections and a config-resolve invariant rejectinghalf_open_max_calls = 0on an active breaker (it could never probe recovery).Proving fast-fail incurs no backoff
Two independent integration tests:
fetchcount must not move (short-circuit happens before the fetch), and the short-circuit metric is bumped.tokio::time::timeout— on the same paused clock — would fire).Tests
ManualClock): open-then-fast-fail-no-backoff, 60s-backoff-skipped, half-open recovery throughget, half-open re-open, 404 never trips, disabled never short-circuits, 50 concurrent misses while OPEN all fast-fail without hitting the origin (guards the coalescing/owner-handoff path).Observability
Three new monotonic counters:
decdn_cache_circuit_breaker_{trips,recoveries,short_circuits}_total.Verification
cargo build,cargo clippy --all-targets -- -D warnings,cargo fmt -- --check, andcargo nextest runall green acrossdecdn-cache(227),decdn-config-types/decdn-common(641 combined), anddecdn-node/decdn-cli(901). Anti-panic clippy clean (no unwrap/expect/panic/indexing in the state machine).🤖 Generated with Claude Code