fix(session): Prevent memory leak in pendingResponses on request timeout/cancellation #287
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes a potential memory leak in the
pendingResponses
map within bothMcpClientSession
andMcpServerSession
when requests time out or are cancelled.Motivation and Context
A potential memory leak exists in the
pendingResponses
map within bothMcpClientSession
andMcpServerSession
.Problem Details:
When a request is initiated using the
sendRequest()
method, aMonoSink
is stored in thependingResponses
map, awaiting a response from the peer (server or client). If this peer does not respond and the operation times out (due to the.timeout()
operator), or if theMono
returned bysendRequest()
is cancelled for other reasons before a response is received, the original code did not explicitly remove theMonoSink
from thependingResponses
map.This could lead to an accumulation of unresolved sinks, causing a memory leak over time, especially in scenarios with many unanswered or timed-out requests. This change is needed to enhance the stability and robustness of the session management.
How Has This Been Tested?
onDispose
handler, which is a well-understood pattern for resource cleanup in asynchronous scenarios like timeouts or cancellations.onDispose
handler would be invoked as expected to remove entries frompendingResponses
.Breaking Changes
None. This change only affects internal resource management and does not alter any public APIs or existing behavior from a user's perspective.
Types of changes
Checklist
Additional context
Solution Details:
This commit introduces an
onDispose()
callback within theMono.create()
block in the
sendRequest()
method of bothMcpClientSession
andMcpServerSession
. ThisonDispose()
handler ensures thatpendingResponses.remove(requestId)
is reliably invoked when theMonoSink
is disposed for any reason, including:.timeout()
operator.This approach ensures that resources associated with pending requests are
cleaned up properly under various termination conditions.