Skip to content

feat(gossip): node announce publish/subscribe with peer table - #231

Merged
thiras merged 9 commits into
mainfrom
feat/gossip-node-announce
Apr 16, 2026
Merged

thiras merged 9 commits into
mainfrom
feat/gossip-node-announce

Conversation

@thiras

@thiras thiras commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Implements ADR 001 NodeAnnounce gossip over iroh-gossip with an in-memory peer table and per-rule validation (signature, clock skew, region format, unique hashes, size cap, optional allowlist).
  • Adds a new decdn-gossip crate so the peer table + validation can be reused by a future client library (ADR 012) without pulling in the node binary.
  • Refactors the node runtime from a hand-rolled accept loop to iroh::protocol::Router, cleanly multiplexing cdn/probe/v1 and iroh-gossip's ALPN. ProbeHandler now impls iroh::protocol::ProtocolHandler directly.
  • Adds [gossip] config section (announce_interval_sec, peer_ttl_sec, subscribe_global, hex allowlist) and four /metrics counters/gauge.

PoC shortcuts (deferred to follow-up PRs): ADR 001 rule 2 (staking registry check) is replaced by an optional config allowlist; LoadHint and popular_hashes are stubbed until the cache engine lands; gossip metrics use unlabelled counters (per-topic / per-reason labelling needs iroh-metrics plumbing).

Review iterations

Two rounds of review feedback landed on top of the initial commits.

Round 1 — b15e077 (7 inline comments from Copilot + Gemini):

  • validate_envelope now uses postcard::take_from_bytes (trailing bytes tolerated per ADR 013).
  • verify_signature uses try_into to fold the length check into the slice→array conversion.
  • Subscriber snapshots now_us() once and reuses it across validation and peer-table insert.
  • Dropped unused peer_ttl_sec from GossipRuntimeConfig (TTL lives on PeerTable).
  • Gossip JoinHandles are now held outside the JoinSet and explicitly .abort()ed on shutdown (dropping a handle detaches the task).
  • identity.region is uppercased and validated (2 ASCII letters) at config resolution.
  • gossip.allowlist doc matches the parser (hex, either case).

Round 2 — 1e53aed (findings from a 5-agent review):

  • Dropped the silent "ZZ" region fallback. Publishing without a configured region is now a startup error; library consumers that omit the region get subscribe-only mode with a WARN.
  • Open each gossip topic once and split into (GossipSender, GossipReceiver); the sender goes to the single publisher task, each receiver to its own subscriber. Subscribe failures surface via inc_rejected("subscribe_failed") + error log instead of dying silently. GossipService::spawn is now async.
  • Replaced PeerTable::insert_or_refresh's Err(u64) with a typed StaleTimestamp { existing_us }; the subscriber matches exhaustively so a future failure mode can't be silently mislabeled.
  • now_us() logs once (via atomic flag) when SystemTime is pre-epoch instead of silently returning 0.
  • Runtime shutdown: metrics_stop_tx.send logs at debug when the receiver is gone; gossip-handle join distinguishes panics from cancellations.
  • Docs: AnnounceReject::UnknownVariant documented as reserved (postcard currently surfaces unknown discriminants as DecodeFailed); "ADR 001 rule 2" phrasing corrected; resolve_gossip allowlist doc matches the either-case parser; SHUTDOWN_DEADLINE rationale restored.
  • +10 new tests: normalize_region, parse_node_id_hex, resolve_gossip defaults/rejections, AnnounceReject::label stability.

Test plan

  • cargo build --workspace clean
  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo fmt -- --check clean
  • RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --document-private-items clean
  • cargo nextest run --workspace — 64/64 passing (was 54 before round-2 additions; existing probe loopback suite still green after Router refactor)
  • Two-node integration test (gossip_two_node.rs) — follow-up
  • adr/024-gossip-node-announce.md — follow-up
  • Per-topic / per-reason Prometheus labels — follow-up (requires iroh-metrics plumbing)

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings April 14, 2026 19:50
@thiras thiras changed the title feat(gossip): NodeAnnounce publish/subscribe with peer table feat(gossip): node announce publish/subscribe with peer table Apr 14, 2026

