From fbbe5c3ba52c19d0efbfc3ad4cc9a1925953d1f6 Mon Sep 17 00:00:00 2001 From: Matthew Nibecker Date: Sun, 22 Nov 2026 12:01:03 -0800 Subject: [PATCH] cap JSON reader batches by bytes as well as value count The JSON reader batched a fixed 10,240 values regardless of their size, so inputs with large values could produce batches hundreds of megabytes in size. This exhausts memory in constrained environments such as wasm. Batches now end, by default, at 10,240 values or 16MB of raw input, whichever comes first, so small-value inputs batch as before while large-value inputs stay bounded. A batch always holds at least one value. Oversized batch buffers are no longer returned to the pool. --- cli/inputflags/flags.go | 1 + sio/anyio/lookup.go | 2 +- sio/anyio/reader.go | 5 +++-- sio/jsonio/reader.go | 29 +++++++++++++++++++++++++---- sio/jsonio/stream.go | 31 ++++++++++++++++++++++++------- sio/jsonio/valreader.go | 15 +++++++-------- 6 files changed, 61 insertions(+), 22 deletions(-) diff --git a/cli/inputflags/flags.go b/cli/inputflags/flags.go index a076b0fbe7..c4dde55519 100644 --- a/cli/inputflags/flags.go +++ b/cli/inputflags/flags.go @@ -27,6 +27,7 @@ func (f *Flags) SetFlags(fs *flag.FlagSet) { fs.BoolVar(&f.Dynamic, "dynamic", false, "disable static type checking of inputs") fs.StringVar(&opts.Format, "i", opts.Format, "format of input data [auto,arrows,bsup,csv,json,line,parquet,sup,tsv,zeek]") fs.IntVar(&opts.InputCap, "inputcap", 0, "limit size of batched units of input") + fs.IntVar(&opts.JSON.InputCapBytes, "json.inputcapbytes", 0, "limit size in bytes of batched units of JSON input") fs.BoolVar(&f.Static, "static", false, "statically type check all inputs (reading into memory inputs that can be read only once)") } diff --git a/sio/anyio/lookup.go b/sio/anyio/lookup.go index 6d3877fc96..0b2a7d9d30 100644 --- a/sio/anyio/lookup.go +++ b/sio/anyio/lookup.go @@ -34,7 +34,7 @@ func lookupReader(ctx context.Context, sctx *super.Context, r io.Reader, opts Re case "line": return newVioPuller(sctx, lineio.NewReader(r)), nil case "json": - return jsonio.NewReader(context.Background(), sctx, r, opts.Pushdown, opts.ConcurrentReaders, opts.InputCap), nil + return jsonio.NewReader(context.Background(), sctx, r, opts.Pushdown, opts.ConcurrentReaders, opts.InputCap, opts.JSON), nil case "parquet": return parquetio.NewReader(ctx, sctx, r, opts.Pushdown, opts.ConcurrentReaders) case "sup": diff --git a/sio/anyio/reader.go b/sio/anyio/reader.go index 1a7b844f52..0d199af5c8 100644 --- a/sio/anyio/reader.go +++ b/sio/anyio/reader.go @@ -31,6 +31,7 @@ type ReaderOpts struct { ConcurrentReaders int CSV csvio.ReaderOpts InputCap int + JSON jsonio.ReaderOpts } func NewReader(ctx context.Context, sctx *super.Context, r io.Reader, opts ReaderOpts) (vio.Puller, error) { @@ -93,7 +94,7 @@ func NewReader(ctx context.Context, sctx *super.Context, r io.Reader, opts Reade // sake of tests. jsonErr := isJSONStream(track, 10) if jsonErr == nil { - return jsonio.NewReader(ctx, sctx, track.Reader(), opts.Pushdown, opts.ConcurrentReaders, opts.InputCap), nil + return jsonio.NewReader(ctx, sctx, track.Reader(), opts.Pushdown, opts.ConcurrentReaders, opts.InputCap, opts.JSON), nil } jsonErr = fmt.Errorf("json: %w", jsonErr) track.Reset() @@ -171,7 +172,7 @@ func isCSVStream(track *Track, delim rune, name string) error { } func isJSONStream(track *Track, want int) error { - r := jsonio.NewValReader(track, 0) + r := jsonio.NewValReader(track) for range want { if _, err := r.Next(); err != nil { if errors.Is(err, io.EOF) { diff --git a/sio/jsonio/reader.go b/sio/jsonio/reader.go index 9cdeb80222..740943fdcc 100644 --- a/sio/jsonio/reader.go +++ b/sio/jsonio/reader.go @@ -19,19 +19,39 @@ import ( const defaultInputCap = 10 * 1024 +// defaultByteCap bounds the raw input bytes in a batch so that inputs with +// large values don't produce huge batches. Inputs with small values hit +// defaultInputCap first. Memory-constrained environments (e.g., wasm) may +// want a smaller cap via ReaderOpts.InputCapBytes. +const defaultByteCap = 16 * 1024 * 1024 + +type ReaderOpts struct { + // InputCapBytes limits the raw input bytes in a batch. Zero means + // defaultByteCap. + InputCapBytes int +} + type Reader struct { sctx *super.Context ctx context.Context stream *stream + byteCap int projection field.Projection hasClosed atomic.Bool } -func NewReader(ctx context.Context, sctx *super.Context, r io.Reader, p vio.Pushdown, concurrentReaders, inputCap int) *Reader { +// NewReader returns a Reader that parses input in batches of at most +// inputCap values or about opts.InputCapBytes bytes, whichever is reached +// first. Zero means the default for either limit. +func NewReader(ctx context.Context, sctx *super.Context, r io.Reader, p vio.Pushdown, concurrentReaders, inputCap int, opts ReaderOpts) *Reader { if inputCap == 0 { inputCap = defaultInputCap } + byteCap := opts.InputCapBytes + if byteCap == 0 { + byteCap = defaultByteCap + } var proj field.Projection if p != nil { // Type-only projections aren't supported so the data for @@ -41,7 +61,8 @@ func NewReader(ctx context.Context, sctx *super.Context, r io.Reader, p vio.Push return &Reader{ sctx: sctx, ctx: ctx, - stream: newStream(ctx, r, concurrentReaders, inputCap), + byteCap: byteCap, + stream: newStream(ctx, r, concurrentReaders, inputCap, byteCap), projection: proj, } } @@ -63,12 +84,12 @@ func (r *Reader) ConcurrentPull(done bool, _ int) (vector.Any, error) { for i := range table.Len() { if err := ast.Preorder(byteconv.UnsafeString(table.Bytes(i)), builder, nil); err != nil { err = preorderErr(i, start, table, err) - bytesTablePool.Put(table) + putBytesTable(table, r.byteCap) r.close() return nil, err } } - bytesTablePool.Put(table) + putBytesTable(table, r.byteCap) return jsonvec.Materialize(r.sctx, builder), nil } diff --git a/sio/jsonio/stream.go b/sio/jsonio/stream.go index df156c75c6..14d9ab379b 100644 --- a/sio/jsonio/stream.go +++ b/sio/jsonio/stream.go @@ -16,15 +16,17 @@ type stream struct { once sync.Once ctx context.Context inputCap int + byteCap int } -func newStream(ctx context.Context, r io.Reader, n int, inputCap int) *stream { +func newStream(ctx context.Context, r io.Reader, n, inputCap, byteCap int) *stream { return &stream{ r: r, ch: make(chan result, n), ctx: ctx, done: make(chan struct{}), inputCap: inputCap, + byteCap: byteCap, } } @@ -46,9 +48,9 @@ func (s *stream) next() (*vector.BytesTable, int, error) { func (s *stream) run() { defer close(s.ch) - r := NewValReader(s.r, s.inputCap) + r := NewValReader(s.r) for { - batch, startLineNum, err := readBatch(r) + batch, startLineNum, err := readBatch(r, s.inputCap, s.byteCap) select { case s.ch <- result{batch, startLineNum, err}: if batch == nil || err != nil { @@ -77,19 +79,34 @@ func newBytesTable(inputCap int) *vector.BytesTable { return b } -func readBatch(r *valReader) (*vector.BytesTable, int, error) { - t := newBytesTable(r.inputCap) +// putBytesTable returns t to the pool unless its buffer grew well beyond +// byteCap (e.g., to hold a single oversized value), in which case it is +// dropped so the pool doesn't pin that memory. +func putBytesTable(t *vector.BytesTable, byteCap int) { + if cap(t.RawBytes()) <= 2*byteCap { + bytesTablePool.Put(t) + } +} + +// readBatch reads values from r until the batch holds inputCap values or +// at least byteCap bytes, whichever comes first. A batch always holds at +// least one value so a value larger than byteCap is still read. +func readBatch(r *valReader, inputCap, byteCap int) (*vector.BytesTable, int, error) { + t := newBytesTable(inputCap) start := r.lineNumber() var err error - for range r.inputCap { + for range inputCap { var b []byte if b, err = r.Next(); err != nil { break } t.Append(b) + if len(t.RawBytes()) >= byteCap { + break + } } if t.Len() == 0 { - bytesTablePool.Put(t) + putBytesTable(t, byteCap) t = nil } if errors.Is(err, io.EOF) { diff --git a/sio/jsonio/valreader.go b/sio/jsonio/valreader.go index 848f3a0e2d..e094797ab1 100644 --- a/sio/jsonio/valreader.go +++ b/sio/jsonio/valreader.go @@ -13,16 +13,15 @@ import ( const maxSize = 512 * 1024 * 1024 type valReader struct { - r io.Reader - buf []byte - cursor []byte - EOF bool - line int - inputCap int + r io.Reader + buf []byte + cursor []byte + EOF bool + line int } -func NewValReader(r io.Reader, inputCap int) *valReader { - return &valReader{r: r, buf: make([]byte, 512*1024), inputCap: inputCap} +func NewValReader(r io.Reader) *valReader { + return &valReader{r: r, buf: make([]byte, 512*1024)} } func (r *valReader) Next() ([]byte, error) {