Skip to content

fix(cache): serve empty (0-byte) blobs on the bao cdn/client/v1 path (#1054) - #1085

Merged
yigitdot merged 3 commits into
mainfrom
fix/1054-empty-blob-bao-delivery
Jul 9, 2026
Merged

yigitdot merged 3 commits into
mainfrom
fix/1054-empty-blob-bao-delivery

Conversation

@yigitdot

@yigitdot yigitdot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1054.

Problem

Under ADR 038, cdn/client/v1 serve and receive both route range math 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 (CacheEngine::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 (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_range admits 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 (reject, never clamp — ADR 005). bao_encoded_size returns 0 when total_bytes == 0 or the range set is empty — a 0-byte blob has no wire bytes for any range, and bao-tree's pre-order chunk iterator debug_assert!s non-empty ranges.
  • crates/cache/src/engine.rs — export_bao_range returns Bytes::new() for blob_size == 0, gated on a has(hash) check so an absent or logically-evicted (Add a decdn node evict subcommand that removes a specific blob hash from the local cache and optionally re-pins it from the configured origin #279) empty blob still surfaces a Store error instead of a spurious empty body. The serve deliver loop then emits no ChunkData and a bare StreamEnd.
  • crates/client-pull/src/lib.rs — the security-critical piece: decode_verified_range proves the empty stream against the empty root blake3::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 the fetch_inner comment already warns about. A non-empty requested hash is a typed HashMismatch.

The align_range fix alone unblocks aligned_wire_len in 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_loop also terminates cleanly for total == 0 (pull-ahead skipped → done_pulling → finalize).

Tests

  • align_range empty accept + positive-offset/len reject; bao_encoded_size(0, all()) / (non_empty, empty) → 0 (range_pull.rs)
  • export_bao_range empty round-trip + evicted-errors (pull_through.rs)
  • decode_verified_range empty accept + empty-claim-wrong-root reject (unit)
  • tee empty commit + empty-claim-for-nonempty-hash fail-closed (unit)
  • e2e buffered node-to-node 0-byte delivery (client_loopback.rs)
  • e2e window pull-through 0-byte delivery through the progressive/tee/verify path (node_origin_pull.rs) — this path never calls decode_verified_range, so it is covered separately

Verification

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, the bao_encoded_size total_bytes == 0 guard, and the window-path e2e test). One out-of-scope robustness nit — unbounded zero-length ChunkData frames 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 bao cdn/client/v1 path
  • fix(cache): confirm presence before the empty-blob export short-circuit
  • test(cache): window empty-blob e2e + comment/guard review follow-ups

🤖 Generated with Claude Code

…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]>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

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

Changes

Empty blob support across verified-range flow

Layer / File(s) Summary
Empty-blob range sizing and alignment
crates/bao-range/src/lib.rs, crates/cache/tests/range_pull.rs
bao_encoded_size returns 0 for empty blobs and empty ranges; align_range now documents and enforces that only (0, 0) is valid for a 0-byte blob, with regression tests.
Empty-blob cache export and tee promotion
crates/cache/src/engine.rs, crates/cache/tests/pull_through.rs
export_bao_range returns empty bytes for a present 0-byte blob; tests cover empty-feed promotion, mismatched empty claims, and round-tripping an empty export/import.
Empty-root verification in client decoding
crates/client-pull/src/lib.rs
decode_verified_range now checks total_bytes == 0 against the empty BLAKE3 root and returns HashMismatch for other hashes, with unit tests.
Node empty-blob delivery regression coverage
crates/node/tests/client_loopback.rs, crates/node/tests/node_origin_pull.rs
New end-to-end tests assert empty bytes are delivered for 0-byte blobs and that channel/cache state does not advance incorrectly.

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
Loading

Possibly related PRs

  • decdn/decdn#1052: Introduces the verified-range flow that this PR extends for the empty-blob case.
  • decdn/decdn#1070: Touches the same align_range and export_bao_range sizing logic modified here.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR implements the chosen option by supporting empty blobs end-to-end and adding the requested regression tests.
Out of Scope Changes check ✅ Passed The changes stay focused on empty-blob handling and related test coverage for the bao path.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main fix: serving empty 0-byte blobs on the bao cdn/client/v1 path.
✨ 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 fix/1054-empty-blob-bao-delivery

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

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

🧹 Nitpick comments (1)
crates/node/tests/client_loopback.rs (1)

290-323: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

No cleanup of server_task/endpoints on early assertion failure.

If any ensure! at lines 303, 310-314, or 315-319 fails, or stream_fetch at line 301 errors, the function returns early before line 321-323, leaving client_ep/server_ep unclosed and server_task un-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 the server_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

📥 Commits

Reviewing files that changed from the base of the PR and between 5301864 and 783fa19.

📒 Files selected for processing (6)
  • crates/bao-range/src/lib.rs
  • crates/cache/src/engine.rs
  • crates/cache/tests/pull_through.rs
  • crates/cache/tests/range_pull.rs
  • crates/client-pull/src/lib.rs
  • crates/node/tests/client_loopback.rs

@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.74% (was 81.71%, ▲ +0.03%) — 42916/52506 lines

File Coverage Lines Δ
crates/bao-range/src/lib.rs 96.49% 110/114 ▲ +0.23%
crates/cache/src/engine.rs 89.65% 2312/2579 ▲ +0.21%
crates/client-pull/src/lib.rs 87.57% 662/756 ▲ +0.25%
History
Commit Total Δ vs base
783fa19 81.73% ▲ +0.02%
2b9f344 81.73% ▲ +0.03%
7a2ecad (HEAD) 81.74% ▲ +0.03%

Copilot AI 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.

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.

Comment on lines +2088 to +2096
// 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());
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@yigitdot

yigitdot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Re: CodeRabbit nit on client_loopback.rs cleanup-on-early-assertion-failure — declining.

client_delivers_empty_blob deliberately mirrors the file's established pattern: client_delivery_roundtrip_advances_channel_state (and the other stream_fetch tests) all use straight-line ensure!-then-close/await with no teardown guard. On assertion failure the #[tokio::test] runtime is dropped, which aborts server_task; the only thing lost is a server-side panic surfacing through server_task.await?, which none of the sibling tests guard against either.

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.

@yigitdot

yigitdot commented Jul 9, 2026

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 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]>
@yigitdot
yigitdot requested a review from alpergundogdu July 9, 2026 13:50
@yigitdot
yigitdot merged commit 417d45e into main Jul 9, 2026
23 checks passed
@yigitdot
yigitdot deleted the fix/1054-empty-blob-bao-delivery branch July 9, 2026 14:42
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.

cdn/client/v1: empty (0-byte) blob delivery errors on the bao path

2 participants