Skip to content

Conversation

@mkysel
Copy link
Collaborator

@mkysel mkysel commented Mar 12, 2025

When hammering our alchemy node in testnet, I noticed a bunch of issues that weren't seen in the local test development.

  1. "nonce too high" - it usually indicates that the mempool is too full.
  • gracefully hide the error from the caller if it does get hit
  • prevent it from happening as often by limiting the concurrent number of transactions in flight
  1. Nonce too low - nonce jumps #624
  • Added a few tests that are useful, but dont fix 624
  1. drive-by fix of TestAddRates

Otherwise HA payer works perfectly.

Closes #423

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Introduced a delay mechanism that gracefully handles transient operational issues, contributing to smoother transaction processing.
    • Enhanced concurrent request management to improve performance and stability during simultaneous operations.
  • Tests
    • Added new tests to verify the resilience and robustness of concurrent operations under load.
    • Improved error handling in tests to manage transient failures more effectively, including a retry mechanism for certain operations.

@mkysel mkysel requested a review from a team as a code owner March 12, 2025 18:48
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 12, 2025

Walkthrough

The pull request introduces a new error handling case in the blockchain publisher to manage "nonce too high" errors with a backoff mechanism using a random sleep. It also implements an OpenConnectionsLimiter in the nonce manager to control concurrent requests through a semaphore and wait group. Additionally, it adds two tests for concurrent nonce deletion scenarios in the database sequences test file and enhances the rates admin tests with a retry mechanism for transient errors.

Changes

Files Change Summary
pkg/blockchain/blockchainPublisher.go Introduced a backoff mechanism in withNonce for "nonce too high" errors, logging the event and calling RandomSleep. Added import for utils.
pkg/blockchain/nonceManager.go Added OpenConnectionsLimiter type to manage concurrency, updated SQLBackedNonceManager to use this limiter, and modified GetNonce, fillNonces, and abandonNonces methods for concurrency control.
pkg/db/sequences_test.go Introduced TestAbandonConcurrently and TestAbandonConcurrentlyWithOpenTransaction to test concurrent nonce deletions with and without an active transaction.
pkg/blockchain/ratesAdmin_test.go Updated TestAddRates to implement a retry mechanism for the AddRates method, allowing for handling transient errors more effectively.
pkg/utils/sleep.go Modified RandomSleep to accept context.Context and time.Duration, enhancing responsiveness to cancellation and checking for valid duration.

Sequence Diagram(s)

sequenceDiagram
    participant WithNonce as withNonce
    participant Logger
    participant Sleeper as RandomSleep
    WithNonce->>Logger: Log "nonce too high, backing off"
    WithNonce->>Sleeper: Call RandomSleep(500ms)
    Note right of WithNonce: Delay execution before retrying
Loading
sequenceDiagram
    participant Client
    participant SQLManager as SQLBackedNonceManager
    participant Limiter as OpenConnectionsLimiter
    Client->>SQLManager: Request nonce (GetNonce)
    SQLManager->>Limiter: Acquire semaphore & add to wait group
    Note right of Limiter: Concurrency is limited as per configuration
    Client->>SQLManager: Complete operation (Cancel/Consume)
    Limiter-->>SQLManager: Release semaphore & mark wait group done
Loading

Possibly related PRs

Suggested reviewers

  • fbac

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6f49fdd and 787f948.

📒 Files selected for processing (2)
  • pkg/blockchain/blockchainPublisher.go (2 hunks)
  • pkg/utils/sleep.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd-cli)
  • GitHub Check: Build pre-baked anvil-xmtpd
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
🔇 Additional comments (4)
pkg/blockchain/blockchainPublisher.go (2)

9-9: LGTM: Required import for RandomSleep usage

The utils package import is correctly added to support the new error handling for "nonce too high" errors.


270-284: Good addition of backoff mechanism for "nonce too high" errors

This change effectively addresses one of the main PR objectives by implementing a backoff mechanism when encountering "nonce too high" errors. The random sleep helps prevent overwhelming the blockchain with too many concurrent transactions.

A few observations:

  • The debug logging provides good visibility into the backoff behavior
  • Canceling the nonce context and continuing the loop allows for a fresh attempt
  • Using RandomSleep with context awareness ensures the sleep can be interrupted if needed
pkg/utils/sleep.go (2)

3-7: LGTM: Added context import for enhanced RandomSleep

The context import is correctly added to support the improved RandomSleep implementation.


9-20: Improved RandomSleep with context awareness and better duration handling

The RandomSleep function has been significantly improved:

  1. Now accepts a context.Context for cancellation support
  2. Uses idiomatic time.Duration instead of raw milliseconds
  3. Validates the input duration to avoid negative or zero sleeps
  4. Properly handles context cancellation via select statement

