Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DRAFT] Fix concurrency issue #1591 #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

mintobit
Copy link

@mintobit mintobit commented Mar 23, 2025

Fixes DiceDB/dice#1591

The source of the issue is absence of synchronization when Client is writing to and reading from TCP connection.

Need your feedback, to make sure you are ok with the approach I took:

  • Use fixed 4 byte header for each message (wire.Command/wire.Response)
  • Add correlation_id to each command/response to match them
  • On Client side, read responses from net.Conn in a loop
  • Put responses in corresponding channel (map[corr_id] = chan *Response)
  • Each Client.Fire() reads from a corresponding channel

Here are the links to all of the PRs (this fix requires changes to multiple repositories):
dicedb-go PR
dice PR
dicedb-protos PR

  • Communicate with maintainers on the overall approach
  • Make code production-ready (error handling etc)

Before this change:
before
After this change:
after

Summary by CodeRabbit

  • New Features

    • Enhanced asynchronous command processing with improved cancellation and timeout support for smoother client interactions.
  • Refactor

    • Streamlined message handling with robust validation and error reporting to ensure reliable communication and improved overall performance.

Copy link

coderabbitai bot commented Apr 1, 2025

Walkthrough

The changes refactor the I/O handling in the messaging layer and improve client concurrency management. In ironhawk/io.go, the Read and Write functions now explicitly handle message headers, validate message sizes, and streamline data processing. In main.go, a new context management system is integrated into the Client struct with added mutexes and a pending map for asynchronous response handling. Additionally, the fire method is updated to return a response with timeout error handling, and the Close method now cancels the context for proper termination.

Changes

File Change Summary
ironhawk/io.go Refactored Read to process a header for message size, enforce size limits, and read data into a single buffer. Updated Write to rename the parameter to cmd and include the header in the message buffer.
main.go Added context management (cancel field) and new fields (mutexes and pending map) to the Client struct. Introduced readLoop for processing responses asynchronously, and modified fire (now returning a response) and Close to support proper cancellation and concurrency control.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FireMethod as fire()
    participant Connection
    participant ReadLoop as async readLoop()
    
    Client->>FireMethod: Invoke fire(cmd)
    FireMethod->>Connection: Write command (header + data)
    Connection-->>ReadLoop: Receive response message
    ReadLoop->>PendingMap: Lookup pending channel by command ID
    ReadLoop->>FireMethod: Dispatch response via channel
    FireMethod->>Client: Return response or timeout error
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent race conditions for concurrent queries (#1591)

Poem

I'm a hopped-up rabbit, coding with delight,
Refactoring headers and contexts day and night.
With mutexes and maps, my commands now align,
Async responses flutter in perfect design.
Leaping through changes, my code's light and bright!

✨ 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 plan to trigger planning for file edits and PR creation.
  • @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

@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)
main.go (2)

83-109: Dedicated readLoop for continuously processing responses

  1. Using a select with <-ctx.Done() ensures the loop terminates cleanly when the client is closed.
  2. Locking around the pending map prevents concurrency issues while removing or retrieving the response channel.
  3. panic("no id response received") might be too abrupt for production, but it does surface protocol violations quickly for debugging.
-				panic("no id response received")
+				// consider returning an error or logging the issue instead
+				fmt.Printf("WARN: response received with no matching request: %v\n", resp)

111-141: Refined fire method for sending commands

  1. Generating a unique correlation ID with uuid.New() ensures each request has a distinct channel for handling responses.
  2. The connWriteMu lock around ironhawk.Write() effectively prevents concurrent writes from interleaving, solving concurrency problems on the TCP stream.
  3. The 10-second timeout in the select block is important for preventing indefinite hangs if a response never arrives, but consider making it configurable.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f5c680 and 444855a.

📒 Files selected for processing (2)
  • ironhawk/io.go (1 hunks)
  • main.go (5 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
ironhawk/io.go (1)
wire/cmd.pb.go (6)
  • Response (77-94)
  • Response (107-107)
  • Response (122-124)
  • Command (24-31)
  • Command (44-44)
  • Command (59-61)
🔇 Additional comments (10)
ironhawk/io.go (4)

4-9: Proper import additions for reading/writing protocol headers
The newly introduced imports "encoding/binary", "io", and "net" align well with the new header-based protocol approach. This is a clean, direct way to manage binary-encoded message sizes in a TCP context.


13-14: Validate the maximum message size
Defining maxMessageSize = 32 * 1024 * 1024 and headerSize = 4 helps guard against excessively large payloads and ensures enough bytes are reserved for the header.


18-41: Robust ‘Read’ function with size checks

  1. Reading a fixed-size header, followed by a bounded payload governed by messageSize, is a safe way to handle untrusted input.
  2. The check for zero-length messages and the upper bound limit help mitigate potential buffer overflows or denial-of-service vectors.
  3. Returning a descriptive error in each failure case simplifies troubleshooting.

Overall, this code addresses potential concurrency concerns by cleanly separating read operations and providing explicit error results.


44-60: Efficient ‘Write’ function design

  1. Constructing a unified buffer of [header + message] is a straightforward way to keep the protocol consistent.
  2. The calls to binary.BigEndian.PutUint32 and copy are idiomatic.
  3. Proper error propagation from conn.Write(messageBuffer) ensures robust handling of I/O failures.

This approach nicely complements the new read logic, simplifying debugging and providing a consistent message format.

main.go (6)

4-4: Context import
Adding "context" makes it possible to coordinate cancellation and timeouts for the client’s networking activities, enhancing concurrency safety.


21-29: New fields for concurrency control and response tracking

  1. cancel context.CancelFunc, connWriteMu sync.Mutex, and pendingMu sync.Mutex provide critical scaffolding to avoid data races.
  2. The pending map, keyed by uuid.UUID, is an effective way to match each command to its async response channel.

59-62: Initialize pending map and store it in the client
This ensures every Client instance can manage request-response channels without requiring global structures or external caches, thus simplifying concurrency.


69-70: Context creation and cancel assignment
Obtaining a cancellable context for the Client is a clean design choice. It allows the client to gracefully close ongoing operations.


72-78: Kick off readLoop after handshake attempt
Starting the reading goroutine (go client.readLoop(ctx)) early helps ensure that messages arriving soon after the handshake are handled properly. This approach reduces race conditions between initial writes and reads.


245-246: Clean client teardown via c.cancel()
Invoking cancel() ensures that all goroutines listening on ctx.Done() can exit gracefully and promptly, avoiding resource leaks. This is a solid best practice for concurrency.

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.

Bug: Concurrent queries over the same connection
2 participants