Repository navigation
fix(cache): serve empty (0-byte) blobs on the bao cdn/client/v1 path (#1054) - #1085
Conversation
…1054) Under ADR 038, cdn/client/v1 serve and receive route through align_range(byte_offset, byte_len, total_bytes), which rejected byte_offset >= blob_size. A 0-byte blob (align_range(0, 0, 0)) therefore errored with RangeOutOfBounds on both the serve (export_bao_range) and the receiver (decode_verified_range / aligned_wire_len), whereas the pre-bao get()/export_range path served it as empty bytes — a behavior regression. Support empty blobs (issue option 1): - align_range: admit the whole (empty) blob (0, 0) as an empty AlignedRange (fetch_start == fetch_end == 0, empty chunk_ranges, zero wire_len); a positive offset or explicit positive length on a 0-byte blob still rejects. - bao_encoded_size: short-circuit an empty range set to 0 (bao-tree's pre-order chunk iterator asserts non-empty ranges). - export_bao_range: return empty directly for blob_size == 0, so the serve emits no ChunkData and a bare StreamEnd. - decode_verified_range: prove the empty stream against the empty root blake3::hash(&[]) explicitly — a non-empty requested hash is a HashMismatch. Without this the empty range decodes trivially and would be accepted for ANY root (the silent verification bypass fetch_inner already warns about). The window pull-through tee needs no change: its existing hash verification already promotes the empty-root blob and fails closed for a wrong hash. Tests: align_range empty cases; export_bao_range empty round-trip; decode empty accept/reject; tee empty commit + fail-closed; and an end-to-end node-to-node 0-byte delivery regression test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
WalkthroughThis PR adds explicit 0-byte blob handling across range sizing, cache export, client verification, and node delivery paths. Empty blobs now return empty bytes when the empty root matches, and mismatched empty claims fail with typed errors. ChangesEmpty blob support across verified-range flow
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant ClientHandler
participant CacheEngine
participant decode_verified_range
participant ChannelState
ClientHandler->>CacheEngine: stream_fetch for 0-byte blob
CacheEngine->>decode_verified_range: verify empty root
decode_verified_range-->>CacheEngine: empty Bytes
CacheEngine-->>ClientHandler: empty Bytes
ClientHandler->>ChannelState: inspect persisted state
ChannelState-->>ClientHandler: no nonce advance, zero bytes delivered
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 addresses issue #1054 by adding comprehensive support for empty (0-byte) blobs across the bao-range, cache, and client-pull crates. It ensures that 0-byte blobs are correctly aligned, verified against the empty root hash, and transferred as empty bytes without triggering out-of-bounds errors or verification bypasses. There are no review comments, and I have no additional feedback to provide.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
crates/node/tests/client_loopback.rs (1)
290-323: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueNo cleanup of
server_task/endpoints on early assertion failure.If any
ensure!at lines 303, 310-314, or 315-319 fails, orstream_fetchat line 301 errors, the function returns early before line 321-323, leavingclient_ep/server_epunclosed andserver_taskun-awaited (it will only terminate when the test's tokio runtime is torn down). Not a correctness bug for the assertion itself, but on failure the panic message loses theserver_task.await?outcome and the task keeps running until the runtime drops.♻️ Optional: guard cleanup with a helper or `tokio::select!`
- anyhow::ensure!(got.as_ref().is_empty(), "empty blob delivers empty bytes"); + let result = (|| -> anyhow::Result<()> { + anyhow::ensure!(got.as_ref().is_empty(), "empty blob delivers empty bytes"); + let persisted = store.load_all()?; + let only = persisted + .first() + .ok_or_else(|| anyhow::anyhow!("no persisted channel"))?; + anyhow::ensure!( + only.last_nonce() == U256::ZERO, + "no voucher for a 0-byte blob, nonce: {}", + only.last_nonce() + ); + anyhow::ensure!( + only.last_bytes_delivered() == U256::ZERO, + "0 bytes delivered, got {}", + only.last_bytes_delivered() + ); + Ok(()) + })(); + + client_ep.close().await; + server_ep.close().await; + server_task.abort(); + result?; + Ok(())🤖 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/client_loopback.rs` around lines 290 - 323, The test flow in client_loopback.rs leaves `client_ep`, `server_ep`, and `server_task` uncleaned if `stream_fetch` or any `anyhow::ensure!` fails before the final cleanup block. Update the `empty blob delivers empty bytes` test path so cleanup is guaranteed via a guard/helper or equivalent scoped teardown around `stream_fetch`, `store.load_all`, and the `ensure!` checks, and ensure `server_task.await?` is still observed even on early return.
🤖 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/client_loopback.rs`:
- Around line 290-323: The test flow in client_loopback.rs leaves `client_ep`,
`server_ep`, and `server_task` uncleaned if `stream_fetch` or any
`anyhow::ensure!` fails before the final cleanup block. Update the `empty blob
delivers empty bytes` test path so cleanup is guaranteed via a guard/helper or
equivalent scoped teardown around `stream_fetch`, `store.load_all`, and the
`ensure!` checks, and ensure `server_task.await?` is still observed even on
early return.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: ee1b579c-850f-4be5-a76c-045dc77983ab
📒 Files selected for processing (6)
crates/bao-range/src/lib.rscrates/cache/src/engine.rscrates/cache/tests/pull_through.rscrates/cache/tests/range_pull.rscrates/client-pull/src/lib.rscrates/node/tests/client_loopback.rs
Coverage reportTotal: 81.74% (was 81.71%, ▲ +0.03%) — 42916/52506 lines
History
|
There was a problem hiding this comment.
Pull request overview
This PR fixes a regression introduced by bao verified-range streaming on cdn/client/v1 (ADR 038) where 0-byte blobs (total_bytes == 0) incorrectly failed range alignment and delivery. It makes empty blobs a supported degenerate case end-to-end (serve, receive/decode, and tee/pull-through), while explicitly preventing the “empty stream verifies for any root” bypass on the receiver.
Changes:
- Update range alignment / wire-size calculation to admit
(byte_offset=0, byte_len=0, blob_size=0)as a valid empty aligned range and avoid bao-tree iteration assertions on empty ranges. - Ensure the serve path returns an empty bao wire form for empty blobs, and the receive path explicitly verifies empty delivery against the empty BLAKE3 root (otherwise typed
HashMismatch). - Add unit + integration regression coverage for empty-blob behavior across align/encode/decode, pull-through round-trip, tee behavior, and node-to-node delivery.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/bao-range/src/lib.rs | Allow align_range(0,0,0) (empty blob) and short-circuit bao_encoded_size for empty range sets. |
| crates/cache/src/engine.rs | Serve-side: return empty bytes for 0-byte blobs on the bao export path; add tee tests for empty-blob promote/fail-closed behavior. |
| crates/client-pull/src/lib.rs | Receive-side: explicitly validate empty streams against the empty root; add unit tests for accept/reject cases. |
| crates/cache/tests/range_pull.rs | Add alignment regression tests for empty blobs and out-of-bounds empty-blob requests. |
| crates/cache/tests/pull_through.rs | Add pull-through round-trip regression test for exporting/importing a 0-byte blob via bao. |
| crates/node/tests/client_loopback.rs | Add e2e regression test for 0-byte node-to-node delivery on cdn/client/v1 with no voucher/channel advancement. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // A 0-byte blob (#1054) has no chunk groups and no proof: the header-less | ||
| // wire form is empty. `align_range` already confirmed the request is the | ||
| // whole (empty) blob, and the caller resolved presence/completeness | ||
| // (`BlobStatus::Complete { size: 0 }` → `blob_size == 0`). Return empty | ||
| // directly rather than driving an empty `export_bao` stream, whose | ||
| // terminal `Done` we would otherwise depend on to clear the `!done` guard. | ||
| if blob_size == 0 { | ||
| return Ok(Bytes::new()); | ||
| } |
There was a problem hiding this comment.
Fixed in 2b9f344. Gated the empty early-return on self.has(hash).await? (which also honors a logical eviction, #279), returning a Store error otherwise — consistent with the non-empty path faulting on a missing hash.
Note on the "absent" wording: iroh-blobs treats the empty blob as trivially present, so pure absence is not a reachable state for the empty hash; the meaningful case the guard covers is a logically-evicted hash, which has reports as absent. Added export_bao_range_empty_blob_evicted_errors to lock that in.
…it (#1054 review) export_bao_range's 0-byte early-return skipped the store, so it returned an empty body even for a logically-evicted (#279) hash — breaking the method's documented "absent -> Store error" contract and the eviction takedown, while the non-empty path stops serving an evicted blob. Gate the empty return on self.has(hash) (which honors eviction) and error otherwise. The empty blob is trivially present in iroh-blobs, so eviction — not absence — is the state that must stop the empty serve; the new regression test evicts and asserts the Store error. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Re: CodeRabbit nit on
Adding a closure-guard to just this one test would make it the lone inconsistency. If we want guaranteed teardown, it should be a file-wide helper applied uniformly — out of scope for this bugfix. CodeRabbit itself rated this Trivial / Low value. |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request addresses issue #1054 by adding support for 0-byte (empty) blobs in the BAO-based range delivery path. It introduces short-circuiting and validation logic in bao_encoded_size, align_range, export_bao_range, and decode_verified_range to handle empty blobs correctly while ensuring that empty streams are only accepted for the empty root hash. Comprehensive unit, integration, and regression tests have been added across the crates to verify empty blob promotion, round-trips, eviction behavior, and end-to-end loopback delivery. I have no additional 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.
…t/guard fixes Follow-ups from the multi-agent PR review: - bao-range: strengthen the bao_encoded_size guard to `total_bytes == 0 || chunk_ranges.is_empty()`. A 0-byte blob has zero wire bytes for ANY range, but ChunkRanges::all() (used by the window-path test helper) is not empty, so the is_empty()-only guard would walk a 0-byte BaoTree over all() — a latent sharp edge. Also correct the comment: bao-tree debug_asserts (not asserts) non-empty ranges. New unit test covers (0, all()) and (non_empty, empty). - node: add window_pull_through_serves_and_caches_empty_blob — the fused progressive/tee path (open_progressive_pull -> UpstreamPull::finish -> tee promote -> leaf verify) never calls decode_verified_range, so the buffered e2e did not cover it. Confirms 0 wire bytes deliver empty, B promotes the empty blob, and no upstream voucher is paid. - Comment accuracy: fix the export_bao_range_empty_blob_evicted_errors doc (the non-empty path has no eviction check; callers gate it), and tighten the decode_verified_range cross-reference to fetch_inner's bypass (same root cause, different trigger). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Fixes #1054.
Problem
Under ADR 038,
cdn/client/v1serve and receive both route range math throughalign_range(byte_offset, byte_len, total_bytes), which rejectedbyte_offset >= blob_size. A 0-byte blob (align_range(0, 0, 0)) therefore errored withRangeOutOfBoundson both the serve (CacheEngine::export_bao_range) and the receiver (decode_verified_range/aligned_wire_len), whereas the pre-baoget()/export_rangepath served it as empty bytes — a (degenerate) behavior regression flagged in CodeRabbit review on #1052 and deferred to keep that PR focused.Approach
Implements option 1 from the issue — support empty blobs. An empty blob is legitimate content-addressed content whose canonical root is
blake3::hash(&[])(==Hash::new(&[])).crates/bao-range/src/lib.rs—align_rangeadmits the whole empty blob(0, 0)as an emptyAlignedRange(fetch_start == fetch_end == 0, emptychunk_ranges, zerowire_len); a positive offset or explicit positive length on a 0-byte blob still rejects (reject, never clamp — ADR 005).bao_encoded_sizereturns0whentotal_bytes == 0or the range set is empty — a 0-byte blob has no wire bytes for any range, and bao-tree's pre-order chunk iteratordebug_assert!s non-empty ranges.crates/cache/src/engine.rs—export_bao_rangereturnsBytes::new()forblob_size == 0, gated on ahas(hash)check so an absent or logically-evicted (Add adecdn node evictsubcommand that removes a specific blob hash from the local cache and optionally re-pins it from the configured origin #279) empty blob still surfaces aStoreerror instead of a spurious empty body. The servedeliverloop then emits noChunkDataand a bareStreamEnd.crates/client-pull/src/lib.rs— the security-critical piece:decode_verified_rangeproves the empty stream against the empty rootblake3::hash(&[])explicitly. Without it, the empty range decodes trivially (no chunk group to verify) and would be accepted for any requested hash — the silent verification bypass thefetch_innercomment already warns about. A non-empty requested hash is a typedHashMismatch.The
align_rangefix alone unblocksaligned_wire_lenin both the buffered (fetch_inner) and progressive (open_progressive_pull) receive paths.Window pull-through / tee — no production change
The window-pull-through tee needs no code change: its existing hash verification (
import_and_verify_stream) already promotes the empty-root blob and fails closed for a wrong hash.window_forward_loopalso terminates cleanly fortotal == 0(pull-ahead skipped →done_pulling→ finalize).Tests
align_rangeempty accept + positive-offset/len reject;bao_encoded_size(0, all())/(non_empty, empty)→ 0 (range_pull.rs)export_bao_rangeempty round-trip + evicted-errors (pull_through.rs)decode_verified_rangeempty accept + empty-claim-wrong-root reject (unit)client_loopback.rs)node_origin_pull.rs) — this path never callsdecode_verified_range, so it is covered separatelyVerification
cargo fmt -- --check,cargo clippy --workspace --all-targets -- -D warnings, the bao-range/cache/client-pull suites (302 tests), and the node window/e2e/pull-through tests all pass.Review
Addressed automated review (Copilot: added the
has()presence/eviction guard) and a multi-agent review pass (comment accuracy, thebao_encoded_sizetotal_bytes == 0guard, and the window-path e2e test). One out-of-scope robustness nit — unbounded zero-lengthChunkDataframes on the receive loop (pre-existing, QUIC-bounded, no integrity/payment impact) — is tracked separately in #1088.Commits
fix(cache): serve empty (0-byte) blobs on the baocdn/client/v1pathfix(cache): confirm presence before the empty-blob export short-circuittest(cache): window empty-blob e2e + comment/guard review follow-ups🤖 Generated with Claude Code