Repository navigation
perf: transfer broadcast chunks to the first listener - #219
Conversation
[Medium impact] The PR appears safe to merge; no blocking issues were found. SummaryAdds
No actionable issues were found. The previous-review comparison was not used because the merge bases differed; the full PR diff was reviewed. Reviews (4) · Last reviewed commit: "Merge branch 'main' into perfloop-pr-ope..." · Reviewed by Greptile |
Signed-off-by: Perfloop Agent <[email protected]>
Signed-off-by: Perfloop Agent <[email protected]>
Signed-off-by: Perfloop Agent <[email protected]>
Signed-off-by: Perfloop Agent <[email protected]>
Conflicts resolved: README.md keeps both appended lines; broadcaster.go Complete() uses the PR's closeWithError with main's b.err; caching.go keeps the PR's cachePipeReadError wrapping alongside main's relayErr branch.
PR #263 fixed two real bugs: a slow-consumer disconnect dropped its ErrSlowConsumer on the floor when the listener's buffer was full (so the cache listener drained to a clean close and committed a truncated body under the full Content-Length), and an upstream mid-body drop surfaced as io.ErrUnexpectedEOF, which the ocache backend accepted as "small value, done". The cachePipeReadError wrapping for the second bug is kept as is. Its fix for the first bug was unsafe: closeWithError made room for the error chunk by receiving one queued chunk. Channels are FIFO, so that removed the OLDEST unread chunk, and a consumer that had read chunks 0..k-1 next received k+1 at k's offset - wrong bytes on the wire before the error arrived. Replace the displacement with a terminal-error field on Listener: - closeWithError now records the error in Listener.termErr (written under Broadcaster.mu before close(ch)), tries a best-effort non-blocking send of Chunk{Err: err}, and closes the channel. Queued data chunks are never dropped or reordered. - Listener.Err() exposes the terminal error. It is valid once Chunks() has closed: the close happens-before the receive that observes it, so consumers read it without extra locking after their range loop ends. - Both consumers honour it. writeChunksToResponse (client path) returns Err() after the loop exactly as it would an error chunk, so a disconnected client never gets a clean EOF with a short body. setupCacheListener (cache path) sets chunkErr from Err() when the loop ended on a clean close, so the pipe fails and no metadata is committed. - Subscribe's already-done path records termErr too, for consistency. Defense in depth: PutWithMetaStreamIfVersion now counts the bytes the store consumed and refuses the meta commit with ErrBodyLengthMismatch when they differ from meta.ContentLength (short or long), mirroring the io.ReadFull guard in putBlocksFromStream. This closes the root cause behind #251 and #249 even if some future producer loses the error signal. The versioned body is left to age out via TTL, as with a lost precondition. Tests: the slow-consumer test now reads Err() after the loop (the error chunk is best-effort on a full queue); new broadcaster tests assert that a full-buffer disconnect delivers every queued chunk in order with no hole and then surfaces the error via Err(), and that a failed Complete on a full queue does the same; new cache tests assert a short or long body is not committed and an exact or unknown length still is. The PR's handler-level tests pass unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NGTev5ePU5jHubGtdoUfK6
Route every broadcast disconnect through Listener.closeWithError: the disconnectSlowConsumer helper used by both the copying Broadcast path and the ownership-transferring broadcastOwnedLocked path now records termErr, queues a best-effort error chunk, and closes the channel without displacing queued data. Complete() keeps #260's headerCh/headerErr behaviour and #263's closeWithError completion. On the owned path a chunk rejected by a full owner queue is never queued, so the caller keeps and releases that buffer; a chunk already queued stays with its listener and is released by the consumer's drain. Adds a test pinning that owned-path disconnect contract. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NGTev5ePU5jHubGtdoUfK6
#263 is now on main; keep disconnectSlowConsumer (which routes through closeWithError) and the owned-chunk disconnect test. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NGTev5ePU5jHubGtdoUfK6
ovaistariq
left a comment
There was a problem hiding this comment.
Reviewed: ownership transfer of broadcast chunks to the first listener with copies for the others; buffer release traced for every disconnect path and pinned by test; disconnects route through closeWithError.
|
🎉 This PR is included in version 1.22.3 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |
Avoid copying each upstream body chunk for the first broadcast listener.
BroadcastOwnedprepares independent chunks for the other listeners, then transfers the input buffer to the first listener with room.streamFromUpstreamleases pooled buffers for default-sized chunks and keeps the existing reusable path for larger configured chunks. The existingBroadcastAPI remains copy-preserving for callers that do not transfer ownership.Added ownership and isolation tests for transfer, later listeners, unaccepted input, and slow consumers. Added real HTTP cache-miss benchmarks for the fetching client and inline cache listener, plus streaming benchmarks that check response bytes, clone work, and CPU and heap profiles.
Checks:
make lint-cimake buildmake testmake test-integrationmake test-racemake test-coveragemake lintWorkload:
4 MiB streamed body with one consuming listenerB/opclone-bytes/opmemmove-bytes/opWorkload:
4 MiB streamed body with one pre-stream coalesced listenerB/opclone-bytes/opmemmove-bytes/opWorkload:
4 MiB full GET cache miss with fetching client onlyB/opGenerated by Perfloop. Measurements and checks.
Note
Medium Risk
Changes buffer ownership on the hot upstream streaming and broadcast path; incorrect use could cause data races or double-free, though the split API and tests mitigate this.
Overview
Adds
BroadcastOwned, which gives the caller’s buffer to the first listener with queue space and still copies for every other listener, whileBroadcaststays copy-only so reusable read buffers cannot race with consumers. Slow-consumer handling is centralized indisconnectSlowConsumer.streamFromUpstreamnow leases pooled chunk buffers for default-sized reads and usesBroadcastOwnedwhen transfer succeeds (re-leasing before the next read); larger configured chunk sizes keep the existing reusable slice +Broadcastpath.New unit tests cover ownership transfer, buffer isolation, slow consumers, and unaccepted input. New HTTP/stream benchmarks measure allocations and clone/memmove bytes for single-listener, coalesced, and cache-listener GET paths.
Reviewed by Cursor Bugbot for commit 83385de. Bugbot is set up for automated code reviews on this repo. Configure here.