Skip to content

[ISSUE #3517]⚡️Memory Management Fix for AtomicPtr-based Address Fields in HA Client#3518

Merged
rocketmq-rust-bot merged 1 commit intomainfrom
op-3517
Jun 24, 2025
Merged

[ISSUE #3517]⚡️Memory Management Fix for AtomicPtr-based Address Fields in HA Client#3518
rocketmq-rust-bot merged 1 commit intomainfrom
op-3517

Conversation

@mxsm
Copy link
Owner

@mxsm mxsm commented Jun 24, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #3517

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Enabled the ability to update the HA master address through the service and client interfaces.
  • Bug Fixes

    • Resolved previously unimplemented methods for updating the HA master address, ensuring proper delegation and functionality.
  • Refactor

    • Improved internal handling of the HA master address for better performance and reliability.

Copilot AI review requested due to automatic review settings June 24, 2025 13:24
@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution🎉!

💡CodeRabbit(AI) will review your code first🔥!

Note

🚨The code review suggestions from CodeRabbit are to be used as a reference only, and the PR submitter can decide whether to make changes based on their own judgment. Ultimately, the project management personnel will conduct the final code review💥.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

Walkthrough

The changes replace asynchronous locking with atomic pointer operations for managing HA master addresses in the HA client and related service layers. They implement previously missing trait methods, ensure safe memory management by freeing old pointers, and delegate address updates through the appropriate service and client structures.

Changes

File(s) Change Summary
rocketmq-store/src/ha/default_ha_client.rs Changed master_ha_address to Arc<AtomicPtr<String>>; replaced async locking with atomic pointer logic; implemented update_ha_master_address with safe memory management.
rocketmq-store/src/ha/default_ha_service.rs Implemented update_ha_master_address to delegate to the internal HA client.
rocketmq-store/src/ha/general_ha_client.rs Implemented update_ha_master_address to delegate to the correct underlying HA client or panic if unset.

Sequence Diagram(s)

sequenceDiagram
    participant Service as DefaultHAService
    participant Client as DefaultHAClient
    participant Memory as System Memory

    Service->>Client: update_ha_master_address(new_addr)
    Client->>Memory: Free old pointer (if any)
    Client->>Memory: Allocate and store new pointer
Loading
sequenceDiagram
    participant General as GeneralHAClient
    participant Default as DefaultHAClient
    participant Auto as AutoSwitchHAClient

    alt default_ha_client is set
        General->>Default: update_ha_master_address(new_addr)
    else auto_switch_ha_client is set
        General->>Auto: update_ha_master_address(new_addr)
    else no client set
        General->>General: panic("No HA service is set")
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Consistent AtomicPtr usage for master_ha_address in DefaultHAClient (#3517)
Fixed memory leak in address updates for HA addresses (#3517)
Implemented missing update_ha_master_address in HAClient for DefaultHAClient (#3517)
DefaultHAService delegates update_ha_master_address to HA client (#3517)
GeneralHAClient implements and delegates update_ha_master_address correctly (#3517)

Poem

A hop and a skip, a pointer anew,
No memory leaks, just clean skies of blue!
The HA addresses now swap with a cheer,
Delegation flows smoothly, the intent is clear.
With atomic precision, the code is now bright—
This rabbit approves: the future’s alight!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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.

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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR replaces RwLock<Option<String>> with AtomicPtr<String> for address fields in DefaultHAClient to improve memory management and implements the previously todo!() methods.

  • Implement update_ha_master_address in GeneralHAClient
  • Forward update_ha_master_address in DefaultHAService
  • Swap out lock-based fields for AtomicPtr in DefaultHAClient and handle pointer allocation/free

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
general_ha_client.rs Added conditional logic to forward update_ha_master_address
default_ha_service.rs Replaced todo!() with a forward to inner HA client’s method
default_ha_client.rs Swapped RwLock for AtomicPtr, updated initialization, getters, and setter with raw pointers
Comments suppressed due to low confidence (2)

rocketmq-store/src/ha/default_ha_client.rs:145

  • The new AtomicPtr-based getters and setters lack unit tests. Please add tests covering null-pointer behavior, address updates, and concurrent access to validate correct pointer management.
        let addr_ptr = self.master_ha_address.load(Ordering::SeqCst);

fn update_ha_master_address(&self, new_address: &str) {
todo!()
// Safely free the old pointer before storing the new one
let old_address = self.master_address.load(Ordering::SeqCst);
Copy link

Copilot AI Jun 24, 2025

Choose a reason for hiding this comment

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

Loading the old pointer and freeing it before storing the new one can introduce race conditions under concurrent access. Use swap to atomically exchange the pointer (let old_ptr = self.master_address.swap(new_ptr, Ordering::SeqCst)) and then free old_ptr.

Copilot uses AI. Check for mistakes.
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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e10afa and 8707b74.

📒 Files selected for processing (3)
  • rocketmq-store/src/ha/default_ha_client.rs (4 hunks)
  • rocketmq-store/src/ha/default_ha_service.rs (1 hunks)
  • rocketmq-store/src/ha/general_ha_client.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: auto-approve
  • GitHub Check: test
  • GitHub Check: build
🔇 Additional comments (5)
rocketmq-store/src/ha/default_ha_service.rs (1)

202-202: LGTM! Proper delegation implementation.

The implementation correctly delegates to the underlying HA client, following the same pattern as update_master_address. This completes the service layer implementation for HA master address updates.

rocketmq-store/src/ha/general_ha_client.rs (1)

84-90: LGTM! Consistent delegation pattern implementation.

The implementation correctly follows the established pattern used by update_master_address and other methods in this file. The delegation logic and error handling are appropriate and consistent.

rocketmq-store/src/ha/default_ha_client.rs (3)

66-66: LGTM! Performance improvement with atomic operations.

The change from Arc<RwLock<Option<String>>> to Arc<AtomicPtr<String>> eliminates async locking overhead and provides better performance for address management in the HA client.


123-123: LGTM! Constructor updated appropriately.

The constructor initialization is correctly updated to use AtomicPtr::default() for the new field type.


144-152: LGTM! Atomic operations implementation is correct.

The get_ha_master_address method correctly uses atomic load operations and safe pointer dereferencing to retrieve the address without async locking.

Comment on lines 684 to 696
fn update_ha_master_address(&self, new_address: &str) {
todo!()
// Safely free the old pointer before storing the new one
let old_address = self.master_address.load(Ordering::SeqCst);
if !old_address.is_null() {
unsafe {
// Convert the old pointer back into a Box to free the memory
let _ = Box::from_raw(old_address);
}
}
// Store the new address
let new_address_ptr = Box::into_raw(Box::new(new_address.to_string()));
self.master_address.store(new_address_ptr, Ordering::SeqCst);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical bug: Method is updating the wrong field!

The update_ha_master_address method is incorrectly updating self.master_address instead of self.master_ha_address. This appears to be a copy-paste error from the update_master_address method.

Apply this fix:

 fn update_ha_master_address(&self, new_address: &str) {
     // Safely free the old pointer before storing the new one
-    let old_address = self.master_address.load(Ordering::SeqCst);
+    let old_address = self.master_ha_address.load(Ordering::SeqCst);
     if !old_address.is_null() {
         unsafe {
             // Convert the old pointer back into a Box to free the memory
             let _ = Box::from_raw(old_address);
         }
     }
     // Store the new address
     let new_address_ptr = Box::into_raw(Box::new(new_address.to_string()));
-    self.master_address.store(new_address_ptr, Ordering::SeqCst);
+    self.master_ha_address.store(new_address_ptr, Ordering::SeqCst);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn update_ha_master_address(&self, new_address: &str) {
todo!()
// Safely free the old pointer before storing the new one
let old_address = self.master_address.load(Ordering::SeqCst);
if !old_address.is_null() {
unsafe {
// Convert the old pointer back into a Box to free the memory
let _ = Box::from_raw(old_address);
}
}
// Store the new address
let new_address_ptr = Box::into_raw(Box::new(new_address.to_string()));
self.master_address.store(new_address_ptr, Ordering::SeqCst);
}
fn update_ha_master_address(&self, new_address: &str) {
// Safely free the old pointer before storing the new one
- let old_address = self.master_address.load(Ordering::SeqCst);
+ let old_address = self.master_ha_address.load(Ordering::SeqCst);
if !old_address.is_null() {
unsafe {
// Convert the old pointer back into a Box to free the memory
let _ = Box::from_raw(old_address);
}
}
// Store the new address
let new_address_ptr = Box::into_raw(Box::new(new_address.to_string()));
- self.master_address.store(new_address_ptr, Ordering::SeqCst);
+ self.master_ha_address.store(new_address_ptr, Ordering::SeqCst);
}
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/default_ha_client.rs around lines 684 to 696, the
method update_ha_master_address is incorrectly updating the field
self.master_address instead of self.master_ha_address. To fix this, replace all
occurrences of self.master_address with self.master_ha_address in this method,
ensuring the old pointer is freed and the new address is stored in
self.master_ha_address.

@codecov
Copy link

codecov bot commented Jun 24, 2025

Codecov Report

Attention: Patch coverage is 0% with 22 lines in your changes missing coverage. Please review.

Project coverage is 26.18%. Comparing base (4e10afa) to head (8707b74).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-store/src/ha/default_ha_client.rs 0.00% 15 Missing ⚠️
rocketmq-store/src/ha/general_ha_client.rs 0.00% 6 Missing ⚠️
rocketmq-store/src/ha/default_ha_service.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3518      +/-   ##
==========================================
- Coverage   26.18%   26.18%   -0.01%     
==========================================
  Files         555      555              
  Lines       78635    78648      +13     
==========================================
  Hits        20593    20593              
- Misses      58042    58055      +13     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Collaborator

@rocketmq-rust-bot rocketmq-rust-bot left a comment

Choose a reason for hiding this comment

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

LGTM

@rocketmq-rust-bot rocketmq-rust-bot merged commit 8711443 into main Jun 24, 2025
22 of 24 checks passed
@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved and removed ready to review waiting-review waiting review this PR labels Jun 24, 2025
@mxsm mxsm deleted the op-3517 branch June 26, 2025 03:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI review first Ai review pr first approved PR has approved auto merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Memory Management Fix for AtomicPtr-based Address Fields in HA Client

3 participants