Repository navigation
feat(node): implement DHT BatchStore handler-side admission (closes #648) - #713
Conversation
Implements ACs 17-20 of ADR 022 §Batch token accounting: publishers can now send a single BatchStoreRequest covering many hashes destined for one receiver instead of N separate Store RPCs (~80% wire-bytes reduction at C ≥ 10k cached blobs), with a per-hash Store fallback for receivers that don't implement batching. Handler admission (handlers/dht.rs, ACs 17/19): - Route BatchStore through handle_batch_store: batch-level holder == authenticated NodeId check once (mismatch -> MALFORMED_MESSAGE stream-close per ADR 022 step 2), then per-hash admission identical to N separate Stores (active-staker filter + RecordStore::insert_at) sharing one receiver-anchored receive_us. One bool per hash in request order. Oversize (>256) rejected at wire decode -> MALFORMED_MESSAGE. - Thread peer_ip into handle_one/dispatch; dispatch returns Result<_, app_code> for the stream-close case. Two-stage rate-limit accounting (rate_limit.rs, AC 18): - Refactor check() to share a metric-free try_admit_one; add admit_batch_extra() consuming up to n-1 more units cheapest-first with short-circuit, byte-for-byte equivalent to N separate Store admissions. Stage 1 (the frame token) is already charged in serve(). No rejection counter bump on the partial-admit boundary. Publisher fallback (batch_fallback.rs new, client.rs, AC 20): - BatchStoreFallback: bounded per-receiver unsupported_until cache (default 15 min), lazy expiry, clock-injected for tests. - client::batch_store primitive + batch_store_with_fallback: skips batch when cached unsupported; on an UNSUPPORTED (0x01) close caches the negative result + retries per-hash; malformed/too-large/rate-limited/ transport errors hard-fail (no per-hash storm). - Fix exchange_on: a peer stream-reset was collapsed by iroh's AsyncRead into an io::Error with no typed source, so extract_app_error_code lost the code and fallback never fired. Now probe recv.received_reset() and re-surface ReadError::Reset(code) typed. Metrics: dht_batch_store_received, dht_batch_store_hashes_deferred_rate_limit; per-hash outcomes reuse the existing dht_store_* counters. Tests: 13 unit (rate-limit, fallback cache, classifier) + 8 loopback (roundtrip, holder-mismatch MALFORMED, >256 MALFORMED, partial rate-limit admit, single-hash boundary, primitive roundtrip, batch-vs-fallback path selection, and end-to-end UNSUPPORTED-close -> cache -> per-hash fallback). Scope: the republish scheduler is not rewired to group hashes by receiver (that consumes these building blocks and belongs to #630); AC 20's publisher-MUST is satisfied by the tested batch_store_with_fallback helper. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements BatchStore support and fallback negotiation in the DHT client and handler according to ADR 022. It introduces a BatchStoreFallback cache to track unsupported peers, implements two-stage rate-limiting for batched stores, and adds comprehensive tests. The review feedback highlights several key performance optimization opportunities: reusing a single QUIC connection during per-hash fallback instead of opening sequential connections, locking the record store mutex once before the insertion loop in handle_batch_store rather than repeatedly inside it, and passing a prune flag to disable redundant map pruning operations during stage-2 rate-limit checks.
Coverage reportTotal: 89.40% (was 89.27%, ▲ +0.13%) — 21995/24603 lines
History
|
There was a problem hiding this comment.
Pull request overview
Implements ADR 022 BatchStore handler-side admission and publisher-side fallback negotiation, enabling batched STORE publications (≤256 hashes) with two-stage rate-limit accounting and per-receiver capability caching. This reduces wire overhead for dense publications while preserving per-hash admission semantics and providing safe fallback to per-hash Store when batching is unsupported.
Changes:
- Add
BatchStorehandling in the DHT server: single holder/auth check, stage-2 token accounting, per-hash admission + ack results. - Extend DHT rate limiting with stage-2 batch token consumption (
admit_batch_extra) without inflating rejection counters. - Add publisher-side
BatchStoreclient primitive and fallback cache + integration tests/metrics for batch adoption and deferred hashes.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
crates/node/src/handlers/dht.rs |
Implements server-side BatchStore dispatch and admission, including stream-close behavior for holder mismatch and stage-2 rate-limit charging. |
crates/node/src/dht/rate_limit.rs |
Refactors admission to reuse a metric-free try_admit_one and adds admit_batch_extra() for stage-2 batch token accounting with tests. |
crates/node/src/dht/client.rs |
Adds batch_store + batch_store_with_fallback, error classification for fallback, and improves reset-code surfacing in exchange_on. |
crates/node/src/dht/batch_fallback.rs |
Introduces a per-receiver TTL cache for batch-unsupported peers (AC20) with unit tests. |
crates/node/src/metrics.rs |
Adds batch-related counters (dht_batch_store_received, dht_batch_store_hashes_deferred_rate_limit) and increment helpers. |
crates/node/src/dht/mod.rs |
Exposes the new fallback module and re-exports fallback types/constants. |
crates/node/tests/dht_loopback.rs |
Adds/updates loopback integration tests for holder mismatch MALFORMED behavior, oversize batches, partial admission, and end-to-end fallback negotiation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Apply automated-reviewer (gemini, copilot) findings; all behaviour- preserving except the metric-counting fix, which is covered by a new regression test. - client::per_hash_fallback: reuse a single QUIC connection across the fallback set via exchange_on instead of opening one connection per hash (up to 256 sequential handshakes). Each per-hash exchange keeps its own DHT_CLIENT_TIMEOUT. - handle_batch_store: lock the record store once before the loop (no .await inside) instead of per-hash; only lock on the active path. Fixes the inaccurate "rejecting remaining hashes" log spamming once per hash on a poisoned mutex (now logged once, "rejecting all hashes"). - handle_one: a dispatch Err(app_code) is a deliberate protocol rejection (holder-mismatch -> MALFORMED stream-close) already counted by dht_store_rejected_holder_mismatch; reset the stream and return Ok(()) so it no longer inflates dht_requests_failed (reserved for post- admission internal failures). New test asserts the counter split. - rate_limit::try_admit_one: add a `prune` flag; admit_batch_extra passes false. Stage-2 units key on the same (peer, ip) stage-1 already inserted, so they can't grow the keyed maps -> the per-unit prune check is redundant (bound upheld by stage-1 + periodic GC). - batch_store_with_fallback: guard an over-cap (>256) batch up front with a clear error log + per-hash fallback, instead of burning a doomed batch round-trip that looked like a normal all-false rejection. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Code reviewReviewed the BatchStore admission + fallback path. CLAUDE.md compliance is clean and the earlier Gemini/Copilot comments look addressed. Three non-blocking observations, roughly in severity order, plus one design note:
decdn/crates/node/src/dht/client.rs Lines 350 to 358 in 8b722d3
decdn/crates/node/src/dht/client.rs Lines 273 to 295 in 8b722d3
decdn/crates/node/src/dht/batch_fallback.rs Lines 48 to 55 in 8b722d3 Design note (likely intentional, flagging only so it's a conscious call): decdn/crates/node/src/dht/client.rs Lines 147 to 152 in 8b722d3 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
…ck map Address alpergundogdu's PR #713 review (the two actionable observations; #1 and the design note verified correct, no change). #2 per_hash_fallback aggregate timeout: a receiver that accepts the connection but never answers could pin one publish task for up to MAX_BATCH_STORE_HASHES x DHT_CLIENT_TIMEOUT (~34 min). Bail after MAX_CONSECUTIVE_FALLBACK_TIMEOUTS (3) back-to-back read timeouts; any answering outcome resets the run so a slow-but-responsive peer is not cut off. Thread the per-hash timeout as a parameter (prod passes DHT_CLIENT_TIMEOUT) and expose per_hash_fallback as a reusable building block for the #630 republish scheduler. New loopback test asserts exactly K streams open against a non-answering stub. #3 BatchStoreFallback size cap: DEFAULT_BATCH_FALLBACK_MAX_ENTRIES = 4096 (mirrors rate_limit max_tracked_per_peer); a new mark at capacity evicts the soonest-to-expire entry. No periodic GC -- unlike rate_limit's keyspace maps (keyed by attacker-supplied inbound IP/peer, hence #676's sweep) this map is keyed only by receivers the local node chose to publish to that returned a 0x01 close, so it is not externally inflatable and a static cap suffices. Unit tests cover cap eviction, no-evict-on-re-mark, and zero-cap clamp. fmt + clippy clean; node suite 318 pass (dht_loopback 21/21). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
#1616) (#1748) * feat(node): batch DHT re-publish by receiver; drop BatchStore fallback (#1616) The BatchStore handler (admission + two-stage rate-limit accounting) already shipped in #713. What was missing: the outbound batch primitive was dead code (tests only) and the re-publish scheduler never batched. BatchStore is mandatory in cdn/dht/v1 — every node ships discriminants 4/5 from day one — so the "optional-with-fallback" framing was a version-negotiation shim for a peer that cannot exist pre-launch. Per the pre-launch rule (no version negotiation; delete the old shape), rip it out and batch unconditionally. - publish.rs: the periodic drain groups due hashes by receiver (each hash's K+3 closest) and sends one client::batch_store per receiver, split at the 256-hash cap. Eager per-insert publish stays per-hash Store (a size-1 batch buys nothing). New pure group_by_receiver, unit-tested. - Delete the fallback shim: batch_fallback.rs (BatchStoreFallback), batch_store_with_fallback, classify_batch_error, per_hash_fallback, extract_app_error_code + downcast helpers, and the exchange_on reset-probing that only fed them. Keep client::batch_store, client::store, and the whole receiver-side handler. - ADR 022: BatchStore/BatchStoreAck are mandatory in cdn/dht/v1 (no fallback, no negotiation); rewrite §STORE Flow Batched STORE, §Schema Evolution, and AC 19. Fix the stale "handler deferred to a follow-up issue" docstrings in protocol/src/dht.rs. Net -1054/+210. cargo fmt/clippy clean; nextest 1009 passed. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(node): reject mis-sized BatchStoreAck; run republish sweep off the select loop Address PR review: - client::batch_store now errors on a BatchStoreAck whose results length doesn't match the request, instead of silently returning a vector that mis-maps onto the request hashes. The deleted fallback wrapper used to guard this; the primitive is now called directly, so it must guard itself. - The periodic republish drain reschedules the held hashes, then fires the batched publish on a detached task rather than awaiting it inside the run_republish select loop. A slow/unreachable receiver could otherwise hold the loop for up to (chunks × DHT_CLIENT_TIMEOUT), delaying the shutdown signal and eager cache-insert publishes. The sweep is best-effort — abandoned on shutdown, retried next cycle. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Implements ACs 17-20 of ADR 022 §Batch token accounting (closes #648). Publishers can now send a single
BatchStoreRequestcovering many hashes destined for one receiver instead of n separateStoreRPCs (~80% wire-bytes reduction atC ≥ 10kcached blobs per ADR 022 §DHT Bandwidth Analysis), with a per-hashStorefallback for receivers that don't implement batching.Handler admission (
handlers/dht.rs, ACs 17/19)BatchStorethroughhandle_batch_store: batch-levelholder == authenticated NodeIdcheck once (mismatch →MALFORMED_MESSAGEstream-close per ADR 022 §Batch token accounting step 2), then per-hash admission identical to n separateStores (active-staker filter +RecordStore::insert_at) sharing one receiver-anchoredreceive_us. Oneboolper hash in request order. Oversize (>256) is rejected at wire decode →MALFORMED_MESSAGE(AC 19).peer_ipintohandle_one/dispatch;dispatchreturnsResult<_, app_code>for the stream-close case.Two-stage rate-limit accounting (
rate_limit.rs, AC 18)check()to share a metric-freetry_admit_one; addsadmit_batch_extra()consuming up ton-1more units cheapest-first with short-circuit — byte-for-byte equivalent to n separateStoreadmissions. Stage 1 (the frame token) is already charged inserve(). No rejection-counter bump on the partial-admit boundary.Publisher fallback (
batch_fallback.rsnew,client.rs, AC 20)BatchStoreFallback: bounded per-receiverunsupported_untilcache (default 15 min), lazy expiry, clock-injected for tests.client::batch_storeprimitive +batch_store_with_fallback: skips batch when cached unsupported; on anUNSUPPORTED(0x01) close caches the negative result + retries per-hash; malformed/too-large/rate-limited/transport errors hard-fail (no per-hash storm).exchange_on(surfaced by the new AC20 integration test): a peer stream-reset was collapsed by iroh'sAsyncReadinto anio::Errorwith no typed source, soextract_app_error_codelost the code and fallback would never have fired against a real node. Now probesrecv.received_reset()and re-surfacesReadError::Reset(code)typed.Metrics
dht_batch_store_received,dht_batch_store_hashes_deferred_rate_limit; per-hash outcomes reuse the existingdht_store_*counters.Tests
13 unit (rate-limit two-stage, fallback-cache TTL, error classifier) + 8 loopback integration (roundtrip, holder-mismatch MALFORMED, >256 MALFORMED, partial rate-limit admit, single-hash boundary, primitive roundtrip, batch-vs-fallback path selection, and end-to-end
UNSUPPORTED-close → cache → per-hash fallback). Full suite: 381 pass; clippy + fmt clean.A multi-agent PR review (code/tests/errors/types/comments) was run; its findings are addressed in this branch.
Scope
The republish scheduler is not rewired to group hashes by receiver — that consumes these building blocks and belongs to #630. AC 20's publisher-MUST is satisfied by the tested
batch_store_with_fallbackhelper.🤖 Generated with Claude Code