Repository navigation
feat(client-pull): retry + peer-cache fallback for registry bootstrap - #1341
Conversation
…#1166) Client discovery did a single per-fetch `getActiveNodes` read with no retry and no cache, so a transient RPC blip failed the whole fetch. ADR 012 section Bootstrap already specifies the shape; implement it. - Wrap each paginated `getActiveNodes` page call in the ADR's fixed [1 s, 5 s, 30 s] retry schedule. Hardcoded as a private const table in `discovery` rather than reusing `decdn_config_types::RetryPolicy`, which is an origin-scoped *doubling* policy (it would silently give 1/2/4 s) and would add a `client-pull -> config-types` edge. - Persist the resolved candidate set to `peers.json` under the resolved client data dir on a successful read, and fall back to it when every retry is exhausted. With no cache, exit with the exact ADR wording: "Cannot reach bootstrap sources. Check network connectivity and RPC endpoint configuration." (registry failure kept as the cause). - Wire `decdn fetch` and `decdn bundle pull` through the new `discovery::bootstrap_nodes`. - Correct ADR 012's peer-cache path to the client-scoped location the code uses. DNS-seed merge, periodic registry refresh, and a channel cache are out of scope. The paginated read loop itself was already implemented and is reused unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
WalkthroughThe client bootstrap flow classifies registry failures, retries paginated node reads, persists peer caches, and falls back to cached peers. CLI bundle and fetch discovery use this flow, while the ADR documents updated client data and cache paths. ChangesClient bootstrap and peer discovery
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant CLI
participant bootstrap_nodes
participant CapacityBond
participant peers_json
CLI->>bootstrap_nodes: request bootstrap nodes
bootstrap_nodes->>CapacityBond: getActiveNodes with pagination and retry
CapacityBond-->>bootstrap_nodes: active node pages
bootstrap_nodes->>peers_json: persist successful peer list
bootstrap_nodes-->>CLI: live peers or cached peers with warning
Note 🎁 Summarized by CodeRabbit FreeYour 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 |
There was a problem hiding this comment.
Code Review
This pull request implements the ADR 012 client bootstrapping and peer-cache persistence, adding retry backoff logic for registry queries and a fallback mechanism that reads from a cached peers.json file when the registry is unreachable. The feedback suggests improving the robustness of the cache writing process by using tempfile::NamedTempFile to avoid potential race conditions from static temporary filenames, which requires adding tempfile to the production dependencies. Additionally, adding a warning log for peer cache version mismatches is recommended to improve observability.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
Coverage reportTotal: 81.40% (was 81.33%, ▲ +0.07%) — 52948/65046 lines
History
|
The peer cache wrote through a fixed `peers.json.tmp`, so two `decdn` processes sharing a client data dir could interleave into that one file and then rename the tear into place; the write was also never fsynced, so a crash after the rename could still surface a truncated cache. Write through `tempfile::NamedTempFile` in the target dir instead — unique name, fsync before persist, auto-cleanup on a failed write. Also log the peer-cache version mismatch that was previously collapsed silently into "no usable cache", matching the warn the undecodable case already emits. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review of #1341 found the peer-cache fallback rested on machinery that does not exist: `decdn` installs no tracing subscriber and does not depend on `tracing`, so all five `tracing::warn!` sites were unreachable from the only binary that calls `bootstrap_nodes`. A user whose RPC was down waited 36 s in silence and then fetched against a peer list of unknown age with no indication at all. Provenance now travels in the return type. `bootstrap_nodes` returns `Bootstrap::{Live, Cached}` carrying the cache age and the sanitized registry error, and both CLI call sites print `Bootstrap::warning()` to stderr — matching the `eprintln!` convention the fetch path already uses for degraded-but-proceeding states. `PeerCache` gains `written_at` so the age is expressible; done now, while `PEER_CACHE_VERSION` is 1 and nothing has shipped, because adding it later costs a version bump that invalidates every deployed cache. A cache that cannot be persisted is reported the same way instead of only being logged: a read-only data dir otherwise disarms the fallback silently, forever. Both error renders are sanitized. `%e` on an alloy transport error forwards reqwest's ` for url (<url>)` tail, and an rpc_url commonly carries an API key (#954) — the comment claiming otherwise was wrong and is gone. `%err` on the `anyhow::Error` also dropped the cause; that is `sanitize_err_chain` now. Deterministic failures are no longer retried. A typo'd capacity_bond_address or a rejected API key cost the full 36 s before reporting an error that was never going to change; `is_permanent` returns those immediately, naming the likely misconfiguration. `is_retry_err` is deliberately not used — it is a 429/503 allowlist that would classify a refused connection as permanent. The retry loop is extracted as `paginate_with_retry` and now has behavioral tests under paused time: 4 calls and exactly 36 s of virtual sleep on a failing page, 1 call and no sleep on a permanent one, and a retry that resumes pagination at the right offsets. Previously the only retry "test" asserted a const against its own literal and would have passed with the loop deleted. Also pins the on-disk JSON shape, covers malformed and unreadable caches, and covers the cache-write-failure path. Cache reads distinguish a missing file from an unreadable one, the version tag is decoded before the body so a future shape change really is a version mismatch rather than an opaque decode error, and `active_nodes`/`peer_cache_path` are private so no caller can bypass the ADR 012 contract. Comment corrections: RetryPolicy's defaults are 100/200/400 ms (not 1/2/4 s), config-types is already in this crate's graph, the retry budget is per page, the directory entry is not fsynced, and step 6 is the caller's job. ADR 012's tree and paths now match the code. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Ran a multi-agent review over the branch (code quality, test coverage, silent failures, comment accuracy, type design). Three findings were load-bearing; all are fixed in d202508. 1. The observability this PR's design rests on did not exist. Provenance now travels in the return type: 2. A latent API-key leak, guarded by a comment asserting the opposite. The retry log's 3. The headline feature had no behavioral test. Also in d202508:
Filed as follow-ups, out of scope here: #1346 (ADR advertises an unimplemented Verification: |
altanoruc
left a comment
There was a problem hiding this comment.
Reviewed the current head (d202508). Two correctness/operability gaps remain in the new retry and peer-cache fallback paths; details inline.
Two gaps from review of d202508. `is_permanent` treated every `RpcError::ErrorResp` as deterministic, but providers signal rate limiting that way — over HTTP 200 with a JSON-RPC error body, so the HTTP status check never saw it. Infura's -32005, Alchemy's -32016, QuickNode's -32007/-32012 and a plain 429 in the JSON `code` all went straight to the cache/error path on the first attempt, skipping the 1/5/30 s schedule for one of the most common transient failures there is. `ErrorResp` now defers to `ErrorPayload::is_retry_err` — the allowlist is the right shape at this layer, unlike the transport layer where it would misclassify a refused connection. A paused-time test covers a rate-limited page being retried and one that then succeeds. The cache-read diagnostics were still only logged, so they were still unreachable: `read_peer_cache` collapsed EACCES, malformed JSON, wrong version, and empty into `None`, and a simultaneous registry outage returned BOOTSTRAP_UNREACHABLE naming only the registry cause. The user was never told a cache existed or why it was skipped — at exactly the moment the cache was supposed to save them. `read_peer_cache` now returns `CacheRead::{Ok, Absent, Unusable(reason)}`, and `Unusable` is layered under BOOTSTRAP_UNREACHABLE so `{err}` still renders the ADR-pinned sentence verbatim while `{err:#}` — what `main()` prints — names the file and the reason. `Absent` stays silent, since no file is the ordinary first-run state. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Conflicts came from #1357 (proxy warming) touching the same two files. `crates/cli/src/commands/fetch.rs`: main threaded a `warming: ProxyWarmingParams` argument through `discover_provider` and `probe_and_rank` while this branch replaced `rpc_url` + `client_region` with a single `chain: &ResolvedChain`. Kept both — `chain` for the region and data dir, `warming` passed on to `probe_and_rank`. Main's `#[allow(clippy::too_many_arguments)]` is dropped: the `chain` consolidation takes the signature from 8 arguments back to 7, and clippy confirms it is no longer needed. `crates/client-pull/src/discovery.rs`: main's `WarmingCandidate` / `proxy_warming_order` merged cleanly; only the test module collided, where both sides are pure additions. Kept both sets. `crates/cli/src/commands/bundle_pull.rs` auto-merged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…#1350, #1355) (#1358) Follow-ups filed off the reviews of #1340, #1341 and #1353. Closes #1342, #1343, #1344, #1345, #1350 and #1355; #1356 was closed as a duplicate of #1347, which stays open for the deferred swap-revert tests. BREAKING: `ReportGate` and `ReputationWiring`'s struct literal are gone — `ReputationWiring` is now a sum type (`Disabled` / `Enabled { sink, staked, publish }`), so an admission set without a sink is unrepresentable rather than warned about at runtime. That deletes the test #1344 asked for instead of adding it. `GossipRuntimeConfig::subscribe_reputation` is also gone; the operator-facing `[gossip] subscribe_reputation` key is unchanged, but `decdn-node` now resolves it into the wiring variant at the one site that builds it, so there is a single off-switch instead of two. `AnnounceGate::Disabled` is `#[cfg(test)]`. It fails OPEN on ADR 001 rule 2 and was guarded only by a doc comment plus a test on `announce_staked_gate`, which would have stayed green if a future edit passed `Disabled` to `spawn` — the hole #1170 closed. It no longer exists in production builds. Transaction submission is unified in `decdn_incentive::tx::send`, including both swap venues (they spend USDC and read the hash after `get_receipt()`, so a receipt timeout named no transaction at all). `send` takes a caller-owned `landed` slot: `Some` means "may have taken effect" — including the unreadable- receipt case — and is cleared on a confirmed revert. `bond`, `setup`, `register` and `appeal` use it. `channel` deliberately does not: it classifies a revert as an expected outcome rather than an error. That slot is what makes the re-run guidance safe. The earlier wording asserted "no TOKEN was transferred" / "on-chain state is unchanged" and told the operator to re-run immediately; alloy's nonce filler resolves against the pending block, so re-running while a bond tx is in flight submits a second one and doubles the bond. `setup`'s live phases are one fallible section with a single reporting site, so a failure at any phase emits the aggregated `--json` summary with whatever landed — previously a register-phase failure printed nothing and a landed swap's hash had no machine-readable carrier at all. `build_summary` emits one shape on both paths with a `partial` flag. Note for the record: commit `edb3e80`'s message asserts a symbol (`bundle_pull::discover_candidates`) that does not exist — copied from #1350's text without verifying, in a commit about fixing inaccurate comments. The code is correct; the message could not be amended. Tests: new `cli_setup_partial` e2e journey drives the production binary against anvil (with a new `ChainFixture::pause_capacity_bond` lever, since starving the operator of TOKEN trips the pre-flight instead of entering the live phase); the gossip integration test's drain now varies its payload per round, because plumtree dedups byte-identical messages for 90s and a constant payload collapsed a 50-round budget to ~6. Every new test was mutation-verified.
…1361) (#1362) Six filed review follow-ups from the #1360 and #1341 reviews, plus the residual half of #1347. - #1361 — `CapacityBond.declareMbps(0)` accepted from an inactive operator, releasing a tier four deactivation paths could otherwise never clear. Active operators still revert. +49 bytes. - #1359 — new `decdn node deregister`; `unbond --all` issues `declareMbps(0)` for unregistered operators, without which #1361 had no CLI path. - #1348 — `decdn_protocol::Region` newtype; `region_hint` `String` -> `Option<Region>`; `PEER_CACHE_VERSION` 1->2. - #1349 — registry retry budget made aggregate across pages; `--timeout-ms` bounds the registry read. - #1347 — `tx::run_then_cleanup` extracted and tested; deferral note corrected. - #1346 — `[cache] peer_cache_path` dropped from ADR 012. A five-agent review before opening the PR found and fixed: the discovery timeout cancelling the ADR-012 peer-cache fallback; a "trapped bond" justification overstated ~100x (a tier-down declaration always released all but `bondRequired(minCapacityMbps)` — 199.7 of 20,252.7 TOKEN was actually trapped); two vacuous tests that passed with their feature mutated out; `--region usa` silently ignored; and stale claims in ADR 003 and the contract NatSpec. Copilot review: fixed `Region`'s deserializer echoing rejected input into operator-facing errors. Pushed back on a claimed missing `Future` import — it is in the Rust 2024 prelude and the crate compiles. Closes #1346, #1347, #1348, #1349, #1359, #1361.
Client discovery did a single per-fetch
CapacityBond.getActiveNodesread with no retry and no cache, so a transient RPC blip failed the whole fetch. ADR 012 § Bootstrap already specifies the shape; this implements it.What changed
Retry with backoff. Each paginated
getActiveNodespage call is wrapped in the ADR's fixed[1 s, 5 s, 30 s]schedule (REGISTRY_RETRY_BACKOFF, a private const table incrates/client-pull/src/discovery.rs).This deliberately does not reuse
decdn_config_types::RetryPolicy: that is a geometric doubling policy scoped to node-side origin fetches, so reusing it verbatim would silently produce 1/2/4 s — the wrong schedule — and would add aclient-pull → config-typesdependency edge that the documented crate flow does not have.Peer cache with fallback. On a successful read the resolved candidate list is persisted (versioned JSON, temp-file + rename so a crash mid-write cannot truncate a good cache). When every retry is exhausted, the cached list is used instead. With no usable cache, the error is the exact ADR wording, with the underlying registry failure retained as the cause:
An empty successful read is returned as-is but does not overwrite a populated cache — an emptied registry is no reason to discard the last known-good peer list, and both call sites reject an empty set anyway.
Cache location.
peers.jsonunder the already-resolved client data dir (--data-dir>[identity] data_dir>cli::default_client_data_dir()→~/.decdn/client), alongsidekeystore.jsonand the buyer-channel store.client-pullis a library and does not resolve a home directory itself; the CLI passeschain.data_dirin.Call sites wired through the new
discovery::bootstrap_nodes:decdn fetch(discover_provider) anddecdn bundle pull.discover_providernow takes&ResolvedChaininstead of three separate fields (it crossed clippy'stoo_many_argumentsthreshold otherwise).ADR touch-up. ADR 012's peer-cache path is corrected in place to the client-scoped
~/.decdn/client/peers.jsonthe code actually uses — a path correction only, all four occurrences plus the directory tree.The paginated read loop (offset /
PAGE_SIZE/ short-page termination) was already implemented and is reused unchanged.Deliberately out of scope
dns_seedkey was added and the ADR was not amended to allow one.[bootstrap] registry_refresh_secsis not implemented here; no background task.Tests
Six new tests in
discovery.rs, all written first and confirmed failing (compile error: the items did not exist) before implementing:retry_backoff_is_the_adr_012_schedule— asserts the const table the retry loop reads, so the schedule is checked without sleeping 36 s.peer_cache_round_trips/absent_cache_reads_as_none— persistedpeers.jsondeserializes back to the same candidates.successful_read_persists_the_cache.exhausted_retries_fall_back_to_the_cache.exhausted_retries_without_a_cache_report_the_adr_error— asserts the exact ADR string and that the registry failure survives in the cause chain.an_empty_registry_read_leaves_a_populated_cache_intact.The fallback decision is factored into a pure sync
resolve_bootstrap(registry_result, data_dir)precisely so these are assertable without a live RPC or real sleeps.Verification
Secret hygiene: the new retry log records offset/attempt/backoff and the transport error, never
rpc_url(which commonly carries an API key) — consistent with the existing redaction convention in this module.🤖 Generated with Claude Code
Closes #1166
Summary by CodeRabbit
New Features
Bug Fixes
Documentation