@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 introduces the decdn-gossip crate, which implements gossip transport, a peer table, and NodeAnnounce validation using iroh-gossip. The changes include TTL-based peer eviction, signature verification logic, and integration into the node runtime via the iroh protocol Router. Feedback suggests optimizing the subscriber loop by reusing timestamp values to ensure consistency and utilizing try_into for more idiomatic signature byte handling.

Comment thread crates/gossip/src/service.rs Resolved
Comment thread crates/gossip/src/validation.rs Resolved

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 001 NodeAnnounce gossip over iroh-gossip, adding shared wire types + a reusable gossip runtime/peer-table crate, and refactoring the node runtime to use iroh::protocol::Router for ALPN multiplexing.

Changes:

  • Add decdn-protocol::gossip wire types (GossipEnvelope, NodeAnnounce, etc.) and re-export them from decdn-protocol.
  • Introduce new decdn-gossip crate with pure validation, an in-memory peer table, and publisher/subscriber service tasks.
  • Refactor node runtime from a custom accept loop to Router, update probe handler/tests, and add gossip config + metrics.

Reviewed changes

Copilot reviewed 20 out of 21 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
crates/protocol/src/lib.rs Exposes new gossip module + re-exports gossip wire types and topic constants.
crates/protocol/src/gossip.rs Defines postcard-serialized gossip envelope/payload types with versioning and tests.
crates/gossip/src/lib.rs New crate entrypoint exporting gossip runtime components.
crates/gossip/src/validation.rs Adds signature/region/clock-skew/hash validation for inbound announces.
crates/gossip/src/peer_table.rs Adds TTL-bounded peer table with monotonic timestamp enforcement.
crates/gossip/src/service.rs Adds publisher/subscriber/TTL-sweeper tasks wiring iroh-gossip to the peer table.
crates/gossip/src/metrics.rs Adds GossipMetrics trait + noop implementation.
crates/node/src/runtime/mod.rs Switches node runtime to Router, wires in gossip service, and adds endpoint builder + metrics adapter.
crates/node/src/handlers/probe.rs Updates probe handler to implement ProtocolHandler and moves connection gauge handling into the handler.
crates/node/src/handlers/mod.rs Removes custom Handler trait in favor of ProtocolHandler convention.
crates/node/tests/probe_loopback.rs Updates loopback test to call ProtocolHandler::accept.
crates/node/src/metrics.rs Adds gossip-related counters/gauge and adapter methods.
crates/node/src/config/types.rs Adds [gossip] config section types (interval/ttl/subscription/allowlist).
crates/node/src/config/resolved.rs Adds resolved gossip config struct to resolved config model.
crates/node/src/config/mod.rs Implements gossip config resolution + allowlist parsing helpers.
crates/node/Cargo.toml Adds dependency on new decdn-gossip crate.
crates/node/src/runtime/dispatch.rs Removes custom accept-loop implementation (replaced by Router).
crates/node/src/runtime/endpoint.rs Removes old endpoint builder that pre-advertised handler ALPNs.
crates/gossip/Cargo.toml Adds new decdn-gossip crate manifest + dependencies.
Cargo.toml Adds crates/gossip to workspace members and workspace deps.
Cargo.lock Locks new decdn-gossip crate and its dependency graph.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/node/src/config/mod.rs Resolved
Comment thread crates/gossip/src/validation.rs Resolved
Comment thread crates/gossip/src/service.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
thiras added a commit that referenced this pull request Apr 14, 2026
- validation: decode envelopes with `take_from_bytes` so trailing bytes
  are tolerated per ADR 013 (matches the protocol crate's existing
  envelope_trailing_bytes_tolerated test).
- validation: fold the signature length check into `try_into` for a
  more idiomatic slice-to-fixed-array conversion.
- service: snapshot the clock once per inbound message so validation
  and peer-table insert share a timestamp (avoids racing a mid-flight
  clock adjustment and drops one syscall).
