Repository navigation
refactor(bao): type-design tightenings, deferred tests, doc sweep (#1060) - #1070
Conversation
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]>
- 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]>
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]>
WalkthroughThis PR switches verified-range streaming and pull accounting to wire-byte sizing. ChangesBao Wire-Byte Accounting Refactor
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 refactors the cache tee-fill and progressive pull-through paths to support header-less bao streams in accordance with ADR 038. It introduces a TeeReservation mechanism to defer framing the verifying decoder until the whole-blob size is known from the upstream header. Additionally, it introduces a dedicated CacheError::VerifyFailed variant to distinguish mid-stream bao verification failures from whole-stream HashMismatch errors. Tests have been updated accordingly, including a new multi-group offset resume test and a golden wire size test to prevent silent encoding shape changes. I have no further feedback to provide as the changes are well-implemented and thoroughly tested.
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.
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]>
|
/gemini review |
There was a problem hiding this comment.
Pull request overview
This PR applies the follow-ups from #1060 to the ADR 038 bao verified-range streaming work: it tightens type design around range sizing and verification failure taxonomy, adds the deferred multi-group resume + golden wire-size tests, and updates docs/comments to reflect bao-per-group verification and wire-vs-content byte accounting. The intent is refactoring and misuse-prevention (no protocol/wire behavior changes).
Changes:
- Move wire-length computation onto
AlignedRange(blob_size+wire_len()), and simplifyencode_verified_rangecall sites by removing redundantblob_sizeparameters. - Replace the
Hash::EMPTYsentinel path with explicit verification-failure outcomes (CacheError::VerifyFailed/StreamCommitOutcome::VerifyFailed) and propagate through the tee/window pull-through flow. - Add missing coverage for multi-group resume and a hard-coded “golden” wire-size expectation to detect upstream
bao-treeencoding-shape changes.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/tests/node_to_node_pull_through.rs | Update test narratives/error wording to reflect bao group verification (“verify-failed”) rather than whole-blob hashing. |
| crates/node/tests/node_origin_pull.rs | Adjust encode_verified_range usage to match the new signature (no separate blob_size arg). |
| crates/node/tests/client_loopback.rs | Add multi-group resume test that asserts wire-bytes metering exceeds content suffix when proof parents are present. |
| crates/node/src/node_origin.rs | Clarify accounting semantics: delivered bytes vs voucher/wire bytes under bao streaming; rename accessor to expected_wire_bytes. |
| crates/node/src/handlers/client.rs | Switch tee handling to a reservation→begin flow (content size known after upstream header), and route corruption via VerifyFailed. |
| crates/client-pull/src/lib.rs | Replace free bao_encoded_size usage with AlignedRange::wire_len; rename expected→expected_wire_bytes; update docs for bao verification model. |
| crates/cache/tests/range_pull.rs | Update call sites for new encode_verified_range signature; add golden wire-size test; refine proof-overhead comment. |
| crates/cache/src/lib.rs | Re-export TeeReservation to support the new two-phase tee opening API. |
| crates/cache/src/error.rs | Add CacheError::VerifyFailed to represent mid-stream bao verification failures without fake “actual hash” sentinels. |
| crates/cache/src/engine.rs | Implement TeeReservation + begin(content_size); refactor tee decode source to be header-less; map verify failures explicitly. |
| crates/bao-range/src/lib.rs | Extend AlignedRange to store blob_size and provide wire_len(); remove redundant size parameter from encode_verified_range. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
|
/gemini review |
Coverage reportTotal: 82.11% (was 82.11%, ● 0.00%) — 42380/51615 lines
History
|
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]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
crates/cache/tests/range_pull.rs (1)
344-346: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDuplicated header-strip logic.
The "strip the 8-byte size header from
combined" computation is repeated verbatim inassert_encoded_size_matchesand the golden test. Consider extracting a small shared helper to avoid drift if the header size or error message needs to change.♻️ Proposed helper extraction
+fn strip_size_header(combined: &[u8]) -> anyhow::Result<u64> { + u64::try_from(combined.len())? + .checked_sub(8) + .ok_or_else(|| anyhow::anyhow!("combined encoding shorter than its 8-byte header")) +}Then call
strip_size_header(&combined)?at both use sites instead of inlining the computation.Also applies to: 403-405
🤖 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/cache/tests/range_pull.rs` around lines 344 - 346, The 8-byte header stripping logic is duplicated in `assert_encoded_size_matches` and the golden test, so extract a shared helper such as `strip_size_header` that computes the wire length from `combined` and returns the same error on short input. Update both call sites to use that helper instead of inlining the `u64::try_from(...).checked_sub(8)` sequence, keeping the behavior and error message consistent.crates/client-pull/src/lib.rs (1)
556-561: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated wire-len derivation between
fetch_innerandopen_progressive_pull.Both functions independently re-derive the aligned range and
wire_len()fromresp.body.total_bytes/byte_offset, with near-identical comments. Since this PR already touches both sites for the rename, consider extracting a small shared helper (e.g.fn expected_wire_bytes(byte_offset: u64, total_bytes: u64) -> anyhow::Result<u64>) to keep the two call sites from drifting.♻️ Proposed helper
+fn expected_wire_bytes(byte_offset: u64, total_bytes: u64) -> anyhow::Result<u64> { + let aligned = align_range(byte_offset, 0, total_bytes) + .map_err(|e| anyhow::anyhow!("range alignment: {e}"))?; + Ok(aligned.wire_len()) +}Then both call sites become
let expected_wire = expected_wire_bytes(byte_offset, total_bytes)?;.Also applies to: 908-911
🤖 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/client-pull/src/lib.rs` around lines 556 - 561, The wire-length calculation is duplicated in the call sites used by fetch_inner and open_progressive_pull, which risks the logic drifting over time. Extract the shared aligned-range/wire_len derivation into a small helper such as expected_wire_bytes(byte_offset, total_bytes) in crate::client-pull::lib, and update both fetch_inner and open_progressive_pull to call it instead of re-implementing the same logic and comments.
🤖 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/cache/src/engine.rs`:
- Around line 3121-3197: The match on `bao_tree::io::DecodeError` inside
`bao_decoded_source` is not future-proof because the enum is non-exhaustive. Add
a fallback `_` arm in that `match decode_err` block, and map any unknown variant
to the same transport-class error handling used for non-corruption cases so the
function continues to compile against `bao_tree 0.16.0` and later.
---
Nitpick comments:
In `@crates/cache/tests/range_pull.rs`:
- Around line 344-346: The 8-byte header stripping logic is duplicated in
`assert_encoded_size_matches` and the golden test, so extract a shared helper
such as `strip_size_header` that computes the wire length from `combined` and
returns the same error on short input. Update both call sites to use that helper
instead of inlining the `u64::try_from(...).checked_sub(8)` sequence, keeping
the behavior and error message consistent.
In `@crates/client-pull/src/lib.rs`:
- Around line 556-561: The wire-length calculation is duplicated in the call
sites used by fetch_inner and open_progressive_pull, which risks the logic
drifting over time. Extract the shared aligned-range/wire_len derivation into a
small helper such as expected_wire_bytes(byte_offset, total_bytes) in
crate::client-pull::lib, and update both fetch_inner and open_progressive_pull
to call it instead of re-implementing the same logic and comments.
🪄 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: 1f3a8d43-8913-47fe-8e46-5e873ece7b1f
📒 Files selected for processing (11)
crates/bao-range/src/lib.rscrates/cache/src/engine.rscrates/cache/src/error.rscrates/cache/src/lib.rscrates/cache/tests/range_pull.rscrates/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.rs
💤 Files with no reviewable changes (1)
- crates/node/tests/node_origin_pull.rs
There was a problem hiding this comment.
Code Review
This pull request refactors the cache's tee-fill mechanism to consume a header-less bao interleaved stream by introducing a TeeReservation step. The TeeReservation holds the in-flight claim until the whole-blob content size is known, at which point the verifying decoder is framed out-of-band via TeeReservation::begin. Additionally, a new VerifyFailed error variant is introduced to distinguish mid-stream bao verification failures from whole-stream hash mismatches. The PR also updates various metrics, tests, and APIs to consistently use expected_wire_bytes and includes a golden wire size test to guard against silent encoding changes. I have no feedback to provide as there are no review comments.
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.
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]>
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]>
Closes #1060 — the agreed follow-ups deferred from the #1052 multi-agent review of ADR 038 bao verified-range streaming. The four blockers were fixed in 80d0c80; these are the type-design tightenings, two test-coverage gaps, and the doc sweep left stale by the whole-blob-hash → bao-per-group shift. No wire/behaviour change — the refactors are type tightenings that close misuse seams the crypto never sees.
Section A — type design
AlignedRangecarriesblob_size+wire_len()— replaces the freebao_encoded_size(total, ranges)at its production call sites, so a mismatched(total, ranges)pair can't silently yield a plausible-but-wrong payment bound. Dropped the now-redundantblob_sizeparam fromencode_verified_range.Dedicated
StreamCommitOutcome::VerifyFailed/CacheError::VerifyFailed— replaces theHash::EMPTYsentinel inHashMismatch(which rendered as the real empty-blob hash). Routed through the tee corruption-scoring path end-to-end.Renamed
expected→expected_wire_bytesthroughUpstreamPull/NodeProgressivePull/receive_and_pay, where the wire-vs-content unit lived only in comments.TeeSinktakes the content size at open —open_tee_sinkreturns aTeeReservation(the coalescing in-flight claim), andTeeReservation::begin(content_size)frames the verifying decoder once the upstream's signedtotal_bytesis known. The forwarded wire is header-less; the magic first 8-byte write is gone.Design note: the size is only known from the upstream header after the coalescing claim must be taken, so this uses a two-phase reservation →
beginsplit rather than a setter — keeping the cache: concurrent origin pull-through for the same hash can result in duplicate fetches and redundant insertions into iroh-blobs #305 coalescing guarantee intact while passing the size at decoder-creation time.Section B — deferred tests
client_byte_offset_returns_suffix_multi_group): a ~200 KiB blob resumed at a non-aligned 70 KiB offset, soexport_bao_range↔decode_verified_rangerun over real proof parent nodes (assertswire > content) — the existing test uses a single-leaf 4 KiB blob.1,578,944-byte expectation for a 1.5 MiB blob (96 chunk groups → 95 parents × 64 B + content), so abao-treebump that changes the encoding shape fails instead of passing silently (ADR 038 §Risks). Cross-checked against the real emitted encoding.strictly more→at least as muchcomment.Section C — doc / comment sweep
Aligned stale whole-blob-hash and "the tee's
import_bao" narratives with the bao-per-group model acrossclient-pull,engine,node_origin,handlers/client, andnode_to_node_pull_through; added the content-vs-wire unit notes (pull_through_bytes, region accounting, depositguard_bytes) and theChannelRecvStreaminert-by-design notes. No behaviour change.Review follow-ups
02ae7bb, from a multi-agent self-review): routeCacheError::HashMismatchalongsideVerifyFailedat the three tee-verdict sites. Unreachable on a fully-decoded tee stream today, but it guards against a future decoder change landing a corrupt upstream in the benign local-store-fault arm (the protocol/node: bao verified-range streaming on cdn/client/v1 (verified resume + parallel multi-source fetch) #915 swallow). Same commit fixes three stale docs: therecv_bytestruncation path,encode_verified_range's# Errors, and theguard_bytesproof-overhead figure.cargo docprivate intra-doc link (414f019);bao_decoded_sourcecontent_sizeprovenance (8dbb824, Copilot); dedupstrip_size_header/aligned_wire_lenhelpers (881fd02, CodeRabbit)._arm to theDecodeErrormatch — verifiedbao-tree 0.16.0'sio::DecodeErroris not#[non_exhaustive](5 variants), so the match is exhaustive; a wildcard would tripunreachable_patternsunder-D warnings, and keeping it exhaustive is intentional so a future variant breaks the build (CodeRabbit withdrew the finding).Verification
cargo fmt --check+cargo clippy --workspace --all-targetsclean.cargo nextest run: bao-range/cache/client-pull 293 passed; node 681 passed (run--no-fail-fastper the macOS APFS gotcha).cargo doc,clippy,doctest,rustfmt,public API snapshot,cargo deny.🤖 Generated with Claude Code