These changes enhance the robustness of the function while making it more responsive to cancellation signals, which is especially important in the context of blockchain transactions that may need to be aborted.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mkysel mkysel added the service/gateway Items related to the gateway service label Mar 12, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
pkg/blockchain/blockchainPublisher.go (3)

10-10: Consider random seeding.

By default, the global random generator always produces the same sequence of pseudo-random values unless seeded. Confirm whether this is desired or if rand.Seed(time.Now().UnixNano()) should be called at an appropriate entry point.


231-237: Ensure cancellation handling.

randomSleep blocks until the sleep duration completes, which may conflict with context cancellations. Consider passing in the context to exit early if the operation should be canceled:

-func randomSleep(maxDuration time.Duration) {
+func randomSleep(ctx context.Context, maxDuration time.Duration) {
    ...
+   select {
+   case <-time.After(randDuration):
+   case <-ctx.Done():
+       return
+   }
}

278-292: Add metrics or logs for repeated backoffs.

When “nonce too high” appears frequently, it can indicate a backlog or node-side issue. Logging or metering the frequency of this path can help detect systemic errors.

pkg/blockchain/nonceManager.go (2)

23-28: Clear concurrency manager approach.

Adding optional metrics for the number of in-flight requests, average wait time, and maximum concurrency usage can provide helpful visibility into how the manager is performing.


91-92: Avoid dual decrement of wait group.

Both Cancel and Consume call wg.Done(). Consider a single finalizer approach if there’s any scenario where both might be invoked, to avoid double wg.Done().

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 42cbc62 and 68aa066.

📒 Files selected for processing (3)
  • pkg/blockchain/blockchainPublisher.go (3 hunks)
  • pkg/blockchain/nonceManager.go (4 hunks)
  • pkg/db/sequences_test.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd-cli)
  • GitHub Check: Push Docker Images to GitHub Packages (xmtpd)
  • GitHub Check: Build pre-baked anvil-xmtpd
🔇 Additional comments (9)
pkg/db/sequences_test.go (2)

386-419: Solid concurrency validation.

Concurrent deletions are well-handled using a wait group and atomic integer. The final assertion correctly confirms the total deletions.


421-465: Good test coverage with uncommitted transactions.

Providing an open transaction while concurrently deleting ensures the system behaves correctly under partial locks. The final count of 199 demonstrates that exactly one nonce was withheld by the open transaction.

pkg/blockchain/nonceManager.go (7)

9-9: No issues with the import.


30-33: Meaningful concurrency limits.

Defining these constants in a single location simplifies adjusting concurrency bounds and clarifies intent.


46-48: Initialization logic is consistent.

The SQLBackedNonceManager always obtains a RequestManager, maintaining concurrency limits consistently.


106-106: Unambiguous function signature.

Eliminating named returns enhances clarity and reduces confusion about return paths.


114-114: Consistent simplified signature.

Matches the updated style in fillNonces for more uniform code.


34-43:

Details

❓ Verification inconclusive

Edge case check for zero or negative concurrency.

While the code caps values above MaxConcurrentRequests, it doesn’t handle zero or negative concurrency. Verify if such input can happen:


🏁 Script executed:

#!/bin/bash
rg "NewRequestManager("

Length of output: 112


Action Required: Verify Zero/Negative Concurrency Usage in NewRequestManager

The current implementation only limits values above MaxConcurrentRequests and does not explicitly handle cases where maxConcurrent is zero or negative. This could result in unintended behavior (e.g., creating an unbuffered channel). Please verify whether any callers might pass zero or negative values.

  • Verification Step:
    Run the following command (with the escaped parenthesis) to locate all invocations of NewRequestManager in the codebase:
    #!/bin/bash
    rg "NewRequestManager\(" -n .
  • Based on the search results, confirm if any call sites could supply zero or negative values. If they can, consider adding explicit validation (e.g., returning an error or defaulting to a minimum valid value).

86-87:

Details

❓ Verification inconclusive

Double-check symmetry in semaphore usage.

Confirm that each semaphore acquisition has exactly one corresponding release to avoid potential channel underflow or panic:


🏁 Script executed:

#!/bin/bash
rg "semaphore <- struct{}"

Length of output: 152


Below is an updated review comment. Since the original literal regex search produced an error, please run the following command manually to verify that every semaphore “send” is matched with a “receive” (ensuring symmetrical usage):

rg -F "semaphore <- struct{}" .

Double-check symmetry in semaphore usage.
Please confirm that each semaphore acquisition (i.e. every place where an empty struct is sent into the semaphore channel) is paired with a corresponding release (i.e. reading from the channel such as on lines 86–87 in pkg/blockchain/nonceManager.go) to avoid potential channel underflow or panics.

@mkysel mkysel merged commit d7399ae into main Mar 13, 2025
6 of 7 checks passed
@mkysel mkysel deleted the mkysel/more-nonces branch March 13, 2025 15:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

service/gateway Items related to the gateway service

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement a proper nonce manager

3 participants