Skip to content

fix(service): keep cancellation writes from blocking request timeouts - #1531

Open
perfloop-agent wants to merge 11 commits into
modelcontextprotocol:mainfrom
perfloop-oss:perfloop-pr-open-pqkpkdq1cd
Open

perfloop-agent wants to merge 11 commits into
modelcontextprotocol:mainfrom
perfloop-oss:perfloop-pr-open-pqkpkdq1cd

Conversation

@perfloop-agent

@perfloop-agent perfloop-agent commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for a response can hang indefinitely after its configured timeout when the peer stops reading. RequestHandle::await_response waits for the cancellation write before returning ServiceError::Timeout; this change makes that notification best-effort, so a stalled write no longer holds the timeout result.

Timeout cancellations now use a shared 1024-permit limit, separate from subscription and abandonment cancellation. Permits remain held through write completion; the service still owns partial writes. Expiration closes the response receiver and removes its closed responder independently of cancellation delivery, including when dispatch has not yet registered it. Cleanup follows the original registration even if callers change the handle’s public fields. The public API is unchanged.

For eight requests expiring together on a writable peer, the previous single-permit design dropped seven cancellation notifications. The new concurrent-timeout test checks that all eight arrive.

Subscription cleanup now has one exit path, including when a response sender closes.

Limit: timeout cancellation can be dropped when the queue is full or closed or all 1024 permits are occupied; returning a timeout does not guarantee the remote operation has stopped.

Limit: stalled writes can still delay graceful quit; original request sends are not capped by this change.

Cost: completed duplex requests add one allocation and 178 allocated bytes per operation in the measured builds. Timing remained inconclusive after 128 pairs; no speed or timing-preservation claim is made.

Limit: the full crate suite with only default features remains unvalidated.

Fixes #1530
cc @DaleSeo @gocamille

Tests and allocation costs

crates/rmcp/tests/test_timeout_cancel.rs covers stalled custom-transport cancellation, one-byte duplex backpressure, writable-peer delivery, concurrent expiration, saturation, abandonment independence, responder association and retargeted handles. The stalled-send, duplex-backpressure, writable-peer and concurrent-expiration cases use 50 ms timeouts with five-second outer deadlines; the saturation test uses 20 ms timeouts. Unit coverage includes full and closed queues, subscription/progress cleanup, transferred receivers, late timeout-option mutation and shutdown cleanup.

Cargo tests passed 330 default-feature library tests, 210 no-default-feature library tests, and 895 tests with default features plus client,transport-io; the latter run had zero failures and seven ignored doctests. Scoped Clippy, changed-file formatting and documentation generation with warnings denied passed.

Allocation measurements below used a harness not included in this PR. Values are per operation; Base and This change columns are medians. All displayed paired changes had identical lower and upper sequential bounds. These are allocation increases, not improvements. The shared semaphore is initialized only on first timeout cancellation; request registrations are needed even for initially untimed handles because callers can subsequently enable a timeout.

Input Metric Base This change Change Complete pairs
Untimed request queueing allocations/op 7 8 +1; 14.3% more allocations 9
Untimed request queueing allocated bytes/op 1291 1339 +48 B; 3.72% more bytes 9
Queued request batch allocations/op 7.03125 8.03125 +1; 14.2% more allocations 11
Queued request batch allocated bytes/op 1684.8359375 1740.8359375 +56 B; 3.32% more bytes 11
Completed duplex ping allocations/op 117.015625 118.015625 +1; 0.855% more allocations 12
Completed duplex ping allocated bytes/op 15498.578125 15676.578125 +178 B; 1.15% more bytes 12
Progress-enabled duplex ping allocations/op 120.015625 121.015625 +1; 0.833% more allocations 13
Progress-enabled duplex ping allocated bytes/op 16154.578125 16332.578125 +178 B; 1.10% more bytes 13
Duplex tool call allocations/op 210.015625 211.015625 +1; 0.476% more allocations 13
Duplex tool call allocated bytes/op 71225.578125 71403.578125 +178 B; 0.250% more bytes 13
Connect, ping and shutdown allocations/op 294 295 +1; 0.340% more allocations 14
Connect, ping and shutdown allocated bytes/op 123875 124707 +832 B; 0.672% more bytes 14

Case and evidence


Made by Perfloop. Human sponsor: Tomás Senart.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
@perfloop-agent
perfloop-agent requested a review from a team as a code owner December 1, 2026 03:22
@github-actions github-actions Bot added T-test Testing related changes T-core Core library changes labels Dec 1, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T06:57:14.630647Z c36a16f New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions
github-actions Bot requested a review from connor4312 December 1, 2026 03:22
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@connor4312 is on triage rotation this week and is the reviewer for this one.

Labels come from the PR labeler. Please review the change.

