Skip to content

servlet: Don't rely on racy headersSent when writing trailers - #13211

Merged
shivaspeaks merged 1 commit into
grpc:masterfrom
shivaspeaks:race-fix
Nov 30, 2026
Merged

shivaspeaks merged 1 commit into
grpc:masterfrom
shivaspeaks:race-fix

Conversation

@shivaspeaks

@shivaspeaks shivaspeaks commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Since #13195, Sink's writes are serialized by a lock and ignored once trailers are written. But writeTrailers() still decided whether it must write headers from AbstractServerStream's headersSent, which is set before Sink.writeHeaders() acquires the lock and is read without it.

If cancel() closes the stream on a container thread in that window (e.g. AsyncListener.onError() after the client resets the stream), writeTrailers() sees headersSent == true and skips the headers and setTrailerFields(). The application's writeHeaders() then finds the stream closed and is ignored, so the response completes without "content-type: application/grpc" or grpc-status trailers.

Conversely, if writeHeaders() wins the lock after cancel() has read
headersSent == false, writeTrailers() calls setTrailerFields() again, on a possibly committed response, which throws IllegalStateException.

Track in the Sink, under its lock, whether headers have been written and use that instead of the headersSent argument. It is set before flushing, so a flush failure, which re-enters writeTrailers() via cancel(), doesn't write the headers again.

ServletServerStreamTest forces the interleaving deterministically by
holding the Sink's lock while the stream is cancelled.

cl/1031755943

@shivaspeaks
shivaspeaks merged commit c78815a into grpc:master Nov 30, 2026
17 of 18 checks passed
@shivaspeaks
shivaspeaks deleted the race-fix branch November 30, 2026 16:03
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.

2 participants