Skip to content

fix(kit/jsonrpc): deliver a reply that arrives as the connection closes - #40

Merged
bketelsen merged 1 commit into
mainfrom
kit/jsonrpc-reply-before-close
Oct 28, 2026
Merged

bketelsen merged 1 commit into
mainfrom
kit/jsonrpc-reply-before-close

Conversation

@frostyard-machines

Copy link
Copy Markdown
Contributor

What

kit/jsonrpc: Client.Call can lose a reply that arrives just before the server closes the connection.

Call waits on its reply channel and on Done in one select. A server that replies and then closes (frostnotes' rpc.shutdown does) can make both ready at once, and select picks one at random: the call then fails with connection closed although its reply came. This made frostnotes' rpc.shutdown tests flaky under -race.

Fix

readLoop hands every reply to its call's buffered channel before it closes Done. So when Call sees Done, it now first takes a reply that is already in its channel, and reports the closed connection only when none is there. The decode of a reply moves to a small helper, callResult. The kit's API does not change.

Test

TestAReplyBeforeTheCloseReachesTheCall wraps the client's end of a pipe so that Write returns only after Done is closed: the reply and Done are both ready when Call starts to wait. It runs 64 calls.

  • Before the fix: it failed on every run (jsonrpc: connection closed), 3 of 3.
  • After the fix: go test -race -count=200 -run TestAReplyBeforeTheCloseReachesTheCall ./jsonrpc/ passes, and go test -race -count=20 ./jsonrpc/ passes.
  • make check passes.

After the merge

  • Brian tags kit/v0.3.1 (the tag is his).
  • Then Irulan opens a frostnotes PR that bumps the kit to kit/v0.3.1.

Client.Call waited on its reply channel and on Done in one select. When
the server replied and then closed the connection (as a shutdown method
does), both could be ready, and select picked one at random: half the
time the call failed with "connection closed" although its reply had
come. readLoop hands over every reply before it closes Done, so Call now
takes a reply that is already there before it reports the closed
connection.

The new test makes Write return only after Done, so both are ready when
Call waits; it failed every run before the fix.
@frostyard-machines frostyard-machines added the ready-for-human Reviewed, CI green: ready for Brian to review and merge label Oct 28, 2026
@bketelsen
bketelsen merged commit 488fe6e into main Oct 28, 2026
7 checks passed
@bketelsen
bketelsen deleted the kit/jsonrpc-reply-before-close branch October 28, 2026 10:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Reviewed, CI green: ready for Brian to review and merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants