This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git


The following commit(s) were added to refs/heads/main by this push:
     new 9e9c059f fix(arrow/ipc): keep zstd decoders with the reader that made 
them (#1630)
9e9c059f is described below

commit 9e9c059f378ae3c186c52a60969b42c85a9dbcc2
Author: Matt Topol <[email protected]>
AuthorDate: Fri Nov 20 12:20:52 2026 -0500

    fix(arrow/ipc): keep zstd decoders with the reader that made them (#1630)
    
    ### 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 u [...]
    
    ### 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.
---
 arrow/ipc/compression.go               | 72 ++++++++++++++++++++++++----------
 arrow/ipc/compression_test.go          | 61 ++++++++++++++++++++++++----
 arrow/ipc/file_reader.go               | 70 +++++++++++++++++----------------
 arrow/ipc/file_reader_internal_test.go |  4 +-
 arrow/ipc/reader.go                    | 32 ++++++---------
 5 files changed, 156 insertions(+), 83 deletions(-)

diff --git a/arrow/ipc/compression.go b/arrow/ipc/compression.go
index 7027d448..d4aed4d7 100644
--- a/arrow/ipc/compression.go
+++ b/arrow/ipc/compression.go
@@ -57,6 +57,12 @@ type zstdCompressor struct {
 // level, 1-4 for the zstd.EncoderLevel a WithZstdLevel value maps to. A new
 // encoder allocates its window and match tables (about 2 MB at the default
 // level), which dominates the cost of compressing a small record batch.
+//
+// Unlike decoders, encoders can be shared process-wide: they are only used
+// through the streaming API (Reset, Write, Close), which keeps no channel
+// between streams, so an encoder used inside a testing/synctest bubble can be
+// reused outside it. EncodeAll would break that, since it receives from a
+// channel the encoder makes on first use.
 var zstdEncoderPools [zstd.SpeedBestCompression + 1]sync.Pool
 
 func zstdEncoderPoolIndex(zstdLevel int) int {
@@ -135,25 +141,46 @@ type decompressor interface {
        Close()
 }
 
-var zstdDecompressorPool = sync.Pool{
-       New: func() any {
-               // WithDecoderConcurrency(1): Each pooled decoder is used by 
one goroutine at a time, so a single
-               // block decoder is enough. The default would create up to four 
that
-               // could never run in parallel;
-               //
-               // WithDecodeAllCapLimit(true): The cap limit bounds DecodeAll 
to cap(dst), so a frame claiming a
-               // larger content size can't allocate beyond the buffer the 
caller
-               // sized from the uncompressed length prefix.
-               dec, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1), 
zstd.WithDecodeAllCapLimit(true))
-               if err != nil {
-                       panic(err)
-               }
-               return &zstdDecompressor{Decoder: dec}
-       },
+// zstdDecoders reuses zstd decoders within one reader. Decoders are not
+// shared between readers: a zstd.Decoder owns a channel, and a channel made
+// inside a testing/synctest bubble must not be used outside that bubble, so a
+// decoder has to stay with the reader whose goroutines created it.
+//
+// The zero value is ready to use. It is safe for concurrent use, since
+// FileReader.RecordBatchAt may be called concurrently, and keeps at most as
+// many decoders as were in use at once.
+type zstdDecoders struct {
+       mu   sync.Mutex
+       idle []*zstdDecompressor
+}
+
+func (c *zstdDecoders) get() *zstdDecompressor {
+       c.mu.Lock()
+       if n := len(c.idle); n > 0 {
+               z := c.idle[n-1]
+               c.idle = c.idle[:n-1]
+               c.mu.Unlock()
+               return z
+       }
+       c.mu.Unlock()
+
+       // WithDecoderConcurrency(1): Each decoder is used by one goroutine at 
a time, so a single
+       // block decoder is enough. The default would create up to four that
+       // could never run in parallel;
+       //
+       // WithDecodeAllCapLimit(true): The cap limit bounds DecodeAll to 
cap(dst), so a frame claiming a
+       // larger content size can't allocate beyond the buffer the caller
+       // sized from the uncompressed length prefix.
+       dec, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1), 
zstd.WithDecodeAllCapLimit(true))
+       if err != nil {
+               panic(err)
+       }
+       return &zstdDecompressor{Decoder: dec, owner: c}
 }
 
 type zstdDecompressor struct {
        *zstd.Decoder
+       owner *zstdDecoders
 }
 
 func (z *zstdDecompressor) Decompress(dst, src []byte) error {
@@ -174,12 +201,15 @@ func (z *zstdDecompressor) Decompress(dst, src []byte) 
error {
        return nil
 }
 
-// Close returns the decoder to the pool. z.Decoder.Close() is deliberately
-// not called: zstd.NewReader(nil) starts no goroutines, so a pooled decoder
+// Close returns the decoder to its reader. z.Decoder.Close() is deliberately
+// not called: zstd.NewReader(nil) starts no goroutines, so an idle decoder
 // only holds GC-reclaimable state and there is nothing to tear down. Closing
 // it would make the decoder unusable for the next borrower.
 func (z *zstdDecompressor) Close() {
-       zstdDecompressorPool.Put(z)
+       c := z.owner
+       c.mu.Lock()
+       c.idle = append(c.idle, z)
+       c.mu.Unlock()
 }
 
 type lz4Decompressor struct {
@@ -213,12 +243,14 @@ func (z *lz4Decompressor) Close() {
        z.Reset(nil)
 }
 
-func getDecompressor(codec flatbuf.CompressionType) decompressor {
+// getDecompressor returns a decompressor for codec. zstd decoders come from,
+// and return to, zd.
+func getDecompressor(codec flatbuf.CompressionType, zd *zstdDecoders) 
decompressor {
        switch codec {
        case flatbuf.CompressionTypeLZ4_FRAME:
                return &lz4Decompressor{Reader: lz4.NewReader(nil)}
        case flatbuf.CompressionTypeZSTD:
-               return zstdDecompressorPool.Get().(*zstdDecompressor)
+               return zd.get()
        }
        return nil
 }
diff --git a/arrow/ipc/compression_test.go b/arrow/ipc/compression_test.go
index 7e3c41ba..88984913 100644
--- a/arrow/ipc/compression_test.go
+++ b/arrow/ipc/compression_test.go
@@ -25,6 +25,7 @@ import (
        "runtime"
        "sync"
        "testing"
+       "testing/synctest"
 
        "github.com/apache/arrow-go/v18/arrow/array"
        "github.com/apache/arrow-go/v18/arrow/internal/flatbuf"
@@ -68,7 +69,7 @@ func compressibleBytes(n int, seed int64) []byte {
 func TestDecompressorRoundTrip(t *testing.T) {
        for _, tc := range testCodecs {
                t.Run(tc.name, func(t *testing.T) {
-                       dec := getDecompressor(tc.codec)
+                       dec := getDecompressor(tc.codec, new(zstdDecoders))
                        defer dec.Close()
 
                        for i, n := range []int{1, 100, 4096, 300_000, 17, 
300_000} {
@@ -84,7 +85,7 @@ func TestDecompressorRoundTrip(t *testing.T) {
 func TestDecompressorEmptyDestination(t *testing.T) {
        for _, tc := range testCodecs {
                t.Run(tc.name, func(t *testing.T) {
-                       dec := getDecompressor(tc.codec)
+                       dec := getDecompressor(tc.codec, new(zstdDecoders))
                        defer dec.Close()
                        assert.NoError(t, dec.Decompress(nil, nil))
                        assert.NoError(t, dec.Decompress([]byte{}, []byte{1, 2, 
3}))
@@ -97,7 +98,7 @@ func TestDecompressorSizeMismatch(t *testing.T) {
 
        for _, tc := range testCodecs {
                t.Run(tc.name, func(t *testing.T) {
-                       dec := getDecompressor(tc.codec)
+                       dec := getDecompressor(tc.codec, new(zstdDecoders))
                        defer dec.Close()
                        compressed := compressBuffer(t, tc.codec, want)
 
@@ -114,7 +115,7 @@ func TestDecompressorSizeMismatch(t *testing.T) {
        // zstd frames declare their content size, so a prefix that is too small
        // is caught instead of silently truncating.
        t.Run("zstd/short-destination", func(t *testing.T) {
-               dec := getDecompressor(flatbuf.CompressionTypeZSTD)
+               dec := getDecompressor(flatbuf.CompressionTypeZSTD, 
new(zstdDecoders))
                defer dec.Close()
                assert.Error(t, dec.Decompress(make([]byte, len(want)-1), 
compressBuffer(t, flatbuf.CompressionTypeZSTD, want)))
        })
@@ -125,7 +126,7 @@ func TestZstdDecompressorBoundedByDestination(t *testing.T) 
{
        compressed := compressBuffer(t, flatbuf.CompressionTypeZSTD, 
make([]byte, 64<<20))
        require.Less(t, len(compressed), 64<<10)
 
-       dec := getDecompressor(flatbuf.CompressionTypeZSTD)
+       dec := getDecompressor(flatbuf.CompressionTypeZSTD, new(zstdDecoders))
        defer dec.Close()
 
        dst := make([]byte, 16)
@@ -153,7 +154,7 @@ func 
TestZstdDecompressorRejectsHugeDeclaredSizeWithoutAllocating(t *testing.T)
        require.True(t, hdr.HasFCS)
        require.Equal(t, uint64(declared), hdr.FrameContentSize)
 
-       dec := getDecompressor(flatbuf.CompressionTypeZSTD)
+       dec := getDecompressor(flatbuf.CompressionTypeZSTD, new(zstdDecoders))
        defer dec.Close()
 
        // warm up, so decoder state that is created lazily isn't counted below
@@ -181,7 +182,7 @@ func 
TestZstdDecompressorRejectsHugeDeclaredSizeWithoutAllocating(t *testing.T)
 func TestZstdDecompressorSpareCapacity(t *testing.T) {
        const n, capacity = 100, 128
 
-       dec := getDecompressor(flatbuf.CompressionTypeZSTD)
+       dec := getDecompressor(flatbuf.CompressionTypeZSTD, new(zstdDecoders))
        defer dec.Close()
 
        compress := func(size int) []byte {
@@ -219,7 +220,7 @@ func TestDecompressorRecoversAfterTruncatedInput(t 
*testing.T) {
 
        for _, tc := range testCodecs {
                t.Run(tc.name, func(t *testing.T) {
-                       dec := getDecompressor(tc.codec)
+                       dec := getDecompressor(tc.codec, new(zstdDecoders))
                        defer dec.Close()
                        compressed := compressBuffer(t, tc.codec, want)
 
@@ -286,3 +287,47 @@ func TestReadCompressedConcurrently(t *testing.T) {
                })
        }
 }
+
+// A channel made inside a testing/synctest bubble must not be used outside it,
+// so compressed reads and writes in one bubble must not leave state behind
+// that later reads and writes elsewhere pick up.
+func TestCompressedRoundTripAcrossSynctestBubbles(t *testing.T) {
+       for _, tc := range testCodecs {
+               t.Run(tc.name, func(t *testing.T) {
+                       rec := benchmarkRecordBatch(4, 2048)
+                       defer rec.Release()
+
+                       roundTrip := func(t *testing.T) {
+                               var stream bytes.Buffer
+                               w := NewWriter(&stream, 
WithSchema(rec.Schema()), tc.opt)
+                               require.NoError(t, w.Write(rec))
+                               require.NoError(t, w.Close())
+
+                               rdr, err := 
NewReader(bytes.NewReader(stream.Bytes()))
+                               require.NoError(t, err)
+                               defer rdr.Release()
+                               require.True(t, rdr.Next())
+                               assert.True(t, array.RecordEqual(rec, 
rdr.RecordBatch()))
+                               require.NoError(t, rdr.Err())
+
+                               var file bytes.Buffer
+                               fw, err := NewFileWriter(&file, 
WithSchema(rec.Schema()), tc.opt)
+                               require.NoError(t, err)
+                               require.NoError(t, fw.Write(rec))
+                               require.NoError(t, fw.Close())
+
+                               fr, err := 
NewFileReader(bytes.NewReader(file.Bytes()))
+                               require.NoError(t, err)
+                               defer fr.Close()
+                               got, err := fr.RecordBatchAt(0)
+                               require.NoError(t, err)
+                               defer got.Release()
+                               assert.True(t, array.RecordEqual(rec, got))
+                       }
+
+                       synctest.Test(t, roundTrip)
+                       roundTrip(t)
+                       synctest.Test(t, roundTrip)
+               })
+       }
+}
diff --git a/arrow/ipc/file_reader.go b/arrow/ipc/file_reader.go
index 1a7f0ed9..61230fe4 100644
--- a/arrow/ipc/file_reader.go
+++ b/arrow/ipc/file_reader.go
@@ -200,23 +200,29 @@ func (r *mappedReaderImpl) dict(_ memory.Allocator, f 
*footerBlock, i int) (data
        }, nil
 }
 
+// ipcDecoder holds what Reader and FileReader both need to turn dictionary
+// and record batch messages into arrays.
+type ipcDecoder struct {
+       schema *arrow.Schema
+       // fields dictTypeMap
+       memo           dictutils.Memo
+       mem            memory.Allocator
+       swapEndianness bool
+       zstd           zstdDecoders
+}
+
 // FileReader is an Arrow file reader.
 type FileReader struct {
+       ipcDecoder
+
        r readerImpl
 
        footer footerBlock
 
-       // fields dictTypeMap
-       memo dictutils.Memo
-
-       schema *arrow.Schema
        record arrow.RecordBatch
 
        irec int   // current record index. used for the arrio.Reader interface
        err  error // last error
-
-       mem            memory.Allocator
-       swapEndianness bool
 }
 
 // NewMappedFileReader is like NewFileReader but instead of using a 
ReadAtSeeker,
@@ -232,13 +238,12 @@ func NewMappedFileReader(data []byte, opts ...Option) 
(*FileReader, error) {
        var (
                cfg = newConfig(opts...)
                f   = FileReader{
+                       ipcDecoder: ipcDecoder{memo: dictutils.NewMemo(), mem: 
cfg.alloc},
                        r: &mappedReaderImpl{
                                data:            data,
                                maxMetadataSize: cfg.maxMetadataSize,
                                maxBodySize:     cfg.maxBodySize,
                        },
-                       memo: dictutils.NewMemo(),
-                       mem:  cfg.alloc,
                }
        )
 
@@ -254,13 +259,12 @@ func NewFileReader(r ReadAtSeeker, opts ...Option) 
(*FileReader, error) {
        var (
                cfg = newConfig(opts...)
                f   = FileReader{
+                       ipcDecoder: ipcDecoder{memo: dictutils.NewMemo(), mem: 
cfg.alloc},
                        r: &basicReaderImpl{
                                r:               r,
                                maxMetadataSize: cfg.maxMetadataSize,
                                maxBodySize:     cfg.maxBodySize,
                        },
-                       memo: dictutils.NewMemo(),
-                       mem:  cfg.alloc,
                }
        )
 
@@ -338,7 +342,7 @@ func (f *FileReader) readSchema(ensureNativeEndian bool) 
error {
                }
                kind, err = func() (dictutils.Kind, error) {
                        defer msg.Release()
-                       return readDictionary(&f.memo, msg.meta, msg.body, 
f.swapEndianness, f.mem)
+                       return f.readDictionary(msg.meta, msg.body)
                }()
                if err != nil {
                        return err
@@ -477,17 +481,17 @@ func (f *FileReader) RecordBatchAt(i int) 
(arrow.RecordBatch, error) {
                return nil, fmt.Errorf("arrow/ipc: message %d is not a 
RecordBatch", i)
        }
 
-       return loadRecordBatch(f.schema, &f.memo, msg.meta, msg.body, 
f.swapEndianness, f.mem)
+       return f.loadRecordBatch(msg.meta, msg.body)
 }
 
-func loadRecordBatch(schema *arrow.Schema, memo *dictutils.Memo, meta, body 
*memory.Buffer, swapEndianness bool, mem memory.Allocator) (rec 
arrow.RecordBatch, err error) {
+func (d *ipcDecoder) loadRecordBatch(meta, body *memory.Buffer) (rec 
arrow.RecordBatch, err error) {
        defer func() {
                if pErr := recover(); pErr != nil {
                        rec = nil
                        err = utils.FormatRecoveredError("arrow/ipc: error 
reading record batch", pErr)
                }
        }()
-       return newRecordBatch(schema, memo, meta, body, swapEndianness, mem), 
nil
+       return d.newRecordBatch(meta, body), nil
 }
 
 // RecordAt returns the i-th record from the file. Ownership is transferred to 
the
@@ -521,7 +525,7 @@ func (f *FileReader) ReadAt(i int64) (arrow.RecordBatch, 
error) {
        return f.RecordBatch(int(i))
 }
 
-func newRecordBatch(schema *arrow.Schema, memo *dictutils.Memo, meta 
*memory.Buffer, body *memory.Buffer, swapEndianness bool, mem memory.Allocator) 
arrow.RecordBatch {
+func (d *ipcDecoder) newRecordBatch(meta, body *memory.Buffer) 
arrow.RecordBatch {
        var (
                msg   = flatbuf.GetRootAsMessage(meta.Bytes(), 0)
                md    flatbuf.RecordBatch
@@ -532,7 +536,7 @@ func newRecordBatch(schema *arrow.Schema, memo 
*dictutils.Memo, meta *memory.Buf
 
        bodyCompress := md.Compression(nil)
        if bodyCompress != nil {
-               codec = getDecompressor(bodyCompress.Codec())
+               codec = getDecompressor(bodyCompress.Codec(), &d.zstd)
                defer codec.Close()
        }
 
@@ -546,24 +550,24 @@ func newRecordBatch(schema *arrow.Schema, memo 
*dictutils.Memo, meta *memory.Buf
                        meta:     &md,
                        rawBytes: body,
                        codec:    codec,
-                       mem:      mem,
+                       mem:      d.mem,
                },
-               memo:    memo,
+               memo:    &d.memo,
                max:     kMaxNestingDepth,
                version: MetadataVersion(msg.Version()),
        }
 
        pos := dictutils.NewFieldPos()
-       cols := make([]arrow.Array, schema.NumFields())
-       for i := 0; i < schema.NumFields(); i++ {
-               data := ctx.loadArray(schema.Field(i).Type)
+       cols := make([]arrow.Array, d.schema.NumFields())
+       for i := 0; i < d.schema.NumFields(); i++ {
+               data := ctx.loadArray(d.schema.Field(i).Type)
                defer data.Release()
 
-               if err := dictutils.ResolveFieldDict(memo, data, 
pos.Child(int32(i)), mem); err != nil {
+               if err := dictutils.ResolveFieldDict(&d.memo, data, 
pos.Child(int32(i)), d.mem); err != nil {
                        panic(err)
                }
 
-               if swapEndianness {
+               if d.swapEndianness {
                        swapEndianArrayData(data.(*array.Data))
                }
 
@@ -571,7 +575,7 @@ func newRecordBatch(schema *arrow.Schema, memo 
*dictutils.Memo, meta *memory.Buf
                defer cols[i].Release()
        }
 
-       return array.NewRecordBatchWithMetadata(schema, cols, rows, customMeta)
+       return array.NewRecordBatchWithMetadata(d.schema, cols, rows, 
customMeta)
 }
 
 type ipcSource struct {
@@ -910,7 +914,7 @@ func (ctx *arrayLoaderContext) loadUnion(dt 
arrow.UnionType) arrow.ArrayData {
        return array.NewData(dt, int(field.Length()), buffers, subs, 0, 0)
 }
 
-func readDictionary(memo *dictutils.Memo, meta *memory.Buffer, body 
*memory.Buffer, swapEndianness bool, mem memory.Allocator) (dictutils.Kind, 
error) {
+func (d *ipcDecoder) readDictionary(meta, body *memory.Buffer) 
(dictutils.Kind, error) {
        var (
                msg   = flatbuf.GetRootAsMessage(meta.Bytes(), 0)
                md    flatbuf.DictionaryBatch
@@ -922,14 +926,14 @@ func readDictionary(memo *dictutils.Memo, meta 
*memory.Buffer, body *memory.Buff
        md.Data(&data)
        bodyCompress := data.Compression(nil)
        if bodyCompress != nil {
-               codec = getDecompressor(bodyCompress.Codec())
+               codec = getDecompressor(bodyCompress.Codec(), &d.zstd)
                defer codec.Close()
        }
 
        id := md.Id()
        // look up the dictionary value type, which must have been added to the
        // memo already before calling this function
-       valueType, ok := memo.Type(id)
+       valueType, ok := d.memo.Type(id)
        if !ok {
                return 0, fmt.Errorf("arrow/ipc: no dictionary type found with 
id: %d", id)
        }
@@ -939,24 +943,24 @@ func readDictionary(memo *dictutils.Memo, meta 
*memory.Buffer, body *memory.Buff
                        meta:     &data,
                        codec:    codec,
                        rawBytes: body,
-                       mem:      mem,
+                       mem:      d.mem,
                },
-               memo: memo,
+               memo: &d.memo,
                max:  kMaxNestingDepth,
        }
 
        dict := ctx.loadArray(valueType)
        defer dict.Release()
 
-       if swapEndianness {
+       if d.swapEndianness {
                swapEndianArrayData(dict.(*array.Data))
        }
 
        if md.IsDelta() {
-               memo.AddDelta(id, dict)
+               d.memo.AddDelta(id, dict)
                return dictutils.KindDelta, nil
        }
-       if memo.AddOrReplace(id, dict) {
+       if d.memo.AddOrReplace(id, dict) {
                return dictutils.KindNew, nil
        }
        return dictutils.KindReplacement, nil
diff --git a/arrow/ipc/file_reader_internal_test.go 
b/arrow/ipc/file_reader_internal_test.go
index 35ff72d4..c75f0126 100644
--- a/arrow/ipc/file_reader_internal_test.go
+++ b/arrow/ipc/file_reader_internal_test.go
@@ -23,7 +23,6 @@ import (
 
        "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/arrow/array"
-       "github.com/apache/arrow-go/v18/arrow/internal/dictutils"
        "github.com/apache/arrow-go/v18/arrow/memory"
        "github.com/stretchr/testify/require"
 )
@@ -64,7 +63,8 @@ func TestLoadRecordBatchReturnsMalformedMetadataErrors(t 
*testing.T) {
        body := memory.NewBufferBytes(nil)
        defer body.Release()
 
-       rec, err := loadRecordBatch(arrow.NewSchema(nil, nil), 
&dictutils.Memo{}, meta, body, false, memory.DefaultAllocator)
+       d := ipcDecoder{schema: arrow.NewSchema(nil, nil), mem: 
memory.DefaultAllocator}
+       rec, err := d.loadRecordBatch(meta, body)
        require.Error(t, err)
        require.Nil(t, rec)
 }
diff --git a/arrow/ipc/reader.go b/arrow/ipc/reader.go
index edd50fc8..bb09eefd 100644
--- a/arrow/ipc/reader.go
+++ b/arrow/ipc/reader.go
@@ -28,7 +28,6 @@ import (
        "github.com/apache/arrow-go/v18/arrow/internal/debug"
        "github.com/apache/arrow-go/v18/arrow/internal/dictutils"
        "github.com/apache/arrow-go/v18/arrow/internal/flatbuf"
-       "github.com/apache/arrow-go/v18/arrow/memory"
        "github.com/apache/arrow-go/v18/internal/utils"
 )
 
@@ -36,22 +35,19 @@ import (
 // Reader expects a schema (plus any dictionaries) as the first messages
 // in the stream, followed by records.
 type Reader struct {
-       r      MessageReader
-       schema *arrow.Schema
+       ipcDecoder
+
+       r MessageReader
 
        refCount atomic.Int64
        rec      arrow.RecordBatch
        err      error
 
-       // types dictTypeMap
-       memo               dictutils.Memo
        readInitialDicts   bool
        done               bool
-       swapEndianness     bool
        ensureNativeEndian bool
        expectedSchema     *arrow.Schema
 
-       mem memory.Allocator
        // size limits for the message readers this Reader creates itself
        maxMetadataSize int64
        maxBodySize     int64
@@ -76,11 +72,9 @@ func NewReaderFromMessageReader(r MessageReader, opts 
...Option) (reader *Reader
        }
 
        reader = &Reader{
-               r:        r,
-               refCount: atomic.Int64{},
-               // types:    make(dictTypeMap),
-               memo:               dictutils.NewMemo(),
-               mem:                cfg.alloc,
+               ipcDecoder:         ipcDecoder{memo: dictutils.NewMemo(), mem: 
cfg.alloc},
+               r:                  r,
+               refCount:           atomic.Int64{},
                ensureNativeEndian: cfg.ensureNativeEndian,
                expectedSchema:     cfg.schema,
                maxMetadataSize:    cfg.maxMetadataSize,
@@ -112,11 +106,9 @@ func NewReader(r io.Reader, opts ...Option) (rr *Reader, 
err error) {
        cfg := newConfig(opts...)
        mr := NewMessageReader(r, opts...)
        rr = &Reader{
-               r:        mr,
-               refCount: atomic.Int64{},
-               // types:    make(dictTypeMap),
-               memo:               dictutils.NewMemo(),
-               mem:                cfg.alloc,
+               ipcDecoder:         ipcDecoder{memo: dictutils.NewMemo(), mem: 
cfg.alloc},
+               r:                  mr,
+               refCount:           atomic.Int64{},
                ensureNativeEndian: cfg.ensureNativeEndian,
                expectedSchema:     cfg.schema,
                maxMetadataSize:    cfg.maxMetadataSize,
@@ -242,7 +234,7 @@ func (r *Reader) getInitialDicts() bool {
                        r.err = fmt.Errorf("arrow/ipc: IPC stream did not have 
the expected (%d) dictionaries at the start of the stream", numDicts)
                        return false
                }
-               if _, err := readDictionary(&r.memo, msg.meta, msg.body, 
r.swapEndianness, r.mem); err != nil {
+               if _, err := r.readDictionary(msg.meta, msg.body); err != nil {
                        r.done = true
                        r.err = err
                        return false
@@ -277,7 +269,7 @@ func (r *Reader) next() bool {
        msg, r.err = r.r.Message()
 
        for msg != nil && msg.Type() == MessageDictionaryBatch {
-               if _, r.err = readDictionary(&r.memo, msg.meta, msg.body, 
r.swapEndianness, r.mem); r.err != nil {
+               if _, r.err = r.readDictionary(msg.meta, msg.body); r.err != 
nil {
                        r.done = true
                        return false
                }
@@ -305,7 +297,7 @@ func (r *Reader) next() bool {
                return false
        }
 
-       r.rec = newRecordBatch(r.schema, &r.memo, msg.meta, msg.body, 
r.swapEndianness, r.mem)
+       r.rec = r.newRecordBatch(msg.meta, msg.body)
        return true
 }
 

Reply via email to