Repository navigation
perf(node,protocol): zero-copy ChunkData framing via vectored QUIC writes (#1791) - #1828
Conversation
There was a problem hiding this comment.
Pull request overview
This PR optimizes the cdn/client/v1 serve-path hot loop by switching ChunkData framing from “encode into a contiguous buffer” to “encode small headers on-stack + vectored QUIC writes of Bytes”, enabling a near-zero-copy payload path while keeping the wire format byte-identical.
Changes:
- Add stack-based
ChunkDataheader/framing encoders indecdn-protocol(plus a newChunkTooLargevalidation error) and reuse a sharedencode_varint_u32. - Rework node-side frame production (
ChunkFramer,CoherentFrameProducer) to cut frames asVec<Bytes>slices (viaBytes::split_to) instead of coalescing intoBytesMut. - Introduce vectored write helpers (
write_chunk_payload_multi) and switch serve loops to send headers + payload chunks viaSendStream::write_all_chunks.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/protocol/src/message.rs | Adds ChunkTooLarge validation error for oversized ChunkData frames. |
| crates/protocol/src/framing.rs | Exposes encode_varint_u32 to support stack-based header encoding. |
| crates/protocol/src/client.rs | Adds header-only / framing+header encoders and size validation for zero-copy write path. |
| crates/node/src/handlers/client/wire.rs | Adds vectored ChunkData write helpers (header on stack + payload Bytes). |
| crates/node/src/handlers/client/serve_leg.rs | Switches coherent serve leg to request chunk vectors and use vectored writes. |
| crates/node/src/handlers/client/serve_encoder.rs | Replaces BytesMut coalescer with queued Bytes and returns frame chunks for vectored writes. |
| crates/node/src/handlers/client/mod.rs | Removes now-unused encode_chunk_frame imports from client handler module. |
| crates/node/src/handlers/client/delivery.rs | Replaces copy-based framing with queued Bytes framing and vectored writes on hit-path delivery. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
278721e to
2857b91
Compare
Coverage reportTotal: 82.02% (was 81.93%, ▲ +0.09%) — 68158/83102 lines
History
|
2857b91 to
6f8109a
Compare
|
All 3 review threads addressed in
Also kept |
…ites (#1791) Group D serve-path hot path: the per-MiB cost is per-frame validation + copies + allocations + QUIC writes. 1 KiB frames were already lifted to sender-chosen ≤1 MiB in #1804; this finishes items 2 and 3 without a wire change (pre-launch, but byte-identical so no ALPN bump needed). - protocol: add CHUNK_DATA_HEADER_MAX / CHUNK_FRAME_HEADERS_MAX, encode_chunk_data_header / encode_chunk_frame_headers on a stack [u8;11] (framing varint + discriminant + varint(payload_len)) validated against MAX_MESSAGE_SIZE (new ChunkTooLarge), reusing framing::encode_varint_u32; add ChunkTooLarge to MessageValidationError; validate encode_chunk_frame as well (crates/protocol/src/client.rs, framing.rs, message.rs). - node: replace BytesMut coalescer with VecDeque<Bytes> queue + queued in ChunkFramer (delivery.rs) and CoherentFrameProducer (serve_encoder.rs); next_frame_chunks returns Vec<Bytes> slices via Bytes::split_to (zero-copy spanning), next_frame kept #[cfg(test)] for framing_matches_slice_chunks_at_every_target. - node: wire.rs add write_chunk_payload{_multi} — header on stack (≤11 B) + payload Bytes via SendStream::write_all_chunks (noq-1.0.0 vectored, reference-counted). sum(payload_chunks) == total_len checked, empty rejected. serve_leg + delivery loops switched to next_frame_chunks + write_chunk_payload_multi; credit window accounting unchanged, faulted is now terminal on the miss leg (mirrors hit path). Verified: cargo build/clippy clean, cargo nextest -p decdn-protocol (145), -p decdn-node lib/framing (4) + client_loopback (110) + node_to_node (4); vectored header == old postcard+framing bytes (1 MiB golden via /tmp/vec_test). Refs #1791
6f8109a to
f244325
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.
Suppressed comments (1)
crates/protocol/src/client.rs:829
- Same as
encode_chunk_frame: this earlyChunkTooLargeguard reportslen: payload_leneven though the error message says "frame length". Reporting the postcard frame-body length keeps the error consistent and avoids confusion when debugging oversized frames.
if payload_len > crate::framing::MAX_MESSAGE_SIZE as usize {
return Err(MessageValidationError::ChunkTooLarge { len: payload_len });
}
…unk_data_header at MAX_MESSAGE_SIZE
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.
Suppressed comments (2)
crates/protocol/src/client.rs:796
- On
total > out.len(),encode_chunk_data_headerreportsChunkTooLarge { len: payload_len }, but the error variant is defined as a frame-length error. This should report the computed postcard frame length for consistent error semantics.
let total = 1usize.saturating_add(varint_len);
if total > out.len() {
return Err(MessageValidationError::ChunkTooLarge { len: payload_len });
}
crates/protocol/src/client.rs:839
encode_chunk_frame_headersusesChunkTooLarge { len: total }when the header buffer is too small, butChunkTooLarge.lenis documented/worded as the frame length. Use the computedpostcard_lenhere to keep diagnostics consistent with the variant definition.
let total = framing_len.saturating_add(hdr_len);
if total > out.len() {
return Err(MessageValidationError::ChunkTooLarge { len: total });
}
…frame path The vectored path was correct on the wire but had converted several loud failures into silent ones, and left the invariant docs naming a door the serve paths no longer use. - protocol: the ChunkData type doc and MessageValidationError::EmptyChunk enumerate every route to a frame body; both now name all three encode_chunk_* helpers, and encode_chunk_frame_headers rather than encode_chunk_frame as the door the serve paths use. encode_chunk_frame's own doc no longer describes a delivery loop that does not call it. - protocol: encode_chunk_data_header / chunk_frame_postcard_len / CHUNK_DATA_HEADER_MAX / encode_varint_u32 are pub(crate) — the node uses only CHUNK_FRAME_HEADERS_MAX and encode_chunk_frame_headers. Their guards now error rather than write a short header, and the u32 clamp is a map_err, so a MAX_MESSAGE_SIZE change cannot turn one into a wrong length prefix. The stated buffer maxima say what they actually bound. - node: chunk_frame_bufs assembles a frame's write buffers as a pure function and write_chunk_bufs does only I/O, so serve_leg no longer meters a node-side framing fault as node_pull_through_client_abandoned (#856). The <= 4 stack fast path is gone: export items are 64 B proof nodes and 16 KiB leaves, so a 1 MiB frame spans ~130 chunks and never took it, and its guards returned Ok(()) having written nothing. - node: both framers refuse a zero target instead of answering None, which the serve loops read as a fully delivered blob and follow with StreamEnd. drain_frame is shared by both rather than duplicated, and reports a queued/queue desync rather than an end of blob. - node: write_chunk_payload is deleted (unused). Tests: chunk_frame_bufs against encode_chunk_frame + write_frame at 1, 2, 4, 5 and 130 chunks; its length-mismatch and empty refusals; drain_frame boundaries; a zero target on both framers; CoherentFrameProducer's fault is terminal (the twin of a_mid_export_fault_propagates); the header golden test gains the framing-varint boundaries (125/126, 16_381/16_382, 2_097_149/2_097_150) and the 2^21 payload width; EmptyChunk and ChunkTooLarge at the new doors; chunk_frame_postcard_len against the encoded header. Refs #1791 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Contracts coverageLine coverage: 89.69% (2575/2871 lines) |
Gas snapshotNo gas changes vs base. |
…frame path (#1835) * docs(node,protocol): correct stale and misattributed docs on the zero-copy frame path The mid-export-fault test's doc block sat above the zero-target test inserted in front of it, so the fault test read as undocumented and the zero-target test opened with a summary about a fault it does not exercise. Re-attach it. `frame_target` does not floor at one bao chunk group — only its room term does, and `payment.frame_target_bytes` may be as low as 1. State what actually makes a zero target unreachable: `frame_target` never returns zero. Name the queue where a comment still named the removed `buf`, cut the two changelog-voice phrasings, drop the claim that the delivery loop calls `encode_chunk_frame`, and say what the returned byte count is on both framers. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(node): surface serve-path framing faults to operators Every accounting refusal on the serve path was correct and silent. The delivery aborts without `StreamEnd`, the client neither receives a mislabelled frame nor pays the closing voucher — and the only trace is a `debug!` in the dispatch sink, below the default `RUST_LOG=info`. To an operator that reads as a client that hung up. Give the four framing refusals a `tracing::error!` with the hash, give `CoherentFrameProducer` the `hash` field its cache-hit twin already carries so its encode fault logs the same way, and carry the cause as `FrameAccountingFault` so both serve loops can meter `decdn_serve_frame_accounting_fault_total` without misfiling a store fault or a peer disconnect as a node bug. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(node,protocol): make impossible framing states loud rather than silent Each of these is unreachable today. Each also degrades the wrong way if that ever stops being true, and the failures they guard are the ones nobody would find. `write_varint_u32` dropped its length prefix to zero bytes and returned `Ok`, after which `write_frame` wrote the payload anyway — a frame with no prefix, desyncing the peer's stream and the cumulative wire-byte count vouchers are paid against, silently on both sides. `encode_varint_u32` now stops rather than counting a byte it did not write, and the prefix write refuses a short buffer. `pump` dropped the encode future on both success and fault, so the terminal state was enforced only by its caller remembering to set `faulted`; it poisons itself now. A closed channel under a live encoder is a contradiction, not end-of-range. Both `Ok(None)` doors — the one that tells the serve loop the blob is complete — now rest on the queue, not only on its counter, and `drain_frame` uses `checked_sub` so a desync cannot clamp that counter to zero. Also: `ChunkTooLarge`'s field is `frame_len`, since it is always larger than the `payload_len` the caller passed and reading it as one is what confused review; and `write_chunk_bufs` takes its buffers by value, since `write_all_chunks` empties them and nothing has a use for what is left. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(node,protocol): pin the zero-copy shape, the hit-leg fault clear, and the encode ceiling Nothing asserted the property the whole change exists for. Every framer test routed through the coalescing test shims, and the `drain_frame` test compared `total` against a sum of the same lengths `total` was built from — a tautology. A `drain_frame` rewritten to concatenate passed the entire suite. Assert the chunk counts instead, at both framers and at `drain_frame`, and cover the boundary cases the shape can break on: a frame ending exactly on an item boundary, a target past everything queued, and an under-counting `queued` that must not be clamped to zero. Verified by falsification — a coalescing `drain_frame` now fails five of them. Also bring the cache-hit fault test up to its coherent twin, which already asserted the refusal is the poison guard's and that the queue was cleared; pin `encode_chunk_frame`'s ADR 013 ceiling, which is the door an out-of-tree caller reaches; and give the miss leg's only large blob a position-varying fill, since a constant one compares equal under a within-frame permutation. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Closes #1791
Group D serve-path hot path (#1791, siblings #1788-1790). The steady-state per-chunk loop is already lock-free; costs are frame count and copies. Two of three items touch the wire — pre-launch rule applies now and stops at first deployment.
What changed (no wire change, byte-identical)
1. Already done in #1804 — 1 KiB → sender-chosen ≤1 MiB (
CHUNK_BYTES),frame_target_bytes(1 MiB default), ADR 005 updated. No further work.2. Two full memcpys + one heap allocation per frame → zero-copy
crates/protocol:CHUNK_DATA_HEADER_MAX/CHUNK_FRAME_HEADERS_MAX,encode_chunk_data_header/encode_chunk_frame_headerson stack[u8;11](framing varint + discriminant + varint(payload_len)) validated againstMAX_MESSAGE_SIZE(newMessageValidationError::ChunkTooLarge— now “frame length” not “payload length”,crates/protocol/src/message.rs:147), reusesframing::encode_varint_u32.crates/node:ChunkFramer(delivery.rs) andCoherentFrameProducer(serve_encoder.rs) replacedBytesMutcoalescer withVecDeque+queued;next_frame_chunksreturnsVecviaBytes::split_to(zero-copy spanning),next_framekept#[cfg(test)]forframing_matches_slice_chunks_at_every_target.crates/node/handlers/client/wire.rs:write_chunk_payload_multi— header on stack (≤11 B) + payloadBytesviaSendStream::write_all_chunks(noq-1.0.0 vectored, reference-counted).sum(payload_chunks) == total_lenchecked, empty rejected. Stack fast-path forheader+≤4chunks avoidsVecalloc on small frames; larger splits fall back toVec.serve_leg+deliveryloops switched tonext_frame_chunks+ vectored write; credit window unchanged,faultednow terminal on miss leg (mirrors hit path).3. Batch / vectored QUIC writes
Per-frame vectored (
header + payloadasByteschunks) replaceswrite_varint+write_all(payload)(2 writes + alloc). N-frame batching (multipleChunkDataper QUIC write) deferred per issue: “Measure after items 1–2 — they may make this moot.” At 1 MiB frames, ~1280 writes/s at 10 Gbps.Verification
cargo build && cargo clippyclean (denyunwrap_used,indexing_slicing)cargo nextest -p decdn-protocol146 pass (incl.encode_chunk_frame_matches_the_generic_encoder+ newencode_chunk_frame_headers_matches_framed_encode_chunk_frameacross 1,2,127,128,129,300,16 383/384/385,1 KiB,64 KiB,1 MiB varint boundaries)cargo nextest -p decdn-protocol --features public-api-test147 pass (snapshot updatedpublic_api__public_api.snapforCHUNK_DATA_HEADER_MAX,CHUNK_FRAME_HEADERS_MAX,encode_chunk_data_header,encode_chunk_frame_headers,encode_varint_u32,ChunkTooLarge)cargo nextest -p decdn-nodelib framing 4 pass,cargo test --test client_loopback110 pass,--test node_to_node_pull_through4 passencode_chunk_frame+write_frame(1 MiB golden)cargo fmt -- --checkclean32924167610success →32925636535after review fixes in progressReview fixes (Copilot)
ChunkTooLargemessage/doc → “frame length” (coverspostcard_len/total),crates/protocol/src/message.rs:147crates/protocol/src/client.rs:2039write_chunk_payload_multistack fast-path for ≤4 chunks,crates/node/src/handlers/client/wire.rs:276encode_chunk_frame/encode_chunk_frame_headersearly guards now report the postcard frame length (chunk_frame_postcard_len) rather than the raw payload length, soChunkTooLargestays a frame-length error,crates/protocol/src/client.rs:732encode_chunk_data_headernow rejects anypayload_lenwhose postcard frame body (1 + varint + payload) would exceedMAX_MESSAGE_SIZE, matchingencode_chunk_frame,crates/protocol/src/client.rs:777Risks
read_frame+decode_messageunchanged, no dual-format reader needed per pre-launch policy.CoherentFrameProducernow terminal on encode fault (mirrorsChunkFramer),faultedclears queue;drain_queueduplicated (vs shared helper) left as follow-up.