Repository navigation
fix(service): keep cancellation writes from blocking request timeouts - #1531
perfloop-agent wants to merge 9 commits into
Conversation
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@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. |
There was a problem hiding this comment.
💡 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".
| 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())); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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_peerpasses 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:
- Bound the cancellation writes like the channel is bounded: keep a shared counter/
SemaphoreinPeerfor in-flight cancellation notifications and skiptry_sendwhen it is saturated. Dropping is already the documented semantics of this PR, and it keeps memory flat. - Alternatively cap
send_task_setgrowth in the service loop and drop notification writes past the cap (requests must stay, responses are on a separateresponse_send_tasksset). - If neither is in scope here, the limit belongs in the docs, not only the PR body: a sentence on
RequestHandle::await_response/PeerRequestOptionsthat a timeout is best-effort and may be silently dropped. Note that the pool entry also keepshas_pending_outbound_requesttrue, 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.
|
Correction to my review above: I wrote that the PR base equals current 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>
e6bc8b8 to
9924fa1
Compare
|
Rebased onto |
|
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. |
connor4312
left a comment
There was a problem hiding this comment.
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
sendonly finishes after the POST round trip. So any two cancellations within one RTT collide. mainawaitedsend_notificationfor 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_poolentry 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_requesttrue. WithUnknownstream 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
Subscriptionnever 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_toolfutures dropped together by one outertimeout/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.
|
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>
9924fa1 to
c36a16f
Compare
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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_capacityis still a plain#[tokio::test]with a 5ms timeout and a 200ms outer deadline. - Squash the refactor commits.
2bd3cab("consolidate shared peer state") and63b1b5b("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>inRequestRegistration, theis_closed()guards, and threeretargeted_*/transferred_*tests) protects against users swapping the publicRequestHandlefields. That's correct given those fields arepub, but a short comment onRequestRegistrationexplaining why would save the next reader ofservice.rssome time. Making those fields read-only in v4 would let us drop the guards altogether.
| struct TestServer; | ||
| impl crate::ServerHandler for TestServer {} | ||
|
|
||
| #[tokio::test] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 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. |
c36a16f to
86c4212
Compare
|
The queue-capacity test now uses paused Tokio time, |
There was a problem hiding this comment.
💡 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".
| (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)), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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>
Waiting for a response can hang indefinitely after its configured timeout when the peer stops reading.
RequestHandle::await_responsewaits for the cancellation write before returningServiceError::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
Timeoutwithout 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.rscovers 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.
Case and evidence
Made by Perfloop. Human sponsor: Tomás Senart.