Skip to content

[Store][DO NOT Merge Now](fix) avoid MR resource leak and destructor hang on master failure - #2336

Closed
LujhCoconut wants to merge 1 commit into
kvcache-ai:mainfrom
LujhCoconut:fix/mr-related-resource-leak
Closed

LujhCoconut wants to merge 1 commit into
kvcache-ai:mainfrom
LujhCoconut:fix/mr-related-resource-leak

Conversation

@LujhCoconut

Copy link
Copy Markdown
Collaborator

Description

This PR fixes RDMA Memory Region (MR) resource leaks in mooncake-store that occur when the master service exits or becomes unreachable before the store service gracefully unmounts its segments.

Root Cause (source code verified)

Three independent code paths leak MRs:

  1. Client::~Client() performs synchronous RPC to master during destruction.
    When master is dead, each UnmountSegment() call hits UnmountSegmentImpl(), which returns early on RPC failure without calling transfer_engine_->unregisterLocalMemory(). All mounted segments' MRs are leaked.

    • File: client_service.cpp:355-363 (destructor loop)
    • File: client_service.cpp:2598-2603 (early return on RPC failure)
  2. UnmountSegmentImpl bails out on RPC failure without local cleanup.
    If master_client_.UnmountSegment() fails, the function returns immediately, skipping transfer_engine_->unregisterLocalMemory().

    • File: client_service.cpp:2598-2603
  3. Mount path lacks rollback on RPC failure.
    In MountSegmentAndGetId, registerLocalMemory() succeeds first, but if the subsequent MountSegment() RPC fails, the TE-side MR is never unregistered.

    • File: client_service.cpp:2670-2696

Why RPC is skippable in destructor

MasterService::ClientMonitorFunc (master_service.cpp:5658) handles dead clients via TTL expiry:

  • Store sends periodic Ping heartbeats
  • If store exits, heartbeats stop
  • After client_live_ttl_sec_, master marks client as expired
  • ClientMonitorFunc auto-runs PrepareUnmountSegment → ClearInvalidHandles → CommitUnmountSegment

Therefore, the destructor's UnmountSegment RPC is best-effort optimization, not a correctness dependency.

What this PR fixes

Problem Location Fix
Destructor MR leak when master is dead Client::~Client() Skip master RPC, call unregisterLocalMemory() directly
UnmountSegmentImpl skips TE cleanup on RPC failure Client::UnmountSegmentImpl() Continue with unregisterLocalMemory() even if master notification fails
Mount path MR leak on RPC failure Client::MountSegmentAndGetId() Rollback registerLocalMemory() if MountSegment() fails

Changes

  • Client::~Client(): Skip all master RPCs during destruction. Perform only local unregisterLocalMemory() cleanup. Master will clean up metadata via TTL.
  • Client::UnmountSegmentImpl(): Continue with unregisterLocalMemory() even if master notification fails. Log the failure but do not leak the MR.
  • Client::MountSegmentAndGetId(): Rollback registerLocalMemory() if MountSegment() RPC fails.

Module

  • Mooncake Store (mooncake-store)
  • Transfer Engine (mooncake-transfer-engine)
  • Mooncake EP (mooncake-ep)
  • Integration (mooncake-integration)
  • P2P Store (mooncake-p2p-store)
  • Python Wheel (mooncake-wheel)
  • PyTorch Backend (mooncake-pg)
  • Mooncake RL (mooncake-rl)
  • CI/CD
  • Docs
  • Other

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Breaking change
  • Documentation update
  • Other

Checklist

  • I have performed a self-review of my own code.
  • I have formatted my own code using ./scripts/code_format.sh before submitting.
  • I have updated the documentation.
  • I have added tests to prove my changes are effective.

