Skip to content

feat(node): chain-backed origin directory + OriginAssignment/PublisherRegistry bindings (#651) - #830

Merged
thiras merged 3 commits into
mainfrom
feat/651-chain-origin-directory
Jun 9, 2026
Merged

thiras merged 3 commits into
mainfrom
feat/651-chain-origin-directory

Conversation

@thiras

@thiras thiras commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

What

Implements the remaining slice of #651 — the chain-backed OriginDirectory plus the OriginAssignment / PublisherRegistry alloy bindings it needs. The StakerSet + ChainStakerSet half of #651 already shipped; this fills in the origin-directory half that was stubbed (origin.rs carried only the trait + ConfigOriginDirectory).

Why

The DHT prefetch authorized-origin gate (ADR 022) reads from an OriginDirectory, but the runtime wired an empty ConfigOriginDirectory, so the gate rejected every hash and prefetch could never fire. This unblocks #820 (prefetch live acquisition) by giving the gate a real, chain-fed directory. prod-blocking.

How

Resolution chain (ADR 022 §FIND_VALUE Flow "Origin discovery", ADR 011 §Origin Assignment Authority):

PublisherRegistry.namespaceOf(H) → OriginAssignment.getOrigins(namespaceId)
  → CapacityBond.nodeIdOf(operator) → keep active == true

A hash with no claiming namespace falls back to the default-open allow-list (getOrigins(0)); a hash that is neither claimed nor default-open resolves to no origins (per ADR 022 line 306).

OriginDirectory::lookup_origins is synchronous, so — exactly like ChainStakerSet — ChainOriginDirectory snapshots chain state at bootstrap and follows the membership-mutating events thereafter, serving every lookup from an in-memory cache:

  • Bootstrap: windowed ContentClaimed log replay (the only hash→namespace write path, so replay is complete) builds hash → namespaces; getOrigins point reads snapshot namespace → operators and the default-open set; nodeIdOf resolves operator → NodeId.
  • Watcher: a 7-event loop across both contracts (ContentClaimed, AssignmentActivated/Revoked/BlacklistedAssignmentPruned, DefaultOpenAllowlistUpdated/OperatorAdded/OperatorRemoved) keeps the cache current, with the same exponential-backoff + health-metric semantics as the staker-set watcher.
  • Liveness is delegated to the shared StakerSet (is_active at lookup time) rather than re-tracked, so an OriginAssignment-silent unbond is still reflected; the cache stores only the operator → NodeId binding.

Surface

  • crates/incentive: origin_assignment + publisher_registry sol! bindings (read path + mutating events only).
  • crates/node/src/dht/chain_origin_directory.rs: ChainOriginDirectory — pure DirectoryCache::resolve logic is unit-tested without a chain (multi-namespace union/dedup, default-open fallback, claimed-but-unassigned ≠ default-open, inactive-operator filtering, unbound-operator drop, has_origin agreement); event-application semantics covered.
  • crates/node/src/metrics.rs: decdn_origin_directory_{watcher_restarts,watcher_resolve_failures,watcher_down_seconds,operator_count} family mirroring the staker-set watcher.
  • crates/common + crates/cli: two optional [blockchain] knobs — origin_assignment_address, publisher_registry_address — wired across CLI/env/TOML, config-validate summary, default template, with both-or-neither load-time validation. Unset ⇒ the file-config directory is kept (testnet bring-up path unchanged).
  • crates/node/src/runtime/mod.rs: builds ChainOriginDirectory::bootstrap(...) (reusing the existing provider + staker_set) when both addresses are set; else the ConfigOriginDirectory fallback.

Out of scope

Verification

  • cargo nextest run — 1546/1546 pass (incl. 11 new directory tests + 3 config-resolution tests).
  • cargo clippy --all-targets, cargo fmt --check, cargo doc, cargo deny — all clean (pre-commit).

🤖 Generated with Claude Code

…rRegistry bindings (#651)

Implements the remaining slice of #651: the chain-backed `OriginDirectory`
that resolves a content hash to active authorized-origin NodeIds, reading
from a live event-fed cache. The `StakerSet`/`ChainStakerSet` half of #651
already shipped; this adds the origin-directory half it was missing.

Resolution chain (ADR 022 §FIND_VALUE Flow "Origin discovery", ADR 011):
`PublisherRegistry.namespaceOf(H)` -> `OriginAssignment.getOrigins(ns)` ->
`CapacityBond.nodeIdOf(op)` -> keep `active == true`. A hash with no claiming
namespace falls back to the default-open allow-list (namespace 0); neither
claimed nor default-open resolves to no origins.

`OriginDirectory::lookup_origins` is synchronous, so — like `ChainStakerSet` —
the directory snapshots chain state at bootstrap (windowed `ContentClaimed`
log replay + `getOrigins` point reads) and follows the membership-mutating
events thereafter, serving every lookup from an in-memory cache. Operator
liveness is delegated to the shared `StakerSet` rather than re-tracked, so an
`OriginAssignment`-silent unbond is still reflected. Watcher health metrics
(restarts / down-seconds / resolve-failures / operator-count) mirror the
staker-set watcher.

This unblocks #820 (DHT prefetch live acquisition): the prefetch
authorized-origin gate previously read an empty `ConfigOriginDirectory` and
rejected every hash. The runtime now wires `ChainOriginDirectory` when the new
`blockchain.origin_assignment_address` + `blockchain.publisher_registry_address`
are configured (both-or-neither, validated at load), else keeps the
file-config fallback for testnet bring-up.

- crates/incentive: `origin_assignment` + `publisher_registry` alloy bindings
- crates/node/dht: `ChainOriginDirectory` (pure resolution logic unit-tested
  without a chain; event-application semantics covered)
- crates/node/metrics: `decdn_origin_directory_*` watcher-health family
- crates/common: two optional `[blockchain]` address knobs (CLI/env/TOML,
  config-validate summary, default template) + resolution tests

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 6, 2026 16:42

@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 a chain-backed OriginDirectory (ChainOriginDirectory) that resolves content hashes to active operator NodeIds using an in-memory cache updated by a background event-subscription task. It introduces contract ABI bindings for OriginAssignment and PublisherRegistry, adds configuration options and CLI arguments to support these addresses, and integrates the directory into the prefetch engine. Feedback on the changes suggests optimizing the initial log replay by avoiding scanning from block 0, replacing HashSet deduplication with sorting and deduping a Vec in resolve for better performance and determinism, and using sort_unstable instead of sort in test cases.

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.

@github-actions

github-actions Bot commented Jun 6, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.54% (was 87.46%, ▼ 0.92%) — 30346/35065 lines

File Coverage Lines Δ
crates/cli/src/commands/config.rs 64.43% 96/149 ▲ +2.89%
crates/common/src/config/mod.rs 96.62% 5482/5674 ▲ +0.07%
crates/common/src/config/resolved.rs 100.00% 30/30 ● 0.00%
crates/node/src/dht/chain_origin_directory.rs 37.60% 247/657 new
crates/node/src/metrics.rs 87.24% 677/776 ▲ +0.41%
crates/node/src/runtime/mod.rs 51.85% 785/1514 ▼ 0.81%
crates/node/src/runtime/reload.rs 95.11% 1421/1494 ▲ +0.02%
History
Commit Total Δ vs base
ba45548 86.45% ▼ 1.01%
0dfee77 86.45% ▼ 1.01%
108f721 (HEAD) 86.54% ▼ 0.92%

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

This PR completes the “origin-directory half” of #651 by adding a chain-backed OriginDirectory implementation (plus alloy ABI bindings) and wiring it into the node runtime so the prefetch authorized-origin gate can consult live on-chain state instead of an always-empty directory.

Changes:

  • Added ChainOriginDirectory with bootstrap log replay + event-fed cache, and exported it from crates/node::dht.
  • Added OriginAssignment / PublisherRegistry alloy bindings in crates/incentive.
  • Introduced optional blockchain.origin_assignment_address / blockchain.publisher_registry_address config + CLI plumbing and new origin-directory watcher metrics.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 12 comments.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates test resolved config seed to include new optional blockchain fields.
crates/node/src/runtime/reload.rs Extends runtime reload tests/fixtures with new optional blockchain fields.
crates/node/src/runtime/mod.rs Wires prefetch engine to use ChainOriginDirectory when both contract addresses are configured; otherwise keeps the empty fallback.
crates/node/src/metrics.rs Adds origin-directory watcher counters/gauges and scrape-time downtime recompute plumbing.
crates/node/src/dht/mod.rs Adds module + re-export for chain_origin_directory.
crates/node/src/dht/chain_origin_directory.rs Implements chain-backed origin directory cache + watcher loop + unit tests.
crates/incentive/src/publisher_registry.rs Adds PublisherRegistry sol! bindings (namespace read + ContentClaimed event).
crates/incentive/src/origin_assignment.rs Adds OriginAssignment sol! bindings (getOrigins + assignment/default-open events).
crates/incentive/src/lib.rs Exposes the two new incentive binding modules.
crates/common/src/config/types.rs Adds new optional contract address fields to BlockchainConfig.
crates/common/src/config/resolved.rs Adds new optional fields to ResolvedBlockchain.
crates/common/src/config/mod.rs Resolves/validates both-or-neither addresses and wires env expansion + tests.
crates/common/src/cli/run.rs Adds CLI flags + help text for the new contract address options.
crates/cli/tests/config_validate.rs Updates CLI config validation test fixture for new optional fields.
crates/cli/src/commands/config.rs Prints new fields in config validate summary and updates default config template comments.

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

Comment thread crates/cli/src/commands/config.rs Resolved
Comment thread crates/cli/src/commands/config.rs Resolved
thiras and others added 2 commits June 6, 2026 20:04
Code-review fixes from automated reviewers on #830:

- Replay start block configurable. `ContentClaimed` log replay no longer
  starts at block 0 (which scans the whole L2 history in 9k-block windows).
  Add file-only `blockchain.origin_directory_from_block` (default 0,
  documented to set to the PublisherRegistry deploy block) threaded into
  `ChainOriginDirectory::bootstrap`.

- `origin_directory_operator_count` now tracks the live authorised-origin
  surface. Previously it published `operator_node.len()` — the monotonic
  binding cache that never shrinks on revoke/remove. Redefine the gauge as the
  count of distinct operator addresses currently authorised (∪ over namespaces
  + default-open), recomputed and published AFTER each set-mutating handler
  (activate / revoke / prune / default replace|add|remove / new-namespace),
  not from the binding-update path. New unit test covers the decrease-on-remove
  behaviour.

- `has_any` no longer allocates. It iterated a cloned/collected HashSet,
  defeating its "cheap emptiness check" contract; now iterates the underlying
  sets directly and short-circuits.

- `resolve` returns sorted + deduplicated NodeIds (deterministic) via
  Vec + sort_unstable + dedup instead of a HashSet collect; tests assert the
  order directly.

- Docs corrected: the module resolution-chain now states liveness is applied
  via the shared StakerSet (nodeIdOf supplies only the binding); the CLI help,
  config-validate summary, and field docs no longer claim a "file-config origin
  directory" fallback — unset is an empty deny-all directory and the prefetch
  authorized-origin gate finds no origins.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Multi-agent review follow-ups (no behavioural change to production paths):

Comment-rot fixes (genuine doc/code contradictions):
- `config/mod.rs` resolution + the unset-resolution test comment no longer
  claim a "file-config origin directory" fallback — unset is an empty deny-all
  directory (matches every other doc site and the runtime).
- `Metrics::origin_directory_operator_count` docstring described the pre-fix
  monotonic binding cache; now matches the field doc + impl (authorised-origin
  count that falls on revoke/remove).

Test coverage:
- Symmetric both-or-neither config case: lone publisher address now asserted to
  name the missing origin address (the field-naming branch was only covered in
  one direction).
- Metric-wiring tests for the drift-surfacing guarantee (the type's core value,
  previously untested): restart counter is edge-triggered (one per drift
  window), resolve-failure counter increments, and the operator-count gauge
  reflects `authorized_operator_count` and DROPS on revoke. Ported from
  `chain_staker_set.rs`.

Docs:
- Add a `# Failure model` section enumerating the four drift metrics and the
  silent per-event resolve-failure path (mirroring `chain_staker_set.rs`).
- Note on `on_content_claimed` that a failed `getOrigins` leaves the namespace
  unpopulated (fail-closed) and self-heals on a later event — no dedicated retry.

Deliberately deferred (noted in review): folding the both-or-neither origin
addresses into an `Option<struct>` on `ResolvedBlockchain` to make the lone
state unrepresentable in the validated type. The invariant is already enforced
and tested at the resolution boundary (the only prod constructor) and the
runtime match is defensive; the type refactor is a reasonable follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit f28b994 into main Jun 9, 2026
19 checks passed
@thiras
thiras deleted the feat/651-chain-origin-directory branch June 9, 2026 23:50
thiras added a commit that referenced this pull request Jun 14, 2026
… (#899)

* feat(node): wire live DHT prefetch acquisition + ledger feedback (#820)

Closes AC 7 of #650. PR #819 landed the prefetch decision engine but it only
decided and metered. This wires the live acquisition on top:

- On a `PrefetchDecision::Acquire`, the DHT handler fires a bounded, non-blocking
  background acquisition (`PrefetchAcquirer`) that drives `cache.populate` →
  the existing NodeOrigin pull-through (discover → probe → paid pull → ingest).
  Concurrency-capped (semaphore), per-hash deduped, cancelled on shutdown.
- Spend feeds back via a new `AcquisitionObserver` on `NodeOriginDeps`: it fires
  on every pull that spent (success OR paid-but-failed, whose voucher watermark
  advanced #852) and records per-pull spend/bytes only for prefetch-initiated
  pulls (gated by the in-flight set), so demand-miss pulls never charge the
  prefetch budget. `decdn_prefetch_spend_usdc_total` now non-zero.
- A bounded, TTL'd `PrefetchAcquiredSet` tags prefetch content; the client serve
  path credits `record_served` for those blobs, feeding the demand-quality
  auto-throttle.
- Two new `[prefetch]` config knobs: `max_concurrent_acquisitions` (4) and
  `acquisition_timeout_secs` (30). New acquisition-outcome metrics.

Note: the issue's "OriginAssignment subscription" task was already shipped by
#830 (`ChainOriginDirectory`), so only acquisition + ledger feedback remained.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(node): address PR review on prefetch acquisition (#820)

- InflightGuard::drop now recovers a poisoned lock (PoisonError::into_inner)
  so the RAII cleanup always runs (gemini) — leaving a hash armed would wedge
  dedupe + the observer gate.
- InflightSet::arm logs on a poisoned lock, matching PrefetchAcquiredSet::insert,
  so a dropped acquisition is diagnosable (copilot).
- Corrected prefetch_spend_usdc + add_prefetch_spend docs: spend is charged on
  any prefetch-initiated paid pull that acked vouchers (success OR paid-but-
  failed), not only successes (copilot).
- Raised the e2e poll budget (35s) above the acquirer's 30s deadline so a slow
  CI pull is not declared a failure prematurely (copilot).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[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.

2 participants