Skip to content

feat(cache): gzip/zstd decompression + blob pinning list (#312, #276) - #372

Merged
thiras merged 6 commits into
mainfrom
feat/cache-decompression-pinning-2
May 1, 2026
Merged

thiras merged 6 commits into
mainfrom
feat/cache-decompression-pinning-2

Conversation

@thiras

@thiras thiras commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Two independent cache enhancements that share the same review surface.

Decompression (#312)

  • Inspect `Content-Encoding` on the response. `gzip` → `flate2`; `zstd` → `zstd`; `identity` / unset → pass through. Unrecognized encoding → `OriginError::UnsupportedEncoding` (don't silently pass).
  • Decompression runs before the BLAKE3 verify in `engine.rs` so the hash check operates on the canonical form.
  • Caps decompressed size at the configured `max_blob_size_mb` so a "zip-bomb" origin response is rejected without unbounded memory use.
  • New config knob: `cache.decompress: bool` (default `true`) so operators can opt out for origins they know serve raw bytes.
  • Two new error variants on `OriginError`: `UnsupportedEncoding` and `DecompressionFailed`.
  • Test fixtures cover gzip, zstd, identity, unsupported, and `decompress: false`.

Pinning (#276)

  • New config field `cache.pinned_hashes: Option<Vec>` (hex BLAKE3 hashes, 64 lowercase chars each).
  • Resolved into `HashSet<iroh_blobs::Hash>` at config load with structured errors for invalid hex / wrong length / uppercase. Strict casing matches the project's "fail fast at config-load" preference.
  • `Inner.pinned: ArcSwap<HashSet>` is consulted by a new `eviction_candidates()` helper that filters pinned hashes out of the `access_times_snapshot` so any future eviction loop inherently honors them.
  • Hot-reloadable on SIGHUP via `ArcSwap` (precedent: `payment.rate_per_mb`).

Eviction-ownership finding

deCDN owns eviction logic (no eviction loop has shipped yet — `access_times_snapshot()` is plumbing for one). iroh-blobs handles the underlying store but does not delegate eviction. The pinning predicate slots in at the right seam: when an eviction loop later consumes the candidate set, it inherently respects pinning.

Caveats

  • The "fill cache past `cache_size_mb`, assert pinned hash survives" end-to-end test isn't directly implementable today because no eviction loop exists. The pinning filter is fully tested via `eviction_candidates()` (asserts pinned hashes are excluded from the candidate set, which is the input contract for any future eviction implementation).
  • `parse_pinned_hashes` rejects uppercase hex by design — operators copy-pasting from a UI that upper-cases digests get a clear error rather than a silently-half-pinned set.

New deps

  • `flate2 = "1"`, `zstd = "0.13"`, `arc-swap = "1"` — all MIT/Apache-2.0. `cargo deny check` passes via the pre-commit hook on both commits.

Test plan

  • `cargo fmt -- --check` clean
  • `cargo clippy --workspace --all-targets -- -D warnings` clean
  • `cargo nextest run -p decdn-cache` — 44/44 pass (5 new decompression tests + 2 new pinning tests + originals)
  • `cargo nextest run -p decdn-node` — 198/198 pass (config resolution tests + sighup tests + originals)

Manual end-to-end suggestions for reviewer

  • Configure `HttpOrigin` against a server that gzips responses; pull-through succeeds and BLAKE3 matches.
  • Add a pinned hash to config; verify `engine.eviction_candidates()` excludes it.
  • SIGHUP after editing `pinned_hashes`; verify the new set takes effect without restart.

Closes #312
Closes #276

🤖 Generated with Claude Code

thiras and others added 2 commits May 1, 2026 09:18
Many object-storage origins serve responses with `Content-Encoding:
gzip` or `zstd`. The current `HttpOrigin` returned raw compressed bytes,
which then failed BLAKE3 verification because the content-address is
computed over the canonical (decompressed) form. Add a decoder layer
that runs before bytes are returned from `Origin::fetch` so the verify
in `CacheEngine::pull_through` operates on canonical bytes.

Behaviour:

- inspect `Content-Encoding`: empty/`identity` passes through, `gzip`
  decompresses with `flate2`, `zstd` with the `zstd` crate.
- unrecognised encodings error out with the new
  `OriginError::UnsupportedEncoding` rather than silently passing
  bytes that would later surface as a confusing hash-mismatch.
- decompression is bounded by `max_bytes` inside the decode loop so a
  small compressed body that expands to many GB fails fast rather than
  reaching OOM.
- reqwest's built-in transparent decompression is disabled
  (`.no_gzip().no_deflate().no_brotli().no_zstd()`) so we see the raw
  `Content-Encoding` header and run our own decoders.

Config:

- `cache.decompress` (TOML, defaults to `true`) toggles the decoder.
  Operators with origins that pre-canonicalise can flip it off.
  Wired through `CacheConfig` -> `ResolvedCache` -> `HttpOrigin`.

Tests cover gzip, zstd, identity, unsupported (`br`), and
decompress=false-falls-through-to-hash-mismatch paths.

Closes #312

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Operators running nodes for specific publishers need to guarantee
certain blobs stay cached regardless of LRU pressure. Add a pinned set
to `CacheEngine` and exclude pinned hashes from the eviction-candidate
snapshot so any future LRU implementation inherently respects the
pinning policy.

Eviction-ownership note: as of this commit `decdn-cache` does not yet
implement an eviction loop — `access_times_snapshot()` is plumbing for
future eviction logic. The pinning filter is added at the right seam
(`eviction_candidates()` returns access times minus pinned hashes) so
the eviction loop, when it lands, picks up the policy automatically.
iroh-blobs owns the underlying store but we do not delegate eviction
to it; the deCDN cache will own that decision. This means the pinning
predicate approach works as the instructions specified.

Cache-engine API:

- `CacheEngine::open_with_pinned(...)` — open with an initial pinning
  set.
- `CacheEngine::set_pinned(set)` — atomically swap (`ArcSwap`) the
  pinned set, mirroring the `Arc<AtomicU64>` pattern used for
  `payment.rate_per_mb` (commit 166ae41).
- `CacheEngine::pinned_snapshot() / is_pinned(hash)` — read accessors.
- `CacheEngine::eviction_candidates()` — access-time snapshot with
  pinned hashes filtered out.

No `remove()` method or other public-API additions are made — the
parallel PR's territory is preserved.

Config:

- `cache.pinned_hashes: Option<Vec<String>>` (TOML). Each entry is
  64 lowercase hex chars (BLAKE3 digest size). Invalid hex /
  wrong-length / mixed-case entries fail config resolution
  (`parse_pinned_hashes`) — silent acceptance would surprise the
  operator hours later when their "pinned" blob got evicted.
- `ResolvedCache.pinned_hashes: HashSet<Hash>` is consumed by
  `build_cache` via `open_with_pinned`.

Hot-reload (#236, mirrors `payment.rate_per_mb`):

- `RuntimeReloadState::attach_cache(Some(engine))` is called once at
  startup (right after `build_cache` succeeds).
- Each SIGHUP re-parses `cache.pinned_hashes` and calls
  `engine.set_pinned(...)`. The transactional ordering rule
  (acquire all locks + parse all sections fallibly *before* any
  committing side-effect) is preserved: a malformed pinned-hash
  entry rejects the reload and leaves the previous set in place.
- The "ignored (requires restart)" warning for `cache.*` is
  suppressed when only `pinned_hashes` changed, so operators
  pinning/unpinning don't see a misleading restart notice.

Tests:

- Engine: pinned-hash-exclusion, atomic swap, raw-vs-filtered
  snapshot.
- Config resolution: valid lowercase hex, wrong length, non-hex,
  uppercase rejection, dedup, empty/none.
- Reload: pinning swap on attached cache, invalid-hash rejection
  preserves previous set, no-cache-attached path is a no-op.

Closes #276

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 1, 2026 09:16

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 two cache-focused enhancements across decdn-cache and node config/runtime wiring: (1) transparent gzip/zstd decompression for HTTP origins before BLAKE3 verification, and (2) an operator-configurable pinned-hash set that is excluded from future eviction candidate selection and can be hot-reloaded on SIGHUP.

Changes:

  • Implement Content-Encoding handling in HttpOrigin (gzip/zstd/identity) with size-capped decompression and new typed OriginError variants.
  • Add cache.decompress (default true) and cache.pinned_hashes parsing into a resolved HashSet<Hash>, plumbed into CacheEngine and runtime startup.
  • Add hot-reload support for cache.pinned_hashes via ArcSwap in the cache engine plus node SIGHUP reload logic and tests.

Reviewed changes

Copilot reviewed 13 out of 14 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved-config fixtures for new cache fields.
crates/node/tests/config_validate.rs Updates resolved-config fixtures for new cache fields.
crates/node/src/runtime/reload.rs Adds pinned-hash hot-reload plumbing + cache-section diff suppression logic.
crates/node/src/runtime/mod.rs Attaches cache engine to reload state; wires decompression toggle; opens cache with initial pinned set.
crates/node/src/config/types.rs Adds TOML fields cache.decompress and cache.pinned_hashes.
crates/node/src/config/resolved.rs Adds resolved fields decompress: bool and pinned_hashes: HashSet<Hash>.
crates/node/src/config/mod.rs Implements defaulting/resolve for decompress and parsing/validation for pinned_hashes.
crates/cache/tests/pull_through.rs Adds integration tests for gzip/zstd/identity/unsupported encodings and decompress toggle behavior.
crates/cache/src/origin/http.rs Implements header inspection + decompression + caps; disables reqwest auto-decompression.
crates/cache/src/lib.rs Re-exports OriginError.
crates/cache/src/error.rs Adds typed OriginError variants for unsupported encoding and decompression failure.
crates/cache/src/engine.rs Adds pinned set storage via ArcSwap, plus set_pinned/pinned_snapshot/is_pinned/eviction_candidates.
crates/cache/Cargo.toml Adds deps flate2, zstd, and arc-swap.
Cargo.lock Locks new dependency graph entries.

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

Comment thread crates/cache/src/origin/http.rs Resolved
Comment thread crates/cache/src/origin/http.rs Resolved
Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/runtime/reload.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 introduces transparent gzip and zstd decompression for HTTP origins and implements operator-pinned blob hashes that are excluded from LRU eviction. The changes include manual decompression logic with size capping to prevent resource exhaustion and support for hot-reloading the pinned hash set via SIGHUP. Feedback suggests utilizing existing utility crates for hex validation to improve code maintainability.

Comment thread crates/node/src/config/mod.rs Resolved
thiras and others added 4 commits May 1, 2026 12:44
- clippy 1.95: drop unnecessary trailing comma in `format!()` literal
  in reload.rs:1065. Local clippy was 1.93 and didn't fire the
  `unnecessary_trailing_comma` lint; CI on the newer toolchain caught
  it.

- `decompress=false` no longer silently passes a compressed response
  through. With the toggle off, a `Content-Encoding: gzip|zstd|...`
  response is rejected up-front as `OriginError::UnsupportedEncoding`.
  Identity / unset encodings still pass through unchanged. Operators
  who hit this get an actionable error instead of a downstream
  `HashMismatch` from the BLAKE3 verify.

- Sync `flate2`/`zstd` decompression now offloads to `spawn_blocking`
  above 1 MiB, mirroring the existing
  `engine.rs::BLOCKING_HASH_THRESHOLD` policy. Prevents tokio worker
  starvation on origins that serve large gzipped blobs.

- `attach_cache` no longer silently no-ops on a poisoned mutex.
  Recovers the inner state via `PoisonError::into_inner` so reloads
  don't permanently degrade after an unrelated thread panic; logs an
  error to surface the unhealthy state.

- Reload's cache mutex acquisition moved up next to the other state
  mutexes, before the commit step. A poisoned cache mutex now fails
  the reload before `rate_per_mb` is swapped — preserving the
  "previous values retained on error" contract that the existing
  log-level / file-section locks already honor.

- Tests:
  - `http_origin_decompress_off_rejects_compressed_response` (replaces
    the old test that asserted a confusing downstream HashMismatch)
  - `http_origin_decompress_off_passes_through_identity` to lock in
    the legitimate raw-bytes opt-out path

243/243 tests pass; clippy, fmt, cargo doc clean on the workspace.

Pushback noted: Gemini suggested using a hex utility crate for
pinned-hash validation. Keeping the manual check — it's deliberately
strict on lowercase + 64 chars to fail-fast at config load, which
`hex::decode` (case-insensitive) would silently relax.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…newtypes

Follow-up to the PR #372 review covering the items reviewers flagged
beyond the first round of fixes (a148c02).

Bug fixes
- Reload: `cache_only_reloadable_fields_changed` renamed to
  `cache_changed_only_reloadable_fields`; doc comments now match the
  polarity of the body so a future reader can't invert the call site.
- Reload: `seed_initial_file_snapshot` primes the diff baseline at
  startup, so the first SIGHUP after a pinned-only edit no longer
  emits the spurious `cache.* (cache_dir, sizes, origin, decompress)`
  "requires restart" warning.
- HttpOrigin: non-ASCII `Content-Encoding` headers now surface
  `OriginError::MalformedEncoding` instead of being silently
  downgraded to "no encoding".
- HttpOrigin: pre-stream `Content-Length` cap now also rejects
  oversized compressed bodies — compression ratios < 1 are universal
  in practice, so an advertised compressed length above the
  decompressed cap is malicious or misconfigured either way.

Type design
- `OriginError::DecompressionFailed.encoding` is now
  `SupportedEncoding { Gzip, Zstd }` (closed set) rather than a free
  `String`; `UnsupportedEncoding.encoding` is `Box<str>`.
- `CacheError::origin_error_kind()` walks the anyhow chain and
  recovers the typed `OriginError`, so callers (and tests) no longer
  match on stringified `Display` output.
- `DecompressMode { Auto, Strict }` enum replaces the `bool` knob.
  TOML now reads `decompress = "auto"` / `"strict"`. `Strict` is the
  honest name — it's "refuse non-identity", not "off".
- `PinnedHashes(Arc<HashSet<Hash>>)` newtype shared across the
  resolver, runtime, and engine. `set_pinned(&PinnedHashes) -> PinDiff`
  replaces the discarded `Arc<HashSet<Hash>>` return; the success log
  now reports `pinned_added`/`pinned_removed`/`cache_attached`.
- `EvictionCandidates(HashMap<Hash, Instant>)` newtype with no public
  constructor — "pinned-already-excluded" is now a type-level
  guarantee instead of a doc-comment claim.

Tests (+14, total 312/312 pass)
- Decompression bomb (read_capped mid-stream cap), truncated gzip,
  typed UnsupportedEncoding downcast, case-insensitive `GZIP`/
  `Gzip`/`x-gzip`, multi-encoding header rejection,
  DECOMPRESS_BLOCKING_THRESHOLD crossover, oversized compressed
  Content-Length, empty gzip body, BLAKE3-verify-runs-over-decompressed
  regression guard, strict-mode explicit `identity`,
  PinnedHashes::diff, N→0 unpin reload, attach_cache poison recovery,
  seed_initial_file_snapshot.

Verification
- cargo fmt --check, cargo clippy --workspace --all-targets -D warnings,
  cargo nextest run --workspace (312/312), cargo deny check — all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Reconciles PR #372 (decompression + pin/eviction newtypes) with the
operator-evict feature (#279) that landed on main as 212f815. Both
features touch `CacheEngine` but address orthogonal concerns:

- Pinning (#276): excludes a hash from LRU eviction-candidate
  snapshots. Hot-reloadable via SIGHUP.
- Operator-evict (#279): durable, one-way "stop serving this hash"
  flag persisted to `<cache_dir>/evicted.log`. Used for DMCA
  takedowns and corruption recovery.

Both fields now coexist on `Inner`. Doc comment on `pinned` clarifies
the interaction: pinning prevents *LRU* eviction but does not protect
against an operator `evict()` call. The `Inner` constructor wires
`pinned` (ArcSwap from PinnedHashes) and `evicted` (Mutex<HashSet>
loaded from the on-disk log).

Verification
- cargo build --workspace --all-targets clean
- cargo nextest run --workspace — 330/330 (PR's 14 new tests + main's
  evict tests + originals)
- cargo clippy --workspace --all-targets -D warnings clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI's `cargo doc` job runs with `-D warnings`, which surfaces three
broken / private-target intra-doc links introduced earlier in this PR
and the merge of main:

- `engine.rs`: `[Self::evict]` on the `pinned` field doc resolved
  against `Inner` (the surrounding struct), not `CacheEngine`.
  Re-anchored to `[CacheEngine::evict]`; the sibling `evicted` field
  reference is now plain text since it's a private field.
- `origin/http.rs`: `DecompressMode::Auto` (public) linked to
  `CacheEngine::pull_through` (private) — only resolves under
  `--document-private-items`. Drop the method specifier and link to
  the type itself.
- `runtime/reload.rs`: `seed_initial_file_snapshot` (public) linked
  to `cache_changed_only_reloadable_fields` (private). Same fix —
  inline the function name without the link.

Verified locally: `RUSTDOCFLAGS="-D warnings" cargo doc --workspace
--no-deps --document-private-items` clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras merged commit 86105e3 into main May 1, 2026
11 checks passed
@thiras
thiras deleted the feat/cache-decompression-pinning-2 branch May 1, 2026 11:48
thiras added a commit that referenced this pull request May 1, 2026
…382)

* feat(node): add admin_v1_drain + decdn node drain subcommand (#244)

Adds a loopback JSON-RPC entry point for graceful shutdown that mirrors
the existing admin_v1_peersList / decdn node peers pair. Fire-and-forget
semantics: the RPC fires a runtime DrainTrigger and returns
initiated=true immediately, after which the runtime runs the same
shutdown sequence SIGTERM triggers (stops accept loops, awaits in-flight
ProtocolHandler::shutdown, flushes cache, drains within
SHUTDOWN_DEADLINE). Operators observe completion via process exit
(systemd/K8s) or by polling decdn node health until ECONNREFUSED.

ADR 025 already pre-allocated this method name in its "Future methods"
list, so no new ADR is needed. The ShutdownSignal enum gains an
AdminDrain variant whose Display impl renders as "admin-drain" for the
existing structured "shutdown signal received" log line.

Drive-by: fix a pre-existing test-target compile error in
runtime/reload.rs's test fixture. PR #312/#372 added decompress and
pinned_hashes fields to ResolvedCache but didn't update this fixture,
which blocked cargo nextest. Mirrors the defaults used at reload.rs:744.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(node): clarify drain_trigger field and shutdown ordering (PR #382)

Three doc-only fixes from review:

- AdminState::drain_trigger doc said "Always Some" but the field is
  Arc<DrainTrigger> not Option<…>. Reword to "always present" and call
  out the contrast with the Option-typed announce_trigger / reload_hook.

- DrainResponse and DrainArgs docs called the admin server "the first
  surface to stop" during shutdown, but runtime::run signals metrics
  before admin. Both are stopped before router.shutdown, so "one of the
  first surfaces" is the accurate phrasing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(node): tighten drain rustdoc accuracy from review feedback (PR #382)

- `admin_v1_drain` trait rustdoc: SHUTDOWN_DEADLINE bounds only the
  post-router task drain, not router.shutdown() — a stuck
  ProtocolHandler::shutdown hangs the runtime, the deadline doesn't
  cut it short. Previous wording implied the deadline gated the whole
  router-shutdown path.
- `drain()` handler: comment distinguishes "trigger fired" from
  "runtime is now in the AdminDrain branch". If SIGTERM/SIGINT raced
  the RPC, the runtime has already passed `drain_trigger.wait()` and
  this `fire()` lands in an abandoned arm; functionally fine but a
  future reader shouldn't infer causation from `initiated=true`.
- Coalesce test renamed `_double_fire_` → `_repeated_fire_` and adds a
  third `fire()` so it's robust against a "burns one permit per fire"
  reimplementation. Dropped the "oneshot" framing — a oneshot swap
  fails to compile (Sender::send consumes self) so that wasn't the
  regression class the test actually defends against.
- `NodeCommand::Drain` variant rustdoc echoes the connection-closes-
  before-exit warning that `DrainArgs` already carries, so operators
  reading just the variant doc get the same heads-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: yigitdot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants