Skip to content

refactor(squid-sdk): restructure the fallback around a source pool; enforce its invariants in types - #704

Merged
abernatskiy merged 1 commit into
masterfrom
refactor/fallback-source-pool
Dec 4, 2026
Merged

abernatskiy merged 1 commit into
masterfrom
refactor/fallback-source-pool

Conversation

@abernatskiy

Copy link
Copy Markdown
Contributor

Restructures the fallback data source (@subsquid/squid-sdk/fallback, plus the EVM and Solana fallback builders) after a code-quality review. No behaviour change: the existing suite passes with its scenarios unchanged; only tests that reached into removed internals were ported.

Why

  • Per-stream state (served heights, freshness gauges) lived in objects shared across streams, so every write from a stream needed a released guard, and the rule that every wait goes through alive() had to be enforced by a regex over stream.ts.
  • FallbackDataSource handed its private state to the stream and to head delegation through two hand-built adapter interfaces (StreamHost, HeadHost).
  • stream.ts was close to 850 lines; the EVM and Solana builders were near copies of each other.

What changed

  • SourcePool (pool.ts) owns everything that outlives a stream: slots, claims, selection, the active source, failures and capability probes. StreamHost, HeadHost, the Selector class and slots.ts are gone; selection is pure functions over the slots (selection.ts), and the switch-up candidate rule exists once instead of three times. fallback.ts goes from 697 to ~325 lines.
  • Each FallbackStream owns its state and is its own iterator: served heights and gauges per stream (a released stream's gauges are closed in one place), one release signal instead of two, no per-stream resets in the supervisor. Guarded writes to shared state go from nine to four.
  • stream.ts split: eager switch-up (switch-up.ts) and the pace check (pace-monitor.ts) are synchronous classes, so every await stays in stream.ts; a new test pins that the extracted modules have none.
  • Builders share their source wiring (fallback/downstream.ts, withFallbackRpcDefaults next to withFallbackPortalRetries).
  • Smaller: the failed request kind (data / head) is stated instead of rewriting a probe's cause for the refusal count; the capability probe's timeout is its own error class instead of a duck-typed object; metrics.ts is a table of gauges (scrape output verified byte-identical); SourceHealth.onDelivered() and Claims.lastFailed() replace repeated pairs; the fallback's test helpers are no longer compiled into lib/.

Invariants now enforced by the types

What the inline docs said, the compiler now checks:

Documented Enforced by
A pace report has a shortfall exactly for the too-slow verdicts PaceReport, PaceAssessment and WindowJudgement are discriminated unions (drops a !)
A source's cause exists only while it is unhealthy HealthStatus, used in FallbackMetrics.sources[]
A capability failure is never a freshness reason capabilityFailure(reason: Exclude<FailureReason, FreshnessReason>)
Only a stream moves its own position and delivery state readers hold a read-only StreamView; served / released are read-only from outside
A sweep changes only by condemning a source or switching up Sweep.exhausted / passedOver are ReadonlySets, plus condemned(i)
The policy is fixed once resolved; claims and slot records belong to their owner ResolvedPolicy (and so DEFAULT_POLICY), Claim, SourceSlot, RankedSource are read-only
A window's totals change only through add() StarvationWindow.waitMs / consumerMs are getters

Each row was checked with a @ts-expect-error case. Those cases are not committed, because test files are not typechecked here and a committed type test would check nothing.

Public type surface: PaceReport becomes a union and FallbackMetrics.sources[] correlates health with cause; reading code is unaffected. DEFAULT_POLICY, FallbackDataSource.health, activeIndex and switchCount become read-only. New exported types: HealthStatus, KeptVerdict, TooSlowVerdict.

Deliberately left: FallbackMetrics.sources[].refusals stays optional (public type); the non-empty source list stays a runtime check (a tuple type would reject arrays built at runtime).

Testing

  • tsc clean; npm run build OK.
  • vitest: 669 passed, 5 skipped, three runs in a row; the network-gated e2e and parity suites are skipped as on master.
  • New tests: onDelivered, Claims.lastFailed, a released stream's give-back, the no-await rule for the extracted modules, and a refusal case for a probe given up as a liveness failure.

🤖 Generated with Claude Code

…nforce its invariants in types

No behaviour change. The fallback data source kept per-stream state (served heights, gauges) in
objects shared across streams, so every write from a stream needed a released-guard; its
supervisor handed its private state to the stream and head delegation through two adapter
interfaces; stream.ts was near 850 lines; and the EVM and Solana builders were copies.

- SourcePool (pool.ts) owns everything that outlives a stream: slots, claims, selection, the
  active source, failures and capability probes. StreamHost, HeadHost, Selector and slots.ts are
  gone; selection is pure functions over the slots (selection.ts).
- Each FallbackStream owns its served heights and gauges, and is its own iterator: one release
  signal instead of two, no per-stream resets in FallbackDataSource.
- Switch-up (switch-up.ts) and the pace check (pace-monitor.ts) leave stream.ts. They are
  synchronous, so every await stays in stream.ts; a test pins that.
- The builders share their source wiring (fallback/downstream.ts, withFallbackRpcDefaults).
- The failed request (data or head) is stated instead of rewriting the cause; the capability
  probe's timeout is its own error class; metrics.ts is a table (output byte-identical).
- Documented invariants are now types: PaceReport and WindowJudgement carry a shortfall exactly
  when the source was too slow; a metrics source carries a cause only when unhealthy
  (HealthStatus); capabilityFailure takes no freshness reason; readers get a read-only StreamView;
  Sweep, the resolved policy, claims and slot records are read-only outside their owners.
- The fallback's test helpers are no longer compiled into lib/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The broad concurrency-sensitive refactor spans fallback ownership, iteration, delegation, metrics, and builders, requiring runtime and integration validation of timing, interleavings, and nested-source behavior.

No open issues 🎉

What changed in this PR

Refactors fallback orchestration around a shared SourcePool, moving stream-specific state into FallbackStream and strengthening public type invariants.

Changes:

  • Extracts source selection, switch-up, pacing, gauges, and downstream wiring.
  • Updates EVM/Solana builders, RPC defaults, tests, exports, and build exclusions.
  • Records the SDK package change.
File Description
meta/​squid-sdk/​tsconfig.json Excludes fallback test helpers from compilation.
meta/​squid-sdk/​src/​solana/​fallback/​load-rpc-stream.ts Uses shared missing-peer handling for Solana RPC streams.
meta/​squid-sdk/​src/​solana/​fallback/​builder.ts Uses shared downstream construction for Solana fallback sources.
meta/​squid-sdk/​src/​rpc-retries.ts Centralizes fallback RPC retry defaults.
meta/​squid-sdk/​src/​fallback/​switch-up.ts Extracts synchronous source switch-up logic.
meta/​squid-sdk/​src/​fallback/​stream.ts Makes fallback streams self-owned async iterators with per-stream state.
meta/​squid-sdk/​src/​fallback/​stream-release-effects.test.ts Tests release effects and stream-state isolation.
meta/​squid-sdk/​src/​fallback/​starvation.ts Enforces starvation-window and judgement invariants.
meta/​squid-sdk/​src/​fallback/​slots.ts Removes obsolete slot abstractions.
meta/​squid-sdk/​src/​fallback/​selector.ts Removes the replaced selector class.
meta/​squid-sdk/​src/​fallback/​selection.ts Provides functional source selection over pool slots.
meta/​squid-sdk/​src/​fallback/​selection.test.ts Updates tests for functional source selection.
meta/​squid-sdk/​src/​fallback/​refusals.ts Distinguishes data and head request refusal tracking.
meta/​squid-sdk/​src/​fallback/​refusals.test.ts Tests request-kind refusal behavior.
meta/​squid-sdk/​src/​fallback/​pool.ts Adds shared source-pool orchestration for claims, health, probing, and failover.
meta/​squid-sdk/​src/​fallback/​policy.ts Makes resolved fallback policies readonly.
meta/​squid-sdk/​src/​fallback/​pace.ts Defines discriminated pace assessment types.
meta/​squid-sdk/​src/​fallback/​pace-monitor.ts Extracts synchronous pace monitoring.
meta/​squid-sdk/​src/​fallback/​metrics.ts Consolidates fallback metric definitions and typing.
meta/​squid-sdk/​src/​fallback/​index.ts Updates the public fallback exports and type surface.
meta/​squid-sdk/​src/​fallback/​health.ts Adds correlated health status types and delivery transitions.
meta/​squid-sdk/​src/​fallback/​health.test.ts Tests source health transitions after delivery.
meta/​squid-sdk/​src/​fallback/​heads.ts Delegates head handling through the source pool.
meta/​squid-sdk/​src/​fallback/​gauges.ts Adds per-stream gauge management.
meta/​squid-sdk/​src/​fallback/​fallback.ts Simplifies fallback datasource and supervisor ownership.
meta/​squid-sdk/​src/​fallback/​fallback-stream-release.test.ts Tests fallback stream release lifecycle and await rules.
meta/​squid-sdk/​src/​fallback/​fallback-heads.test.ts Updates fallback head tests for pool access.
meta/​squid-sdk/​src/​fallback/​fallback-freshness.test.ts Updates fallback freshness and pool activation tests.
meta/​squid-sdk/​src/​fallback/​downstream.ts Shares downstream source construction utilities.
meta/​squid-sdk/​src/​fallback/​diagnostics.ts Tightens failure-reason diagnostics types.
meta/​squid-sdk/​src/​fallback/​diagnostics.test.ts Updates diagnostics tests for the revised imports and types.
meta/​squid-sdk/​src/​fallback/​claims.ts Adds failed-claim tracking and claim invariants.
meta/​squid-sdk/​src/​fallback/​claims.test.ts Tests failed-claim state handling.
meta/​squid-sdk/​src/​fallback/​capability.ts Adds explicit capability probe timeout errors.
meta/​squid-sdk/​src/​evm/​fallback/​load-rpc-stream.ts Uses shared missing-peer handling for EVM RPC streams.
meta/​squid-sdk/​src/​evm/​fallback/​builder.ts Uses shared downstream construction for EVM fallback sources.
common/​changes/​@subsquid/​squid-sdk/​refactor-fallback-source-pool_2026-12-05-00-00.json Records the SDK package release change.

Review effort: Lite

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are recorded for the fallback source-pool refactor.

No open issues 🎉

Review effort: Balanced

@abernatskiy
abernatskiy merged commit 29e8794 into master Dec 4, 2026
4 checks passed
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