Skip to content

feat(cache): add per-origin half-open circuit-breaker for pull-through (#963) - #986

Merged
thiras merged 4 commits into
mainfrom
feat/963-origin-circuit-breaker
Jun 25, 2026
Merged

thiras merged 4 commits into
mainfrom
feat/963-origin-circuit-breaker

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

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.

  • CLOSED — requests flow into the retry loop; consecutive origin-unavailable failures counted. On reaching failure_threshold, trips to OPEN. Any success (or a permanent per-object answer like 404) resets the count.
  • OPEN — every miss fast-fails before the retry/backoff loop runs (no backoff incurred, origin not even called) until cooldown_ms elapses, then the next acquire transitions to HALF-OPEN.
  • HALF-OPEN — admits up to half_open_max_calls trial 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 existing OriginPullError Permanent-vs-Transient taxonomy via a new TerminalFailure classification 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 spurious NotFound.

Defaults chosen

Knob Default Rationale
enabled true Breaker on by default
failure_threshold 5 High enough to ride out a single flaky request, low enough to trip within a handful of misses during a real outage [judgment call — tune for your origin's flakiness]
cooldown_ms 30_000 (30s) Long enough to shed the retry-storm, short enough to resume promptly [judgment call]
half_open_max_calls 1 Standard single-probe half-open recipe

enabled = false (or failure_threshold = 0) opts out and reproduces pre-#963 behaviour exactly. Surfaced via cache.circuit_breaker in the config schema (CircuitBreakerPolicy in the config-types leaf crate), with #[serde(default)] partial sections and a config-resolve invariant rejecting half_open_max_calls = 0 on an active breaker (it could never probe recovery).

Proving fast-fail incurs no backoff

Two independent integration tests:

  1. Call counter — while OPEN, the origin's fetch count must not move (short-circuit happens before the fetch), and the short-circuit metric is bumped.
  2. Paused-clock + timeout — a 60s-backoff retry policy under a paused Tokio clock: the OPEN miss must resolve without registering a backoff timer (a leaked retry would register a 60s timer and the tokio::time::timeout — on the same paused clock — would fire).

Tests

  • State machine (unit, 12 tests, manual clock): closed→open on threshold, success resets count, open short-circuits until cooldown, half-open success→closed, half-open failure→open, half-open trial-concurrency cap, multi-trial config, 404 never trips, disabled/zero-threshold inactive, metric counters.
  • Engine integration (7 tests, injected ManualClock): open-then-fast-fail-no-backoff, 60s-backoff-skipped, half-open recovery through get, 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).
  • Config resolver (5 tests): defaults, full/partial section, disabled skips half-open invariant, rejects active zero half-open.

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, and cargo nextest run all green across decdn-cache (227), decdn-config-types/decdn-common (641 combined), and decdn-node/decdn-cli (901). Anti-panic clippy clean (no unwrap/expect/panic/indexing in the state machine).

Note: a separate PR (#962, range pull-through) touches the same crates/cache engine concurrently; implemented cleanly for merge-time reconciliation.

🤖 Generated with Claude Code

#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]>
Copilot AI review requested due to automatic review settings June 24, 2026 13:58

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread crates/cache/src/circuit_breaker.rs Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 OriginBreaker state machine (CLOSED/OPEN/HALF-OPEN) and wires it into CacheEngine pull-through across fallback origins.
  • Adds CircuitBreakerPolicy to 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.

Comment thread crates/cache/src/engine.rs Resolved
Comment thread crates/cache/src/engine.rs Resolved
…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]>
@github-actions

github-actions Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 83.67% (was 83.55%, ▲ +0.12%) — 41393/49470 lines

File Coverage Lines Δ
crates/cache/src/circuit_breaker.rs 96.82% 335/346 new
crates/cache/src/engine.rs 90.89% 2045/2250 ▼ 0.35%
crates/cache/src/lib.rs 100.00% 28/28 ● 0.00%
crates/cache/src/retry.rs 80.26% 187/233 ▼ 4.25%
crates/common/src/config/mod.rs 96.96% 6325/6523 ▲ +0.01%
crates/common/src/config/resolved.rs 100.00% 48/48 ● 0.00%
crates/config-types/src/circuit_breaker.rs 100.00% 60/60 new
crates/node/src/metrics.rs 83.04% 862/1038 ▲ +0.12%
crates/node/src/runtime/mod.rs 49.76% 927/1863 ▲ +0.05%
crates/node/src/runtime/reload.rs 95.24% 1460/1533 ▲ +0.01%
History
Commit Total Δ vs base
4a93754 83.73% ▲ +0.12%
e2ab649 (HEAD) 83.67% ▲ +0.12%

thiras and others added 2 commits June 25, 2026 23:34
…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]>
@thiras
thiras merged commit afc513b into main Jun 25, 2026
20 checks passed
@thiras
thiras deleted the feat/963-origin-circuit-breaker branch June 25, 2026 20:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants