Skip to content

feat(gateway): cache what pulls deliver and serve repeats from it - #2905

Closed
alpergundogdu wants to merge 2 commits into
mainfrom
gateway-cache
Closed

alpergundogdu wants to merge 2 commits into
mainfrom
gateway-cache

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

The last step of #2881's plan for the gateway: decdn gateway keeps what it pulls in a decdn-cache CacheEngine and serves a repeat request from it. It builds on #2884 (the cache without its AWS SDK), #2886 (the eviction loop in the cache), #2887 (a Streamer that fills a store the caller opens) and #2903 (a streamed admit that reports progress and stops early).

What changes

  • The gateway cache lives under <data-dir>/cache. --cache-mb (default 10240) sets its size, and --cache-mb 0 turns it off. The node's eviction loop runs on it, with the node's default marks and free-disk margin. The gateway shuts the cache down on exit, so its last writes reach the database.
  • Pulls fill the cache. fetch::CacheStores and CacheStore are a StreamStore over CacheEngine: each leg is admitted through admit_bao_stream_until, which verifies every chunk group, reports progress and honors a lowered end. FetchHost::with_stream_cache makes every streamed fetch on the gateway's host fill it. decdn get keeps its scratch directory.
  • Hits cost nothing. A request is a hit when the cache holds every byte of its response at the size the response states: the whole blob, or the chunk groups of its one Range. A hit is served out of the cache with the same headers a pull gets. It starts no pull, spends no capability and charges no allowance. A blob held whole also answers HEAD with its length, with no size lookup.
  • Partial hits are charged as pulls. A request the cache holds only part of streams as a pull. The pull fetches only the missing chunk groups, and the allowance charges the response as it does today.
  • Fix in decdn-client: contiguous_byte_ranges now ends a span with no end at the blob's size. Before, it dropped that span. The cache's bitfield gives the span that holds a blob's last chunk an open end, so a stream reading the cache stopped one span short (stream fetch finished with 1540096 of 1572864 bytes readable). ClientRangedStore never yields an open span, so decdn get was not affected.
  • Metrics: a new decdn_gateway_cache_hits_total counter, in /_status and on the dashboard.
  • Dependency check: decdn-cli → decdn-cache is now an allowed edge. The CLI may link iroh-blobs; the client SDK and sponsord still may not, and nothing may link the AWS SDK. The workspace takes decdn-cache without default features, and the node turns on s3. The table, its tests, the CLAUDE.md dependency paragraph and the docs that said the CLI links no blob store are all updated.
  • StreamStores contract: an implementation now documents whether two streams may fill one store at once. Concurrent pulls of one blob share one cache entry, and each admit is verified and idempotent.
  • Docs: adr/appendix-gateway.md § Cache, the gateway module doc and the Docker README.

Tests

  • cache_store: a drained leg lands in the cache for the next stream; a lowered end stops a leg at a chunk-group boundary; a Streamer over the cache reads back the whole 1.5 MB blob it fills (this test failed before the contiguous_byte_ranges fix).
  • driver: an open span runs to the end of the blob.
  • gateway: a cached blob is served with no pull and no allowance; a cached Range is served as a 206; a partial entry that misses the request is no hit.
  • gateway_public e2e, which needs anvil:
    • the existing journey runs with --cache-mb 0, so its pull and allowance accounting is unchanged;
    • a new journey pulls a blob once, then checks that a repeat GET and a Range come from the cache, that the node writes no byte for them, and that the allowance stays put.
  • cargo nextest run -p decdn-cli -p decdn-cache -p decdn-node, the anvil-e2e gateway suite, cargo clippy --workspace --all-targets --all-features with warnings denied, cargo doc, check_crate_edges.py and its pytest suite, cargo fmt --check, the dashboard tests.

Not in this PR

  • A spent allowance answers 402 before a hit is looked up, and so does a loopback page with no covering capability. Hits are free, but they are not served past those gates.
  • A cache entry being read or filled is not pinned against eviction. A blob the eviction loop releases mid-read ends that response with an error. Pinning entries in use is the follow-up client: re-evaluate running decdn-client on the iroh-blobs store (0.104.1) #2881 names.
  • The SDK contract suites run against the default, with the cache on.

🤖 Generated with Claude Code

