Skip to content

feat(cache): wire iroh-blobs GC into runtime (#518) - #521

Merged
thiras merged 3 commits into
mainfrom
518-cache-gc-wiring
May 11, 2026
Merged

thiras merged 3 commits into
mainfrom
518-cache-gc-wiring

Conversation

@thiras

@thiras thiras commented May 10, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #518 (the periodic-sweep + metrics half). #520 tracks the
manual on-demand admin RPC, blocked on upstream iroh-blobs exposing
gc_run_once.

After #271's streaming refactor, every mid-stream pull-through failure
(hash mismatch, cap breach, idle timeout, decoder failure) committed
partial bytes to iroh-blobs and dropped the TempTag without
promotion. Without GC running, those bytes leaked for the lifetime of
the process and across restarts (FsStore persists). A hostile origin
streaming max_blob_size_mb - 1 of garbage and erroring on the last
byte could fill the disk over a few thousand requests.

This wires iroh-blobs' built-in GC loop into the runtime via
Options { gc: Some(GcConfig { ... }) } and instruments each cycle via
the add_protected callback hook.

Design

  • Sweep cadence: new cache.gc_interval_sec config field, default
    300s, 0 disables. Threaded through ResolvedCache -> build_cache
    -> CacheEngine::open_full(gc_interval: Duration).
  • Metrics: two new counters on CacheMetrics:
    • gc_runs_total — bumped per cycle once the pre-sweep snapshot
      succeeds.
    • gc_bytes_reclaimed_total — diff of the previous cycle's pre-sweep
      snapshot vs the current cycle's. Hashes that disappeared between
      those two snapshots are exactly what the previous sweep deleted
      (the cache crate has no other public delete path). Attribution
      lags one sweep cycle
      : the first cycle records a baseline and
      bumps zero bytes.
  • Cycle break: Inner.gc_store_handle: Option<Arc<OnceLock<FsStore>>>
    holds the strong Arc; the cb closure captures Weak. On engine
    drop the strong Arc drops, the cb's Weak::upgrade returns None,
    the iroh-blobs actor's last sender drops, the runtime is aborted.
    Without this, the cb -> FsStore clone -> actor -> GC task -> cb
    cycle would pin the iroh-blobs runtime alive past engine drop.
  • Send + Sync dance: iroh-blobs requires the ProtectCb future
    to be Send + Sync, but its own RPC layer (blobs().list().stream(),
    blobs().status(...)) returns futures that are only Send. The cb
    spawns the snapshot work on a tokio task and awaits a
    oneshot::Receiver (which is Send + Sync) so the outer future
    matches iroh-blobs' demanded shape.

Why not a manual admin RPC

iroh_blobs::store::gc::gc_run_once is pub inside a private mod gc;
and not re-exported. Blobs::delete and clear_protected are
pub(crate). The only externally-reachable GC trigger is Options.gc.
#520 tracks the on-demand path, blocked on upstream exposing the sweep
API. The disk-leak threat #518 was filed for is fully addressed by the
periodic sweep — the manual trigger is operator ergonomics.

Test plan

  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo fmt --check clean
  • cargo nextest run --workspace passes (689 tests, 6 new)
  • gc_reclaims_partial_import_bytes — hash-mismatch threat model
  • gc_reclaims_cap_breach_partial_bytes — BlobTooLarge threat model
  • gc_disabled_does_not_reclaim_or_emit_metrics — ZERO-interval branch
  • gc_attribution_lags_one_cycle — locks in the off-by-one design
  • resolve_cache_gc_interval_{defaults_when_absent,from_file_overrides_default,zero_disables} — config plumbing
  • End-to-end smoke against a hostile-origin fixture in staging (manual; can be deferred to cache: expose manual on-demand iroh-blobs GC trigger (blocked on upstream) #520 work)

🤖 Generated with Claude Code

Partial-import bytes from hash-mismatch and mid-stream cap-breach
pull-through paths previously leaked disk indefinitely (the runtime
never invoked iroh-blobs GC). A hostile origin streaming
`max_blob_size_mb - 1` of garbage and erroring on the last byte could
fill disk over a few thousand requests.

Wires iroh-blobs' built-in GC loop via `Options { gc: Some(GcConfig { ... }) }`
in `CacheEngine::open_full`. The `add_protected` callback is the
instrumentation hook: it snapshots the blob set per cycle, diffs against
the previous cycle's snapshot, and bumps `gc_runs_total` /
`gc_bytes_reclaimed_total`. Attribution lags one sweep cycle.

The cb captures `Weak<OnceLock<FsStore>>` (with the strong `Arc` held in
`Inner.gc_store_handle`) so engine drop releases the iroh-blobs runtime
cleanly — without this, the cb -> FsStore clone -> actor -> GC task -> cb
cycle would pin the runtime alive past engine drop.

New `cache.gc_interval_sec` config field, default 300s, `0` disables.

Manual on-demand `decdn admin cache gc` is deferred to #520:
`iroh_blobs::store::gc::gc_run_once` is `pub` inside a private `mod gc;`
and not re-exported, and `Blobs::delete` is `pub(crate)`. The only
externally-reachable trigger is `Options::gc`.

Tests (6 new, 689 total pass):
- gc_reclaims_partial_import_bytes: hash-mismatch threat model
- gc_reclaims_cap_breach_partial_bytes: BlobTooLarge threat model
- gc_disabled_does_not_reclaim_or_emit_metrics: ZERO interval branch
- gc_attribution_lags_one_cycle: locks in the off-by-one design
- resolve_cache_gc_interval_{defaults_when_absent,from_file_overrides_default,zero_disables}

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 10, 2026 15:17
@github-actions

github-actions Bot commented May 10, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 88.28% (was 88.21%, ▲ +0.08%) — 12276/13905 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 92.14% 1173/1273 ▼ 0.18%
crates/cli/src/commands/config.rs 61.60% 77/125 ▲ +0.12%
crates/common/src/admin.rs 69.57% 16/23 ● 0.00%
crates/common/src/config/mod.rs 96.55% 3356/3476 ▲ +0.03%
crates/node/src/admin.rs 95.84% 622/649 ● 0.00%
crates/node/src/metrics.rs 62.67% 183/292 ▲ +1.88%
crates/node/src/runtime/mod.rs 53.81% 388/721 ▲ +0.13%
crates/node/src/runtime/reload.rs 95.17% 1181/1241 ▲ +0.01%
History
Commit Total Δ vs base
cec54f3 88.27% ▲ +0.07%
61e0e74 88.28% ▲ +0.07%
08de26e (HEAD) 88.28% ▲ +0.08%

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

Wires iroh-blobs’ periodic garbage collection into the deCDN cache runtime and plumbs a new cache.gc_interval_sec configuration setting through config resolution, runtime cache construction, and CLI config output, with accompanying tests and new cache GC metrics.

Changes:

  • Add cache.gc_interval_sec (default 300s, 0 disables) and thread it through config resolution into CacheEngine::open_full.
  • Integrate iroh-blobs GC via Options { gc: Some(GcConfig { ... }) } and instrument per-cycle GC metrics.
  • Add tests covering partial-import byte reclamation, disabled-GC behavior, and the “lagged by one cycle” attribution design.

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/cache/src/engine.rs Adds GC wiring into FsStore options, callback instrumentation, and new open_full parameter for GC interval.
crates/cache/src/metrics.rs Introduces two new cache GC counters and updates metric documentation.
crates/cache/tests/pull_through.rs Adds GC reclamation/attribution/disabled-branch tests and updates engine construction calls.
crates/cache/tests/s3_origin.rs Updates engine construction calls to pass a GC interval argument.
crates/common/src/config/types.rs Adds gc_interval_sec to TOML cache config schema.
crates/common/src/config/resolved.rs Adds resolved gc_interval_sec to ResolvedCache.
crates/common/src/config/mod.rs Adds DEFAULT_GC_INTERVAL_SEC and resolves gc_interval_sec from file/default.
crates/common/src/cli/node.rs Updates decdn node evict CLI docs to reference periodic GC sweep behavior/config.
crates/common/src/admin.rs Updates admin RPC docs to reference periodic GC sweep behavior.
crates/cli/src/commands/config.rs Prints gc_interval_sec in config validation summary and documents it in the sample config.
crates/cli/tests/config_validate.rs Updates resolved-config test fixture to include gc_interval_sec.
crates/node/src/runtime/mod.rs Passes configured GC interval into CacheEngine::open_full when building cache.
crates/node/src/runtime/reload.rs Updates resolved-config test fixtures to include gc_interval_sec.
crates/node/tests/sighup_signal.rs Updates resolved-config test fixture to include gc_interval_sec.
crates/node/src/metrics.rs Updates cache-engine construction in metrics tests to pass a GC interval.
crates/node/src/admin.rs Updates test documentation comment to reference the correct tracking issue.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/cache/src/metrics.rs Resolved
Comment thread crates/cache/src/metrics.rs Resolved
Comment thread crates/common/src/config/mod.rs Resolved

@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 implements periodic garbage collection for the iroh-blobs store to prevent disk leakage from partial imports and logical evictions. It introduces a configurable gc_interval_sec setting, wires the GC loop in the cache engine, and adds metrics to track GC runs and reclaimed bytes. Feedback was provided regarding the snapshot_blob_sizes function, which currently performs sequential RPC calls; parallelizing these calls is recommended to avoid performance bottlenecks in environments with a large number of blobs.

Comment thread crates/cache/src/engine.rs Resolved
thiras and others added 2 commits May 10, 2026 18:34
Address review feedback on #521:

- iroh-metrics' OpenMetrics encoder appends `_total` to every Counter
  unconditionally (iroh-metrics-0.38.3/src/encoding.rs:490). Field
  names that already include `_total` get exported as `..._total_total`.
  Rename `gc_runs_total` -> `gc_runs` and `gc_bytes_reclaimed_total`
  -> `gc_bytes_reclaimed`. Exported names stay `decdn_cache_gc_runs_total`
  and `decdn_cache_gc_bytes_reclaimed_total`. (Copilot review.)

- Reword `DEFAULT_GC_INTERVAL_SEC` doc: the previous "leak up to
  gc_interval_sec * max_blob_size_mb" formula was dimensionally wrong
  (seconds * MB). The actual bound is per-request: a single failed
  pull-through orphans up to `max_blob_size_mb`; a stream of failures
  inside one interval compounds as `requests_in_window * max_blob_size_mb`.
  (Copilot review.)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address second-round review feedback on #521:

- code-reviewer: cycle-break docs overstated what `Weak<OnceLock<FsStore>>`
  achieves. iroh-blobs `run_gc(store: Store, ...)` owns its own `Store`
  clone for the lifetime of its loop, so the actor + runtime stay
  resident until process exit (or `gc_run_once` Err). The `Weak` ensures
  the cb body no-ops past engine drop and contributes no strong ref —
  it does not, on its own, shut the iroh-blobs runtime down. Reworded
  `Inner.gc_store_handle` and `gc_protect_callback` docs accordingly,
  with a forward reference to #520. Added an INVARIANT note that no
  `Arc::clone` of `gc_store_handle` may escape `Inner`.

- comment-analyzer: the GC orphan-rate alert framing was wrong.
  `pull_through_bytes` is bumped per chunk regardless of mid-stream
  failure (#418), so in the hostile-origin scenario almost every byte
  pulled is later reclaimed by GC and the ratio approaches 1.0 — not
  "nonzero numerator vs zero denominator". Rewrote as a high-ratio
  alert. Standardized all four ratio formulas to use the
  encoder-suffixed exported names so operators can paste PromQL
  verbatim.

- comment-analyzer: `gc_disabled_does_not_reclaim_or_emit_metrics` test
  doc referenced `if !gc_interval.is_zero()` but the actual code is
  `if gc_interval.is_zero() { None } else { Some(...) }`. Fixed the
  reference to match the source.

- pr-test-analyzer (Critical): no test asserted the GC counters appear
  in the OpenMetrics scrape output with the encoder-appended `_total`
  suffix. The rename was specifically motivated by encoder behavior;
  a regression that re-renamed the field to include `_total` would
  emit `..._total_total` and break dashboards but pass every existing
  test. Added `decdn_cache_gc_runs_total` /
  `decdn_cache_gc_bytes_reclaimed_total` to
  `cache_metrics_counters_start_at_zero` (zero-state) and
  `cache_metrics_handle_shares_atomic_with_registered_group`
  (post-bump), locking in the round-trip both at construction and
  after metric writes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras requested a review from alpergundogdu May 10, 2026 16:32
@alpergundogdu

Copy link
Copy Markdown
Contributor

Code review

No blocking issues. Two sub-threshold observations:

  1. gc_attribution_lags_one_cycle has a small race window — once the poll observes gc_runs >= 1, cycle 2 can fire before the immediate gc_bytes_reclaimed == 0 assertion reads. The 500ms interval gives generous slack, but nothing synchronizes the read against cycle 2 on a slow CI host. Probably fine in practice.

// Poll for cycle 1 to fire. The cb bumps gc_runs_total once per
// sweep, so the transition 0 -> 1 marks cycle 1 completion.
let cycle1_deadline = std::time::Instant::now() + gc_interval * 4;
while metrics.gc_runs.get() < 1 {
anyhow::ensure!(
std::time::Instant::now() < cycle1_deadline,
"cycle 1 did not fire within {}ms",
(gc_interval * 4).as_millis()
);
tokio::time::sleep(Duration::from_millis(20)).await;
}
// Cycle 1 fired. Both counter bumps happen in the same cb body, so
// observing `gc_runs_total >= 1` means `gc_bytes_reclaimed_total`
// has already taken its cycle-1 contribution (which must be 0 —
// no prior baseline to diff against).
anyhow::ensure!(
metrics.gc_bytes_reclaimed.get() == 0,
"after cycle 1, gc_bytes_reclaimed_total must be 0 (no prior baseline to diff against); got {}",
metrics.gc_bytes_reclaimed.get()
);

  1. snapshot_blob_sizes maps BlobStatus::Partial { size: None } to 0. If iroh-blobs ever emits an unknown-size partial for the cap-breach / hash-mismatch paths this PR targets, gc_bytes_reclaimed would silently under-attribute. Observability only — reclaim itself is iroh-blobs' job.

let size = match status {
iroh_blobs::api::blobs::BlobStatus::NotFound => continue,
iroh_blobs::api::blobs::BlobStatus::Partial { size } => size.unwrap_or(0),
iroh_blobs::api::blobs::BlobStatus::Complete { size } => size,
};

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@thiras

thiras commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — verified both. tl;dr: (1) is real-but-negligible, (2) doesn't apply to the threat-model paths.

(1) gc_attribution_lags_one_cycle race. Confirmed there's no formal sync barrier — the cb's two .inc calls aren't atomic together, and the test reads the two counters separately. But between the loop exit at L275 and the assertion read at L282 there is zero .await and zero I/O, only synchronous code and comments. For cycle 2 to fire in that gap you need gc_interval (500ms) − 20ms-poll-slack ≈ ~480ms of OS preemption between two adjacent synchronous lines. Pathological enough that I'd file the test as load-bearing-but-fragile rather than reach for a fix; happy to add a Mutex<()> or Notify if a future flaky run argues otherwise.

(2) Partial { size: None } under-attribution. The general concern is valid, but the specific claim "for the cap-breach / hash-mismatch paths this PR targets" is wrong. I instrumented snapshot_blob_sizes to log every BlobStatus and re-ran both threat-model tests:

gc_reclaims_cap_breach_partial_bytes  → Complete size=1048576
gc_reclaims_partial_import_bytes      → Complete size=53

Neither path produces a Partial entry. Reason is in count_and_cap_stream (engine.rs:1474-1515): on cap breach or upstream error it deliberately terminates the stream with None, not Err — otherwise iroh-blobs' add_stream bidi channel hangs waiting for Done. From iroh-blobs' POV the stream completed cleanly, so it commits a Complete blob under whatever (wrong) hash the received bytes produce. The engine drops the TempTag and GC reclaims it via the Complete { size } arm — fully accounted.

Partial { size: None } could arise from other iroh-blobs paths (e.g., interrupted client-protocol fetch where bao-tree hasn't validated total size), but those are out of scope here. Worth a follow-up if/when we wire the client-protocol partial-fetch surface.

@thiras
thiras merged commit 040b1ed into main May 11, 2026
10 checks passed
@thiras
thiras deleted the 518-cache-gc-wiring branch May 11, 2026 10:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cache: wire iroh-blobs GC into runtime — partial-import bytes (hash-mismatch, mid-stream cap breach) currently leak disk indefinitely

3 participants