- service: remove the unused `peer_ttl_sec` field from
  `GossipRuntimeConfig`; TTL is already configured on the `PeerTable`
  at construction, and having it in two places was misleading.
- runtime: abort gossip JoinHandles explicitly during shutdown. A
  dropped JoinHandle detaches the task in tokio, so the previous
  wrapper-in-JoinSet pattern would hit the 15s shutdown timeout and
  leak the underlying gossip loops.
- config: uppercase and validate `identity.region` at resolution time;
  a bad value (e.g. "us") would otherwise cause the node to publish
  announces that it and its peers all reject at validation time.
- types: doc that `gossip.allowlist` accepts hex in either case, since
  the parser already does (`is_ascii_hexdigit`).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Apr 14, 2026
Correctness:
- Drop the "ZZ" region fallback in the publisher. Any region string is
  signed into every NodeAnnounce; a missing region would otherwise look
  valid to peers and silently indexed as region "ZZ". `decdn-node` now
  requires `identity.region` at config resolution whenever gossip would
  publish; the library `GossipService` disables the publisher (with a
  WARN) if no region is configured.
- Open each gossip topic exactly once in `GossipService::spawn` and
  split it into `(GossipSender, GossipReceiver)` — the sender goes to
  the single publisher task, each receiver to its own subscriber task.
  Previously publisher and subscriber each opened their own
  subscription per topic, so a transient subscribe failure on one side
  could leave the node happily broadcasting into a topic it doesn't
  ingest (or silently dropping inbound events while publishing fine).
  `GossipService::spawn` is now async to permit the pre-subscribe pass.
- Surface subscribe failures via `GossipMetrics::inc_rejected` with a
  stable `subscribe_failed` label and an error-level log. Old code only
  warned/debug-logged and left the task silently dead.
- Replace `PeerTable::insert_or_refresh`'s `Err(u64)` with a typed
  `StaleTimestamp { existing_us: u64 }`. Subscriber task matches the
  error exhaustively so a future `PeerTable` failure mode cannot be
  silently mislabeled as `stale_timestamp`.
- Log once (behind a `std::sync::atomic::AtomicBool`) when
  `SystemTime::duration_since(UNIX_EPOCH)` fails in `now_us`. Prior
  silent `unwrap_or(0)` left operators with a node publishing
  announces peers rejected as `ClockSkew` with no local signal.

Runtime shutdown:
- Replace `let _ = metrics_stop_tx.send(())` with a `debug!` when the
  receiver is already gone, so shutdown ordering is debuggable.
- Log panicked gossip-task joins during shutdown; stay silent on the
  expected `is_cancelled()` path.
- Restore the WHY on `SHUTDOWN_DEADLINE` (probe accept + close
  timeouts combined).

Docs:
- `AnnounceReject::UnknownVariant` is unreachable today (postcard
  surfaces unknown discriminants as `DecodeFailed`). Documented as
  reserved for when `GossipPayload` grows a second variant and the
  decoder gains a manual peek.
- `validate_envelope` doc: allowlist is a PoC stand-in for ADR 001
  rule 2, not the rule itself.
- `resolve_gossip` doc: allowlist accepts hex in either case, matching
  the parser.

Tests (+10 passing, 64 total):
- `normalize_region` — accepts `US`/`us`/`Us`; rejects `usa`, `u1`,
  empty, `U`, `U S`, `Ü1`, `12`, `U-`.
- `parse_node_id_hex` — either case, mixed case, nibble order, 63/65
  length, non-hex rejection.
- `resolve_gossip` — defaults when absent, rejects zero interval, zero
  TTL, bad allowlist entry.
- `AnnounceReject::label` stability — freezes the Prometheus label
  contract. Adding a new variant without updating this test fails to
  compile.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
thiras and others added 5 commits April 14, 2026 23:53
Implements ADR 001 NodeAnnounce gossip over iroh-gossip, with an
in-memory peer table and signature-aware validation. Refactors the
node runtime from a hand-rolled accept loop to iroh::protocol::Router
so gossip's ALPN multiplexes cleanly alongside cdn/probe/v1.