Automated triage. Labels are a first pass and the assigned maintainer has the final say.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6bc8b8495

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread crates/rmcp/src/service.rs Outdated
let _ = self.peer.send_notification(notification.into()).await;
// Cancellation is best-effort: a stalled transport must not delay the timeout.
self.peer
.try_cancel_request(self.id.clone(), Some(reason.to_owned()));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Bound in-flight cancellations when the writer stalls

When the peer stops reading/responding and the caller retries after each returned timeout, this enqueue is not actually bounded by CLIENT_CHANNEL_BUFFER_SIZE: the service loop immediately drains every notification into its unbounded send_task_set, while the corresponding request remains in local_responder_pool until the cancellation's Transport::send completes. Each timeout can therefore leave another permanently pending send future and responder, so the exact stalled-write case fixed here can grow memory without limit; bound, coalesce, or abort in-flight best-effort cancellations while still returning the timeout promptly.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for flagging this. Agreed: pending sends can grow while the writer stalls. Request sends already insert responders into local_responder_pool and spawn into the same unbounded send_task_set. Before this fix, a stalled cancellation write prevented callers from getting the timeout back at all. A separate change could bound in-flight sends if the maintainers want it.

@jokemanfire jokemanfire left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at e6bc8b84 against d0dab0e3. The fix does what it says, and I could reproduce the bug it targets — but the follow-up it leaves open is real, and I measured it.

Gate at the head SHA (worktree, shared CARGO_TARGET_DIR)

  • cargo fmt --all -- --check → clean.
  • cargo clippy -p rmcp --lib --features "client,server,macros,schemars" -- -D warnings -A clippy::result_large_err → clean.
  • cargo test -p rmcp --test test_timeout_cancel --features "client,server,macros,schemars" → 3 passed (including the writable-peer control).

Red before green: the new test file copied onto d0dab0e3 fails exactly where it should —

  • timeout_returns_when_cancellation_send_stalls → panicked at tests/test_timeout_cancel.rs:76 (no timeout result within the 200 ms bound),
  • timeout_returns_when_async_rw_cancellation_is_backpressured → panicked at :107,
  • timeout_cancellation_reaches_a_writable_peer passes on both sides, so the control is a real control.

The bounded-ness of the enqueue is the part I would not ship as-is. Codex's P1 is right, and it is easy to demonstrate: I wrote a Transport whose request writes succeed but whose notification writes increment a counter and never complete, then timed out 30 pings in a row with a 20 ms timeout.

stalled cancellation sends after 30 timeouts: 30

So each returned timeout leaves one permanently pending write future plus its local_responder_pool entry. That is by construction: notification events are spawned into the unbounded send_task_set (service.rs:1611-1650), while the pool entry is removed only when that write completes (service.rs:1571-1578). Before this PR the caller was stuck behind the first such write, which masked the growth; now callers can loop, so an application that retries on timeout against a stalled peer grows without bound. try_send bounds the channel, not the in-flight sends.

Concrete options, cheapest first:

  1. Bound the cancellation writes like the channel is bounded: keep a shared counter/Semaphore in Peer for in-flight cancellation notifications and skip try_send when it is saturated. Dropping is already the documented semantics of this PR, and it keeps memory flat.
  2. Alternatively cap send_task_set growth in the service loop and drop notification writes past the cap (requests must stay, responses are on a separate response_send_tasks set).
  3. If neither is in scope here, the limit belongs in the docs, not only the PR body: a sentence on RequestHandle::await_response / PeerRequestOptions that a timeout is best-effort and may be silently dropped. Note that the pool entry also keeps has_pending_outbound_request true, so a stalled write can hold off the graceful-quit path (service.rs:1472-1477) — worth mentioning in the same breath.

Minor: send_timeout_cancel_notification already calls unregister_subscription, and await_response calls it again on the way out — harmless today, but the second call is now the only one that runs for the early-return paths, so it is easy to drop one by accident later.

Not approving until the in-flight growth has either a bound or an explicit follow-up issue + doc note; everything else here checks out.

@jokemanfire

Copy link
Copy Markdown
Member