decdn gateway keeps a decdn-cache CacheEngine under <data-dir>/cache
(--cache-mb, default 10240; 0 turns it off) with the node's eviction
loop on it. Every pull streams into it through CacheStores, a
StreamStore over admit_bao_stream_until. A request whose bytes the
cache holds, whole or its one Range, is served from it with no pull
and no allowance charge, and counts in decdn_gateway_cache_hits_total.

The CLI may now link iroh-blobs (decdn-cache without its s3 feature);
the client SDK and sponsord still may not. contiguous_byte_ranges ends
an open span at the blob's size, which the cache's bitfield needs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 16, 2026 11:52

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.

Note

Copilot was unable to complete this review at the selected tier due to model policy or plan restrictions.

🟡 Changes recommended

Approval is blocked by unresolved critical lifecycle/concurrency risk where the cache eviction task may continue mutating state during engine shutdown due to not being awaited, alongside an overly restrictive Sync bound on streamed responses that can break valid non-Sync stream implementations.

2 open issues
What changed in this PR

Adds a persistent, size-bounded cache to decdn gateway so streamed pulls populate decdn-cache under <data-dir>/cache and repeat requests (including single-Range) can be served directly from cache without starting a pull or charging allowance/capability, alongside a client range-span bug fix plus metrics/docs/tests and dependency-edge updates.

Changes:

  • Add gateway cache configuration (--cache-mb, 0 disables), eviction integration, and shutdown flushing.
  • Route streamed pulls to fill the cache and serve cache hits (whole blob or single Range) with identical headers and a new cache-hit metric + dashboard tile.
  • Fix open-ended range span handling in decdn-client and update tests, docs, and crate-edge guards for the CLI→cache linkage.
File Description
docker/​README.decdn.md Documents gateway cache persistence/location and how repeat requests are served from cache in Docker deployments.
crates/​node/​Cargo.toml Updates node features to enable decdn-cache's s3 support where required.
crates/​e2e/​tests/​gateway_public.rs Adds an anvil-backed public gateway e2e journey asserting cache hits avoid pulls and do not change allowance or node bytes.
crates/​common/​src/​cli/​gateway/​tests.rs Adds CLI parsing tests covering --cache-mb defaults and disabling the cache with 0.
crates/​common/​src/​cli/​gateway.rs Introduces the --cache-mb gateway flag and documents cache semantics in help text.
crates/​client/​src/​streamer.rs Clarifies the StreamStores contract, including how shared stores behave under concurrent fills.
crates/​client/​src/​driver/​tests.rs Adds a regression test ensuring an open-ended span runs to the end of the blob.
crates/​client/​src/​driver.rs Fixes contiguous_byte_ranges so an open-ended span is treated as extending to total_bytes.
crates/​cli/​src/​commands/​gateway/​worker.rs Threads an optional cache-backed StreamStores into gateway host/worker construction so pulls can fill the cache.
crates/​cli/​src/​commands/​gateway/​tests.rs Adds unit tests validating cached whole-blob and range serving, plus partial/miss behavior falling back to pulls.
crates/​cli/​src/​commands/​gateway/​status/​tests.rs Updates status snapshot tests to include the new cache-hits counter field.
crates/​cli/​src/​commands/​gateway/​metrics/​tests.rs Extends metrics exposition tests to assert decdn_gateway_cache_hits_total behavior and naming.
crates/​cli/​src/​commands/​gateway/​metrics.rs Adds a cache-hit counter and exposes it in both status JSON and Prometheus/OpenMetrics output.
crates/​cli/​src/​commands/​gateway.rs Implements gateway cache open/eviction/shutdown and the cache-hit serving path (including HEAD/Range handling).
crates/​cli/​src/​commands/​fetch/​cache_store/​tests.rs Adds tests for cache-backed streaming ingest, stop-at behavior, and reading back filled content.
crates/​cli/​src/​commands/​fetch/​cache_store.rs Implements CacheStores/CacheStore as a StreamStore over CacheEngine for streaming fills and reads.
crates/​cli/​src/​commands/​fetch.rs Plumbs an optional stream cache into the fetch path so gateway streamed fetches populate cache instead of only scratch storage.
crates/​cli/​README.md Updates CLI documentation to reflect linking store-only decdn-cache (AWS-free) and revised blob-store linkage statements.
crates/​cli/​dashboard/​src/​view.test.ts Updates dashboard view tests/fixture expectations to include the cache-hits counter.
crates/​cli/​dashboard/​src/​fixtures/​status-public.json Adds cache_hits to the public status fixture counters.
crates/​cli/​dashboard/​src/​fixtures/​status-pool-error.json Adds cache_hits to the pool-error status fixture counters.
crates/​cli/​dashboard/​src/​fixtures/​status-loopback.json Adds cache_hits to the loopback status fixture counters.
crates/​cli/​dashboard/​src/​contract.test.ts Extends dashboard contract tests to require/support the new cache_hits counter field.
crates/​cli/​dashboard/​src/​components/​StatTiles.tsx Adds a “Cache hits” stat tile and wires it to the status counters model.
crates/​cli/​dashboard/​src/​components/​StatTiles.test.ts Updated as part of this pull request.
crates/​cli/​dashboard/​src/​api.ts Extends dashboard API types/models to include the cache_hits counter.
crates/​cli/​Cargo.toml Adds decdn-cache (store-only) and related dependencies for the CLI and adjusts dependency/feature commentary accordingly.
crates/​bao-range/​src/​lib.rs Updates crate-level documentation to align with revised blob-store linkage constraints across components.
CLAUDE.md Updates dependency-flow documentation to reflect the now-allowed CLI→decdn-cache edge and related constraints.
Cargo.toml Adjusts workspace dependency configuration so decdn-cache is pulled in store-only by default (default-features = false).
Cargo.lock Updates the lockfile to reflect new/adjusted dependencies introduced by the gateway cache work.
adr/​appendix-gateway.md Documents gateway cache behavior, hit rules, configuration, and associated observability fields.
adr/​appendix-binaries.md Updates the binaries appendix to reflect the CLI’s updated dependency/linkage footprint.
adr/​038-bao-verified-range-streaming.md Adjusts ADR wording to match the updated component boundaries and dependency assumptions after cache integration.
.github/​scripts/​tests/​test_check_crate_edges.py Updates crate-edge tests to allow the CLI’s new linkage while continuing to guard against forbidden AWS dependencies.
.github/​scripts/​check_crate_edges.py Extends the dependency-edge checker to permit the CLI’s allowed blob-store/cache linkage and keep other roots constrained.

