Skip to content

Conversation

@iuwqyir
Copy link
Contributor

@iuwqyir iuwqyir commented Jun 3, 2025

TL;DR

Added thread safety to ABI parsing to prevent concurrent map write panics.

What changed?

  • Added a mutex to protect JSON decoding in the GetABIForContract function
  • Modified the ABI parsing process to first read the entire response body and then parse it
  • Added proper error logging when ABI parsing fails
  • Improved error handling with more specific error messages

How to test?

  1. Run the indexer with high concurrency settings
  2. Verify that no concurrent map write panics occur during ABI parsing
  3. Check logs for proper error messages when ABI parsing fails

Why make this change?

The abi.JSON function internally uses maps that are not thread-safe. When multiple goroutines call this function concurrently, it can lead to "concurrent map writes" panics. This change adds a mutex to synchronize access to the JSON decoding process, preventing these race conditions while maintaining the ability to process requests concurrently.

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability and thread safety when fetching and parsing contract ABI data.
    • Enhanced error handling and logging for ABI parsing failures.

@coderabbitai
Copy link

coderabbitai bot commented Jun 3, 2025

Walkthrough

The GetABIForContract function in internal/common/abi.go is updated to read the entire ABI JSON response body into memory before parsing. A mutex is introduced to serialize JSON decoding for thread safety, and improved error logging is added for parsing failures. No changes are made to function signatures.

Changes

File(s) Change Summary
internal/common/abi.go Refactored GetABIForContract to read response body fully, added mutex for JSON decode, improved error logging.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant GetABIForContract
    participant HTTPServer

    Caller->>GetABIForContract: Call with (chainId, contract)
    GetABIForContract->>HTTPServer: Request ABI JSON
    HTTPServer-->>GetABIForContract: Respond with JSON body
    GetABIForContract->>GetABIForContract: Read full response body
    GetABIForContract->>GetABIForContract: Lock mutex for JSON decode
    GetABIForContract->>GetABIForContract: Decode ABI JSON
    GetABIForContract->>GetABIForContract: Unlock mutex
    GetABIForContract-->>Caller: Return parsed ABI or error
Loading

Possibly related PRs

Suggested reviewers

  • catalyst17
  • AmineAfia
  • nischitpra
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

Copy link
Contributor Author

iuwqyir commented Jun 3, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@iuwqyir iuwqyir marked this pull request as ready for review June 3, 2025 16:10
Copy link

@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: 0

🧹 Nitpick comments (2)
internal/common/abi.go (2)

21-21: Consider the performance implications of the global mutex.

While the mutex addresses the thread safety issue with abi.JSON, using a global mutex will serialize ALL JSON decoding operations across the entire application, potentially creating a significant bottleneck under high concurrency.

Consider these alternatives:

  1. Use a more granular locking mechanism (e.g., per-contract or per-chain mutex pool)
  2. Investigate if the abi.JSON function can be made thread-safe internally
  3. Use a worker pool pattern to limit concurrent ABI parsing operations
-	jsonDecodeMutex sync.Mutex
+	// Consider using a sync.Map or mutex pool for more granular locking
+	abiParseMutexes sync.Map // map[string]*sync.Mutex for per-contract locking

83-88: Optimize string conversion and enhance error context.

The current implementation has a minor performance issue with unnecessary string conversion and could benefit from more detailed error context.

Apply this optimization to avoid string conversion overhead:

-	// Parse the ABI
-	parsedABI, err := abi.JSON(strings.NewReader(string(body)))
+	// Parse the ABI  
+	parsedABI, err := abi.JSON(bytes.NewReader(body))

Also add the bytes import:

+	"bytes"
	"fmt"

The enhanced error logging with contract and chain ID context is excellent for debugging.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c3e03d and d21df05.

📒 Files selected for processing (1)
  • internal/common/abi.go (3 hunks)
🔇 Additional comments (3)
internal/common/abi.go (3)

5-5: LGTM: Required imports added correctly.

The new imports for io and log are necessary for the enhanced functionality.

Also applies to: 15-15


72-76: Good approach to read the entire response body.

Reading the entire response body before parsing improves stability and aligns with the goal of avoiding concurrent map write issues during streaming JSON decoding.


78-80: Mutex protection addresses the core thread safety issue.

The mutex successfully serializes access to the abi.JSON function, preventing the concurrent map write panics mentioned in the PR objectives.

@iuwqyir iuwqyir merged commit 856a78e into main Jun 3, 2025
6 checks passed
@iuwqyir iuwqyir deleted the 06-03-improve_abi_parsing branch June 3, 2025 16:16
iuwqyir added a commit that referenced this pull request Jun 3, 2025
This reverts commit 856a78e, reversing
changes made to 3c3e03d.
iuwqyir added a commit that referenced this pull request Jun 3, 2025
# Simplify ABI Parsing Logic

Refactors the contract ABI fetching logic in `GetABIForContract` by:
- Removing the unnecessary step of reading the entire response body into memory
- Parsing the ABI directly from the response body stream
- Eliminating the JSON decode mutex that's no longer needed
- Removing unused imports (`io` and `log`)

This change makes the code more efficient by avoiding an extra memory allocation and simplifying the error handling path.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

- **Refactor**
  - Improved the process for retrieving and parsing contract ABIs, resulting in a more efficient and streamlined experience when interacting with contract data.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

3 participants