Skip to content

fix(router): invoke toToken.address.toLowerCase() in per-pair cache key#446

Merged
thedavidmeister merged 4 commits into
masterfrom
2026-06-15-router-cache-key-fix
Jun 16, 2026
Merged

fix(router): invoke toToken.address.toLowerCase() in per-pair cache key#446
thedavidmeister merged 4 commits into
masterfrom
2026-06-15-router-cache-key-fix

Conversation

@thedavidmeister

Copy link
Copy Markdown
Contributor

What

The per-pair throttle-cache key read toToken.address.toLowerCase without the call parens in all four RainSolverRouter query methods (getMarketPrice, tryQuote, findBestRoute, getTradeParams) and in the coupled reader prepareRouter (src/core/process/round.ts:109).

A method reference stringifies to its source code, so the key's second segment became the constant function toLowerCase() { [native code] } for every token — the key depended only on fromToken and collided across all toTokens.

BUGGY key = "0xfrom..-function toLowerCase() { [native code] }"   // same for every toToken
FIXED key = "0xfrom..-0xto.."                                     // distinct per toToken

Impact (real bug, latent)

RainSolverRouter.cache is a prefetch-throttle counter, not a result cache — the query methods always run a live Promise.all and return live results, so the collision never returned a stale route/quote/price. But the counter gates prepareRouter (skip pool-data prefetch once a pair's counter > 3). With the key collapsed to the sell token only:

  • Cross-pair contamination: unrelated pairs sharing a sell token share one counter, so pair (X, Z) can push the gate past its skip threshold and cause (X, Y) to skip prefetch even though it was never warmed.
  • Throttle saturates ~2x too fast: prepareRouter's (sell→buy) and (sell→native) calls collapse to the same key, double-incrementing the sell-token counter per round.

Mitigated (not catastrophic) by the newPoolCreated force-prefetch branch and the separately, correctly keyed route caches — but genuinely incorrect cross-pair behavior. Full diagnosis + probe in #445.

Fix

Add the missing () at all four router.ts sites and the coupled round.ts:109 reader (fixing only the writer would break the gate, since the reader key would stop matching the writer key).

Tests (mutation-validated)

  • src/router/router.test.ts — for each of the four methods: one fromToken + two different toTokens yields two distinct cache entries (cache.size === 2, exact keys asserted). Collides to size 1 (FAILS) under the missing-() mutation.
  • src/core/process/round.test.ts — a pair pre-warmed under the correctly-keyed counter skips prefetch; a different buyToken (same sellToken) still prefetches. FAILS under the round.ts missing-() mutation (prefetch wrongly runs).

Verified each new test passes with the fix and fails when the () is reverted at the corresponding site. tsc + eslint clean; full vitest unit suite green (the lone transport.test.ts flake is an environmental EADDRINUSE :9292 port clash, passes in isolation; e2e-fork is pre-existing/environmental).

Note: #443 also added tests to src/router/router.test.ts; trivial rebase if it lands first.

Closes #445

🤖 Generated with Claude Code

The per-pair throttle-cache key read `toToken.address.toLowerCase`
without the call parens in all four RainSolverRouter query methods
(getMarketPrice/tryQuote/findBestRoute/getTradeParams) and in the
coupled reader at prepareRouter (round.ts). A method reference
stringifies to its source, so the key's second segment collapsed to the
constant `function toLowerCase() { [native code] }`, making the key
depend only on fromToken and collide across every toToken.

The cache is a prefetch-throttle counter (not a result cache), so the
collision never returned a stale route/quote/price, but it corrupted the
prefetch gate: pairs sharing a sell token shared one counter, so an
unrelated pair could push the gate past its skip threshold (and the
counter saturated ~2x too fast). Fixing only the writer would break the
gate, so the round.ts reader is fixed in lockstep.

Adds mutation-validated tests: distinct toTokens now yield distinct
cache entries, and a warmed pair skips prefetch via the correctly-keyed
counter. Both fail under the missing-`()` mutation.

Closes #445

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@thedavidmeister thedavidmeister self-assigned this Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@thedavidmeister, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 51 minutes and 51 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 04f12b5c-b4ba-4436-a782-df645b645a30

📥 Commits

Reviewing files that changed from the base of the PR and between 08492e8 and 80cf804.

📒 Files selected for processing (2)
  • src/core/process/round.test.ts
  • src/router/router.test.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 2026-06-15-router-cache-key-fix

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

Comment @coderabbitai help to get the list of available commands and usage tips.

State what the per-pair cache key construction does now (the key includes
the lowercased toToken/buyToken address, distinct per token) rather than
narrating the missing-`()` mutation, the old bug, or before/after framing.
Comment-only; no code or logic changes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Resolve conflict in src/router/router.ts getMarketPrice: keep master's
`{ price: string; route?: MultiRoute }` return type and layer #446's
`toToken.address.toLowerCase()` (invoked) onto the per-pair cache key.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Resolve router.test.ts conflict: keep all three describe blocks
(per-pair cache key, cache mechanism, getError classification) and
correct stale comments to describe the current per-pair cache-key
behavior. Production fix already landed on master via #443, so this
branch now contributes tests and doc comments only.

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

Copy link
Copy Markdown
Contributor Author

Reviewed 80cf804: approved by maintainer; conflict resolved via merge of master (production fix already in master via #443 — this contributes the mutation-validated per-pair cache-key tests + corrected doc comments). build, unit tests, git-clean, CodeRabbit all green; the only reds are the e2e-fork suite, which is environmental (fails identically on master). Merging.

@thedavidmeister thedavidmeister merged commit 8b255c9 into master Jun 16, 2026
5 of 13 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

@coderabbitai assess this PR size classification for the totality of the PR with the following criterias and report it in your comment:

S/M/L PR Classification Guidelines:

This guide helps classify merged pull requests by effort and complexity rather than just line count. The goal is to assess the difficulty and scope of changes after they have been completed.

Small (S)

Characteristics:

  • Simple bug fixes, typos, or minor refactoring
  • Single-purpose changes affecting 1-2 files
  • Documentation updates
  • Configuration tweaks
  • Changes that require minimal context to review

Review Effort: Would have taken 5-10 minutes

Examples:

  • Fix typo in variable name
  • Update README with new instructions
  • Adjust configuration values
  • Simple one-line bug fixes
  • Import statement cleanup

Medium (M)

Characteristics:

  • Feature additions or enhancements
  • Refactoring that touches multiple files but maintains existing behavior
  • Breaking changes with backward compatibility
  • Changes requiring some domain knowledge to review

Review Effort: Would have taken 15-30 minutes

Examples:

  • Add new feature or component
  • Refactor common utility functions
  • Update dependencies with minor breaking changes
  • Add new component with tests
  • Performance optimizations
  • More complex bug fixes

Large (L)

Characteristics:

  • Major feature implementations
  • Breaking changes or API redesigns
  • Complex refactoring across multiple modules
  • New architectural patterns or significant design changes
  • Changes requiring deep context and multiple review rounds

Review Effort: Would have taken 45+ minutes

Examples:

  • Complete new feature with frontend/backend changes
  • Protocol upgrades or breaking changes
  • Major architectural refactoring
  • Framework or technology upgrades

Additional Factors to Consider

When deciding between sizes, also consider:

  • Test coverage impact: More comprehensive test changes lean toward larger classification
  • Risk level: Changes to critical systems bump up a size category
  • Team familiarity: Novel patterns or technologies increase complexity

Notes:

  • the assessment must be for the totality of the PR, that means comparing the base branch to the last commit of the PR
  • the assessment output must be exactly one of: S, M or L (single-line comment) in format of: SIZE={S/M/L}
  • do not include any additional text, only the size classification
  • your assessment comment must not include tips or additional sections
  • do NOT tag me or anyone else on your comment

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.

Router per-pair cache key drops toToken: toToken.address.toLowerCase missing () (cross-pair throttle collision)

1 participant