Skip to content

fix(transport): finish a message left in the sink when SinkStreamTransport closes - #1574

Open
joulook wants to merge 6 commits into
modelcontextprotocol:mainfrom
joulook:fix/sinkstream-flush
Open

joulook wants to merge 6 commits into
modelcontextprotocol:mainfrom
joulook:fix/sinkstream-flush

Conversation

@joulook

@joulook joulook commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Motivation and Context

Follow-up to #1558, from the approving review there, which noted that SinkStreamTransport::close() has the same
gap and suggested either the same bounded flush or a line in the Transport::send/close docs.

SinkStreamTransport::send is SinkExt::send: poll_ready, start_send, then poll_flush. Since #1549 the
service loop drops a progress notification's send future when the peer cancels the request. If the future is
dropped during the flush, the sink has accepted the message but not finished writing it. close() returned
Ok(()) without touching the sink, so with no later message the peer gets nothing (a sink that holds items until
flushed) or a truncated message (a sink that writes bytes as it goes, such as a FramedWrite or a websocket stream
over a full socket).

No transport shipped in rmcp builds on SinkStreamTransport (child-process and in-memory use AsyncRwTransport;
the worker transport passes whole messages through a channel). It is reached through the IntoTransport impl for
any (Sink, Stream) pair or Sink + Stream type, which the module docs suggest for websockets, as in
examples/transport/src/websocket.rs. Since the gap is in the shipped adapter, this takes the bounded flush rather
than the docs line.

How Has This Been Tested?

tests/test_sink_stream_flush.rs, the scenario of test_progress_flush.rs over SinkStreamTransport: one tool
call with a progress token, the progress send is pending when the client cancels, nothing else is written, the
client closes its input and reads everything the server wrote. Each test was run three times on main and on this
branch.

test main 3725772 this PR
FramedWrite sink over a 64-byte pipe: frame abandoned mid-flush fails 3/3 (output ends inside the progress frame) passes 3/3
a sink that holds accepted items until flushed fails 3/3 (progress notification missing) passes 3/3
EOF read before the send future is dropped (the byte sink, then the holding sink, in one test) fails 3/3 (at the byte sink, the first case) passes 3/3 (both cases)
a peer that stops reading: the server still stops in time passes passes (stops after CLOSE_FLUSH_TIMEOUT)

Full runs on this branch:

  • cargo test -p rmcp --features <all but local>: 2 009 / 2 / 18; the two failures are test_with_python, whose
    uv was not on the PATH; re-run with uv: 2 passed;
  • --all-features: 1 327 / 0 / 32;
  • --lib --no-default-features: 211 / 0 / 0;
  • test_progress_flush: 5 / 0;
  • cargo fmt --check: clean; clippy with -D warnings: clean in the CI set (all features with all targets, all
    but local with all targets, default, the session feature with server, each feature except local alone).

Breaking Changes

None.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)

Additional context

  • The change.
    • CLOSE_FLUSH_TIMEOUT (500 ms) moves from async_rw.rs to transport.rs, with a helper
      flush_before_close that flushes a sink bounded by it and ignores a write error or the timeout.
    • AsyncRwTransport::close() calls the helper; its behaviour is unchanged.
    • SinkStreamTransport::close() takes the sink's lock and calls the helper. The 500 ms bound covers the
      flush, after the lock is acquired: a send future that is still alive holds the lock until it ends or is
      dropped, as in AsyncRwTransport::close(). The service loop drops the abandoned progress send and ends its
      other send tasks before it closes the transport. It still does not call
      poll_close on the sink, as before, so a websocket stream, for example, sends no close frame from here.
  • Same limits as fix(transport): finish a stdio frame whose send future is dropped #1558. Best effort: a peer that does not read within 500 ms still gets a partial or missing
    message, and once the sink's lock is held, closing takes up to 500 ms longer when the sink holds a message. send() and receive() are unchanged.

