Skip to content

feat(protocol): bao verified-range streaming on cdn/client/v1 (#915) - #1052

Merged
yigitdot merged 7 commits into
mainfrom
feat/915-bao-verified-range
Jul 6, 2026
Merged

yigitdot merged 7 commits into
mainfrom
feat/915-bao-verified-range

Conversation

@yigitdot

@yigitdot yigitdot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Implements ADR 038 (#915): the cdn/client/v1 paid-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:

  1. Resume fetches (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.
  2. No safe parallel multi-source fetch (disjoint ranges can't be independently verified). This PR is the safety precondition; the scheduler itself is ADR 039 (out of scope).

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

Receive side (the fix)

  • client-pull replaces the flat blake3::Hasher with a bao verifying decoder in both the buffered and progressive paths. expected_wire replaces the content-byte bound throughout; the aligned superset is trimmed to the requested span (zero-copy Bytes::slice). Resume-tail-corruption and wrong-root now reject with the typed 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 (keeps count_and_cap_stream + the StreamCommitOutcome taxonomy intact). A corrupt/lying upstream is now detected by the tee (HashMismatch) → scored upstream_verify_failed, not promoted, no StreamEnd; a local store fault remains the served-but-not-cached path. Node-to-node payment meters wire bytes.

No StreamRequest/StreamResponse/voucher/StreamEnd envelope 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-targets clean, cargo fmt --check clean, cargo doc clean. Added bao round-trip / resume / corrupt-tail / wrong-root unit tests in client-pull and cache; 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, finish doc accuracy, test-assertion cleanup. Out-of-scope findings spun out: #1054 (empty-blob delivery), #1055 (overlong-range_data guard).

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 a TeeVerdict into reputation scoring. Also: mid-stream corruption no longer misclassifies as a local store fault (TeeSink::write surfaces the import verdict; new upstream_verify_failed routing + abandon_corrupt), the tee decoder splits corruption from truncation (matching the client-side taxonomy), and export_bao_range refuses 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

  • Multi-source parallel fetch scheduler + range-addressed discovery — ADR 039.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added support for verified range-based blob delivery, including range alignment, size calculation, and verification-aware encoding.
    • Introduced a new export path for serving verified blob ranges without the leading size header.
  • Bug Fixes

    • Range pulls now verify integrity during decode and reject incomplete or corrupted deliveries.
    • Delivery accounting and voucher boundaries now use verified wire sizes instead of raw payload lengths.
  • Chores

    • Added a new shared workspace crate and marked the related design decision as accepted.

@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds 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.

Changes

Bao Verified-Range Streaming (ADR 038)

Layer / File(s) Summary
Shared bao-range crate and workspace wiring
Cargo.toml, adr/038-bao-verified-range-streaming.md, crates/bao-range/Cargo.toml, crates/bao-range/src/lib.rs
Adds the decdn-bao-range workspace crate, its alignment/encoding/verification helpers, and marks ADR 038 accepted.
Cache engine bao decode, export, and re-export
crates/cache/Cargo.toml, crates/cache/src/range_pull.rs, crates/cache/src/engine.rs
Re-exports shared range helpers, decodes bao verified-stream input in open_tee_sink, maps verification failures to HashMismatch, and adds export_bao_range.
Client-pull wire accounting and verified decoding
crates/client-pull/Cargo.toml, crates/client-pull/src/lib.rs
Switches receive-path completeness checks to bao wire sizes, removes whole-blob BLAKE3 verification, refactors UpstreamPull for wire-byte semantics, and adds decode_verified_range plus tests.
Node delivery path and pull finalization
crates/node/src/handlers/client.rs, crates/node/src/node_origin.rs
Routes delivery through export_bao_range, adds the tee size header and expected wire-byte accounting, and changes pull finalization to distinguish success, short upstreams, and bao hash mismatches.
Cache range export and wire-size tests
crates/cache/tests/pull_through.rs, crates/cache/tests/range_pull.rs
Adds end-to-end export_bao_range tests and checks bao_encoded_size against the actual header-less wire length produced by encode_verified_range.
Node accounting and range-pull tests
crates/node/tests/support/mod.rs, crates/node/tests/client_loopback.rs, crates/node/tests/node_origin_pull.rs, crates/node/tests/node_to_node_pull_through.rs, crates/node/tests/origin_range_pull.rs
Updates node test helpers and assertions to use bao wire sizes, and changes range-pull and pull-through tests to decode verified bao output and meter vouchers on wire length.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

  • decdn/decdn#1007: Modifies crates/node/src/handlers/client.rs around bounded/offset range delivery, which is directly related to this PR’s switch to cache.export_bao_range and wire-size-based delivery flow.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main protocol change to bao verified-range streaming on cdn/client/v1.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/915-bao-verified-range

Comment @coderabbitai help to get the list of available commands.

@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 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.

Comment thread crates/cache/src/engine.rs Resolved
Comment thread crates/client-pull/src/lib.rs Resolved
@github-actions

github-actions Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 83.21% (was 83.20%, ▲ +0.02%) — 42340/50881 lines

File Coverage Lines Δ
crates/bao-range/src/lib.rs 96.00% 96/100 new
crates/cache/src/engine.rs 89.69% 2262/2522 ▼ 0.99%
crates/cache/src/error.rs 40.74% 11/27 ● 0.00%
crates/cache/src/range_pull.rs 100.00% 3/3 ▲ +4.30%
crates/client-pull/src/lib.rs 87.19% 640/734 ▲ +1.82%
crates/node/src/handlers/client.rs 78.57% 979/1246 ▼ 0.45%
crates/node/src/metrics.rs 84.74% 994/1173 ● 0.00%
crates/node/src/node_origin.rs 88.97% 500/562 ▼ 0.15%
History
Commit Total Δ vs base
991526e 83.20% ● 0.00%
2517b03 83.20% ● 0.00%
9b85d68 83.20% ● 0.00%
bb44676 83.20% ● 0.00%
bccdef6 83.20% ● 0.00%
24b5d21 83.20% ● 0.00%
80d0c80 83.21% ▲ +0.01%
905cb2c (HEAD) 83.21% ▲ +0.02%

yigitdot added a commit that referenced this pull request Jun 30, 2026
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]>

@coderabbitai coderabbitai 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f51f4b and 991526e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock, !**/*.lock
📒 Files selected for processing (18)
  • Cargo.toml
  • adr/038-bao-verified-range-streaming.md
  • crates/bao-range/Cargo.toml
  • crates/bao-range/src/lib.rs
  • crates/cache/Cargo.toml
  • crates/cache/src/engine.rs
  • crates/cache/src/range_pull.rs
  • crates/cache/tests/pull_through.rs
  • crates/cache/tests/range_pull.rs
  • crates/client-pull/Cargo.toml
  • crates/client-pull/src/lib.rs
  • crates/node/src/handlers/client.rs
  • crates/node/src/node_origin.rs
  • crates/node/tests/client_loopback.rs
  • crates/node/tests/node_origin_pull.rs
  • crates/node/tests/node_to_node_pull_through.rs
  • crates/node/tests/origin_range_pull.rs
  • crates/node/tests/support/mod.rs

Comment thread crates/bao-range/src/lib.rs Resolved
Comment thread crates/cache/src/engine.rs Resolved
Comment thread crates/cache/src/engine.rs Resolved
Comment thread crates/cache/tests/pull_through.rs Resolved
Comment thread crates/client-pull/src/lib.rs Resolved
Comment thread crates/client-pull/src/lib.rs Resolved
yigitdot added a commit that referenced this pull request Jun 30, 2026
`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]>
yigitdot added a commit that referenced this pull request Jun 30, 2026
- 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]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist

Copy link
Copy Markdown

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@yigitdot

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 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.

Comment thread crates/client-pull/src/lib.rs Resolved
Comment thread crates/bao-range/src/lib.rs Resolved
yigitdot added a commit that referenced this pull request Jul 2, 2026
`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]>
yigitdot and others added 5 commits July 2, 2026 20:15
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]>
@yigitdot
yigitdot force-pushed the feat/915-bao-verified-range branch from bccdef6 to 24b5d21 Compare July 2, 2026 17:15
…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]>
@yigitdot
yigitdot merged commit 860d725 into main Jul 6, 2026
24 checks passed
@yigitdot
yigitdot deleted the feat/915-bao-verified-range branch July 6, 2026 14:38
yigitdot added a commit that referenced this pull request Jul 6, 2026
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]>
yigitdot added a commit that referenced this pull request Jul 7, 2026
) (#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]>
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