Correction to my review above: I wrote that the PR base equals current origin/main; it does not any more. d0dab0e3 is still an ancestor, but main is now c8e8b084 (#1471 async_rw oversized-stdio reply, #1529 ci doc links). Neither touches service.rs, model.rs, handler/ or the transport this PR changes, and all numbers in the review were produced at the PR head SHA, so the findings stand — only that one clause was wrong.

Worth a rebase before merge so CI exercises both new main commits alongside this change.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
@perfloop
perfloop Bot force-pushed the perfloop-pr-open-pqkpkdq1cd branch from e6bc8b8 to 9924fa1 Compare December 1, 2026 15:40
@perfloop-agent

Copy link
Copy Markdown
Contributor Author

Rebased onto c8e8b084. The timeout, cancellation and response-drain tests pass together on that base.

@perfloop-agent

Copy link
Copy Markdown
Contributor Author

Thanks for reproducing this: best-effort cancellations now share one permit per peer, held through write completion and responder cleanup, and the new 30-timeout regression checks that only one stalled cancellation write starts. await_response now documents dropping and delayed graceful quit, and subscription cleanup has one common exit path, including closed response senders. This bounds cancellation writes, not original request sends or all responder registrations.

@github-actions github-actions Bot added the T-handler Handler implementation changes label Dec 1, 2026

@connor4312 connor4312 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.

Making the timeout cancellation best-effort is the right fix for #1530. The single-permit semaphore, though, drops cancellations in normal, non-stalled operation and leaks state when it does.

Blocking 1: requests that time out together lose their cancellations, and their responders leak (service.rs:891 Semaphore::new(1), :1048-1051)

The permit is held from try_cancel_request until the loop has finished transport.send and handled SendTaskResult (:1575-1579). Any other try_cancel_request on the peer in that window returns silently.

  • Take N concurrent requests with the same timeout against a hung server on a healthy transport. All N timers fire together. Request 1 gets the permit, and requests 2..N send nothing. On a current-thread runtime this is deterministic.
  • On streamable HTTP, the notification send only finishes after the POST round trip. So any two cancellations within one RTT collide.
  • main awaited send_notification for every timeout, so all N were sent. The spec says the sender SHOULD send them.

It's worse than a missed notification:

  • The local_responder_pool entry of a dropped request is only removed when its own cancel write completes (:1587-1594) or when the peer replies. A hung server never replies, so those entries leak for the life of the connection.
  • Leaked entries keep has_pending_outbound_request true. With Unknown stream origin, RoleClient::enforce_peer_request_association (client.rs:406-411) then accepts every server→client sampling, roots or elicitation request as associated.

Blocking 2: the permit is shared with lifecycle cleanup that was unbounded before

try_cancel_request is also used by PendingSubscriptionRequest::drop (client.rs:518), AbandonedRequestGuard::drop (:554), Subscription::drop (:737) and the lagged/closed subscription paths (service.rs:1797/1804). While a timeout cancellation holds the permit:

  • A dropped Subscription never tells the server. It has already been unregistered locally, so the server keeps streaming it, and those notifications reach the handler as unsolicited.
  • Several call_tool futures dropped together by one outer timeout/select! send only one abandonment cancellation.

Explicit RequestHandle::cancel takes no permit, so behaviour now differs between the two kinds of cancellation in a way that's hard to see.

Suggested fix:

  • Bound stalled writes rather than serialising healthy ones. For example, use a permit count around the outbound channel capacity, and only for the timeout path, so subscription and abandonment cleanup keep their old behaviour.
  • Whenever a cancellation is dropped, still remove the local responder and progress watcher, and log at debug/trace, so a drop never becomes a leak.
  • Add a regression test: K requests with the same timeout over a writable duplex, asserting the peer receives K notifications/cancelled.

Nit: timing in tests/test_timeout_cancel.rs:23-24

A 50 ms timeout with a 200 ms deadline (and 200 ms notified() waits) is tight on loaded macOS/Windows runners. The regression is an unbounded hang, so a 2–5 s outer deadline catches it just as well. Or use start_paused = true where no real I/O is involved.

@perfloop-agent

Copy link
Copy Markdown
Contributor Author

Thanks; the one-permit limit also affects lifecycle cancellations and is too restrictive for simultaneous timeouts. I’m separating the timeout path, allowing a channel-sized burst, and checking how to release local request state even when the cancellation cannot be queued. I’ll add the concurrent writable-peer regression and widen the tests’ outer deadlines.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
@perfloop
perfloop Bot force-pushed the perfloop-pr-open-pqkpkdq1cd branch from 9924fa1 to c36a16f Compare December 3, 2026 06:51

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c36a16f2b4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

self.rx.close();
// The request may still be queued. Publish expiration before removing
// its responder, so the service loop cannot register a closed waiter later.
self.registration.timed_out.store(true, Ordering::Release);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Abort original writes when their requests time out

With the inspected AsyncRwTransport, if the peer stops reading after the first request, its cancellation can hold the writer mutex indefinitely; every sequential retry's original request write then waits behind it in the unbounded send_task_set. Setting timed_out only cleans up responder registration, while timeout_cancellation_semaphore covers only notification writes, so the newly prompt timeout lets the caller enqueue another retained task/message on every retry until memory is exhausted. Signal or abort the corresponding request-send task when this registration expires, or bound request sends as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Original request-send queueing is unchanged: at base 50fc08ad, concurrent callers already spawn original writes into send_task_set behind a stalled writer; prompt timeouts let sequential retries encounter that same existing limit. For both started writes and those waiting for the writer, Transport::send requires that dropping the future leave either a whole message or none, so framing corruption is not a supported reason to reject aborting these tasks. The description already notes that original request sends are not capped here; would you like that bounded in a separate change?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

T-core Core library changes T-handler Handler implementation changes T-test Testing related changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Request timeout can hang when the cancellation notification cannot be written

3 participants