@LujhCoconut

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request modifies the client service to prevent destructor hangs and memory registration leaks by performing local cleanup instead of synchronous RPCs to the master during client destruction, proceeding with local cleanup if master unmounting fails, and rolling back memory registration upon mount failures. The review feedback correctly points out that calling unregisterLocalMemory with a single argument still triggers a synchronous RPC to the master by default, and suggests passing false as the second argument to ensure purely local cleanup.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread mooncake-store/src/client_service.cpp Resolved

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the client segment cleanup and error handling in mooncake-store/src/client_service.cpp. It skips master RPCs during client destruction to prevent hangs, ensures local memory unregistration proceeds even if master unmount notifications fail, and adds rollback logic for local memory registration when mounting to the master fails. The review feedback identifies critical improvements: resolving a potential deadlock during destruction by releasing mounted_segments_mutex_ before making synchronous RPCs, adding a defensive null check for transfer_engine_ to prevent dereferencing errors in RPC-only mode, and propagating master unmount errors to the caller instead of swallowing them.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread mooncake-store/src/client_service.cpp Resolved
Comment thread mooncake-store/src/client_service.cpp Resolved
Comment thread mooncake-store/src/client_service.cpp Resolved
@LujhCoconut
LujhCoconut force-pushed the fix/mr-related-resource-leak branch from ba1ec38 to 7c0dc7c Compare June 5, 2026 07:26
@LujhCoconut

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request updates the client service and transfer engine to avoid hangs and deadlocks during segment mounting and unmounting, introducing an update_metadata flag to control metadata synchronization. The review highlights several critical issues: releasing the mounted_segments_mutex_ lock before the synchronous master RPC introduces a race condition and potential use-after-free during destruction; hardcoding false for update_metadata during unmount prevents metadata synchronization even when the master is healthy; and missing updates to the vector overloads of unregisterLocalMemory in header files will cause compilation errors.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread mooncake-store/src/client_service.cpp Resolved
Comment thread mooncake-store/src/client_service.cpp Resolved
@LujhCoconut LujhCoconut closed this Jun 5, 2026
@LujhCoconut LujhCoconut reopened this Jun 5, 2026
@LujhCoconut
LujhCoconut force-pushed the fix/mr-related-resource-leak branch from 7c0dc7c to dfd0482 Compare June 5, 2026 08:30
@LujhCoconut

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes client cleanup and segment mounting by performing local transfer engine cleanup during destruction (skipping master RPCs to avoid hangs), continuing local cleanup on unmount failures, and moving the synchronous MountSegment RPC outside of the mutex lock. It also introduces an update_metadata flag to unregisterLocalMemory to bypass metadata synchronization when appropriate. The review feedback identifies critical issues, including potential null pointer dereferences on transfer_engine_ in UnmountSegmentImpl and MountSegmentAndGetId, and a race condition in MountSegmentAndGetId where concurrent mounts could bypass overlap checks because segments are registered in mounted_segments_ only after the RPC completes.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread mooncake-store/src/client_service.cpp Resolved
Comment thread mooncake-store/src/client_service.cpp Resolved
Comment thread mooncake-store/src/client_service.cpp Resolved
@LujhCoconut
LujhCoconut force-pushed the fix/mr-related-resource-leak branch from dfd0482 to 17a699e Compare June 5, 2026 08:51
@LujhCoconut
LujhCoconut marked this pull request as ready for review June 5, 2026 09:20
@alogfans

alogfans commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

CI check seems abnormal.

