Skip to content

feat(node): implement DHT BatchStore handler-side admission (closes #648) - #713

Merged
thiras merged 3 commits into
mainfrom
feat/dht-batch-store-admission
May 29, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/dht-batch-store-admission

Conversation

@thiras

@thiras thiras commented May 29, 2026

Copy link
Copy Markdown
Contributor

Implements ACs 17-20 of ADR 022 §Batch token accounting (closes #648). 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 per ADR 022 §DHT Bandwidth Analysis), with a per-hash Store fallback for receivers that don't implement batching.

Handler admission (handlers/dht.rs, ACs 17/19)

  • Routes BatchStore through handle_batch_store: batch-level holder == authenticated NodeId check once (mismatch → MALFORMED_MESSAGE stream-close per ADR 022 §Batch token accounting 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) is rejected at wire decode → MALFORMED_MESSAGE (AC 19).
  • Threads 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)

  • Refactors check() to share a metric-free try_admit_one; adds 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).
  • Bug fix in exchange_on (surfaced by the new AC20 integration test): 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 would never have fired against a real node. Now probes recv.received_reset() and re-surfaces 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 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_fallback helper.

🤖 Generated with Claude Code

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]>
Copilot AI review requested due to automatic review settings May 29, 2026 21:24

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

Comment thread crates/node/src/dht/client.rs Resolved
Comment thread crates/node/src/handlers/dht.rs Resolved
Comment thread crates/node/src/dht/rate_limit.rs Resolved
Comment thread crates/node/src/dht/rate_limit.rs Resolved
Comment thread crates/node/src/dht/rate_limit.rs Resolved
@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 89.40% (was 89.27%, ▲ +0.13%) — 21995/24603 lines

File Coverage Lines Δ
crates/node/src/dht/batch_fallback.rs 94.12% 112/119 new
crates/node/src/dht/client.rs 76.95% 197/256 ▲ +19.92%
crates/node/src/dht/rate_limit.rs 99.67% 600/602 ▲ +0.06%
crates/node/src/handlers/dht.rs 75.29% 259/344 ▲ +4.01%
crates/node/src/metrics.rs 84.53% 399/472 ▲ +0.27%
History
Commit Total Δ vs base
f333370 89.34% ▲ +0.14%
8b722d3 89.32% ▲ +0.12%
c0fd459 (HEAD) 89.40% ▲ +0.13%

@thiras thiras changed the title feat(node): DHT BatchStore handler-side admission (closes #648) feat(node): implement DHT BatchStore handler-side admission (closes #648) May 29, 2026

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

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 BatchStore handling 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 BatchStore client 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.

Comment thread crates/node/src/handlers/dht.rs Resolved
Comment thread crates/node/src/handlers/dht.rs Resolved
Comment thread crates/node/src/dht/client.rs Resolved
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]>
@alpergundogdu

Copy link
Copy Markdown
Contributor

Code review

Reviewed 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:

  1. The new received_reset() recovery in exchange_on re-surfaces the typed 0x01 reset code, but the whole exchange runs inside exchange()'s 8s timeout, whose .map_err(|_| anyhow!("timed out")) discards any error on elapse. If a near-budget connection has the timeout fire just as received_reset() (L388) resolves, the typed code is lost, so classify_batch_error(None) returns HardFail and the receiver is never cached or fallen-back. Narrow race, but it silently defeats the fallback this code path exists for. Fix: classify/recover the reset before the outer timeout can mask it, or surface Elapsed as its own outcome instead of folding it into a code-less error.

})
.await
.map_err(|_| {
anyhow::anyhow!(
"dht client: request timed out after {} ms",
DHT_CLIENT_TIMEOUT.as_millis()
)
})??;
Ok(response)

  1. per_hash_fallback gives each hash its own 8s timeout but has no aggregate cap, so a peer that hangs on every read can hold the loop for up to MAX_BATCH_STORE_HASHES x 8s (~34 min) on a single publish task. The 15-min unsupported cache bounds repeats, so it is a worst case rather than steady-state, but a loop-level deadline or a "bail after K consecutive timeouts" guard would keep one bad peer from wedging a sweep.

};
for (slot, &hash) in out.iter_mut().zip(hashes) {
let request = wire::DhtMessage::Store(wire::StoreRequest { hash, holder });
let payload = match encode_message(&request) {
Ok(p) => p,
Err(e) => {
tracing::debug!(hash = ?hash, error = %e, "dht per-hash fallback encode failed");
continue;
}
};
match tokio::time::timeout(DHT_CLIENT_TIMEOUT, exchange_on(&conn, &payload)).await {
Ok(Ok(wire::DhtMessage::StoreAck(ack))) => *slot = ack.accepted,
Ok(Ok(other)) => tracing::debug!(
hash = ?hash,
got = variant_name(&other),
"dht per-hash fallback: unexpected response variant"
),
Ok(Err(e)) => {
tracing::debug!(hash = ?hash, error = %e, "dht per-hash fallback Store failed");
}
Err(_) => tracing::debug!(hash = ?hash, "dht per-hash fallback Store timed out"),
}
}

  1. BatchStoreFallback's map has no size cap and no periodic GC; entries are pruned only lazily when that specific peer is re-queried after TTL. A publisher that marks many peers unsupported once and never republishes to them leaves dead entries indefinitely. This is the same unbounded-growth shape that feat(node): bound DHT rate-limiter keyspace via lazy prune + periodic GC (#645) #676 added caps + GC for in rate_limit.rs. Low risk at tens-of-nodes scale, but it re-opens that pattern. Fix: mirror rate_limit.rs with a max-entries cap + periodic GC.

#[allow(missing_debug_implementations)]
pub struct BatchStoreFallback {
ttl: Duration,
/// `peer → instant after which we retry batching`. Presence means
/// "currently treated as unsupported". Pruned lazily in
/// [`Self::supports_batch_at`].
unsupported_until: Mutex<HashMap<NodeId, Instant>>,
}

Design note (likely intentional, flagging only so it's a conscious call): classify_batch_error(None) returns HardFail, so a receiver that silently drops the unknown variant (no 0x01 close) is retried as a batch, not per-hash. ADR 022 AC 20's "MUST fall back on stream-close-without-ack" reads broader than 0x01-only; the batch_fallback module doc deliberately scopes it narrower to avoid an n-deep timeout storm against a merely-unreachable peer. Reasonable tradeoff in an all-new network, just worth confirming the AC-20 scoping is deliberate.

const fn classify_batch_error(code: Option<u32>) -> BatchAttemptOutcome {
match code {
Some(APP_ERR_UNSUPPORTED_MESSAGE) => BatchAttemptOutcome::Unsupported,
_ => BatchAttemptOutcome::HardFail,
}
}

🤖 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]>
@thiras
thiras merged commit 441a676 into main May 29, 2026
19 checks passed
@thiras
thiras deleted the feat/dht-batch-store-admission branch May 29, 2026 23:41
alpergundogdu added a commit that referenced this pull request Aug 18, 2026
#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]>
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.

DHT: implement BatchStore handler-side admission (ACs 17-20 of ADR 022)

3 participants