Skip to content

feat: origin-aware discovery — advertise origin-held content before pull-through (#1130) - #1508

Merged
alpergundogdu merged 9 commits into
mainfrom
claude/issue-1130-plan-09313e
Jul 29, 2026
Merged

alpergundogdu merged 9 commits into
mainfrom
claude/issue-1130-plan-09313e

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes part 1 of #1130 (fs pass-through zero-copy serve is a separate follow-up PR).

What & why

A blob sitting in a node's configured origin (fs directory, or a pinned http/s3 object) was undiscoverable until it had been pulled into the store once. "Presence" was defined as store presence in three places — probe has_blob, DHT announce, and eviction — while the origin was only consulted reactively during a serve. On the default decdn fetch (auto-discovery), the client probes candidates and keeps only those answering has_blob: true, so a cold origin blob was filtered out everywhere and the fetch failed with "none of the probed node(s) hold the requested blob" — the observed "fetch a few times before it sticks."

This PR makes a node advertise what it can serve from its origin before any pull-through, so origin content is discoverable on the first fetch. Origin-kind-agnostic; serving still uses the existing pull-through (the zero-copy fs serve is Design 2, a separate PR).

How

  • Origin::enumerate() (default empty) + a filesystem override that walks {base}/{hex[0..2]}/{hex} presence-only (panic-free hex parse — iroh_blobs::Hash::from_str panics on malformed input).
  • CacheEngine::rescan_origins() builds an ArcSwap<HashMap<Hash,u64>> origin-held index = every enumerable origin's listing ∪ operator pinned_hashes the origin actually has, minus refused/denied hashes, each mapped to size. origin_held_hashes() seeds DHT announce; origin_held_size() backs probe with no per-probe I/O.
  • Probe advertises origin-held content (has_blob: true + origin size) when the store can't — no eviction hold needed (origin content isn't evictable).
  • DHT announce unions the origin-held set into the cold-start republish seed; a periodic rescan (cache.fs_rescan_interval_sec, default 60s) picks up files dropped after boot and pushes them to the scheduler; reload triggers a detached rescan (honoring reload()'s no-await invariant).
  • Gate B fix: a timed-out reactive local-populate now spawns a detached local-origin warm (never node→node), so a slow cold pull finishes in the background and the retry sticks — previously it warmed nothing.

Slash-safety (important)

Advertising has_blob: true for content not in the store is only safe if the serve path never signs an ok:false refusal for it — a signed has_blob:true + signed NotFound within 30s is phantom-announcement evidence (ADR 014). The Task 8 audit found respond_error signs every ok:false, so this PR gates it: for CacheMiss/EvictedSinceProbe on an origin-held hash it now drops (fails silent) instead of signing. Payment/auth rejections are unaffected. The correct consequence for an unservable origin file is a local reputation ding (ADR 008), not a bond slash — and the failure is the publisher's mis-indexing, not the operator's.

Tests

  • Unit: fs enumerate (excludes .obao4/strays); engine rescan_origins (fs ∪ present pins, denied excluded, absent pin excluded); fold_origin_held probe decision; config round-trip.
  • Full suites green: decdn-cache + decdn-common (707), decdn-node (903). decdn-e2e --features anvil-e2e compiles against the new signatures.

Deliberately deferred

  • Zero-copy fs pass-through serve — Design 2, separate PR (this PR still imports fs content into the store on serve; correctness/discovery first).
  • New anvil-e2e first-fetch test — the harness is heavy/flaky; both halves of the probe change are unit-covered. Recommended follow-up.
  • Prewarm for http/s3 — dropped by design (egress cost; pinned-announce covers discovery without fetching bytes ahead of time).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Configurable rescanning of filesystem origins, enabled by default every 60 seconds.
    • Origin-held content can be advertised and served even before it is pulled into the cache.
    • Manual rescans run at startup and during node reloads; periodic rescans can be disabled.
  • Bug Fixes
    • Improved handling of cache misses to avoid false refusal evidence.
    • Local populate timeouts now continue warming content in the background.
  • Documentation
    • Added configuration guidance for rescan frequency and its performance impact.

alpergundogdu and others added 7 commits July 29, 2026 15:45
Add Origin::enumerate() (default empty) with a filesystem override that
walks {base}/{hex[0..2]}/{hex}, presence-only, to list the hashes a node
can serve before any pull-through — the basis for advertising origin
content on probe/DHT (#1130). Uses a panic-free hex parser because
iroh_blobs::Hash::from_str panics on malformed input.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add CacheEngine::rescan_origins() building an ArcSwap<HashMap<Hash,u64>>
of hashes servable from a configured origin before pull-through, mapped
to size. Union of every enumerable origin's listing and operator pins the
origin actually has, minus refused hashes. origin_held_hashes() seeds DHT
announce; origin_held_size() backs probe has_blob/total_bytes with no
per-probe I/O.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Interval for re-walking the fs origin (and re-checking pins) into the
origin-held index; default 60s, 0 disables the periodic rescan (startup
and reload still run one). Classified restart-required in the reload
exhaustive destructure (the timer cadence needs a restart); all
ResolvedCache fixtures updated.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
When the store can't back has_blob:true but the blob is servable from a
configured origin (origin_held_size is Some), sign has_blob:true with the
origin size. Origin content takes no eviction hold, so hold-budget /
stake-lane pressure is irrelevant to it. Fold logic extracted to a pure,
unit-tested fold_origin_held.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
#1130)

Union origin_held_hashes into the cold-start republish seed; rescan the
origin at startup (before the seed), on a periodic fs_rescan_interval_sec
timer (which pushes newly-found hashes into the scheduler — origin
content generates no store-insert event), and on reload (detached, to
honor reload()'s no-await invariant). Origin content is now discoverable
on the first fetch instead of only after a warm.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…#1130)

on_local_populate_timeout now spawns a detached populate_local warm
(local origin only, never node→node) so a slow cold pull finishes in the
background and the next attempt hits a warm store. Previously it warmed
nothing, so a cold origin blob needed several fetches before it stuck
(Gate B). Engine inflight-coalescing dedups concurrent warms.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
respond_error drops (fails silent) instead of signing an availability
StreamResponse{ok:false} when the hash is origin-held. Advertising
has_blob:true for origin content (previous commits) means a serve miss
could otherwise pair a signed has_blob:true probe with a signed NotFound
within 30s — phantom-announcement slash evidence (ADR 014). Payment/auth
rejections are unaffected. Consequence is a reputation ding, not a slash.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 66c51d4f-3a8b-483d-b41d-e93155defbc1

📥 Commits

Reviewing files that changed from the base of the PR and between 4d9d27c and 1e49db5.

📒 Files selected for processing (14)
  • crates/cache/src/engine.rs
  • crates/cache/src/origin/fs.rs
  • crates/cache/src/origin/mod.rs
  • crates/cli/tests/config_validate.rs
  • crates/common/src/config/mod.rs
  • crates/common/src/config/resolved.rs
  • crates/common/src/config/types.rs
  • crates/node/src/handlers/client/fill.rs
  • crates/node/src/handlers/client/wire.rs
  • crates/node/src/handlers/probe.rs
  • crates/node/src/runtime/mod.rs
  • crates/node/src/runtime/reload.rs
  • crates/node/tests/anvil_bringup_shutdown_e2e.rs
  • crates/node/tests/sighup_signal.rs

Walkthrough

Adds filesystem-origin enumeration and an atomically refreshed origin-held index, configurable periodic rescans, runtime/reload integration, origin-aware probe and cache-miss handling, and background local warming after local populate timeouts.

Changes

Origin-held cache flow

Layer / File(s) Summary
Configuration and origin enumeration contracts
crates/common/src/config/..., crates/cache/src/origin/..., crates/cli/tests/config_validate.rs
Adds fs_rescan_interval_sec, the Origin::enumerate contract, and validated filesystem-origin hash enumeration.
Origin-held index lifecycle
crates/cache/src/engine.rs
Adds atomic origin-held hash/size snapshots, rescanning, live refusal filtering, and integration coverage.
Runtime scheduling and reload integration
crates/node/src/runtime/..., crates/node/tests/...
Seeds republishing from origin-held hashes, schedules optional rescans, refreshes on pin reload, and stops the task during shutdown.
Serving decisions and local warming
crates/node/src/handlers/...
Uses origin-held sizes in probe decisions, suppresses matching cache-miss responses, and warms local origins after local populate timeouts.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ProbeHandler
  participant CacheEngine
  participant FilesystemOrigin
  Client->>ProbeHandler: probe hash
  ProbeHandler->>CacheEngine: origin_held_size(hash)
  CacheEngine-->>ProbeHandler: held size or None
  ProbeHandler-->>Client: probe response with availability
  Client->>FilesystemOrigin: request origin-held content
Loading

Note

🎁 Summarized by CodeRabbit Free

Your 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 @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.21% (was 80.24%, ▼ 0.03%) — 53949/67263 lines

File Coverage Lines Δ
crates/cache/src/engine.rs 90.86% 2804/3086 ▲ +0.21%
crates/cache/src/origin/fs.rs 78.48% 536/683 ▲ +0.07%
crates/cache/src/origin/mod.rs 46.67% 35/75 ▼ 4.06%
crates/common/src/config/mod.rs 97.04% 6830/7038 ▲ +0.01%
crates/common/src/config/resolved.rs 100.00% 33/33 ● 0.00%
crates/node/src/handlers/client/fill.rs 56.35% 111/197 ▼ 4.64%
crates/node/src/handlers/client/wire.rs 93.94% 124/132 ▼ 1.26%
crates/node/src/handlers/probe.rs 88.29% 264/299 ▲ +1.02%
crates/node/src/runtime/mod.rs 46.52% 1083/2328 ▼ 0.56%
crates/node/src/runtime/reload.rs 96.53% 1642/1701 ▼ 0.04%
History
Commit Total Δ vs base
01f5092 80.78% ▼ 0.03%
80e87f0 80.71% ▼ 0.03%
1e49db5 (HEAD) 80.21% ▼ 0.03%

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of origin-aware discovery. The mechanical pieces are clean: the hex parser is genuinely panic-free (.get() slicing + Hash::from_bytes, no from_str/unwrap/indexing), the rescan set math (enumerate ∪ present pins, denied/absent excluded) is correct and tested, and the config plumbing round-trips with 0 disabling the cadence. The risk concentrates in the slash-safety story, and as written the gate is too narrow — a transient S3 blip on a pinned object, or a blacklist event under a slow/disabled rescan, can still hand out slashable evidence. Details inline.

The load-bearing fact (ADR 014 §Phantom, item 4 / §38): the on-chain evidence is only probeResponse.has_blob == true + streamResponse.ok == false for the same hash within 30s. The wire error code is unsigned and not part of the evidence — so every signed ok:false for an origin-held hash is phantom evidence, whatever reason produced it.

[Medium — tests] The safety-critical gate has no coverage. Good tests exist for enumerate, rescan_origins set math, fold_origin_held, and config round-trip — but nothing exercises the respond_error origin-held drop, and nothing drives an origin-held hash through a faulting fill to confirm no ok:false is signed. A test asserting "origin-held + origin fault ⇒ no StreamResponse written" would have caught the gate gap below. Fix: add a node-handler test that marks a hash origin-held, forces the fill to HardFault, and asserts the stream is dropped with no signed response (and the same for EvictedSinceProbe/HashDenied).

Note (can't inline — blacklist_watcher.rs isn't in this diff): the blacklist watcher calls set_chain_denied[_one] but never triggers a rescan_origins(), which is half of the finding on engine.rs:1047 below. The robust fix is the read-time refuses() filter; triggering a detached rescan on a deny event (like the reload path) is a weaker alternative.

Comment thread crates/node/src/handlers/client/wire.rs Resolved
Comment thread crates/cache/src/engine.rs Resolved
Comment thread crates/node/src/runtime/reload.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
alpergundogdu and others added 2 commits July 29, 2026 16:49
…ed hashes (#1130)

The prior gate also suppressed EvictedSinceProbe, silencing the signed
refusal that makes an announce-then-evict slashable (broke G-GOV-03). The
gate now fires only for CacheMiss on non-refused origin-held content — the
actual new exposure. refuses() is a live check against a stale snapshot.

Verified locally: g_gov_03_real_evidence passes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
origin_held_size/origin_held_hashes are a per-rescan snapshot, so a hash
blacklisted/evicted/denied after the last rescan lingered in it — making
the probe sign has_blob:true for a just-blacklisted blob (broke
g_node_04). Both now filter through the live refuses() set. Regression
test covers the no-rescan live path.

Verified: full anvil-e2e suite (30/30) passes locally.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu merged commit 644f4be into main Jul 29, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the claude/issue-1130-plan-09313e branch July 29, 2026 16:19
alpergundogdu added a commit that referenced this pull request Jul 29, 2026
main advanced with #1508 (origin-aware discovery), #1504 (event-log replay
elimination), and #1509. One real conflict + one semantic reconciliation:

- crates/node/src/slash_watcher.rs: #1504 replaced the SlashJudge.Slashed event
  with CapacityBond.SlashRecorded (no offenseType field), so the Phase A test
  fixture edit is obsolete — took main's structure.
- crates/node/src/handlers/client/wire.rs: #1508 added a drop-instead-of-sign
  block for origin-held CacheMiss whose ENTIRE rationale was avoiding
  phantom-announcement evidence. With phantom retired and ok:false inert, that
  defense is unnecessary — removed it so origin-held CacheMiss signs like every
  other refusal. Blacklisted hashes still route to ChainHashDenied via the
  refuses() guard.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
thiras added a commit that referenced this pull request Jul 29, 2026
…ons, clear watcher-refactor drift (#1510)

Follow-through on #1504 (every watcher off eth_getLogs replay onto enumeration
views) and #1508 (the discovery half of #1130), which changed the ground under
several open issues.

cache.prewarm (#1130, v0.1) — the http/s3 half of origin-aware serving. Pulls
cache.pinned_hashes into the store at startup and on reload so the first request
does not pay full pull-through latency. Opt-in and restart-required: it spends
origin egress on bytes nobody has asked for. An fs-ONLY origin chain is skipped
by design (that content is already local and is advertised through the
origin-held index); a mixed chain warms, and pins the fs entry serves are
imported as a second copy. Fills local-origin-only, so it never fronts USDC to a
peer. A hash filled by a concurrent pass is not counted as a fetch, so
overlapping warms do not double-count paid egress. Both the startup and reload
legs are cancelled before cache.shutdown() closes the store, so a restart
mid-warm cannot inflate prewarm_failures_total into the shape that metric
documents as a broken pin set. Reload warms coalesce rather than drop: a reload
that loses the single-flight race leaves its work flagged and the holder re-runs,
because both rescan and warm snapshot the pinned set when they start. New
decdn_cache_prewarm_{blobs,bytes,refused,failures}_total. decdn config validate
reports a flag set against an fs-only or empty chain as "set but INERT".

A pinned set larger than cache.cache_size_mb now warns at startup and on reload,
independent of prewarm — pinned blobs are LRU-exempt however they arrived, so the
eviction driver can otherwise never reach its high-water target.

selection stake policy (#1470, v0.1) — Candidate.stake becomes u64. The Option
conflated "not looked up" with "looked up, holds no bond", and the tie-break
ranked unknown strictly below a known zero; once on-chain stake lookup is wired,
one flaky RPC read would have silently sunk a well-staked peer below an unbonded
one. The type has no encoding for a failed read, so the lookup layer must retry
or drop the candidate. Behaviour is unchanged — nothing populates stake yet, and
nothing enforces the boundary until the lookup lands.

metrics reason splits (#1475) — sibling counters are the convention;
probe_hold_unavailable{reason} is the documented exception, earned because its
values share one aggregate and one budget axis (they do not share an alert — the
alert filters to reason="exhausted"). No metric renamed. The observability
appendix documented decdn_gossip_messages_rejected_total{reason=...}, a labelled
name the node has never exported; corrected there and in ADR 019 and
appendix-peer-table-eviction, and the sibling families are now in the registry
where they previously appeared nowhere.

#1493 needed no code: #1504 already shipped ContentBlacklist._regionHashes with
blacklistedHashCount/blacklistedHashes, the watcher bootstraps from a pinned-block
enumeration, and ColdStart::FromBlock is gone workspace-wide. Its "scope to
cached content" alternative was deliberately not taken — dispatch needs a
synchronous verdict for ADR 011 wire-indistinguishability.

Also clears drift #1504/#1508 left behind: chain_origin_directory described a
start-block replay with a persisted cursor, backfill.rs cited a replay_floor that
no longer exists, content_deny said the watcher "replays", and
fs_rescan_interval_sec reached neither DEFAULT_CONFIG nor the config validate
summary.

Follow-ups filed: #1511 (fs zero-copy pass-through), #1513 (more appendix metric
names the exporter never emitted), #1514 (split prewarm_failures by cause), #1517
(inflight-coalescing mutex poisoning is silent and sticky).

Closes #1130
Closes #1470
Closes #1475
Closes #1493
alpergundogdu added a commit that referenced this pull request Jul 30, 2026
PR #1510 bundled five changes; this removes only the `cache.prewarm`
feature (its item #1) and leaves the other four intact — the #1470
`Candidate.stake: u64` change, the #1475 metric sibling-counter
convention docs, and the #1504/#1508 watcher-drift fixes.

Removed:
- `CacheEngine::prewarm` / `prewarm_cancellable` / `prewarm_pinned` and
  the `PrewarmReport` / `PrewarmOutcome` / `FillOwnership` types.
  `populate_inner` reverts to `CacheResult<()>` (the `FillOwnership`
  metering existed only to feed prewarm's coalesced-vs-fetched counts).
- The four `decdn_cache_prewarm_*` counters.
- `cache.prewarm` config field, `DEFAULT_PREWARM`, `prewarm_enabled_for`,
  and the `decdn config validate` / template reporting of the flag.
- Startup prewarm spawn, shutdown cancellation, and the reload-time
  single-flight warm machinery (`warm_in_flight` / `warm_dirty` /
  `warm_wanted` / `prewarm_stop`).
- The prewarm integration-test file and all prewarm unit tests, plus the
  observability-appendix rows and CHANGELOG entry.

Kept (per request): the oversized-pin-set warning
(`warn_if_pins_exceed_cache`), which is independent of prewarm — it runs
unconditionally at startup and on reload. The reload path reverts to a
plain detached `rescan_origins` + budget-warn spawn. The
`fs_rescan_interval_sec` `config validate` reporting (a #1508 drift fix)
is also kept.

Verification: cargo build, clippy --all-targets, fmt --check clean;
cache/common/cli 1096 tests and node 897 tests pass; anvil-e2e compile
gate and RUSTDOCFLAGS=-D warnings doc clean.

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.

1 participant