Skip to content

fix(balance): coalesce concurrent checkBalance RPC reads with epoch-safe invalidation - #652

Open
Tyagiquamar wants to merge 1 commit into
BlockRunAI:mainfrom
Tyagiquamar:fix/balance-check-singleflight
Open

Tyagiquamar wants to merge 1 commit into
BlockRunAI:mainfrom
Tyagiquamar:fix/balance-check-singleflight

Conversation

@Tyagiquamar

@Tyagiquamar Tyagiquamar commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Coalesce concurrent checkBalance() RPC reads in BalanceMonitor (src/balance.ts) and SolanaBalanceMonitor (src/solana-balance.ts) using singleflight deduplication, and guard cache writes with an invalidation epoch so superseded in-flight reads cannot overwrite newer state.

Root Cause & Problem

  1. When the 30s balance cache is cold, expired, or zero, every concurrent checkBalance() / checkSufficient() call fires its own independent RPC request (readContract on Base, /v1/balance on Arc, or getTokenAccountsByOwner with up to 3 retries on Solana). Under concurrent traffic or after the proxy's 2.5s optimistic balance-check timeout leaves a background RPC in flight, subsequent requests stampede the RPC endpoint and trigger rate limits (especially 429s on public Solana RPC).
  2. Calling invalidate() (for example after a payment failure) while an RPC read is already in flight could allow the older read to populate cachedBalance once it resolved.
  3. cachedAt was captured before await this.fetchBalance() rather than when the RPC response arrived, and a 0n result did not clear cachedBalance.

Technical Solution

  • Added inflightFetch to both BalanceMonitor and SolanaBalanceMonitor so concurrent checkBalance() calls share a single in-flight fetchBalance() promise and clean it up in .finally() (allowing subsequent checks to retry after errors or zero balances).
  • Added a cacheEpoch counter incremented by invalidate(). invalidate() clears inflightFetch and ensures any pre-invalidation in-flight read neither overwrites cachedBalance/cachedAt nor clears a newer inflightFetch.
  • Recorded cachedAt = Date.now() upon RPC completion and explicitly cleared cachedBalance/cachedAt when the fetched balance is 0n.
  • Added regression tests in src/balance.arc.test.ts and src/solana-balance.test.ts covering concurrent coalescing, error recovery, and mid-flight invalidate() epoch isolation.

Test Plan

  • npx vitest run src/balance.arc.test.ts src/solana-balance.test.ts src/proxy.balance-check-latency.test.ts src/proxy.health-balance-timeout.test.ts -> 4 test files passed, 15 tests passed (11 in src/balance.arc.test.ts, 2 in src/solana-balance.test.ts, 1 in src/proxy.balance-check-latency.test.ts, 1 in src/proxy.health-balance-timeout.test.ts).
  • npm run typecheck (tsc --noEmit) -> passed (exit code 0).
  • npm run lint (eslint src/ scripts/) -> passed (exit code 0).
  • npx prettier --check src/balance.ts src/solana-balance.ts src/balance.arc.test.ts src/solana-balance.test.ts -> passed (all matched files use Prettier code style).

Summary by CodeRabbit

  • Bug Fixes
    • Balance checks now handle overlapping requests more consistently, avoiding redundant reads when multiple checks run at once.
    • After a balance is refreshed, a slower earlier request can no longer replace the newer result.
    • Failed reads can be retried by a later balance check.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Both balance monitors now share concurrent reads and use an epoch to prevent reads started before invalidation from replacing newer cached results. Tests cover read sharing, retry after failure, and invalidation behavior.

Changes: Balance read coordination

Layer / File(s) Summary
BalanceMonitor read and invalidation
src/balance.ts, src/balance.arc.test.ts
checkBalance() reuses a pending read. Cache updates apply only when the read’s epoch is current. Tests cover concurrent callers, failed-read retry, and late results after invalidation.
Solana balance read and invalidation
src/solana-balance.ts, src/solana-balance.test.ts
checkBalance() reuses a pending RPC read. Cache updates apply only when the read’s epoch is current. Tests cover concurrent callers and late results after invalidation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

  • BlockRunAI/ClawRouter#527: Adds Arc balance fetching to BalanceMonitor, whose fetchBalance() call is now covered by the shared-read and epoch logic.

Suggested reviewers: 1bcmax, tenequm, vickyxai

Merge Risk: Minimal · up to 98a05

This change shares concurrent balance reads and stops reads started before an invalidation from overwriting newer cached balances. No concrete merge-blocking risk was found, and the change is easy to revert.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title follows the conventional commit format and names the main change: concurrent checkBalance RPC reads are coalesced, and invalidation is made epoch-safe. The raw summary confirms both behavior…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title follows the conventional commit format and names the main change: concurrent checkBalance RPC reads are coalesced, and invalidation is made epoch-safe. The raw summary confirms both behaviors in src/balance.ts and src/solana-balance.ts, with matching tests. The title is specific and accurate, and it is a single sentence. It is long at 85 characters, but it stays readable.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b7f6b4b and 98a050c.

Files selected for processing: 4

  • src/balance.arc.test.ts
  • src/balance.ts
  • src/solana-balance.test.ts
  • src/solana-balance.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

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