Found with. We are a research team at MPI-SWS building Daavar, a conformance checker for distributed protocol
implementations. This follow-up came from the review note on #1558. We added the sink-stream transport to the byte-level
frame cell of our model (Daavar benchmarks/mcp-cancel), the cell that showed #1557: each step of the model's write
path follows SinkStreamTransport (send: the sink's lock and SinkExt::send; close()) over a FramedWrite sink
of rmcp's codec on a 64-byte pipe. On that model the transport at main violates the specification program and the
fixed transport conforms, over all interleavings of the cell. The model does not cover a sink that holds a message
whole until it is flushed (the message is then lost whole, not cut, which the cell's framing rule does not flag);
the native test above covers it. This fix was prepared with AI assistance and reviewed by us.

Reproduce with Daavar (conformance test)

The cell ca,s0,frA: one tool call with a progress token, the client cancels it and shuts down, then reads the server's
output to EOF. The specification program writes both chunks of a frame together, so every frame the client reads is
whole or absent. implso follows SinkStreamTransport at 2d77786 (unchanged on main 3725772); implsf follows this fix. The join prints
the words of the implementation the specification does not produce as uncovered.

git clone --recurse-submodules https://github.com/joulook/daavar.git && cd daavar
git checkout 8d6da50 && git submodule update --init --recursive
(cd traceforge && cargo build --release -p traceforge --bin conf-join)
cd benchmarks/mcp-cancel/rust && cargo build --release
B=target/release/tf_mcp_cancel; J=../../../traceforge/target/release/conf-join
$B export spec --out spec.jsonl --model fifo -- spec,ca,s0,frA
$B export impl --out so.jsonl   --model fifo -- implso,ca,s0,frA; $J --decide spec.jsonl so.jsonl   # violation: 1 uncovered of 3, Head(progress) then Eof
$B export impl --out sf.jsonl   --model fifo -- implsf,ca,s0,frA; $J --decide spec.jsonl sf.jsonl   # conforms, 0 uncovered

The cells frC (no cancel; the drain deadline drops the held write after EOF) and frE (a later request after the
abandoned one) are in the benchmark's README with their counts.

Reproduce with the native tests
git clone https://github.com/joulook/rust-sdk.git && cd rust-sdk
git checkout fix/sinkstream-flush
cargo test -p rmcp --test test_sink_stream_flush            # 4 passed
# on main: keep the test, revert the source
git checkout 3725772 -- crates/rmcp/src
cargo test -p rmcp --test test_sink_stream_flush            # 3 failed (the boundedness test passes)

…sport closes

SinkStreamTransport::send is SinkExt::send: poll_ready, start_send, then
poll_flush. Since modelcontextprotocol#1549 the service loop drops a progress notification's
send future when the peer cancels the request. If the future is dropped
during the flush, the sink has accepted the message but not finished
writing it. close() returned Ok(()) without touching the sink, so with no
later message the peer got nothing (a sink that holds items until flushed)
or a truncated message (a sink that writes bytes as it goes, such as a
FramedWrite or a websocket stream over a full socket). This was noted in
the review of modelcontextprotocol#1558, which fixed the same gap in AsyncRwTransport.

CLOSE_FLUSH_TIMEOUT (500 ms) moves from async_rw.rs to transport.rs, with
a helper, flush_before_close, that flushes a sink bounded by it and
ignores a write error or the timeout. AsyncRwTransport::close() now calls
the helper, with unchanged behaviour. SinkStreamTransport::close() takes
the sink's lock and calls it; the sink is still not closed.

Tests in tests/test_sink_stream_flush.rs:
framed_write_progress_abandoned_mid_flush_is_not_left_partial,
holding_sink_abandoned_progress_is_delivered_at_close,
progress_dropped_after_eof_is_delivered_at_close and
close_flush_is_bounded_when_the_peer_stops_reading.
@joulook
joulook requested a review from a team as a code owner December 4, 2026 23:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 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-06T13:22:23.708260Z ffc5034 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.

@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 825ca59b (base 37257723, same as the PR base). CI is fully green here, and I also ran the tests locally because the numbers are worth recording.

What I ran

  • cargo test -p rmcp --test test_sink_stream_flush --features "server,client,transport-async-rw" → 4 passed.
  • cargo test -p rmcp --test test_progress_flush --features "server,client,transport-async-rw,transport-io" → 5 passed (the AsyncRwTransport path still behaves after the inline timeout was replaced by the shared helper).
  • Red before green: I restored sink_stream.rs to 37257723 and kept the new test file → 3 failed / 1 passed:
    • holding_sink_abandoned_progress_is_delivered_at_close → the progress notification, once: []
    • framed_write_progress_abandoned_mid_flush_is_not_left_partial → the output ends inside a message: ["{"jsonrpc":"2.0","method":"notifications/progress","params":{"me"
    • progress_dropped_after_eof_is_delivered_at_close → also fails
    • close_flush_is_bounded_when_the_peer_stops_reading passes on base too, as expected: it bounds shutdown, and before the change close() returned without touching the sink. It is a guard against a future flush that can hang, not a regression test — worth a comment so nobody counts it as one.

Checked by reading

  • SinkStreamTransport::send is SinkExt::send (poll_ready, start_send, poll_flush), so a dropped future really does leave the item inside the sink, both for a byte sink (FramedWrite) and a sink that holds items until flush (Hold). The two sink shapes are covered by the tests, which is the part I cared about: a fix that only handles FramedWrite would pass half the suite.
  • Taking self.sink.lock().await in close() is the only way to reach the sink, and a send future that is still alive holds the same lock, so close now waits for it before the bounded flush — that is documented in the new comment and acceptable for a shutdown path.
  • flush_before_close lives in transport.rs with no cfg, and pub mod sink_stream; is unconditional, so every feature set that compiles the transport module has one user; cargo hack clippy --each-feature -D warnings should stay quiet. I did not run cargo hack (not installed here), so that one is reasoning, not a command.
  • The sink itself is still not closed, same as before; only buffered bytes are pushed out.

No requests from me. The helper extraction is a clean way to keep AsyncRwTransport and SinkStreamTransport from drifting apart.

…sion test

The reviewer noted that close_flush_is_bounded_when_the_peer_stops_reading
also passes on the base commit, where close() returned without touching the
sink. The doc comment now says so, so that nobody counts it as a regression
test: it guards against a future flush that can hang.
@joulook

joulook commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the verification and for recording the numbers.

Agreed on close_flush_is_bounded_when_the_peer_stops_reading: it passes on the base too, because close() returned without touching the sink there; it is a guard against a future flush that can hang, not a regression test. Commit c0e8a8e adds exactly that to its doc comment, nothing else changed.

On cargo hack clippy --each-feature -D warnings: we ran the CI clippy set per feature on the branch before posting; it is clean.

connor4312
connor4312 previously approved these changes Dec 5, 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.

LGTM. This closes the SinkStreamTransport gap from #1558's review, and it reuses the same helper and constant. The service loop shuts down every send task before close(), so taking the sink lock can't deadlock. The flush is bounded and errors are ignored, and send/receive are unchanged. The new tests passed 10 sequential runs and 40 runs at 16 in parallel.

Nit: the Transport::close docs still only say "Close the transport". One line saying close should, best effort, finish a message that a dropped send left buffered would complete the contract that send now documents.

…eft buffered

The send docs say that dropping the returned future must not leave a
partial message on the wire. The close docs now state the other half of
that contract: before closing, close should finish, best effort and within
a bound, a message that a dropped send left buffered, as the stdio and
sink-stream transports do.
@joulook

joulook commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Thank you. Done in b2e72ed: the Transport::close docs now say that, before closing, close should finish, best effort and within a bound, a message that a dropped send future left buffered, so the peer never sees a partial message at the end of the stream, pointing to the send contract. Docs only; no code change.

@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: b2e72eda88

ℹ️ 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".

// alive holds the lock until it ends or is dropped). The sink itself is not closed, as
// before.
let mut write = self.sink.lock().await;
super::flush_before_close::<TxJsonRpcMessage<Role>, _>(&mut *write).await;

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 Skip the closing flush after a terminal sink error

When SinkExt::send has already returned Si::Error because poll_ready or poll_flush failed, the Sink contract permits the sink to be permanently unusable and requires that it not be polled again; compliant sinks may panic on a subsequent poll. This new unconditional flush means the normal sequence of a failed send followed later by EOF/cancellation and service shutdown can turn an ordinary transport error into a panic, whereas close previously did not touch the sink. Track a terminal send failure and skip this best-effort flush in that case, while retaining it for sends that were dropped while pending.

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.

Addressed in c1c198c. SinkStreamTransport now records a send that returned an error, and close skips the best-effort flush after one, so a failed send followed by a normal shutdown no longer polls the sink again. A send future dropped while pending leaves the record unchanged, so the message it left buffered is still flushed; the four existing tests are unchanged and pass.

New test: a sink that fails once and panics on any later poll. It fails on b2e72ed and passes with the commit.

Two notes for the reviewers. The Sink docs state the "no more methods should be called" rule for poll_close; for poll_ready and poll_flush they say the sink may permanently be unable to receive items. Not polling it again is the safe reading in both cases. AsyncRwTransport needs no such guard: its FramedWrite retries the write when flushed again after an error.

A send that returned an error may leave the sink permanently unusable,
and a sink may panic when polled after a failure. SinkStreamTransport
now records a failed send and its close no longer flushes the sink
after one, so the failure is not turned into a panic at shutdown. A
send future dropped while pending leaves the record unchanged: without
an earlier failure, close still flushes the message it left buffered.

AsyncRwTransport is unchanged: its FramedWrite retries the write when
flushed again after an error.

@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: c1c198caff

ℹ️ 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".

// polled after a failure. The sink itself is not closed, as before.
let mut write = self.sink.lock().await;
if !write.failed {
super::flush_before_close::<TxJsonRpcMessage<Role>, _>(&mut write.sink).await;

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 Mark the sink failed when the close flush errors

When poll_flush first fails during close itself rather than during send, flush_before_close discards the inner Si::Error and this path leaves write.failed false. close nevertheless returns Ok(()) and retains the sink, so a caller that invokes close again will poll a sink that the Sink contract permits to be permanently unusable after that error; such sinks can panic on the second close. Propagate whether the helper saw an inner error, or otherwise consume or mark the sink, before returning.

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.

Addressed in 6b773df. flush_before_close now reports how the flush ended (flushed, failed, or timed out), and SinkStreamTransport::close records a failed flush the same way it records a failed send, so a second close does not poll the sink again. close still returns Ok(()).

A flush that timed out is not marked: it is still pending, not failed, so a later close flushes again within the same bound. AsyncRwTransport ignores the result, since its close takes the writer out and drops it.

New test: a sink whose flush fails inside close and which panics on any later poll; close twice, no panic. It fails on c1c198c and passes with the commit; the five existing tests are unchanged.

I also checked the remaining paths: the transport touches its sink only in send and close, so no other place polls it after an error. A send after a failed send still reaches the sink, as before the PR; that is the caller's choice.

flush_before_close now reports how the flush ended: flushed, failed or
timed out. SinkStreamTransport::close records a failed flush as it
records a failed send, so a second close does not poll a sink that may
be permanently unusable. A flush that timed out has not failed (it is
still pending), so a later close flushes again, bounded again.
AsyncRwTransport ignores the result: its close takes and drops the
writer, so nothing polls it again.

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

Re-verified at 6b773df0; the four commits since my last review all hold up.

Runs at this head

  • cargo test -p rmcp --test test_sink_stream_flush --features "server,client,transport-async-rw,transport-io" → 6 passed, including the two new failure-path tests.
  • cargo test -p rmcp --test test_progress_flush --features "server,client,transport-async-rw,transport-io" → 5 passed, so the AsyncRwTransport path still behaves after the helper signature change.
  • cargo clippy -p rmcp --features "server,client,transport-async-rw,transport-io" --all-targets -- -D warnings → clean (34s).

Reading the new commits

  • SinkState.failed is set only on a real error, not on a dropped future, so the drop-mid-flush case still flushes at close — that is the right split, and close_does_not_poll_a_sink_after_a_failed_send pins both halves (poll_ready and poll_flush).
  • A timed-out close flush leaves failed false and the next close flushes again, bounded again; second_close_does_not_poll_a_sink_whose_close_flush_failed covers the failed case. Correct distinction: a timeout is not a failure.
  • AsyncRwTransport::close discards the result with a comment explaining why (the writer is taken and dropped), which is exactly the part a reader would otherwise doubt.
  • The bounded-test comment (c0e8a8e) is what I asked for; the Transport::close doc line matches the behaviour.

One gap to close before this is ready

failed is consulted by close but not by send, so the protection the new comment describes is only half true for users of the public type. With your own FailOnce sink, the second send after a failed send panics instead of returning an error:

let mut t = SinkStreamTransport::new(FailOnce { at_flush: false, failed: false }, futures::stream::empty());
assert!(Transport::<RoleServer>::send(&mut t, progress.clone()).await.is_err()); // first: Err
Transport::<RoleServer>::send(&mut t, progress).await;                          // panics: "poll_ready after the sink failed"

That is defensible on Sink contract grounds — after an error the sink is unusable, and poll_ready may panic — but then the type docs should say so: "after a send or flush error, the transport must not be used again except for close, which will not poll the sink." Right now the SinkState::failed comment says close does not poll it again, which reads as if every path is guarded; someone who catches the error and retries a different message would hit the panic the flag was added to avoid.

I can see why the check is not in send: Si::Error is not Clone, so a stored error cannot be handed out twice, and synthesizing one is not possible. A doc sentence is the pragmatic fix; if you would rather guard the code path, the flag would have to turn into Option<Si::Error> and be taken once, which is a worse trade.

Nothing else from me. Once that sentence is in, I am happy to approve this head.

…er an error

The failed-sink record is consulted by close only. The type docs now state
the rule for users of the public type: after a send or flush error the
transport must not be used again except for close, which then does not
poll the sink; a send after a failed one still reaches the sink, and a
sink may panic when polled after a failure. The comment on the record
says the same, so it no longer reads as if every path were guarded.
@joulook

joulook commented Dec 6, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for re-verifying, and for the reproduction with FailOnce.

Agreed on both points: the comment read as if every path were guarded, and a doc sentence is the better trade than turning the flag into an Option<Si::Error> taken once. Done in ffc5034, docs only:

  • SinkStreamTransport now has type docs stating the rule: after send returns an error, or after the flush in close fails, the transport must not be used again except for close, which then does not poll the sink. They also say plainly that send is not guarded, so a send after a failed one reaches the sink again and the sink may panic.
  • The comment on SinkState::failed now says that only close consults the flag and points to the type docs.

No code change, so the runs you recorded at 6b773df still apply.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants