Skip to content

feat(node): decoupled serve-miss pull+serve legs - #1651

Merged
alpergundogdu merged 12 commits into
mainfrom
feat/1621-b2-part2-serve-leg
Aug 11, 2026
Merged

alpergundogdu merged 12 commits into
mainfrom
feat/1621-b2-part2-serve-leg

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Completes the strategy-B decoupled serve-miss orchestration (#1621 B2 part 2, ADR 037/038). When node B gets a paid client request for a blob it lacks, it runs two decoupled legs — a pull leg that fetches the missing ranges from an upstream peer, and a serve leg that delivers to the client — coordinated over Send + Sync Arcs. This replaces the fused node→node path; the fused window_forward_loop is retained only for the local-outboard serve path.

Why decoupled (strategy B)

iroh's ProtocolHandler::accept requires a Send future, but drive's ingest_stream is deliberately non-Send. So the pull leg runs decdn_client_pull::drive on a dedicated OS thread + current-thread runtime, while the serve leg stays on the accept task. They share only runtime-agnostic state: served_paid (the paid content frontier the pull's WindowPacer bounds against), served_paid_advanced, pull_ended/pull_result (terminal handoff + the no-hang guarantee), and a CancellationToken.

The core problem this solves: a coherent downstream wire

The hard part isn't the threading — it's that the serve leg must emit one coherent whole-range bao verified stream while the pull fills the cache incrementally beside it. A first cut re-encoded each present span separately and concatenated them, which produces bao proof duplicated per span boundary: the wire is both larger than a single whole-blob encode and not decodable as a whole-blob stream (the client fails its hash check / voucher accounting).

The fix (serve_encoder.rs) drives bao_tree's async encode_ranges_validated over three adapters:

  • AwaitingDataReader — an AsyncSliceReader whose read_at awaits the store's present-range frontier (racing pull_ended for no-hang) before reading the leaf content.
  • OutboardReader — reads proof (left, right) pairs from a shared whole-tree outboard the pull leg captures into. iroh-blobs keeps a partial blob's outboard in actor memory with no public reader, and the pre-order walk needs right-spine proof for not-yet-filled subtrees (not derivable from present data), so the node keeps its own copy, fed by CacheEngine::outboard_pairs as each range admits (and seeded from already-held ranges at serve start).
  • ChannelWriter → a bounded channel; CoherentFrameProducer runs the encode future concurrently with frame consumption and re-cuts CHUNK_SIZE frames, keeping the deliver/recoup/credit-window loop unchanged. The whole future stays Send.

What's in the PR

Area Change
Pull leg node_origin/pull_leg.rs: open_pull_leg (discover + channel-open + free header handshake) and run_pull_leg (drive over PeerSource/WindowPacer/NodeFunder, settle-on-drop #852, provider scoring, abandon-drain on cancel and error).
Coherent encoder serve_encoder.rs + serve_outboard.rs (shared awaiting outboard) + CacheEngine::outboard_pairs.
Serve leg serve_leg.rs: the decoupled seller loop (voucher batching, credit window, takedown, client-disconnect metering), driven by the coherent encoder.
Seed-leech cap Re-homed into the pull leg's pacer chain (LeechPacer → PaceDecision::Refuse: no-promote, no-spin, no provider mis-scoring).
Corruption scoring The decoupled pull now scores a lying/corrupt upstream Corruption + emits the verify-failed metric (the #915 property).
Fused loop window_forward_loop retained for serve_via_local_outboard only; ProgressiveSource narrowed. SpanProducer (the incoherent producer) deleted.

Correctness

  • The full window_pull_through_ family is green (16/16). Test expectations that encoded fused-era assumptions were reconciled to the decoupled reality (upstream voucher cadence, unrecouped-lead spend bounds, the two-bi-stream gated fixture) — each verified money-correct first (B pays A for exactly the wire delivered; per-voucher rounding is protocol-mandated, not over-pay).
  • No-hang guarantee: every serve-side await at the fill frontier (data reader, outboard reader) races pull_ended; a failed pull fails the serve rather than parking forever.
  • Money: completion/pacing gate on the paid frontier, never delivered; the upstream spend on client drop/underpay stays bounded to one window; settle-on-drop persists the buyer watermark on every exit.

Review comments addressed

  • Interior-hold outboard seed — seed the shared outboard from already-held ranges at serve start, so the encoder doesn't park on a held span's uncaptured proof node.
  • content_len open-ended boundary — a fully-present blob (ChunkRanges{0..}) no longer undercounts to 0 (was skewing provider scoring + region accounting).
  • served_paid init — seeded to req.byte_offset so the absolute-frontier invariant is explicit (dispatch gates this path to offset 0 today).
  • tee-finalize coverage — investigated re-homing the retired tee_finalize_failure onto the local-outboard path. It turns out the scenario is node→node-specific: there the engine cap applied only at the tee (bytes came from a peer), whereas on the local-outboard path the same max_blob_bytes rejects an oversized blob at origin.fetch before the tee — an earlier, stricter guard. So the size-breach-at-finalize arm can't occur on local-outboard, and the delivery/size-refusal guarantees are already covered by the oversized decoupled test. Direct coverage of the generic local-store-fault finalize arm ((Ok, Err(other))) needs a non-size fault-injection hook — filed as a follow-up.

Follow-ups (filed)

  • Type the client-pull over-delivery error (replace the corruption-scoring string match with a downcastable sentinel).
  • Unify the local-outboard path onto the decoupled legs to drop window_forward_loop entirely — the pacer already supports it; the remaining work is a payment-free local-outboard pull leg + moving the tee's store-fault "serve-but-not-cache" behavior into the decoupled admit path (which would also close the secondary engine-cap gap).

🤖 Generated with Claude Code

alpergundogdu and others added 2 commits August 10, 2026 11:50
…miss driver (Task 11 of #1621 B2 part 2)

Add ClientHandler::serve_leg — the seller half of the decoupled node
serve-miss. It walks the requested range R in order and delivers all of
it to the paying client: held spans are read from the cache via
ServeStore::encode_range; gap spans are awaited on ServeStore::observe
until a concurrent pull leg fills them, racing pull_ended so a pull that
cannot fill a gap fails the serve rather than hanging (the no-hang
guarantee).

Delivery, the credit window, group-commit voucher batching, the
in-flight takedown boundary, and client-disconnect handling are lifted
from window_forward_loop; the byte source swaps from an upstream pull
tee to the cache. served_paid is published as a PAID content frontier
(paid wire mapped through content_paid_frontier) for the pull leg's
WindowPacer; completion gates on payment, never delivery.

Extracts span_plan as a pure, unit-tested helper (present/gap
decomposition of R against a present-range snapshot). serve_leg is not
yet called — orchestration + the pull leg are Tasks 12/13 — so the
module carries a dead_code allow until then. window_forward_loop is
untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…B2 part 2)

Introduces the strategy-B decoupled serve-miss orchestration: the pull leg
runs `drive` on a dedicated OS thread + current-thread tokio runtime while the
serve leg runs on the iroh accept task, coordinating over Send+Sync Arcs
(served_paid, served_paid_advanced, pull_ended, pull_result, CancellationToken).
This split exists because iroh's ProtocolHandler::accept requires a Send future
but drive's ingest_stream is deliberately non-Send.

New crates/node/src/node_origin/pull_leg.rs extracts run_pull_leg (the pull
side); window.rs spawns it, awaits serve_leg, then cancels + joins the thread.

Two verified fixes:

- Teardown hang (was >100 min): on abandon, drive is dropped mid-transfer, which
  queues an upstream Connection::close whose QUIC driver lives on the pull
  thread's current-thread runtime -- dropped before the close flushes. With no
  driver the connection never reaches "closed or timed out", so Endpoint::close()
  waits forever. Add a cancel-only bounded ABANDON_DRAIN so the runtime flushes
  the CONNECTION_CLOSE before it is dropped. No hot-path cost.

- Open-ended range boundary: a fully-present blob observes as ChunkRanges{0..}
  (a single unpaired chunk boundary). contiguous_byte_ranges paired boundaries
  and silently dropped the unpaired trailing one, so a finished blob read as
  entirely absent. Treat an unpaired trailing boundary as [a, total). Also fixes
  span_plan, which shares the helper.

KNOWN GAP (the substantial remaining core of B2 part 2, not landed here): the
serve leg re-encodes downstream bytes by calling encode_range per present span
and concatenating. Each encode_range emits bao proof relative to the root for
its sub-range, so piece-wise concatenation is both larger than one whole-blob
encode and not a decodable whole-blob stream -- the wire diverges from
bao_encoded_size(range) once the window-paced pull fills incrementally and the
serve leg catches multiple spans. The fix requires a streaming, awaiting
whole-range bao encoder (await the present-range watch at the fill frontier,
race pull_ended for no-hang); wait-for-whole deadlocks the pacer and
skip-and-redo is O(n^2). Family status: 10/17 window_pull_through_ tests pass,
zero hangs; the 7 failures trace to this gap and to decoupled-vs-fused
scoring/metric parity. Draft.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@alpergundogdu, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 34 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 98190e06-93e2-4128-8601-2c43e325fa25

📥 Commits

Reviewing files that changed from the base of the PR and between 32e8136 and a48392d.

📒 Files selected for processing (3)
  • crates/node/src/handlers/client/serve_leg.rs
  • crates/node/src/handlers/client/window.rs
  • crates/node/src/node_origin/pull_leg.rs

Walkthrough

The pull-through path now separates downstream serving from upstream pulling. Missing ranges are pulled into the cache, Bao proof nodes are shared between tasks, and cached data is encoded into verified protocol frames with payment and cancellation coordination.

Changes

Decoupled serve and pull

Layer / File(s) Summary
Shared Bao outboard state
crates/cache/src/engine.rs, crates/node/src/node_origin/serve_outboard.rs
The cache exports Bao parent-node pairs. The shared outboard captures, waits for, and loads internal-node pairs while reporting pull failures.
Admission and outboard capture
crates/node/src/node_origin/admit_store.rs, crates/node/src/node_origin/mod.rs, crates/node/src/node_origin/resume.rs
Admitted ranges optionally write proof nodes to the shared outboard. Pull components receive shared dependency and settlement access.
Gap-driven provider pull
crates/node/src/node_origin/pull_leg.rs
The pull leg discovers providers, pulls missing ranges, applies pacing and payment waits, admits data, handles cancellation and corruption, settles watermarks, and publishes terminal results.
Verified range serving
crates/node/src/handlers/client/serve_encoder.rs, crates/node/src/handlers/client/serve_leg.rs, crates/node/Cargo.toml
The serve leg combines cached spans and gaps, performs coherent Bao encoding, emits protocol-sized frames, and handles payment, disconnect, pull, and completion states.
Window pull-through integration
crates/node/src/handlers/client/window.rs, crates/node/src/handlers/client/source.rs, crates/node/tests/node_origin_pull.rs
The window handler runs separate serve and pull legs on coordinated runtimes. The obsolete upstream progressive source path and related test scenario are removed, and integration expectations cover the decoupled flow.

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

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ClientHandler
  participant NodeOrigin
  participant Provider
  participant Cache
  participant SharedOutboard
  Client->>ClientHandler: request byte range
  ClientHandler->>NodeOrigin: discover pull target
  NodeOrigin->>Provider: perform free header handshake
  Provider-->>NodeOrigin: return pull target
  ClientHandler->>Provider: pull missing ranges
  Provider-->>Cache: stream range data
  Cache->>SharedOutboard: capture Bao proof nodes
  ClientHandler->>Cache: read cached ranges
  ClientHandler->>SharedOutboard: load proof nodes
  ClientHandler-->>Client: stream verified frames
Loading

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

…1621 B2 part 2)

Path A foundation for the coherent streaming serve encoder. `SharedOutboard`
(node_origin/serve_outboard.rs) is the whole-tree bao outboard the two decoupled
serve-miss legs share:

- OutboardWriter::save(node, pair) — the pull leg captures proof (parent) nodes
  from the verified upstream bao as each gap admits; interior-mutable, idempotent.
- OutboardReader impls bao_tree::io::fsm::Outboard: its load() awaits a
  not-yet-captured internal node, racing pull_ended/pull_result so a failed pull
  (or a still-missing node after a clean pull) fails the serve rather than
  hanging. Leaf nodes return None (bao_tree sources those from the data reader).

This is what lets the serve leg drive bao_tree's async encode_ranges_validated to
emit ONE coherent whole-range bao stream while the pull fills incrementally:
iroh-blobs keeps a partial blob's outboard in actor memory with no public reader,
and the pre-order walk needs right-spine proof hashes for not-yet-filled subtrees
that aren't derivable from present data, so the node keeps its own copy fed by the
proof nodes the pull already receives.

Unwired (dead_code-allowed) until the capture hook, awaiting data reader, and the
serve encoder that replaces SpanProducer land. 4 unit tests pass; clippy-clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@blacksmith-sh

This comment has been minimized.

alpergundogdu and others added 7 commits August 11, 2026 11:51
…ared outboard (#1621 B2 part 2)

Feeds the shared whole-tree outboard from the pull leg so the serve leg can drive
a coherent whole-range bao encode while the pull fills incrementally.

- cache: CacheEngine::outboard_pairs(hash, chunk_ranges) runs Blobs::export_bao
  over the range and collects EncodedItem::Parent { node, pair } straight from
  iroh-blobs' outboard — no re-hashing, no teeing of the ingest reader. The proof
  emitted for a range includes the right-siblings covering still-absent content,
  so a front-to-back admit sequence unions to the whole tree's internal nodes.
- node: NodeAdmitStore gains an Option<OutboardWriter>; ingest_stream captures the
  just-admitted range's proof nodes into it after the admit commits. run_pull_leg
  takes the writer; window.rs builds shared_outboard(hash, total) and hands the
  writer to the pull thread. (The reader side is minted next, with the encoder
  that replaces SpanProducer; the factory is bound but unused for now.)

Verified end-to-end: capture_reconstructs_the_true_outboard admits a multi-group
blob and asserts every captured interior node equals bao_tree's own
PreOrderMemOutboard for the same content — the byte-identity the coherent encoder
relies on. 7 node tests pass; clippy-clean.

Still TODO: seed already-held ranges at serve start for interior holds (the pull
admits only gaps). The full-miss path needs no seed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ADR 038)

Replaces the incoherent piece-wise encode_range-per-span producer with ONE
verified whole-range stream, fixing the core B2 design flaw: the downstream wire
is now byte-identical to a single whole-blob encode and hash-verifies end to end.

serve_encoder.rs drives bao_tree's async encode_ranges_validated over:
- AwaitingDataReader (impl AsyncSliceReader): read_at awaits the present-range
  watch (racing pull_ended for no-hang), then reads content via
  NodeRangedStore::read. &mut self on the presence check keeps the serve future
  Send (the watch is Send-not-Sync).
- the shared OutboardReader for proof (left,right) pairs, fed by the pull's
  capture.
- a ChannelWriter feeding a bounded channel; CoherentFrameProducer runs the
  encode future concurrently with frame consumption and re-cuts CHUNK_SIZE frames,
  exposing the same next_frame() the serve loop already used — deliver/recoup/
  window/takedown loop unchanged.

serve_leg now takes the store by value + the OutboardReader; window.rs builds the
shared outboard and mints the reader. iroh-io promoted dev->normal dep.

full_blob now delivers a coherent, hash-verifying whole blob (previously failed
on incoherent wire). The remaining window_pull_through_ failures are reached only
because downstream now completes: they assert the decoupled pull's UPSTREAM
payment cadence against fused-era expectations (nonce, 1-unit amount rounding) --
B pays A for exactly the full blob wire, so it is money-correct on bytes; the
cadence assertions need reconciling next. SpanProducer + present/gap helpers linger
under the module's #![allow(dead_code)] until the family is green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…error (#1621 B2 part 2)

The decoupled pull leg wasn't scoring a corrupt upstream as Corruption nor
emitting the upstream-verify-failed metric, so a lying/mid-stream-corrupt
provider escaped its reputation penalty (the #915 property these tests guard).

- is_bao_corruption now recognizes all three shapes that reach the decoupled
  pull: cache CacheError::VerifyFailed/HashMismatch (a wire-complete lie the
  NodeAdmitStore decoder rejects), decdn_client_pull::HashMismatch (typed
  content-addressing sentinel), and client-pull's streaming OVER-DELIVERY guards
  ("more than the ... promised" / "after the promised total") — how a paced
  corrupt stream desyncs and surfaces. A SHORT/truncated stream stays a
  non-corruption transport fault. (The over-delivery match is by stable text
  since client-pull emits it untyped; the scoring tests pin it, so a reword
  fails CI rather than silently dropping the score. A typed over-delivery
  sentinel in client-pull is a nice-to-have follow-up.)
- Emit node_pull_through_upstream_verify_failed on the corruption arm (parity
  with the fused window_forward_loop).
- Extend the abandon-drain to the error path (cancelled || result.is_err()): a
  drive that returns Err strands its upstream QUIC connection exactly like a
  cancel does (it returns without drive's graceful cooperative close), so
  Endpoint::close() would hang forever in teardown. The clean Ok path still
  skips the drain (no hot-path latency).

window_pull_through_lying_upstream_is_not_cached and
window_pull_through_mid_stream_corruption_scores_upstream_not_local now pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…1621 B2 part 2)

The fused node serve-miss path was replaced by the decoupled two-leg design.
These three tests still encoded the fused shape; each is a test-expectation
update (the decoupled behavior was verified correct, no production change).

- window_pull_through_serves_and_caches_full_blob: the window-paced pull leg
  opens the blob in more than one span (the window pause forces a 2nd upstream
  open), so B's upstream watermark is nonce 3 (one extra per-open voucher),
  1_579_008 wire bytes (bao_encoded_size(all) 1_578_944 + 64 for one redundant
  span-boundary bao parent), amount 17 (voucher amounts round up per interval
  delta, not once over the cumulative total). Pin the new exact tuple.

- window_pull_through_drop_after_fill_bounds_upstream_spend: the decoupled leg
  paces on the content frontier and keeps at most one window of UNPAID content
  in flight, so it may finish a sub-2-window blob after one paid interval. Bound
  the UNRECOUPED lead (upstream_bytes - paid <= window + CHUNK_GROUP_BYTES)
  instead of the total pulled, and drop the "must not cache" assertion — caching
  a fully-pulled, within-bound blob is now allowed.

- window_pull_through_concurrent_same_hash_single_upstream_pull: the decoupled
  serve-miss reuses one upstream connection for two bi-streams — a free header
  handshake (byte_offset==0 && byte_len==0, aborted after reading total_bytes,
  no watermark) then the real PeerSource pull. The gated fixture modelled the
  fused single open, so the handshake swallowed the one release and the real
  pull stalled. Loop over the connection's bi-streams and gate only the real
  pull; the handshake records no watermark, so upstream.len() == 1 still holds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…1621 B2 part 2, ADR 037)

The fused window_forward_loop re-checked the seed-leech admission cap per interval;
the decoupled path only gated it at open time, so an abusive peer that passed the
one-shot gate was pulled to completion with no share-ratio re-check (and the
share_ratio_paused metric never fired).

Adds LeechPacer to the pull leg's pacer chain: a WindowPacer plus the ADR 037
§Seed-leech cap. On each pacing decision it accounts the newly-pulled content
bytes (from the driver's pulled_frontier — no per-chunk hook needed) into the
LeechGovernor, then, if the window would draw more, consults poll_admission. A
denial returns PaceDecision::Refuse, which drive turns into a terminal stop: the
partial fill never finalizes (so it does not promote) and a latched `refused` flag
makes run_pull_leg SKIP provider scoring — a leech stop is our own abuse cap, not
provider misbehaviour (mirrors the fused pull.abandon(None)). With no governor
wired it is a pass-through WindowPacer.

window.rs threads self.leech_governor + the served client's node id into
run_pull_leg. The open-time leech_admit gate is unchanged.

window_pull_through_leech_stall_refuses_without_spinning passes; the family is now
15/17 (tee_finalize_failure and underpaid_voucher remain — separate fused-era items).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…fix underpaid bound (#1621 B2 part 2)

The decoupled serve leg never emitted node_pull_through_client_abandoned when a
client dropped or underpaid, so a node paying upstream for a non-paying client was
not alertable (the fused abandon_window_serve emitted it). serve_leg now meters the
abandon on all four client-facing stop shapes — a rejected/underpaid voucher
(BatchStop::Rejected), a collect_voucher_batch Err (underpayment bail / transport
drop), a ChunkData write Err (downstream disconnect), and the no-progress guard
(client stopped paying).

Also fixes window_pull_through_underpaid_voucher_abandons_bounded's stale bound: it
compared the CONTENT window to a WIRE upstream spend, so one window of content
(1 MiB) legitimately costs one window + ~4 KiB bao proof. Widened the slack to one
chunk group.

window_pull_through_underpaid_voucher_abandons_bounded passes; drop_after_fill,
leech_stall, and full_blob still pass. Family now 16/17 (only the fused-era
tee_finalize_failure engine-cap test remains).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…pull path (#1621 B2 part 2)

window_pull_through_tee_finalize_failure_serves_but_does_not_cache (#896) tested the
fused tee.finish() engine-cap-breach behavior (serve-but-not-cache), but the
node-to-node pull-through path it exercised is now the decoupled two-leg design,
which has no tee. The decoupled path bounds blob size via the HANDLER cap
(max_blob_size_bytes → BlobTooLarge), already covered by
window_pull_through_oversized_upstream_aborts_and_releases_tee, and catches a
lying-oversize upstream as bao over-delivery Corruption.

The tee-finalize-failure property still exists on the LOCAL-OUTBOARD serve path
(serve_via_local_outboard → window_forward_loop, which retains the tee); a
follow-up adds coverage there. Retiring this obsolete node-to-node test makes the
window_pull_through_ family green (16/16).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu marked this pull request as ready for review August 11, 2026 13:06
Copilot AI lite review requested due to automatic review settings August 11, 2026 13:06
@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.83% (was 80.88%, ▼ 0.05%) — 60992/75457 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 91.33% 3603/3945 ▼ 0.39%
crates/node/src/handlers/client/mod.rs 89.08% 522/586 ● 0.00%
crates/node/src/handlers/client/serve_encoder.rs 80.89% 127/157 new
crates/node/src/handlers/client/serve_leg.rs 91.67% 132/144 new
crates/node/src/handlers/client/source.rs 79.35% 73/92 ▼ 9.31%
crates/node/src/handlers/client/window.rs 34.93% 175/501 ▼ 28.06%
crates/node/src/node_origin/admit_store.rs 89.96% 206/229 ▲ +8.14%
crates/node/src/node_origin/mod.rs 90.09% 1000/1110 ▼ 2.95%
crates/node/src/node_origin/pull_leg.rs 88.50% 331/374 new
crates/node/src/node_origin/resume.rs 93.75% 630/672 ● 0.00%
crates/node/src/node_origin/serve_outboard.rs 96.57% 197/204 new
History
Commit Total Δ vs base
32e8136 80.70% ▼ 0.18%
a48392d (HEAD) 80.83% ▼ 0.05%

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 implements the “strategy-B” decoupled serve-miss orchestration for the node: the upstream pull leg runs decdn_client_pull::drive on a dedicated OS thread/current-thread Tokio runtime (to accommodate non-Send ingest), while the downstream serve leg stays on the iroh accept task and coordinates via shared Arc state. It also introduces a shared outboard capture/read path to support a coherent whole-range bao re-encode while the cache fills incrementally.

Changes:

  • Add a new gap-driven upstream pull leg (node_origin/pull_leg.rs) and wire it into the window pull-through handler with thread spawn/cancel/join.
  • Introduce a shared whole-tree outboard (node_origin/serve_outboard.rs) plus cache outboard extraction (CacheEngine::outboard_pairs) to support a coherent, streaming bao encoder.
  • Update tests and invariants in crates/node/tests/node_origin_pull.rs to reflect the decoupled cadence and spend bounds.

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/node/tests/node_origin_pull.rs Updates serve-miss test harness for decoupled two-bistream upstream shape; adjusts watermark/spend assertions; removes a tee-finalize-failure test.
crates/node/src/node_origin/serve_outboard.rs Adds shared outboard writer/reader with async waiting semantics tied to pull completion.
crates/node/src/node_origin/resume.rs Exposes settle cadence constants/helpers for reuse by the pull leg driver config.
crates/node/src/node_origin/pull_leg.rs Implements open_pull_leg and run_pull_leg (driver wiring, pacing, settlement-on-drop, scoring, drain-on-abandon).
crates/node/src/node_origin/mod.rs Registers new modules and exports run_pull_leg/shared outboard helpers; adds deps_arc() for cross-thread pull leg.
crates/node/src/node_origin/admit_store.rs Adds optional outboard capture after each admitted range via outboard_pairs.
crates/node/src/handlers/client/window.rs Replaces fused node→node path with decoupled orchestration, thread lifecycle management, and serve-leg invocation.
crates/node/src/handlers/client/source.rs Narrows ProgressiveSource to the remaining local-outboard fused path only.
crates/node/src/handlers/client/serve_leg.rs Adds the decoupled downstream serve loop (voucher batching, credit window, takedown handling), now driven by a coherent encoder.
crates/node/src/handlers/client/serve_encoder.rs Implements a coherent whole-range bao encoder via encode_ranges_validated with awaiting data reader + channel framing.
crates/node/src/handlers/client/mod.rs Registers serve_leg and serve_encoder modules.
crates/node/Cargo.toml Promotes iroh-io to a normal dependency for the coherent encoder.
crates/cache/src/engine.rs Adds CacheEngine::outboard_pairs helper to extract parent hash pairs from export_bao for shared outboard capture.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +265 to +269
let served_paid = Arc::new(AtomicU64::new(0));
let served_paid_advanced = Arc::new(Notify::new());
let pull_ended = Arc::new(Notify::new());
let pull_result: Arc<std::sync::Mutex<Option<anyhow::Result<()>>>> =
Arc::new(std::sync::Mutex::new(None));
Comment thread crates/node/src/node_origin/pull_leg.rs Resolved
Comment thread crates/node/tests/node_origin_pull.rs Resolved
@alpergundogdu alpergundogdu changed the title feat(node): decoupled serve-miss pull+serve legs (WIP, #1621 B2 part 2) feat(node): decoupled serve-miss pull+serve legs Aug 11, 2026
alpergundogdu and others added 2 commits August 11, 2026 14:29
…coder serves (#1621 B2 part 2)

The serve leg produces its downstream wire via CoherentFrameProducer (serve_encoder.rs)
now, so the old piece-wise encode_range producer SpanProducer and its helpers
(contiguous_byte_ranges, span_plan, byte_present, pull_outcome), the Span enum, the
present-poll constants (CHUNK_BYTES, WATCH_OPEN_RETRY, PULL_OK_PRESENCE_*), and the
span_plan unit tests are dead. Delete them and drop the module-wide
#![allow(dead_code)]; prune the now-unused imports and refresh the module/method docs
to describe the coherent encoder instead of the removed ServeStore::encode_range path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t_len, paid-frontier init (#1621 B2 part 2)

Three fixes from PR review of the decoupled serve-miss:

- Seed the shared outboard at serve start with proof nodes for ranges B ALREADY
  holds (window.rs). The pull leg only captures ranges it ADMITS, but a
  range-minimized serve-miss can start with held bytes (ADR 037); without the seed
  the coherent encoder would load a held span's proof node that was never captured,
  park until pull_ended, then fail "outboard node never captured". outboard_pairs
  over the present ranges emits exactly those nodes. No-op on a full miss.

- content_len (pull_leg.rs) dropped an unpaired trailing ChunkRanges boundary, so a
  fully-present blob (ChunkRanges{0..}) undercounted to 0 — skewing provider scoring
  (Outcome::Delivered bytes) and region_accountant.record_pulled. Clamp the
  open-ended run to total.

- Initialize served_paid to req.byte_offset, not 0 (window.rs). The WindowPacer
  bounds pulled_frontier − served_paid_frontier where pulled_frontier is an ABSOLUTE
  content offset; a bare 0 would show a full window of phantom lead for a non-zero
  offset. Dispatch gates this path to byte_offset == 0 today, so this makes the
  absolute-frontier invariant explicit rather than incidental.

Family stays 16/16.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu merged commit d4f777c into main Aug 11, 2026
29 checks passed
alpergundogdu added a commit that referenced this pull request Aug 12, 2026
…1660)

* refactor(cache): relocate serve-miss outboard sharing + fill terminal-state into cache (B3.1)

Move SharedOutboard/OutboardWriter/OutboardReader + the pull_ended/pull_result
terminal pair out of node/src/node_origin/serve_outboard.rs into a new
cache-resident FillSession (crates/cache/src/fill_session.rs). The whole-tree bao
outboard, its capture, the terminal mark_ended/outcome signal, and the shared
downstream paid frontier are now session-owned; both serve-miss legs hold one
Arc<FillSession>. Capture moves into CacheEngine::admit_bao_stream (node threads
the session in). The #1651 await/terminal-race logic moves verbatim. No coalescing
or registry yet (B3.2); behavior preserved (node+cache 1320 tests green).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(cache): range-aware fill registry (attach/remainder planning) (B3.2)

Add FillRegistry to the cache: a serve-miss of range R against the live
in-flight fills for a hash splits into attach = R ∩ covered_union (bytes an
in-flight pull already produces — attach an observer) and remainder = R −
covered_union (bytes no live pull covers — fetch them). Binds the attach handle
to the largest-overlap session and hands back an RAII ObserverLease whose
last-out drop cancels the pull (via CancellationToken) when no observer remains
while the pull is still running (#1610).

FillSession gains covered (set at registration), an observer count, and a
cancel token; new(root, total) keeps working unchanged for existing callers.
CacheEngine holds an Arc<FillRegistry> and exposes fill_plan / register_fill.
No live-pull wiring yet — that is B3.4.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(cache): serialize observer-lease teardown with fill_plan attach (B3.2)

ObserverLease::drop decremented the observer count and fired cancel()
lock-free, while add_observer ran under the FillRegistry map lock. That
opened a resurrection race (a concurrent fill_plan could fetch_add a
session 0->1 between a last-out fetch_sub 1->0 and its cancel(), binding
a live observer to an aborting fill) and let fill_plan attach to sessions
already ended or cancelled.

- ObserverLease now holds Weak<FillRegistry> + Hash; its drop takes the
  registry map lock before the decrement + cancel decision, the same lock
  fill_plan/register_fill hold to attach, so the two are mutually
  exclusive. Upgrade-fail (registry gone) => fill moot, skip.
- Lease minting moves to FillRegistry::mint_lease under the map lock;
  register_fill/fill_plan take self: &Arc<Self> (engine.rs unchanged).
- fill_plan skips dead sessions (ended or cancelled) for both covered_union
  and the attach target.

Tests: fill_plan_skips_cancelled_session, fill_plan_skips_ended_session,
teardown_decrement_and_cancel_are_lock_serialized; four canonical registry
tests kept green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(node): pin shared-pull pacing (pause on window, refuse on leech cap) (B3.3)

LeechPacer already composes WindowPacer (money + ADR 037 window) with the
LeechGovernor's node-wide admission gate, overriding only a Draw with a
terminal Refuse on leech-cap denial. Pin that contract with two unit
tests, both green on first run (confirmation, not a behavior change):
window-full pauses (Wait) rather than terminally refusing, so a
coalesced pull with live observers is never killed by a transient
window-full state; a genuine LeechGovernor denial is the only source of
a terminal Refuse and latches `refused` so run_pull_leg skips provider
scoring.

Also documents that the served_paid frontier the pacer's WindowPacer
bounds against is, under coalescing, the shared max-over-live-observers
paid content frontier (DECISION-B) — a solo pull is the N=1 case. The
actual fetch_max frontier-advance wiring is B3.4's job.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(cache): remove fill session on last observer; serve_leg frontier fetch_max (B3.4a)

Two substrate changes making the shared FillSession safe for N concurrent
observer serve legs (prerequisite for B3.4b orchestration wiring).

1. serve_leg's shared paid-frontier write becomes fetch_max (was store), so
   N observers advancing the SHARED frontier cannot regress each other; the
   pull's WindowPacer binds on the MAX-over-observers paid frontier
   (DECISION-B). Behavior-preserving for N=1 (a single contiguous delivery is
   already monotone, so fetch_max == store).

2. ObserverLease::drop now removes the session from the registry map on
   last-out (prev == 1), by Arc pointer identity so a sibling session for the
   same hash survives; the hash key is dropped when its Vec empties. Fixes a
   slow leak where dead sessions accumulated in the map forever (fill_plan
   skipped them via is_dead but never freed them). Removal + cancel run under
   the held map lock; cancel still fires on last-out while the pull runs.

Tests: last_observer_leaving_removes_session (map-key inspection is the
discriminating check, since fill_plan already skips dead-but-mapped sessions
via is_dead) and removing_one_session_keeps_a_sibling_for_the_same_hash.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(cache): atomic fill claim (attach-or-register under one lock) (B3.4b)

Add FillRegistry::claim: decide attach-vs-own AND register a fresh
FillSession under ONE map-lock acquisition, closing the coalescing TOCTOU
race that the separate fill_plan (read) + register_fill (write) calls
leave open. Two concurrent identical fresh misses can no longer both see
an empty registry and both open a pull.

FillClaim { Attach, Owner } carries the target session + observer lease.
make_session is a closure so the outboard buffer is built only on the
owner branch, never built-and-dropped on attach. The owner covers the
WHOLE R (conservative cut). Add FillSession::total_bytes() so the attach
path signs its StreamResponse without re-running the header handshake.
CacheEngine::claim_fill forwards to the registry. fill_plan/register_fill
kept (additive). Cache-only; orchestration wiring is B3.4c.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(node): range-aware coalescing on both serve-miss orchestrations; delete open_tee_sink (B3.4c)

Both serve-miss orchestrations (serve_via_window_pull_through peer and
serve_via_backend_origin own-origin) now claim the fill atomically via
CacheEngine::claim_fill instead of holding a hash-coarse TeeReservation. After
signing the StreamResponse, each miss either OWNS a fresh pull for the hash or
ATTACHES as an observer to a live same-hash fill, so two concurrent same-hash
misses share ONE upstream/origin fetch while each keeps its own per-channel
voucher stream. serve_leg is already session-based (B3.1), so an attach is just a
serve_leg over the shared FillSession.

Teardown is lease-driven: the pull thread receives the session's shared cancel
token; the owner drops its ObserverLease after serve_leg (last-out cancels the
pull, #1610; otherwise the pull keeps filling for remaining observers) then joins
the bounded pull thread. The attach path drops its lease with no thread to join.

Deletes open_tee_sink / TeeOpen / TeeReservation (and their tests + re-exports),
the two dispatch TeeOpen::Owner/InFlight branches, and the now-unused
await_coalesced_fill. Keeps the inflight origin-fetch map used by populate/get.

Adapts the own-origin coalescing integration test to the new semantics (one
origin fetch, two live serve legs) and adds a disjoint two-hash no-wedge test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(e2e): two clients coalesce onto one upstream pull, each pays its own egress (B3.5)

Two independently-funded cdn/client/v1 buyers fetch the same missing blob
from one pull-through node concurrently. The node runs the range-aware
coalescing serve-miss (CacheEngine::claim_fill): the first miss owns the
single own-origin fill, the overlapping second attaches as an observer and
streams the same filling cache, each metering its own egress over its own
channel and voucher collection. Asserts both misses enter the coalescing
serve tier, both clients get the blob byte-exact, the two channels settle
independently and near-equal (no cross-client leakage), and the concurrent
misses promote one shared cache entry.

The node-to-node paid-upstream variant is not expressible in this harness:
a NodeFixture is funded only for its seller/operator role (a TOKEN capacity
bond), never as an upstream-paying buyer, and there is no cross-node
discovery wiring. The own-origin path exercises the identical claim_fill /
FillSession machinery, so the downstream money property proven here (N
independent per-channel ledgers) is the same. The strict one-pull count and
abandoned-pull leech bound are discharged by the node-level test
window_pull_through_concurrent_same_hash_single_upstream_pull and the
fill_session.rs unit tests.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(node): refresh stale coalescing comments post-open_tee_sink removal (B3)

Comments in node_origin_pull.rs, node_to_node_pull_through.rs,
origin_range_pull.rs, dispatch.rs, and coalesce_two_clients.rs still
described the deleted open_tee_sink/TeeOpen/await_coalesced_fill
mechanism. Update the prose to describe CacheEngine::claim_fill's
Owner/Attach split, and soften an over-claiming assertion-4 doc comment
in coalesce_two_clients.rs. Comments and doc text only; no logic or
assertions changed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(node): canonicalize serve-miss comments (drop retired-mechanism/changelog voice)

Rewrite serve-miss / pull-leg / serve-leg / coalescing / fill comments as
present-tense documentation of what the code IS. Remove references to the
retired fused serve path, window_forward_loop, SpanProducer, upstream tee, and
"re-homed"/"lifted verbatim"/"the old path" narrative, plus project-phase
labels (B2/B3, Flow A/FA.x, Strategy B, Path A, Task N). Correct the stale
serve_via_window_pull_through gate rationale: the byte_offset==0 && byte_len==0
gate is a conservative routing constraint, not a serve_leg limitation
(serve_leg clamps to the requested span; the pull leg is range-minimized).

Comments and doc-comments only; no code, test-assertion, or logic changes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(node): delete dead tee-failure metrics; canonicalize residual serve-miss comments

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(node): move blake3 to dev-dependencies (test-only after the fused path)

The node crate's own code hashes content via `bao_tree::blake3`; the standalone
`blake3` crate is now used only by `tests/self_hosted_discovery.rs` to derive a
gossip topic id. Move it to `[dev-dependencies]` so a production build no longer
links it, and drop the stale comment that justified it via the deleted
window-paced pull-through hashing path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(node): make each coalesced serve leg self-seed held-range proof

An attaching serve leg reads held-range proof nodes from the shared FillSession
outboard, which only the owner seeded (before spawning the pull). That is safe
today — the owner's seed completes before any terminal signal an observer can
observe — but it is a subtle non-local invariant. Extract the seed into
`seed_held_outboard` and call it from the Attach branches of both orchestrations
too, so every serve leg seeds the held-range proof its own coherent encoder
reads. Idempotent (capture overwrites the same bytes) and near-free on a full
miss (empty present set short-circuits before `outboard_pairs`). Also DRYs the
previously duplicated seed block across the two Owner branches.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu deleted the feat/1621-b2-part2-serve-leg branch August 17, 2026 17:47
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