Skip to content

perf: transfer broadcast chunks to the first listener - #219

Merged
ovaistariq merged 11 commits into
mainfrom
perfloop-pr-open-1y6q4gs5fr
Oct 21, 2026
Merged

ovaistariq merged 11 commits into
mainfrom
perfloop-pr-open-1y6q4gs5fr

Conversation

@perfloop

@perfloop perfloop Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Avoid copying each upstream body chunk for the first broadcast listener.

BroadcastOwned prepares independent chunks for the other listeners, then transfers the input buffer to the first listener with room. streamFromUpstream leases pooled buffers for default-sized chunks and keeps the existing reusable path for larger configured chunks. The existing Broadcast API 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-ci
  • make build
  • make test
  • make test-integration
  • make test-race
  • make test-coverage
  • make lint

Workload: 4 MiB streamed body with one consuming listener

Metric Before After Change
B/op 115269 49809 56.8% lower
clone-bytes/op 4194304 0 100% lower
memmove-bytes/op 4194304 0 100% lower

Workload: 4 MiB streamed body with one pre-stream coalesced listener

Metric Before After Change
B/op 162862 97392 40.2% lower
clone-bytes/op 8388608 4194304 50% lower
memmove-bytes/op 8388608 4194304 50% lower

Workload: 4 MiB full GET cache miss with fetching client only

Metric Before After Change
B/op 121926 56458 53.7% lower
Checks: 7 passed.

Generated 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, while Broadcast stays copy-only so reusable read buffers cannot race with consumers. Slow-consumer handling is centralized in disconnectSlowConsumer.

streamFromUpstream now leases pooled chunk buffers for default-sized reads and uses BroadcastOwned when transfer succeeds (re-leasing before the next read); larger configured chunk sizes keep the existing reusable slice + Broadcast path.

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.

@greptile-apps

greptile-apps Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issues were found.

Summary

Adds BroadcastOwned to transfer an upstream buffer to one listener while giving other listeners independent copies.

  • Upstream streams hand one listener the read buffer without copying it.

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

perfloop-agent and others added 9 commits October 18, 2026 05:07
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 ovaistariq 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.

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.

@ovaistariq
ovaistariq merged commit f2adced into main Oct 21, 2026
8 checks passed
@ovaistariq
ovaistariq deleted the perfloop-pr-open-1y6q4gs5fr branch October 21, 2026 21:19
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 21, 2026
@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.22.3 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants