Repository navigation
perf: zstd implement Pooling + DecodeAll with no new reader. - #1331
Conversation
zeroshade
left a comment
There was a problem hiding this comment.
Nice work — the design is right, the risky part (bounding the decode to the destination buffer) is handled correctly, and the tests are unusually thorough for a perf PR. Two minor notes and one question inline; nothing blocking.
What I verified locally
-
go build+go vetclean,go test -race ./arrow/ipc/passes. The change is fully contained —decompressorhas no other implementors or callers outsidearrow/ipc. -
Perf claim reproduces.
codec=zstd/1cols/64batches/stream,-benchtime 20x:main PR ns/op 2,063,127 385,696 (-81%) B/op 1,899,226 686,102 (-64%) allocs/op 3,490 1,241 (-64%) -
Never calling
zstd.Decoder.Close()does not leak goroutines.NewReader(nil)returns at theif r == nilguard befored.Reset(r), so no stream goroutines are ever started; a pooled decoder only retains ablockDec/frameDec, reclaimed by GC when the pool entry is dropped. Worth calling out because it's the obvious thing a future reader will try to "fix". -
Bounding is sound even for frames with unknown content size. I initially suspected
WithDecodeAllCapLimitwas a no-op forfcsUnknownframes, since the explicitlimitToCapcheck inDecodeAllsits insideif frame.FrameContentSize != fcsUnknown. It isn't:frameDec.runDecodersetsmaxSyncLen = cap(dst)-len(dst)unconditionally underlimitToCap, and re-checkslen(history.b) > cap(dst)after every block. Overshoot is bounded by one block. -
wg.Goneeds Go 1.25+;go.modisgo 1.26.0and the CI matrix is[1.26, 1.27], so that's fine. ASF headers present on both new files.
Leaving this as a comment rather than an approval only because of the question on the strictness change below — happy to approve once that's settled.
zeroshade
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround — all four points from the first pass are addressed in 0a1e5a5, and the strictness change is now documented. Re-ran the new tests under -race plus the full arrow/ipc suite locally; all green. Also confirmed the pooled decoder doesn't retain the caller's dst (runDecoder restores history.b) and that frames written without a content size (what our own writer produces for buffers > 128 KiB) are still bounded and size-checked.
A few non-blocking nits inline — fine to address here or in a follow-up.
This review was drafted by an AI-assisted tool and
confirmed by an Apache Arrow maintainer. The maintainer
approving this PR has read the findings and signed off. If
something feels off, please reply on the PR and a maintainer
will follow up.More on how Apache Arrow handles maintainer review:
CONTRIBUTING.md.
|
@zeroshade feedback fixed. |
### Rationale for this change `getCompressor` builds a new `zstd.Encoder` for every writer. A new encoder allocates its window and match tables, about 2.3 MB at the default level, before it compresses anything. A service that writes each table or batch with its own writer pays that on every call. In our case, one writer per series in each Grafana query, this was about 63% of all allocations on that path, and the GC load that followed was a third of the CPU. #1331 pooled the zstd decoders for the same reason, and `parquet/compress` already pools its zstd encoders (#717). This does the same for the IPC writer. ### What changes are included in this PR? - zstd encoders come from a `sync.Pool`, one per encoder level: the library default, plus the four `zstd.EncoderLevel` presets that `WithZstdLevel` maps to. An encoder is only reused for the level it was built with. The encoder options are unchanged. - `Writer.Close`, `FileWriter.Close` and `GetRecordBatchPayload` return the encoders. A writer keeps its encoder for its whole lifetime, so a long-lived stream sees no change. - Before going back to the pool, the encoder is `Reset(nil)`. That waits for any in-flight block goroutines (also after a failed `Write`) and drops the reference to the last output buffer. - lz4 is unchanged. ### Are these changes tested? New `TestZstdEncoderPool`: - `Close` returns every encoder, for `Writer` and `FileWriter` with `WithCompressConcurrency(4)`. This fails without the change. - The output of a reused encoder is byte-identical to its first use, after a larger stream went through it in between. - 16 concurrent writers with mixed sizes and compression concurrency round-trip correctly under `-race`. `go test -race ./arrow/ipc/... ./arrow/flight/...` passes, and `golangci-lint run ./arrow/ipc/` is clean. Run on macOS only. New `BenchmarkWriterZstd`. Old and new test binaries were run alternately, 8 runs each, on an Apple M2 Pro: ``` sec/op B/op allocs/op writer_per_record/256rows 246.4µ → 4.5µ (-98%) 2279Ki → 7.1Ki (-99.7%) 72 → 44 writer_per_record/4096rows 280.7µ → 21.8µ (-92%) 2296Ki → 24.7Ki (-98.9%) 72 → 44 one_writer/256rows 2.98µ → 2.98µ (~) 2.755Ki → 2.755Ki (~) 23 → 23 one_writer/4096rows 19.4µ → 19.6µ (~) 19.54Ki → 19.54Ki (~) 23 → 23 ``` ### Are there any user-facing changes? No API change. Writers that use zstd allocate less. Idle encoders can stay in the pool until GC clears it, at most one per level and per P.
) ### Rationale for this change Fixes #1629. Since #1331, zstd decoders come from a process-wide `sync.Pool`. A `zstd.Decoder` owns a channel that every `DecodeAll` receives from, and a channel made inside a `testing/synctest` bubble must not be used outside that bubble. When a reader inside a bubble created a decoder, the pool could hand it to a reader outside the bubble or in another bubble, and the runtime aborted with `fatal error: receive on synctest channel from outside bubble`. A decoder made outside a bubble is safe to use inside one, so the crash only happens after a decoder was created in a bubble. ### What changes are included in this PR? - `Reader` and `FileReader` each keep their own idle zstd decoders, and the process-wide decoder pool is removed. Go's HTTP/2 server made the same change for the same problem (golang/go#75674). - `FileReader.RecordBatchAt` may be called concurrently, so a `FileReader` keeps as many decoders as were in use at once. - Encoders stay pooled process-wide. They are only used through the streaming API, which keeps no channel between streams, so an encoder used inside a bubble is safe to reuse outside it. A comment on `zstdEncoderPools` records why `EncodeAll` must not be used there. Cost, from `BenchmarkReaderCompressed`, which creates a new reader on every iteration: one decoder per reader, about 1.5 KiB and 11 allocations, with no measurable change in time. ### Are these changes tested? Yes. ### Are there any user-facing changes? Reading zstd-compressed IPC data inside `testing/synctest` bubbles no longer crashes the process. There is no API change.
Rationale for this change
Performance improvement on the zstd path.
What changes are included in this PR?
sync.Poolinstead of being created for every record batch, and each compressed buffer is decoded with oneDecodeAllcall straight into the destination buffer (decoder built withWithDecoderConcurrency(1)andWithDecodeAllCapLimit(true))instead ofReset(bytes.NewReader)+io.ReadFullon a streaming decoder.lz4.Reader; the library already pools its large block buffers internally. (Only a Decompress method wrapper was added.)Are these changes tested?
Added tests + benchmark for zstd (the changed path) - every case improves
Are there any user-facing changes?
Strictness change for zstd. A buffer whose decompressed size differs from the uncompressed-length prefix now returns an error. This matches other arrow libraries (e.g.: arrow-cpp)