Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

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

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

perfloop-agent wants to merge 9 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.

In the one-byte duplex regression, a ping with a 50 ms timeout returns Timeout without waiting for the cancellation frame; after reading resumes, the peer receives the complete notification.

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 ping allocates 15.50 → 15.68 kB/op (+178 B, 1.15%) and one extra allocation. Queued-request batches measured slower, with attribution unresolved; timing preservation is not established.

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. The outbound-capacity unit test now uses paused Tokio time with its existing 5 ms timeout and 200 ms outer deadline. Closed-response cleanup checks the original peer/request identity and watcher channel identity; the new unit test verifies that retargeting peer, ID or token preserves the other subscription’s notification delivery and progress-reset behavior, including missing and removed watcher entries.

Cargo tests passed 330 default-feature library tests and 210 no-default-feature library tests; scoped client/local timeout, progress, subscription, abandonment and response-drain tests also passed with no failures. Scoped Clippy and changed-file formatting 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 16
Untimed request queueing allocated kB/op 1.291 1.339 +48 B; 3.72% more allocated bytes 16
Queued request batch allocations/op 7.031 8.031 +1; 14.2% more allocations 16
Queued request batch allocated kB/op 1.685 1.741 +56 B; 3.32% more allocated bytes 16
Completed duplex ping allocations/op 117.0 118.0 +1; 0.855% more allocations 16
Completed duplex ping allocated kB/op 15.50 15.68 +178 B; 1.15% more allocated bytes 16
Progress-enabled duplex ping allocations/op 120.0 121.0 +1; 0.833% more allocations 17
Progress-enabled duplex ping allocated kB/op 16.15 16.33 +178 B; 1.10% more allocated bytes 17
Duplex tool call allocations/op 210.0 211.0 +1; 0.476% more allocations 17
Duplex tool call allocated kB/op 71.23 71.40 +178 B; 0.250% more allocated bytes 17
Connect, ping and shutdown allocations/op 294 295 +1; 0.340% more allocations 17
Connect, ping and shutdown allocated kB/op 123.9 124.7 +832 B; 0.672% more allocated bytes 17
Progress request queueing allocations/op 10 11 +1; 10.0% more allocations 17
Progress request queueing allocated kB/op 1.951 1.999 +48 B; 2.46% more allocated bytes 17

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-04T05:40:37.747601Z ada776f 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>
@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?

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

Thanks for the rework. Both blocking points from my earlier review are resolved:

  • The limit is now CLIENT_CHANNEL_BUFFER_SIZE, scoped to the timeout path.
  • Local cleanup no longer waits on the cancellation write.
  • Lifecycle cleanup isn't capped any more.
  • The new regression tests cover concurrent timeouts, association enforcement after a stalled timeout, and a saturated timeout limit.

A few non-blocking nits:

  • One test still uses real time (inline). The integration tests now use paused time or a 5s outer deadline, but timeout_does_not_wait_for_outbound_capacity is still a plain #[tokio::test] with a 5ms timeout and a 200ms outer deadline.
  • Squash the refactor commits. 2bd3cab ("consolidate shared peer state") and 63b1b5b ("name shared role-specific state types") mostly reshape types this PR introduces, so they read best folded into the fix. The repo squash-merges anyway, but the final squash message should describe the fix rather than the intermediate refactors.
  • Readability of the retargeting guards. A good share of the new code (the Weak<PeerState> in RequestRegistration, the is_closed() guards, and three retargeted_*/transferred_* tests) protects against users swapping the public RequestHandle fields. That's correct given those fields are pub, but a short comment on RequestRegistration explaining why would save the next reader of service.rs some time. Making those fields read-only in v4 would let us drop the guards altogether.

Comment thread crates/rmcp/src/service.rs Outdated
struct TestServer;
impl crate::ServerHandler for TestServer {}

#[tokio::test]

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.

Nit: this one still runs on real time, a 5ms timeout inside a 200ms outer deadline, which is tight on a loaded CI runner. It doesn't do any real I/O, so #[tokio::test(start_paused = true)] should make it deterministic, as with the other new tests.

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.

Changed this test to #[tokio::test(start_paused = true)]; it passes with the same 5 ms timeout and 200 ms outer deadline measured in virtual time.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
@perfloop-agent

Copy link
Copy Markdown
Contributor Author

Perfloop paused work on this pull request before it answered the open comments. The work reached the usage limit set for this one change, not the workspace's overall limit. An admin of the Perfloop workspace that opened it can continue the work from the Inbox.

@perfloop
perfloop Bot force-pushed the perfloop-pr-open-pqkpkdq1cd branch from c36a16f to 86c4212 Compare December 4, 2026 02:59
@perfloop-agent

Copy link
Copy Markdown
Contributor Author

The queue-capacity test now uses paused Tokio time, RequestRegistration explains why cleanup follows the original peer and request while preserving transferred receivers, and the refactor commits are folded into the ownership fix. Runtime behavior and the documented allocation costs are unchanged.

@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: 86c4212419

ℹ️ 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
(Some(timeout), None, false) => match tokio::time::timeout(timeout, &mut self.rx).await
{
Ok(response) => response.map_err(|_e| ServiceError::TransportClosed)?,
Ok(response) => response.unwrap_or(Err(ServiceError::TransportClosed)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep close cleanup tied to the original registration

When a caller retargets a RequestHandle's public peer/id (a case exercised by retargeted_handle_preserves_other_waiters) and the original response sender then closes before the timeout, this unwrap_or no longer returns early as the previous ? did: await_response falls through to watcher cleanup and self.peer.unregister_subscription(&self.id) on the replacement peer. If that peer has a live subscription or timeout watcher under the same generated id/token, unrelated state is removed even though the closed receiver belonged to the original registration; closed-response cleanup should use the registration's original state/id, or first verify that the mutable public fields still identify it.

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.

Fixed: closed-response cleanup checks the original peer and request ID, and removing a progress watcher additionally requires the original channel identity. The new regression test covers peer/ID/token retargeting and missing or removed watchers, checking that the other subscription still delivers notifications and resets its progress timeout.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>

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