- protocol: add GossipEnvelope / GossipPayload / NodeAnnounce{,Body} /
  LoadHint per ADR 013 (frozen variant order, signed-body split).
- gossip (new crate): PeerTable with monotonic + TTL semantics, pure
  validate_envelope covering all ADR 001 rules (signature, clock skew,
  region format, unique hashes, size cap, optional allowlist),
  GossipService spawning publisher + subscriber + TTL sweeper against
  iroh-gossip, GossipMetrics trait to keep the crate backend-agnostic.
- node: new [gossip] config section with hex allowlist parsing;
  Router replaces dispatch.rs + endpoint.rs; ProbeHandler now impls
  iroh::protocol::ProtocolHandler directly; four new metrics.

PoC shortcuts (deferred): ADR 001 rule 2 (staking registry check) is
replaced by an optional config allowlist; LoadHint and popular_hashes
are stubbed until the cache engine lands. Two-node integration test
and adr/024 are planned follow-ups.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Module-level doc comment used `Self::label`, which rustdoc resolves
against the module rather than the type, breaking `cargo doc` with
-D warnings. Reference the type by name instead.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- validation: decode envelopes with `take_from_bytes` so trailing bytes
  are tolerated per ADR 013 (matches the protocol crate's existing
  envelope_trailing_bytes_tolerated test).
- validation: fold the signature length check into `try_into` for a
  more idiomatic slice-to-fixed-array conversion.
- service: snapshot the clock once per inbound message so validation
  and peer-table insert share a timestamp (avoids racing a mid-flight
  clock adjustment and drops one syscall).
- service: remove the unused `peer_ttl_sec` field from
  `GossipRuntimeConfig`; TTL is already configured on the `PeerTable`
  at construction, and having it in two places was misleading.
- runtime: abort gossip JoinHandles explicitly during shutdown. A
  dropped JoinHandle detaches the task in tokio, so the previous
  wrapper-in-JoinSet pattern would hit the 15s shutdown timeout and
  leak the underlying gossip loops.
- config: uppercase and validate `identity.region` at resolution time;
  a bad value (e.g. "us") would otherwise cause the node to publish
  announces that it and its peers all reject at validation time.
- types: doc that `gossip.allowlist` accepts hex in either case, since
  the parser already does (`is_ascii_hexdigit`).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Correctness:
- Drop the "ZZ" region fallback in the publisher. Any region string is
  signed into every NodeAnnounce; a missing region would otherwise look
  valid to peers and silently indexed as region "ZZ". `decdn-node` now
  requires `identity.region` at config resolution whenever gossip would
  publish; the library `GossipService` disables the publisher (with a
  WARN) if no region is configured.
- Open each gossip topic exactly once in `GossipService::spawn` and
  split it into `(GossipSender, GossipReceiver)` — the sender goes to
  the single publisher task, each receiver to its own subscriber task.
  Previously publisher and subscriber each opened their own
  subscription per topic, so a transient subscribe failure on one side
  could leave the node happily broadcasting into a topic it doesn't
  ingest (or silently dropping inbound events while publishing fine).
  `GossipService::spawn` is now async to permit the pre-subscribe pass.
- Surface subscribe failures via `GossipMetrics::inc_rejected` with a
  stable `subscribe_failed` label and an error-level log. Old code only
  warned/debug-logged and left the task silently dead.
- Replace `PeerTable::insert_or_refresh`'s `Err(u64)` with a typed
  `StaleTimestamp { existing_us: u64 }`. Subscriber task matches the
  error exhaustively so a future `PeerTable` failure mode cannot be
  silently mislabeled as `stale_timestamp`.
- Log once (behind a `std::sync::atomic::AtomicBool`) when
  `SystemTime::duration_since(UNIX_EPOCH)` fails in `now_us`. Prior
  silent `unwrap_or(0)` left operators with a node publishing
  announces peers rejected as `ClockSkew` with no local signal.

Runtime shutdown:
- Replace `let _ = metrics_stop_tx.send(())` with a `debug!` when the
  receiver is already gone, so shutdown ordering is debuggable.
