Repository navigation
feat(node): origin-tier range pull-through on cdn/client/v1 (#823, #990) - #1007
Conversation
, #990) A bounded/offset `cdn/client/v1` cache-miss now scopes its origin fetch to the requested span instead of pulling the whole blob. The engine machinery (`pull_through_range`/`export_range` + the `{H}.obao4` outboard verification on the HTTP/S3/fs adapters) already shipped in #962/#985; this wires it into the live handler and adds the missing size source. - cache: add `Origin::size` (HTTP `HEAD` / S3 `HeadObject` / fs stat) + `CacheEngine::origin_size` so a cold node learns the exact `blob_size` the bao tree needs (the `{H}.obao4` outboard alone doesn't pin the final chunk group). A `Content-Encoding`/missing/absent response degrades to `None`. - node: `try_range_pull_through` runs on a bounded/offset miss (origin size probe -> `pull_through_range` -> serve the verified partial via `export_range`) before the whole-blob fallback, gated on the existing `pull_authorized` ownership check. The size gate uses the probed total for the partial blob; `deliver` serves ranges via `export_range`, metering payment over the served span. The window-paced fallback is gated on `byte_len == 0` so a bounded request can't over-deliver/over-bill the whole blob. A local store fault on the partial-import path logs at `warn`. - adr: amend ADR 037 §Origin-tier pull-through (the design SoT) to document the origin size probe and mark #823 landed. No new ADR — the design was already specified there. - tests: e2e `origin_range_pull.rs` (cold ranged path fetches only the range and stays partial; no-outboard fallback; unauthorized request fronts no origin egress) + `Origin::size`/`origin_size` unit coverage. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
WalkthroughThe pull request adds best-effort origin size probing for range-scoped pull-through, implements it for filesystem, HTTP, and S3 origins, updates the node client handler to serve bounded requests through range export, and adds backend and end-to-end tests plus ADR updates. ChangesRange-scoped origin pull-through
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Code Review
This pull request implements origin-tier range pull-through on cdn/client/v1 (ADR 037). It introduces a best-effort Origin::size probe (using HTTP HEAD, S3 HeadObject, or filesystem metadata) to obtain the exact blob size needed to align and verify a sub-range against the root hash using the {H}.obao4 outboard. The ClientHandler is updated to attempt a range pull-through for bounded/offset cache-miss requests before falling back to a whole-blob pull, and serves range delivery via export_range. Feedback on the changes highlights two critical issues in crates/node/src/handlers/client.rs where whole-tail/offset-only requests (where req.byte_len is 0) are handled. Passing 0 directly to pull_through_range and export_range will result in fetching or exporting zero bytes instead of the actual remaining tail of the blob; the reviewer suggested resolving req.byte_len to the remaining length of the blob when it is 0.
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.
| match self | ||
| .cache | ||
| .pull_through_range(hash, req.byte_offset, req.byte_len, blob_size) |
There was a problem hiding this comment.
If req.byte_len is 0 (representing a whole-tail/offset-only request), passing 0 directly to pull_through_range will result in fetching 0 bytes instead of the actual remaining tail (blob_size - req.byte_offset). We should resolve req.byte_len to the actual remaining length of the blob when it is 0.
let len = if req.byte_len == 0 {
blob_size.saturating_sub(req.byte_offset)
} else {
req.byte_len
};
match self
.cache
.pull_through_range(hash, req.byte_offset, len, blob_size)There was a problem hiding this comment.
byte_len == 0 means "to end-of-blob" throughout this codebase, not zero bytes (ADR 005 §Bounded byte ranges). pull_through_range resolves it via align_range, which sets end = blob_size when byte_len == 0 (crates/cache/src/range_pull.rs:147-148); the existing engine test range_pull_zero_len_reads_to_end covers it. So passing req.byte_len directly is correct — resolving to blob_size - byte_offset here would just duplicate the engine's own handling.
Added an end-to-end handler test resume_to_end_range_pull_serves_tail that drives a byte_offset > 0, byte_len == 0 resume and asserts the whole tail is delivered (not zero bytes).
| &mut recv, | ||
| hash, | ||
| req.byte_offset, | ||
| req.byte_len, |
There was a problem hiding this comment.
If req.byte_len is 0 (offset-only request), passing req.byte_len directly to deliver will cause export_range to be called with byte_len = 0, which will return an empty slice instead of the requested tail. We should resolve req.byte_len to total_bytes - req.byte_offset when it is 0 before passing it to deliver.
| req.byte_len, | |
| if req.byte_len == 0 { total_bytes.saturating_sub(req.byte_offset) } else { req.byte_len }, |
There was a problem hiding this comment.
Same as the pull_through_range thread: export_range resolves byte_len == 0 to the blob end by querying the store size (crates/cache/src/engine.rs), returning the tail rather than an empty slice. deliver reaches it via the byte_offset > 0 branch for a resume. Covered end-to-end by the new resume_to_end_range_pull_serves_tail test.
Coverage reportTotal: 83.09% (was 83.14%, ▼ 0.05%) — 41833/50345 lines
History
|
There was a problem hiding this comment.
Pull request overview
This PR wires origin-tier range-scoped pull-through into the live cdn/client/v1 handler so a cold cache miss for a bounded/offset request can fetch only the needed bytes (plus {H}.obao4), bao-verify against the BLAKE3 root, import a partial blob, and serve the requested span—avoiding whole-blob origin egress while keeping the whole-blob fallback path.
Changes:
- Add an origin size-probe API (
Origin::size+CacheEngine::origin_size) to obtain the exact blob size needed for bao range verification. - Update the node client handler to attempt origin-tier range pull-through on bounded/offset misses and to serve ranges via
export_range(including partial blobs). - Add end-to-end and unit tests covering the cold ranged path, fallbacks, and adapter size semantics; update ADR 037 accordingly.
Reviewed changes
Copilot reviewed 12 out of 13 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/tests/origin_range_pull.rs | New e2e coverage for cold ranged cdn/client/v1 origin pulls, fallback, and unauthorized gating |
| crates/node/src/handlers/client.rs | Attempts origin-tier range pull-through on bounded/offset misses; serves ranges via export_range |
| crates/node/Cargo.toml | Adds bao-tree dev-dependency for e2e test outboard construction |
| crates/cache/tests/s3_origin.rs | Adds unit tests for S3Origin::size semantics (ContentLength, compressed, missing) |
| crates/cache/tests/pull_through.rs | Adds unit tests for HTTP/fs Origin::size and engine origin_size behavior |
| crates/cache/src/origin/s3.rs | Implements Origin::size via HeadObject and adds error classification helper |
| crates/cache/src/origin/mod.rs | Extends Origin trait with best-effort size() probe |
| crates/cache/src/origin/http.rs | Implements Origin::size via HTTP HEAD + Content-Length parsing |
| crates/cache/src/origin/fs.rs | Implements Origin::size via contained canonicalize + metadata stat |
| crates/cache/src/lib.rs | Re-exports RangePullOutcome from the engine |
| crates/cache/src/engine.rs | Adds CacheEngine::origin_size fallback-chain probe used by the handler |
| Cargo.lock | Locks bao-tree as a dependency (via node dev-dep) |
| adr/037-regional-proxy-warming.md | Documents the origin-size probe requirement and marks #823 as landed |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // A `HEAD` is the cheapest way to learn the canonical length — no | ||
| // body crosses the wire. Redirects stay disabled (SSRF, #579); a | ||
| // 3xx is a non-success and degrades to `None`. | ||
| let send_fut = self.client.head(url.clone()).send(); | ||
| let resp = match tokio::time::timeout(self.response_headers_timeout, send_fut).await { | ||
| Err(_elapsed) => { | ||
| return Err(OriginPullError::Transient(anyhow::anyhow!( | ||
| "origin HEAD {url_log} headers timed out" | ||
| ))); | ||
| } | ||
| Ok(Err(reqwest_err)) => { | ||
| return Err(classify_reqwest_error(reqwest_err) | ||
| .map_inner(|e| e.context(format!("origin HEAD {url_log} failed")))); | ||
| } | ||
| Ok(Ok(resp)) => resp, | ||
| }; | ||
| // A missing object (404) or any non-success → unknown size, degrade. | ||
| if !resp.status().is_success() { | ||
| return Ok(None); | ||
| } |
There was a problem hiding this comment.
By design, with the doc corrected rather than the code. size is a best-effort probe on the range-pull path, mirroring get_bounded's outboard read on that same path: any non-success HEAD (404 / permission / 5xx / disabled-redirect 3xx) degrades to None rather than erroring. CacheEngine::origin_size also collapses an Err to None, so classifying wouldn't change handler behavior — and a persistent 403/5xx re-surfaces at full severity on the whole-blob fetch fallback. (3xx is never followed — redirect::Policy::none() — so there's no SSRF exposure either way.)
The real defect was the doc comment overclaiming; fixed it on the Origin::size trait doc and the HTTP impl to state the best-effort behavior accurately.
| &mut send, | ||
| &mut recv, | ||
| hash, | ||
| req.byte_offset, | ||
| req.byte_len, |
There was a problem hiding this comment.
Fixed. Added a bounds check at the size gate that rejects an out-of-bounds bounded range (byte_offset >= total, or byte_offset + byte_len overflowing/exceeding total) with a StreamError before signing the success response, per ADR 005 §Bounded byte ranges ("the node MUST reject ..."). New ServeRejectReason::RangeNotSatisfiable, wire-collapsed to NotFound (reputation-benign — the requester folds a node fault into the node's score, and a client's own malformed range must not penalise the node), with a dedicated metric. Covered by out_of_bounds_range_is_rejected_before_delivery.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
crates/node/tests/origin_range_pull.rs (1)
406-410: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert that fallback uses an un-ranged whole-blob GET.
The
GET /{hex}mock currently matches ranged and un-ranged requests, so this test can still pass without proving the fallback path avoided a ranged data fetch after the outboard miss. Add request-count assertions like the cold-range test.Proposed assertion
anyhow::ensure!( cache.has(hash).await?, "the whole-blob fallback must complete and cache the blob" ); + let ranged_gets = count_requests(&server, |r| { + r.method.as_str() == "GET" + && r.url.path() == format!("/{hex}") + && r.headers.contains_key("range") + }) + .await?; + let wholeblob_gets = count_requests(&server, |r| { + r.method.as_str() == "GET" + && r.url.path() == format!("/{hex}") + && !r.headers.contains_key("range") + }) + .await?; + anyhow::ensure!(ranged_gets == 0, "fallback should not range-fetch data"); + anyhow::ensure!( + wholeblob_gets == 1, + "fallback should fetch the whole blob exactly once" + ); client_ep.close().await;Also applies to: 456-460
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/node/tests/origin_range_pull.rs` around lines 406 - 410, The fallback GET mock currently matches both ranged and un-ranged requests, so the test does not prove the outboard-miss path fetched the whole blob. In the origin_range_pull test around the Mock::given(...).respond_with(...).mount(&server) setup, add request-count assertions like the cold-range test to verify the fallback performs exactly one un-ranged GET /{hex} and does not issue a ranged data fetch. Apply the same assertion update to both affected mock blocks so the fallback path is explicitly validated.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@crates/node/tests/origin_range_pull.rs`:
- Around line 406-410: The fallback GET mock currently matches both ranged and
un-ranged requests, so the test does not prove the outboard-miss path fetched
the whole blob. In the origin_range_pull test around the
Mock::given(...).respond_with(...).mount(&server) setup, add request-count
assertions like the cold-range test to verify the fallback performs exactly one
un-ranged GET /{hex} and does not issue a ranged data fetch. Apply the same
assertion update to both affected mock blocks so the fallback path is explicitly
validated.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 8da34acb-1ced-44a1-ab5f-3f296594c1c2
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock,!**/*.lock
📒 Files selected for processing (12)
adr/037-regional-proxy-warming.mdcrates/cache/src/engine.rscrates/cache/src/lib.rscrates/cache/src/origin/fs.rscrates/cache/src/origin/http.rscrates/cache/src/origin/mod.rscrates/cache/src/origin/s3.rscrates/cache/tests/pull_through.rscrates/cache/tests/s3_origin.rscrates/node/Cargo.tomlcrates/node/src/handlers/client.rscrates/node/tests/origin_range_pull.rs
…823) Addresses code review on PR #1007: - Reject an out-of-bounds bounded range (`byte_offset + byte_len` overflows or exceeds the blob) with a `StreamError` BEFORE signing the success response (ADR 005 §Bounded byte ranges), so a malformed client never accepts a signed `ok: true` that `export_range` then aborts mid-stream. New `ServeRejectReason::RangeNotSatisfiable` collapses to `NotFound` on the wire (reputation-benign — a client's bad range must not penalise the node) with a dedicated `serve_stream_rejected_range_not_satisfiable` metric. - Docs: correct the `Origin::size` trait/HTTP comments — a non-success HEAD (404/permission/5xx/disabled-redirect) degrades to `None` like `get_bounded`, and only a transport fault surfaces as an error; the whole-blob fallback re-surfaces a persistent fault. Fix the stale "fetch_range refuses compressed ranges" claim (only S3 does explicitly) and "one chunk" -> "one chunk group". - Tests: resume-to-end (`byte_len == 0`) e2e proving the tail is served (not zero bytes); out-of-bounds reject e2e; the no-outboard fallback now asserts an un-ranged whole-blob GET and zero ranged GETs. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
crates/node/tests/origin_range_pull.rs (1)
752-758: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the range-specific rejection path.
This only proves some signed refusal happened. Since this PR adds a dedicated range-not-satisfiable counter, expose the test
Metricshandle and assertdecdn_serve_stream_rejected_range_not_satisfiable_totalincrements so cache-miss/unknown-channel regressions cannot satisfy the test accidentally.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/node/tests/origin_range_pull.rs` around lines 752 - 758, The current assertion only checks that the request was refused, but it does not verify the new range-specific rejection path. Update the `origin_range_pull` test to expose and inspect the `Metrics` handle used by the server, and assert that `decdn_serve_stream_rejected_range_not_satisfiable_total` increments when the out-of-bounds request is handled. Keep the existing `read_client_msg`/`StreamResponse` check, but add the metric assertion near the same `ClientMessage::StreamResponse` flow so regressions in cache-miss or unknown-channel paths do not pass the test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/node/tests/origin_range_pull.rs`:
- Around line 181-188: The helper in origin_range_pull.rs currently uses
saturating_sub in the byte_len == 0 branch, which can mask an invalid successful
response when resp.body.total_bytes is less than byte_offset. Update the logic
around the expected calculation to explicitly reject that impossible case before
computing the tail size, using the existing symbols resp.body.total_bytes,
byte_offset, and byte_len in the test helper.
---
Nitpick comments:
In `@crates/node/tests/origin_range_pull.rs`:
- Around line 752-758: The current assertion only checks that the request was
refused, but it does not verify the new range-specific rejection path. Update
the `origin_range_pull` test to expose and inspect the `Metrics` handle used by
the server, and assert that
`decdn_serve_stream_rejected_range_not_satisfiable_total` increments when the
out-of-bounds request is handled. Keep the existing
`read_client_msg`/`StreamResponse` check, but add the metric assertion near the
same `ClientMessage::StreamResponse` flow so regressions in cache-miss or
unknown-channel paths do not pass the test.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 70832caf-317d-4d2b-815d-931154d4446c
📒 Files selected for processing (5)
crates/cache/src/origin/http.rscrates/cache/src/origin/mod.rscrates/node/src/handlers/client.rscrates/node/src/metrics.rscrates/node/tests/origin_range_pull.rs
🚧 Files skipped from review as they are similar to previous changes (3)
- crates/cache/src/origin/mod.rs
- crates/cache/src/origin/http.rs
- crates/node/src/handlers/client.rs
) Addresses CodeRabbit review on PR #1007: - `ranged_paid_pull`: reject an impossible advertised `total_bytes` (`< byte_offset`, or smaller than the requested range end) with `checked_sub`/`ensure` instead of `saturating_sub` to zero, so a server that signs a bad size fails the test loudly. - `out_of_bounds_range_is_rejected_before_delivery`: assert the dedicated `serve_stream_rejected_range_not_satisfiable_total` counter increments. The wire `StreamError` collapses to `NotFound` (shared with cache-miss/unknown-channel), so the metric is the only proof the range-not-satisfiable gate fired specifically. `handler_over_http_origin` now returns the `Metrics` handle. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Context
When a node gets a cache miss and must fill from origin, it fetched the whole blob even when the client only asked for a byte range — paying full S3/R2/B2 egress and disk for bytes the client never requested. The node→node side was solved by ADR 037 (window-paced pull-through + bao verified streaming), but the origin tier stayed strictly whole-blob.
The engine machinery to fix this already shipped (#962/#985):
CacheEngine::pull_through_rangefetches just[start,end)+ the sibling{H}.obao4outboard, bao-verifies the span against the BLAKE3 root, and imports a partial blob;export_rangeserves the sub-range back. But none of it was wired into the livecdn/client/v1handler — a ranged miss still pulled the whole blob and sliced in memory, so #990's test couldn't pass.This PR closes #823 and #990.
What changed
crates/cache— the missing size source.pull_through_rangeneeds the blob's exact total size up front (the{H}.obao4outboard alone doesn't pin the final 16 KiB chunk group), and a cold node doesn't have it. AddedOrigin::size(HTTPHEAD→Content-Length, S3HeadObject, fsstat) +CacheEngine::origin_size. AContent-Encoding/ missing / malformed response degrades toNone(and a wrong size is self-validating — it fails bao verification → whole-blob fallback). The tested engine range path is untouched.crates/node— the handler wiring. On a bounded/offset miss (byte_len > 0 || byte_offset > 0),try_range_pull_throughruns the size probe →pull_through_range→ serves the verified partial viaexport_range, before the whole-blob fallback — gated on the existingpull_authorizedownership check. The size gate uses the probed total for the partial blob;deliversources ranged bytes viaexport_range, so payment is metered over the served span. The window-paced fallback is gated onbyte_len == 0so a bounded request can't over-deliver/over-bill the whole blob, and a local store fault on the partial-import path logs atwarn.adr/037— amended, not a new ADR. ADR 037 §Origin-tier pull-through already specifies this design comprehensively, so #823 was an amendment (documents the origin size probe, marks #823 landed) rather than a duplicative new ADR.Tests
crates/node/tests/origin_range_pull.rs(e2e): a cold ranged request fetches only the range (1 ranged GET, 0 whole-blob GETs), delivers the correct bytes, and leaves the blob partial; the no-outboard path falls back to whole-blob; an unauthorized (no-binding) ranged request fronts zero origin egress.Origin::size/origin_sizeunit coverage (HTTP HEAD + compressed-degrades-to-None, S3 HeadObject + compressed + missing, fs stat,NoOrigin).All 930 cache+node tests pass;
cargo clippy --workspace --all-targets,cargo fmt --check, andcargo deny checkare clean.Review
Reviewed by the pr-review-toolkit agents (code quality, silent failures, test coverage, comment accuracy); two correctness findings (window-path over-billing;
CacheError::Storemasked atdebug) and the comment/coverage suggestions were fixed in-branch.Known follow-ups (out of scope)
origin_range_pull_enabledoperator opt-out knob is still unwired (always-attempt matches itstruedefault).stream_fetchrequester can't yet generate bounded-range requests (serving side is complete; requesting side is offset-only).🤖 Generated with Claude Code
Summary by CodeRabbit