Repository navigation
feat(protocol): bao verified-range streaming on cdn/client/v1 (#915) - #1052
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds a shared bao verified-range crate, routes cache/client/node delivery through bao wire encoding and decoding, and updates completeness, accounting, and tests to use verified wire-byte sizes instead of plaintext lengths. ChangesBao Verified-Range Streaming (ADR 038)
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related issues
Possibly related PRs
🚥 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 ADR 038, introducing the decdn-bao-range leaf crate to support header-less Bao verified-range streaming on cdn/client/v1 while maintaining the CLI's iroh-blobs-free invariant. It updates the cache engine to export and verify Bao streams, and refactors the client pull logic to decode and verify these streams, closing the resume gap. Feedback on the changes highlights a compilation issue in crates/cache/src/engine.rs due to the use of unstable let_chains syntax, which should be refactored for stable Rust compatibility. Additionally, an optimization is suggested in crates/client-pull/src/lib.rs to achieve zero-copy slicing of the decoded plaintext using Bytes::slice instead of copying.
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.
Coverage reportTotal: 83.21% (was 83.20%, ▲ +0.02%) — 42340/50881 lines
History
|
Take ownership of the decoded plaintext as Bytes once and return a zero-copy slice view for the resume/trim path, instead of copying the trimmed span via Bytes::copy_from_slice. Guards the upper bound explicitly so a short decode still errors cleanly and Bytes::slice never panics out of range. (gemini-code-assist review, PR #1052) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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/bao-range/src/lib.rs`:
- Around line 248-286: encode_verified_range currently verifies whatever bytes
are present in range_data, but it does not reject extra trailing bytes beyond
aligned.fetch_len(), so corrupt overlong responses can slip through. Add an
explicit length check at the start of encode_verified_range, before constructing
OffsetReadAt or calling encode_ranges_validated, to ensure range_data.len()
matches aligned.fetch_len() exactly and return a RangeVerifyError on mismatch.
In `@crates/cache/src/engine.rs`:
- Around line 2987-2991: The `import_and_verify_stream` path in `engine.rs` is
masking a truncated tee header by returning `None` when `reader.recv_exact(&mut
size)` fails, which makes malformed peer input look like EOF. Update the
header-read handling around this size read to propagate a
missing/truncated-input error instead of treating it as an empty fill, so the
caller can reject the stream before any store import or empty-blob promotion
occurs. Use the existing `reader.recv_exact`/header parsing flow in this
tee-import branch to distinguish clean closure from short header reads.
- Around line 2093-2097: Handle the zero-byte whole-blob export case before
calling align_range in export_bao_range. When byte_offset, byte_len, and
blob_size indicate an empty blob export, confirm the store already has a
complete zero-byte blob and return Bytes::new() immediately instead of routing
through the range-alignment path. Keep the existing align_range-based behavior
for all non-empty exports and preserve the current error mapping around
export_bao_range.
In `@crates/cache/tests/pull_through.rs`:
- Line 4492: The assertion in the test currently uses direct `[..]` slicing,
which should be avoided per the Rust style guideline. Update the
`anyhow::ensure!` check in `pull_through.rs` to compare the full contents
through slice accessors on `got` and `payload` rather than using direct indexing
syntax, keeping the same “whole-blob bao decodes to original” assertion
semantics.
In `@crates/client-pull/src/lib.rs`:
- Around line 1032-1044: Update the public docs for `finish` in `ClientPull` to
match the current behavior: it now only checks that the full promised wire byte
count was received and no longer performs whole-blob rehashing or returns
`HashMismatch`. Adjust the method comment near `finish` to describe the
short-delivery check and the `short-delivery` failure path, using the `finish`
symbol and related completeness logic so the docs align with the implementation.
- Around line 682-689: The empty-blob fast path in the decode flow around
align_range, BaoTree::new, and DecodeResponseIter must verify the root hash when
total_bytes is zero instead of returning an empty buffer unconditionally. Add an
explicit check against blake3::hash(&[]) before accepting the empty input, and
keep the existing decode path for non-empty blobs. Also add a regression test
covering the zero-length case to ensure only the correct empty-blob hash is
accepted.
🪄 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: 54cbc6ce-8215-4120-8be5-d30442b0aae9
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock,!**/*.lock
📒 Files selected for processing (18)
Cargo.tomladr/038-bao-verified-range-streaming.mdcrates/bao-range/Cargo.tomlcrates/bao-range/src/lib.rscrates/cache/Cargo.tomlcrates/cache/src/engine.rscrates/cache/src/range_pull.rscrates/cache/tests/pull_through.rscrates/cache/tests/range_pull.rscrates/client-pull/Cargo.tomlcrates/client-pull/src/lib.rscrates/node/src/handlers/client.rscrates/node/src/node_origin.rscrates/node/tests/client_loopback.rscrates/node/tests/node_origin_pull.rscrates/node/tests/node_to_node_pull_through.rscrates/node/tests/origin_range_pull.rscrates/node/tests/support/mod.rs
`engine.rs` imports `OriginPullError`, not the bare `OriginError` enum, so the `[\`OriginError\`]` link was unresolved and failed `cargo doc` under `-D warnings`. Point it at `OriginPullError` — the type `import_and_verify_stream` actually returns when the body-phase classifier collapses an untyped transport error. (CI doc gate, PR #1052) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- engine: bao_decoded_source propagates a truncated/missing 8-byte tee header as an error instead of treating it as a clean EOF, so a malformed peer stream fails the import loudly rather than committing empty plaintext. - client-pull: rewrite the `finish` rustdoc to the wire-byte-completeness semantics — it no longer re-hashes the whole blob or returns HashMismatch (bao verification is delegated to the tee + downstream decoder, ADR 038). - tests: use as_ref()/as_slice() instead of `[..]` slicing in a pull_through assertion. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
/gemini review |
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces the decdn-bao-range leaf crate to share iroh-blobs-free Bao verified-range helpers between decdn-cache and decdn-client-pull. It transitions the client-facing delivery path to use header-less Bao interleaved verified-stream encoding, closing the resume verification gap and updating payment metering to count wire bytes (content plus proof overhead). Feedback on the changes highlights two key issues: a potential Out-Of-Memory (OOM) vulnerability in decode_verified_range caused by pre-allocating memory based on untrusted total_bytes headers, and a logic bug in align_range that incorrectly rejects valid range requests for empty (0-byte) blobs.
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.
`decode_verified_range` pre-allocated `Vec::with_capacity(fetch_len())`, where `fetch_len()` derives from the untrusted server `total_bytes` header — a server claiming a huge size could drive an over-allocation. Decoded plaintext can never exceed the received `bao_wire.len()`, so cap the capacity hint there. (gemini-code-assist review, PR #1052) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Implement ADR 038: the cdn/client/v1 paid-delivery payload now carries bao's interleaved verified-stream encoding instead of a flat sequential BLAKE3 hash. This closes the resume-verification gap (byte_offset > 0 previously skipped verification entirely — a node could serve a corrupt tail and the receiver could not reject it) and establishes the safety precondition for parallel multi-source fetch (ADR 039, out of scope). Serve side: - New decdn-bao-range leaf crate (iroh-blobs-free, #578) holding the shared align_range / bao_encoded_size / encode_verified_range helpers; cache re-exports it via range_pull with a lock-step block-size test. - CacheEngine::export_bao_range emits the header-less bao wire for the group-aligned superset of a request; takes the authoritative whole-blob size from the caller (an origin-tier range pull imports a *partial* blob whose status() size is None, #823). - deliver() always serves bao (no raw-byte path), metering wire bytes. Receive side (the security fix): - client-pull replaces the flat blake3::Hasher with a bao verifying decoder in both the buffered and progressive paths; expected_wire (bao-encoded size) replaces the content-byte bound everywhere; the group-aligned superset is trimmed back to the requested span. Resume and wrong-root now reject with the HashMismatch sentinel. Window pull-through (full pipelined, ADR 037 preserved end-to-end): - The serving node forwards the upstream's bao verbatim to the client and tees the same stream into its store via a channel-backed verifying decoder (import path keeps count_and_cap + StreamCommitOutcome intact). A corrupt/lying upstream is detected by the tee (HashMismatch) and scored as upstream_verify_failed without promoting or sending StreamEnd; a local store fault is the served-but-not-cached path. Node-to-node payment now meters wire bytes. No envelope or ALPN change (pre-finalisation clean break). Updates the integration harnesses for wire-byte metering and bao decoding; flips ADR 038 to Accepted. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Take ownership of the decoded plaintext as Bytes once and return a zero-copy slice view for the resume/trim path, instead of copying the trimmed span via Bytes::copy_from_slice. Guards the upper bound explicitly so a short decode still errors cleanly and Bytes::slice never panics out of range. (gemini-code-assist review, PR #1052) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`engine.rs` imports `OriginPullError`, not the bare `OriginError` enum, so the `[\`OriginError\`]` link was unresolved and failed `cargo doc` under `-D warnings`. Point it at `OriginPullError` — the type `import_and_verify_stream` actually returns when the body-phase classifier collapses an untyped transport error. (CI doc gate, PR #1052) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- engine: bao_decoded_source propagates a truncated/missing 8-byte tee header as an error instead of treating it as a clean EOF, so a malformed peer stream fails the import loudly rather than committing empty plaintext. - client-pull: rewrite the `finish` rustdoc to the wire-byte-completeness semantics — it no longer re-hashes the whole blob or returns HashMismatch (bao verification is delegated to the tee + downstream decoder, ADR 038). - tests: use as_ref()/as_slice() instead of `[..]` slicing in a pull_through assertion. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`decode_verified_range` pre-allocated `Vec::with_capacity(fetch_len())`, where `fetch_len()` derives from the untrusted server `total_bytes` header — a server claiming a huge size could drive an over-allocation. Decoded plaintext can never exceed the received `bao_wire.len()`, so cap the capacity hint there. (gemini-code-assist review, PR #1052) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
bccdef6 to
24b5d21
Compare
…r taxonomy (#915 review) A multi-agent review of #1052 found the window pull-through path moved corruption detection to the tee's bao decoder (ADR 038) without rewiring the consequences. Four fixes: - CRITICAL: a wire-complete-but-corrupt upstream was scored `Delivered` (and gossiped) before tee.finish() reported the mismatch, while the downstream blamed the honest forwarder. The finalization now settles the tee FIRST and feeds a `TeeVerdict` into `NodeProgressivePull::finish`, which scores `Corruption` (with provider identity logged) on a corrupt verdict. - Mid-stream corruption was misclassified as a LOCAL store fault (`local_tee_failed`, no reputation outcome): `TeeSink::write` now surfaces the ended import task's own verdict (shared `verdict()` mapping), and the forward loop routes a `HashMismatch` write failure to `upstream_verify_failed` + `abandon_corrupt()`. - `bao_decoded_source` no longer collapses every `DecodeError` into `BaoVerifyMarker`: only Parent/LeafHashMismatch classify as corruption; Io/*NotFound pass through as transport-class (matching the client-side decoder), and the marker now carries the failing node/chunk detail. - `export_bao_range` refuses an export stream that ends without `Done` instead of serving + billing a silently truncated wire. Tests: mid-stream corruption window test (upstream_verify_failed fires, local_tee_failed does not, reputation drops); lying-upstream test now asserts exclusive counters + score drop; client-pull corrupt-middle- group-without-tail (ADR 038 AC#2) and truncation-is-not-HashMismatch; tee wrong-content-bao fixture (was passing for the wrong reason), raw- garbage and truncated-header siblings. Metric/doc comments updated to the tee-as-detector model. Co-Authored-By: Claude Fable 5 <[email protected]>
ADR 038 (bao verified-range streaming) is not yet finalized; revert its status to Draft while the design continues to iterate under #915. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Type-design follow-ups from the #1052 review that close the wire-vs-content misuse seams the crypto never sees: - AlignedRange now carries its blob_size and exposes wire_len(), replacing the free-standing bao_encoded_size(total, ranges) at its production call sites so a mismatched (total, ranges) pair can't yield a wrong payment bound. Drop the now-redundant blob_size param from encode_verified_range. - Add a dedicated StreamCommitOutcome::VerifyFailed / CacheError::VerifyFailed for a mid-stream bao chunk-group verify failure, replacing the Hash::EMPTY sentinel in HashMismatch (which rendered as the real empty-blob hash). - Rename UpstreamPull.expected -> expected_wire_bytes through UpstreamPull / NodeProgressivePull / receive_and_pay, where the wire-vs-content unit previously lived only in comments. - TeeSink takes the content size at open: open_tee_sink now returns a TeeReservation (the coalescing in-flight claim), and TeeReservation::begin (content_size) frames the verifying decoder once the upstream's signed total_bytes is known. The forwarded wire is header-less; the magic first 8-byte write is gone. Co-Authored-By: Claude Opus 4.8 <[email protected]>
) (#1070) * refactor(bao): tighten types for verified-range streaming (#1060) Type-design follow-ups from the #1052 review that close the wire-vs-content misuse seams the crypto never sees: - AlignedRange now carries its blob_size and exposes wire_len(), replacing the free-standing bao_encoded_size(total, ranges) at its production call sites so a mismatched (total, ranges) pair can't yield a wrong payment bound. Drop the now-redundant blob_size param from encode_verified_range. - Add a dedicated StreamCommitOutcome::VerifyFailed / CacheError::VerifyFailed for a mid-stream bao chunk-group verify failure, replacing the Hash::EMPTY sentinel in HashMismatch (which rendered as the real empty-blob hash). - Rename UpstreamPull.expected -> expected_wire_bytes through UpstreamPull / NodeProgressivePull / receive_and_pay, where the wire-vs-content unit previously lived only in comments. - TeeSink takes the content size at open: open_tee_sink now returns a TeeReservation (the coalescing in-flight claim), and TeeReservation::begin (content_size) frames the verifying decoder once the upstream's signed total_bytes is known. The forwarded wire is header-less; the magic first 8-byte write is gone. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(bao): cover multi-group resume and pin a golden wire number (#1060) - Add client_byte_offset_returns_suffix_multi_group: a ~200 KiB blob resumed at a non-group-aligned 70 KiB offset, so the production export_bao_range ↔ decode_verified_range pair runs over real proof PARENT nodes (the existing single-leaf 4 KiB test has none). Asserts wire > content to prove the spine is non-empty. - Add bao_encoded_size_whole_blob_1_5_mib_is_golden: a hard-coded 1,578,944 wire-byte expectation for a 1.5 MiB blob, so a bao-tree bump that changes the encoding shape fails instead of passing (every other expectation is computed with the same helper production uses). Cross-checked against the real emitted encoding. - Fix the "strictly more" comment in assert_encoded_size_matches to "at least as much" (equal for a single-leaf tree). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(bao): sweep stale whole-blob-hash and import_bao narratives (#1060) Align comments with the ADR 038 bao-per-group model left stale by the whole-blob-hash → per-chunk-group verification shift. No behaviour change. - client-pull: HashMismatch is a bao-verify failure, not a whole-blob re-hash; fetch_inner underflow-guard rationale; UpstreamPull/finish docs; the four "the tee's import_bao" mentions now name the verifying decoder (import_and_verify_stream). - engine: import_and_verify_stream doc notes pull_through_bytes meters decoded plaintext on the tee path (under the wire that left the upstream); ChannelRecvStream stop/id inert-by-design and recv_bytes zero-length notes. - node_origin: on_pull "delivered length" and the buffered-path region accounting clarified (bytes.len() is content, the watermark is wire). - handlers/client: note the deposit guard_bytes is a content ceiling while billing is wire (~0.4% loose, benign). - node_to_node_pull_through: verify-failed close reason and bao-per-group narrative. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(bao): drop private intra-doc link from public HashMismatch (#1060) The public `HashMismatch` docstring linked `[decode_verified_range]`, a private fn — `rustdoc::private_intra_doc_links` (denied under RUSTDOCFLAGS=-D warnings) failed the cargo doc CI job. Use a plain code span instead. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(bao): fix bao_decoded_source content_size provenance (#1060) The doc said content_size is passed to CacheEngine::open_tee_sink, but the two-phase split moved it to TeeReservation::begin (once the upstream header is known). Correct the reference (Copilot review). Co-Authored-By: Claude Opus 4.8 <[email protected]> * refactor(bao): dedup wire-len derivation and header-strip (#1060) Address CodeRabbit nitpicks on this PR's own added/modified code: - Extract strip_size_header() in range_pull.rs, used by both assert_encoded_size_matches and the golden test. - Extract aligned_wire_len(byte_offset, total_bytes) in client-pull, shared by fetch_inner and open_progressive_pull so the two receive paths can't drift. Co-Authored-By: Claude Opus 4.8 <[email protected]> * refactor(bao): defensive corruption routing + doc accuracy (#1060) Follow-ups from a multi-agent self-review of this PR (no behaviour change today): - Route CacheError::HashMismatch alongside VerifyFailed at the three tee-verdict sites (mid-stream write, finalize verdict, finalize arm). A whole-blob HashMismatch is unreachable on a fully-decoded tee stream, but nothing guarded it — a future decoder change could otherwise land it in the benign local-store-fault arm and score a corrupt upstream as Delivered + send StreamEnd (the exact #915 swallow). Both are "upstream served wrong bytes". - Fix the ChannelRecvStream::recv_bytes comment: after the header phase was removed, a truncated feed surfaces as a recv_bytes short read -> the decoder's mid-tree *NotFound path, not via recv_exact's eof(). - Reword encode_verified_range's # Errors doc: blob_size is no longer a param (read from aligned.blob_size()). - Qualify the guard_bytes proof-overhead figure (varies with blob size; true wire ceiling is enforced downstream by the overrun check). Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Implements ADR 038 (#915): the
cdn/client/v1paid-delivery payload now carries bao's interleaved verified-stream encoding instead of a flat sequential BLAKE3 hash.Why
A flat digest commits only to the whole blob and is inherently sequential, which left two gaps:
byte_offset > 0) skipped verification entirely — a node could serve a corrupt tail on a resumed range and the receiver had no way to reject it. This is a live security gap. ✅ closed.The content hash already requested is the bao root, so any chunk-group range verifies independently against it with an
O(log n)proof.What changed
Serve side
decdn-bao-rangeleaf crate (iroh-blobs-free, CLI binary-split regression: publisher links cache crate (iroh-blobs/AWS SDK) #578) with the sharedalign_range/bao_encoded_size/encode_verified_rangehelpers;decdn-cachere-exports them viarange_pullwith a lock-step block-size test.CacheEngine::export_bao_rangeemits the header-less bao wire for the group-aligned superset of a request. It takes the authoritative whole-blob size from the caller — an origin-tier range pull (Partial/range origin pull-through: avoid fetching a whole blob from origin to serve a byte range on cache miss #823) imports a partial blob whosestatus()size isNone, so re-deriving it would fail the very ranged serve the partial import enabled.deliver()always serves bao (no raw-byte path); vouchers meter wire bytes (content + ~0.4% proof).Receive side (the fix)
client-pullreplaces the flatblake3::Hasherwith a bao verifying decoder in both the buffered and progressive paths.expected_wirereplaces the content-byte bound throughout; the aligned superset is trimmed to the requested span (zero-copyBytes::slice). Resume-tail-corruption and wrong-root now reject with the typedHashMismatchsentinel.Window pull-through — full pipelined, ADR 037 preserved end-to-end
count_and_cap_stream+ theStreamCommitOutcometaxonomy intact). A corrupt/lying upstream is now detected by the tee (HashMismatch) → scoredupstream_verify_failed, not promoted, noStreamEnd; a local store fault remains the served-but-not-cached path. Node-to-node payment meters wire bytes.No
StreamRequest/StreamResponse/voucher/StreamEndenvelope change and no ALPN bump (pre-finalisation clean break). ADR 038 stays Draft — the design continues to iterate under #915, so this PR no longer flips it to Accepted.Tests
Full workspace green (
cargo nextest run --workspace: 2061 passed),cargo clippy --workspace --all-targetsclean,cargo fmt --checkclean,cargo docclean. Added bao round-trip / resume / corrupt-tail / wrong-root unit tests inclient-pullandcache; updated the node integration harnesses for wire-byte metering and bao decoding (including the cold-partial ranged serve).Review follow-ups
CodeRabbit/gemini rounds: truncated tee header propagated instead of EOF, zero-copy decoded-range trim, OOM-safe decode capacity hint,
finishdoc accuracy, test-assertion cleanup. Out-of-scope findings spun out: #1054 (empty-blob delivery), #1055 (overlong-range_dataguard).Multi-agent self-review (80d0c80): fixed a critical regression — on the window path a wire-complete-but-corrupt upstream was scored
Delivered(and gossiped) while the downstream blamed the honest forwarder; the finalization now settles the tee first and feeds aTeeVerdictinto reputation scoring. Also: mid-stream corruption no longer misclassifies as a local store fault (TeeSink::writesurfaces the import verdict; newupstream_verify_failedrouting +abandon_corrupt), the tee decoder splits corruption from truncation (matching the client-side taxonomy), andexport_bao_rangerefuses a truncated export stream. Pinned by 5 new tests incl. a mid-stream-corruption window test with reputation-drop assertions. Remaining polish tracked in #1060.Out of scope
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Chores