- Log panicked gossip-task joins during shutdown; stay silent on the
  expected `is_cancelled()` path.
- Restore the WHY on `SHUTDOWN_DEADLINE` (probe accept + close
  timeouts combined).

Docs:
- `AnnounceReject::UnknownVariant` is unreachable today (postcard
  surfaces unknown discriminants as `DecodeFailed`). Documented as
  reserved for when `GossipPayload` grows a second variant and the
  decoder gains a manual peek.
- `validate_envelope` doc: allowlist is a PoC stand-in for ADR 001
  rule 2, not the rule itself.
- `resolve_gossip` doc: allowlist accepts hex in either case, matching
  the parser.

Tests (+10 passing, 64 total):
- `normalize_region` — accepts `US`/`us`/`Us`; rejects `usa`, `u1`,
  empty, `U`, `U S`, `Ü1`, `12`, `U-`.
- `parse_node_id_hex` — either case, mixed case, nibble order, 63/65
  length, non-hex rejection.
- `resolve_gossip` — defaults when absent, rejects zero interval, zero
  TTL, bad allowlist entry.
- `AnnounceReject::label` stability — freezes the Prometheus label
  contract. Adding a new variant without updating this test fails to
  compile.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Rename `gossip_will_publish` to `ensure_region_when_publishing_global`
  and lift the interlock into its own helper. The old helper's doc
  claimed "at least one topic subscribed" while the body only checked
  `subscribe_global`; the new helper's name matches what it computes.
- Strengthen `reject_labels_are_stable`: the earlier version was a flat
  sequence of `assert_label` calls, so adding a new variant would
  silently skip the contract. The new version uses an exhaustive
  `match` whose compile failure is the real guarantee. Also pin the
  free-form `SUBSCRIBE_FAILED_LABEL` constant so label drift there
  fails CI too.
- Reference the probe handler's timeout constants by name in the
  `SHUTDOWN_DEADLINE` comment so a future edit to the probe constants
  doesn't silently invalidate the rationale.
- Drop the misleading "transitively" clause from `SUBSCRIBE_FAILED_LABEL`'s
  doc (no transitive usage exists).

Tests (+9, 73 total):
- `ensure_region_when_publishing_global_*`: three branches — rejects
  missing region when global publishing is on, accepts region set,
  accepts the subscribe-only noop config.
- `resolve_gossip_allowlist_happy_path`: mixed-case hex entry flows
  through `parse_node_id_hex` into the expected `[u8; 32]`, closing the
  seam between the two.
- `resolve_gossip_applies_positive_values`: non-default values for
  every resolved field.
- `build_topic_list_*`: four cases covering the empty / global-only /
  region-only / both permutations that feed `GossipService::spawn`'s
  early-return path.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@thiras
thiras force-pushed the feat/gossip-node-announce branch from 869bd3f to 1c10c88 Compare April 14, 2026 20:53
@thiras
thiras requested a review from alpergundogdu April 14, 2026 20:55
Comment thread crates/node/src/config/mod.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
Comment thread crates/gossip/src/service.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
thiras and others added 4 commits April 17, 2026 01:22
- config: clarify parse_node_id_hex doc — accepts either case
- runtime: TODO note for GossipService self-managed shutdown

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Merge with main brought in `decdn config validate` integration tests
that predate the gossip field on `ResolvedConfig`. Add the missing
`ResolvedGossip` literal to `sample_resolved` and an `identity.region`
to `VALID_CONFIG` so the new region-required-when-publishing-global
guard doesn't reject the validate happy-path test.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Rust 1.95.0 promotes `map_unwrap_or` to a workspace-deny lint. Swap
`map(...).unwrap_or(0)` for `map_or(0, ...)` on the SystemTime epoch
fallback in `ProbeHandler::accept` so CI clippy stays green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras merged commit 2fb1381 into main Apr 16, 2026
11 checks passed
@thiras
thiras deleted the feat/gossip-node-announce branch April 16, 2026 22:35
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.

3 participants