Skip to content

Conversation

@mkysel
Copy link
Collaborator

@mkysel mkysel commented Apr 23, 2025

Implement concurrent transaction handling with 50-transaction limit in stress test system

The stress testing system has been updated with concurrent transaction processing and analytics tracking. Key changes include:

  • Implemented semaphore-based concurrency control in stress.go limiting parallel transactions to 50
  • Added atomic counter-based nonce management and transaction result tracking in stress.go
  • Updated CastSendCommand.Nonce field type to *uint64 in cast.go for Ethereum compatibility
  • Configured duration encoding for logging in log.go

📍Where to Start

Start with the concurrent transaction handling changes in stress.go, which contains the core modifications to the stress testing system including the semaphore implementation and transaction flow updates.


Macroscope summarized 5f4853c.

Summary by CodeRabbit

  • Refactor

    • Improved concurrency control and nonce management for stress testing, allowing up to 50 simultaneous transactions and more accurate performance analytics.
    • Enhanced logging output with better duration formatting and clearer nonce representation.
  • Style

    • Updated internal type consistency for nonce values to improve reliability and maintainability.

@mkysel mkysel requested a review from a team as a code owner April 23, 2025 18:02
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 23, 2025

Warning

Rate limit exceeded

@mkysel has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 3 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5f4853c and ec22f66.

📒 Files selected for processing (1)
  • pkg/stress/stress.go (3 hunks)

Walkthrough

The changes update the nonce handling in the stress testing code by changing the nonce type from int to uint64 for better type consistency and safety. The StressIdentityUpdates function is refactored to use an atomic counter and a semaphore for concurrent transaction execution, allowing up to 50 simultaneous transactions. Logging is improved with enhanced duration encoding and more precise nonce logging. The logger configuration is also updated to specify how durations are encoded in log output.

Changes

File(s) Change Summary
pkg/stress/cast.go Changed the Nonce field in the CastSendCommand struct from *int to *uint64.
pkg/stress/stress.go Refactored StressIdentityUpdates to use atomic nonce management and semaphore-based concurrency; changed getCurrentNonce return type from int to uint64; improved logging and removed sleep-based throttling.
pkg/utils/log.go Added EncodeDuration with zapcore.StringDurationEncoder to logger's EncoderConfig.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant StressIdentityUpdates
    participant Goroutine
    participant Logger

    Caller->>StressIdentityUpdates: Call with parameters
    StressIdentityUpdates->>StressIdentityUpdates: Initialize atomic nonceCounter and semaphore
    loop n times
        StressIdentityUpdates->>Goroutine: Launch goroutine (acquire semaphore)
        Goroutine->>StressIdentityUpdates: Atomically increment nonceCounter
        Goroutine->>Logger: Log transaction start
        Goroutine->>Goroutine: Execute transaction
        Goroutine->>Logger: Log transaction result and duration
        Goroutine->>Goroutine: Release semaphore
    end
    StressIdentityUpdates->>StressIdentityUpdates: Wait for all goroutines
    StressIdentityUpdates->>Logger: Log aggregate analytics
    StressIdentityUpdates-->>Caller: Return
Loading

Possibly related PRs


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
🪧 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 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

@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 (1)
pkg/stress/stress.go (1)

85-89: Consider aggregating errors for caller awareness

While errors are correctly logged for individual transactions, the function always returns nil regardless of how many transactions failed. Consider adding an error return that indicates if the stress test encountered a significant number of failures.

 func StressIdentityUpdates(
 	ctx context.Context,
 	logger *zap.Logger,
 	n int,
 	contractAddress, rpc, privateKey string,
-) error {
+) (int, error) {
     // ... existing code ...
     
     logger.Info("Stress Test Summary",
 		zap.Int("total_transactions", n),
 		zap.Int("successful_transactions", successCount),
 		zap.Duration("total_duration", totalDuration),
 		zap.Duration("average_duration", avgDuration),
 	)
 
-	return nil
+	// Return the number of failed transactions so caller can determine success
+	failedCount := n - successCount
+	if failedCount > 0 {
+		return failedCount, fmt.Errorf("%d of %d transactions failed", failedCount, n)
+	}
+	return 0, nil
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22ff64a and 5f4853c.

📒 Files selected for processing (3)
  • pkg/stress/cast.go (1 hunks)
  • pkg/stress/stress.go (3 hunks)
  • pkg/utils/log.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/stress/stress.go (1)
pkg/stress/cast.go (1)
  • CastSendCommand (12-19)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (Node)
🔇 Additional comments (8)
pkg/utils/log.go (1)

24-31: Great addition of EncodeDuration configuration!

Adding the EncodeDuration: zapcore.StringDurationEncoder field to the encoder config ensures that durations will be formatted as human-readable strings in the logs. This complements the duration logging added in the stress testing code and improves readability of performance metrics.

pkg/stress/cast.go (1)

18-18: Good type change for nonce field

Changing the Nonce field type from *int to *uint64 is a good practice since:

  1. Ethereum nonces are non-negative values that can grow large
  2. This matches the type used in the updated stress testing logic
  3. It provides better type safety by preventing negative values

This change aligns well with the concurrent nonce handling implemented in the stress code.

pkg/stress/stress.go (6)

32-40: Well-structured result tracking implementation

The Result struct is a good design choice for tracking metrics. It captures all relevant transaction data (index, nonce, success status, and duration) which enables the detailed analytics reporting added at the end of the function.


41-41: Effective concurrency management with semaphore

Using a semaphore channel with 50 slots is an excellent approach to limit concurrent transactions. This prevents overwhelming the node with too many simultaneous requests while still achieving high throughput.


48-50: Thread-safe nonce management

Using an atomic counter for nonce management is the correct approach for concurrent execution. This ensures each transaction gets a unique, sequential nonce without race conditions.


51-91: Solid implementation of concurrent transaction execution

The implementation correctly:

  1. Launches each transaction in its own goroutine
  2. Uses the semaphore pattern to limit concurrency
  3. Safely increments the nonce counter with atomic operations
  4. Protects shared state (results slice) with a mutex
  5. Includes proper timing and logging

This is a significant improvement over sequential execution for stress testing.


95-111: Excellent analytics reporting

The aggregation and reporting of test metrics is thorough and well-structured. Calculating and logging total transactions, success rate, total duration, and average duration provides valuable insights into the stress test performance.


116-116: Good type consistency improvement

Changing the return type of getCurrentNonce from int to uint64 improves type consistency and safety throughout the codebase. This aligns properly with Ethereum's use of nonces as unsigned integers.

@macroscopeapp
Copy link

macroscopeapp bot commented Apr 23, 2025

Implement concurrency limiting and analytics tracking in stress test with 50 concurrent operation cap

  • Adds concurrency control using a semaphore in stress.go to limit concurrent operations to 50
  • Implements atomic nonce management with uint64 type in cast.go
  • Adds transaction result tracking and timing measurements in stress.go
  • Configures duration encoding for log output in log.go

📍Where to Start

Start with the concurrency and nonce management changes in stress.go, which contains the core stress testing logic and the new semaphore implementation.


Macroscope summarized ec22f66.

@mkysel mkysel merged commit 414e324 into main Apr 23, 2025
7 of 8 checks passed
@mkysel mkysel deleted the mkysel/stress-better branch April 23, 2025 19:27
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