Review effort: Balanced

Comment on lines 415 to +424
// The worker's queued lane writes land before the store dir is removed.
gateway.pulls.stop().await;
drop(temp_store);
drop(eviction);
// The cache's last writes reach its database before the process exits.
if let Some(engine) = &cache
&& let Err(e) = engine.shutdown().await
{
tracing::warn!(error = %e, "the gateway cache did not shut down cleanly");
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: start_eviction now returns the task handle too, and close_cache sends the stop and awaits the loop before calling shutdown(), so no release races the last writes.

🤖 Addressed by Claude Code

Comment on lines +3059 to +3063
body: S,
) -> Result<Response<Body>, PullError>
where
S: futures_util::Stream<Item = Result<Frame<Bytes>, std::io::Error>> + Send + Sync + 'static,
{

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No change: the gateway's Body is http_body_util::combinators::BoxBody, and .boxed() requires Send + Sync, so streamed_response needs the Sync bound. That is also why a cache hit reads through a spawned task into a channel rather than polling the cache read future in the body.

🤖 Addressed by Claude Code

@github-code-quality

github-code-quality Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Code coverage overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

main 1410068 gateway-cache 8c0b4f7 +/-
77% 77% 0%
View coverage of the 10 most impacted files.
File main 1410068 gateway-cache 8c0b4f7 +/-
crates/cli/src/...ands/gateway.rs 81% 79% -2%
crates/cli/src/...mmands/fetch.rs 47% 46% -1%
crates/protocol/src/framing.rs 93% 92% -1%
crates/client/src/source.rs 94% 94% 0%
crates/cli/src/...teway/worker.rs 83% 83% 0%
crates/node/src...s/client/mod.rs 92% 92% 0%
crates/client/src/driver.rs 96% 96% 0%
crates/cli/src/...eway/metrics.rs 100% 100% 0%
crates/node/src/dht/publish.rs 77% 78% +1%
crates/cli/src/.../cache_store.rs 0% 84% +84%

ℹ️ Calculations represent line coverage. Results may change as calculations are updated.


Updated November 16, 2026 12:16 UTC

The pointer journey runs its gateway with --cache-mb 0, since it counts
a repeat request against the namespace allowance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Combined into #2908, which carries this PR's commits together with the rest of the stack so they land as one.

@alpergundogdu
alpergundogdu deleted the gateway-cache branch November 18, 2026 11:23
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.

2 participants