Skip to content

perf: zstd implement Pooling + DecodeAll with no new reader. - #1331

Merged
zeroshade merged 5 commits into
apache:mainfrom
samueleresca:zstd-pooling
Oct 12, 2026
Merged

zeroshade merged 5 commits into
apache:mainfrom
samueleresca:zstd-pooling

Conversation

@samueleresca

@samueleresca samueleresca commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Rationale for this change

Performance improvement on the zstd path.

What changes are included in this PR?

  • zstd: decoders come from a sync.Pool instead of being created for every record batch, and each compressed buffer is decoded with one DecodeAll call straight into the destination buffer (decoder built with WithDecoderConcurrency(1) and WithDecodeAllCapLimit(true)) instead of Reset(bytes.NewReader) + io.ReadFull on a streaming decoder.
  • lz4 : no functional change. It keeps its original per-batch 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

SMALL buffers (4 KiB per column)
time      : -70.5% to -78.3% in all 8 cases
            1 col,  1 batch  (stream)  9.89 us  ->  2.92 us
            1 col, 64 batches (stream)  592.9 us -> 128.7 us
            16 cols, 64 batches (file)  3.67 ms  ->  894 us
B/op      : -60% (1 col, 1 batch), -64% (1 col, 64 batches), -22% (16 cols)
allocs/op : -45% (1 col, 1 batch) to -70% (16 cols, 64 batches)

LARGE buffers
per column   time                          B/op                        allocs/op
16 KiB       77.6 us  -> 24.0 us  (-69%)   306.9 KiB -> 157.1 KiB (-49%)   184 -> 78  (-58%)
256 KiB      796.7 us -> 191.7 us (-76%)   20.6 MiB  -> 2.05 MiB  (-90%)   185 -> 81  (-56%)
4 MiB        4.63 ms  -> 3.05 ms  (-34%)   51.1 MiB  -> 32.1 MiB  (-37%)   189 -> 79  (-58%)

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)

@samueleresca samueleresca changed the title zstd: implement Pooling + DecodeAll with no new reader. perf: zstd implement Pooling + DecodeAll with no new reader. Sep 20, 2026
@samueleresca
samueleresca marked this pull request as ready for review September 21, 2026 18:56

@zeroshade zeroshade left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 vet clean, go test -race ./arrow/ipc/ passes. The change is fully contained — decompressor has no other implementors or callers outside arrow/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 the if r == nil guard before d.Reset(r), so no stream goroutines are ever started; a pooled decoder only retains a blockDec/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 WithDecodeAllCapLimit was a no-op for fcsUnknown frames, since the explicit limitToCap check in DecodeAll sits inside if frame.FrameContentSize != fcsUnknown. It isn't: frameDec.runDecoder sets maxSyncLen = cap(dst)-len(dst) unconditionally under limitToCap, and re-checks len(history.b) > cap(dst) after every block. Overshoot is bounded by one block.

  • wg.Go needs Go 1.25+; go.mod is go 1.26.0 and 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.

Comment thread arrow/ipc/compression.go Resolved
Comment thread arrow/ipc/compression.go Resolved
Comment thread arrow/ipc/compression.go Resolved
Comment thread arrow/ipc/compression_test.go Resolved

@zeroshade zeroshade left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread arrow/ipc/compression.go Resolved
Comment thread arrow/ipc/file_reader.go Resolved
@samueleresca

Copy link
Copy Markdown
Member Author

@zeroshade feedback fixed.

@zeroshade
zeroshade merged commit 7c13a60 into apache:main Oct 12, 2026
23 checks passed
zeroshade pushed a commit that referenced this pull request Oct 29, 2026
### 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.
zeroshade added a commit that referenced this pull request Nov 20, 2026
)

### 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.
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