Comment on lines +2615 to +2619
int rc = 0;
if (transfer_engine_) {
rc = transfer_engine_->unregisterLocalMemory(
reinterpret_cast<void*>(it->second.base), false);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The old code called unregisterLocalMemory(addr) which defaulted to update_metadata=true, triggering metadata_->segmentManager().synchronizeLocal(). Now all unmount paths (including the happy path where master is alive) skip metadata sync.

This means even a successful unmount no longer publishes the MR removal to other peers via the metadata service. Remote nodes may still attempt RDMA reads/writes to the now-deregistered MR, causing silent failures or crashes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for catching this! You're right that was a bug.
The latest push fixes it — UnmountSegmentImpl now passes unmount_result.has_value() instead of hardcoded false:

 rc = transfer_engine_->unregisterLocalMemory(                                                                       
      reinterpret_cast<void*>(it->second.base),
      unmount_result.has_value());  // true when master alive, false when dead 

So the master-alive path still calls synchronizeLocal() to notify peers, while the failure path (master dead) skips it since there's no point syncing metadata when the master is gone — it will self-cleanup via TTL expiry.

Comment thread mooncake-store/src/client_service.cpp Outdated

segment_id = segment.id;
mounted_segments_[segment_id] = segment;
auto mount_result = master_client_.MountSegment(segment);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Here doing RPC without lock. Could a race condition occur?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed, thanks for flagging it. The current version keeps the entire operation under mounted_segments_mutex_ — the master RPC, rollback, and segment insertion all happen inside the lock scope.

@LujhCoconut
LujhCoconut force-pushed the fix/mr-related-resource-leak branch from 17a699e to 4073475 Compare June 8, 2026 03:52

@staryxchen staryxchen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Only a mirror issue not blocking: (void*)buffer -> reinterpret_cast<void*>(buffer)

@LujhCoconut
LujhCoconut force-pushed the fix/mr-related-resource-leak branch 2 times, most recently from 3729958 to ed59478 Compare June 8, 2026 09:22
- Skip synchronous master Unmount RPC in Client destructor; master cleans
  up via ClientMonitorFunc TTL. Prevents hang if master is frozen and MR
  leak if master is dead.
- Continue local TE unregister in UnmountSegmentImpl even when master
  notification fails.
- Rollback TE registration in MountSegmentAndGetId when mount to master
  fails, preventing orphaned MRs.
@LujhCoconut
LujhCoconut force-pushed the fix/mr-related-resource-leak branch from ed59478 to afc097a Compare June 8, 2026 11:10
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 55.26316% with 17 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
mooncake-store/src/client_service.cpp 55.26% 17 Missing ⚠️

📢 Thoughts on this report? Let us know!

Comment on lines 2721 to +2726
if (!mount_result) {
ErrorCode err = mount_result.error();
LOG(ERROR) << "mount_segment_to_master_failed base=" << buffer
<< " size=" << size << ", error=" << err;
// Rollback: unregister the TE memory that was just registered
int unreg_rc = transfer_engine_->unregisterLocalMemory(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'm worried the current handling here isn't robust enough — it runs into the same issue @ykwd raised in PR #2345.

The issue of "RDMA memory leak on MountSegment failure" does indeed exist and is a known problem. The new rollback at client_service.cpp:2726 unregisters the MR whenever MountSegment returns an error:

auto mount_result = master_client_.MountSegment(segment);
if (!mount_result) {
    transfer_engine_->unregisterLocalMemory(buffer, false);  // unsafe
    return tl::unexpected(err);
}

The problem is that !mount_result is ambiguous. invoke_rpc collapses three different outcomes into the same RPC_FAIL:

  1. request never sent → master didn't mount → rollback safe
  2. request sent but response lost (timeout / reset / master crashed after commit) → master may have mounted successfully → rollback unsafe
  3. master rejected → rollback safe

In case (2) the master still considers the segment valid and will route peers to it, but we've just deregistered the MR locally — turning a memory leak into a cross-node inconsistency where peers RDMA to a dead rkey. This is exactly the concern that led to the cleanup being removed in PR #2345 and tracked in Issue #2364.

It's also made worse by update_metadata=false: the descriptor stays published in the TE metadata server even though the MR is gone, so the stale rkey remains discoverable.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed. But I haven't come up with a particularly elegant approach yet.

@LujhCoconut LujhCoconut changed the title [Store](fix) avoid MR resource leak and destructor hang on master failure [Store][DO NOT Merge Now](fix) avoid MR resource leak and destructor hang on master failure Jun 9, 2026
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown

This PR has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Please update the PR or comment to keep it open.

@github-actions github-actions Bot added the stale label Oct 8, 2026
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

This PR was closed because it has been inactive for 104 days. Feel free to reopen if you'd like to continue the work.

@github-actions github-actions Bot closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants