From 88c38c271c1cb8672fdf7d8562c2907ceb9c990c Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 30 Nov 2026 21:01:59 +0100 Subject: [PATCH 1/2] dataframe: refuse an Array block result of Series#map / DataFrame#apply before converting it A column holds scalars: go-dataframe's fromValues refuses a []any ("cannot hold []interface {}") on the Map and Apply paths, and no other path accepts nested results. Yet the block result went through dfValue first, so `s.map { b }` over 200k rows built 200k converted Arrays (4.7 s, 5.9 GiB, 88M allocs on a large b) before the refusal. blockResult refuses a []any at once with an ArgumentError naming the row. 200k rows x 64-element Array: 465 MiB / 1.80M allocs -> 6 MiB / 0.2M allocs. A flat block costs the same as before (1.198M allocs at v0.4.0 and at f094d13: #14's memo adds no allocation to scalar results). Co-Authored-By: Claude Sonnet 5.5 --- dataframe.go | 19 +++++++++++++++++-- dfvalue_test.go | 30 ++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/dataframe.go b/dataframe.go index 308782b..17f0695 100644 --- a/dataframe.go +++ b/dataframe.go @@ -1365,10 +1365,12 @@ func (e *dfEnv) apply(c *rb.Call) (any, error) { df := frameOf(c) cols := df.Columns() var blockErr error + row := -1 s, err := df.Apply(name, func(r dataframe.Row) any { if blockErr != nil { return nil } + row++ ps := make([]any, len(cols)) for i, col := range cols { ps[i] = []any{col, e.outAny(r.Get(col))} @@ -1379,7 +1381,7 @@ func (e *dfEnv) apply(c *rb.Call) (any, error) { blockErr = err return nil } - out, err := dfValue(v.Go()) + out, err := blockResult(v.Go(), row) if err != nil { blockErr = err } @@ -1391,6 +1393,17 @@ func (e *dfEnv) apply(c *rb.Call) (any, error) { return e.result(s, err) } +// blockResult is what a map/apply block returned for a row, as one cell. A +// column holds scalars (go-dataframe refuses a []any: "cannot hold"), so an +// Array is refused here, before dfValue converts it: a block returning an +// Array per row of a large Series would otherwise build every one first. +func blockResult(v any, row int) (any, error) { + if _, ok := v.([]any); ok { + return nil, argError("the block returned an Array for row %d: a column holds scalars", row) + } + return dfValue(v) +} + func (e *dfEnv) resample(c *rb.Call) (any, error) { if err := kwOnly(c, "on"); err != nil { return nil, err @@ -1496,16 +1509,18 @@ func (e *dfEnv) seriesMap(c *rb.Call) (any, error) { return nil, err } var blockErr error + row := -1 s, err := seriesOf(c).Map(func(x any) any { if blockErr != nil { return nil } + row++ v, err := b.Call(e.outAny(x)) if err != nil { blockErr = err return nil } - out, err := dfValue(v.Go()) + out, err := blockResult(v.Go(), row) if err != nil { blockErr = err } diff --git a/dfvalue_test.go b/dfvalue_test.go index a5cb3d5..300ff9e 100644 --- a/dfvalue_test.go +++ b/dfvalue_test.go @@ -39,8 +39,6 @@ str = DataFrame::Series.new(["Lyon", "Rome"])`) `df.loc(ARG)`, `df.loc(ARG, ["x"])`, `s.loc(ARG)`, - `s.map { ARG }`, - `df.apply { ARG }`, `str.isin(ARG)`, } { for arg, msg := range map[string]string{ @@ -52,6 +50,34 @@ str = DataFrame::Series.new(["Lyon", "Rome"])`) } } +// A column holds scalars (go-dataframe refuses a []any), so a map/apply block +// returning an Array is refused at the first row it returns one, naming the +// row, before any conversion: 200k rows of a big Array stay small, not +// seconds and GiB. +func TestMapAndApplyRefuseAnArrayResultBeforeConverting(t *testing.T) { + defer debug.SetMemoryLimit(debug.SetMemoryLimit(1 << 30)) + in := newInterp(t) + eval(t, in, `cyc = []; cyc << cyc +deep = 0; 70.times { deep = [deep] } +b = (1..64).to_a +big = DataFrame::Series.new((1..200_000).to_a) +df = DataFrame.new(x: [1, 2], y: [3, 4]) +s = DataFrame::Series.new([1, 2, 3])`) + for _, src := range []string{`s.map { cyc }`, `s.map { deep }`, `s.map { [cyc, 1] }`, `s.map { [1] }`, `df.apply { cyc }`, `df.apply { [1] }`} { + evalErr(t, in, src, "ArgumentError", "returned an Array for row 0") + } + evalErr(t, in, `s.map { |x| x == 2 ? [x] : x }`, "ArgumentError", "returned an Array for row 1") + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + evalErr(t, in, `big.map { b }`, "ArgumentError", "returned an Array for row 0") + runtime.ReadMemStats(&after) + if got := after.TotalAlloc - before.TotalAlloc; got > 8<<20 { + t.Errorf("refusing allocated %d MiB, want under 8", got>>20) + } + // Scalar results still map. + eval(t, in, `raise "bad" unless s.map { |x| x * 2 }.to_a == [2, 4, 6]`) +} + // An Array shared at several places is converted once: 21 doublings are 2^21 // leaves from a few dozen objects, and a call that converts it once per key or // row (query keywords, Series#map, DataFrame.new) must stay small however many From 3338716cb65b0a8ca640fe0ffb3f32121d183184 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 30 Nov 2026 21:33:19 +0100 Subject: [PATCH 2/2] dataframe: make the map/apply block-result check an allowlist by class An Array was refused, but a Hash (or any other object) result still went through Go() and dfValue before go-dataframe refused it: `big.map { h }` over 20k rows with a 1000-key Hash cost 1.8 GiB. blockResult now takes the Ruby value and accepts exactly the classes that become what fromValues takes (nil, true/false, Integer, Float, Complex, String, Symbol, Time), refusing any other by class name at its row, before any conversion. Co-Authored-By: Claude Sonnet 5.5 --- dataframe.go | 22 +++++++++++++--------- dfvalue_test.go | 36 +++++++++++++++++++++++++----------- 2 files changed, 38 insertions(+), 20 deletions(-) diff --git a/dataframe.go b/dataframe.go index 17f0695..6e13059 100644 --- a/dataframe.go +++ b/dataframe.go @@ -1381,7 +1381,7 @@ func (e *dfEnv) apply(c *rb.Call) (any, error) { blockErr = err return nil } - out, err := blockResult(v.Go(), row) + out, err := blockResult(v, row) if err != nil { blockErr = err } @@ -1394,14 +1394,18 @@ func (e *dfEnv) apply(c *rb.Call) (any, error) { } // blockResult is what a map/apply block returned for a row, as one cell. A -// column holds scalars (go-dataframe refuses a []any: "cannot hold"), so an -// Array is refused here, before dfValue converts it: a block returning an -// Array per row of a large Series would otherwise build every one first. -func blockResult(v any, row int) (any, error) { - if _, ok := v.([]any); ok { - return nil, argError("the block returned an Array for row %d: a column holds scalars", row) +// column holds what go-dataframe's fromValues takes (nil, bool, numbers, +// string, time.Time); the Ruby classes that become those are allowed, and +// anything else (Array, Hash, Series, an object) is refused by class, before +// Go() or dfValue converts it: a block returning a big Array or Hash per row +// of a large Series would otherwise build every one first. +func blockResult(v rb.Value, row int) (any, error) { + switch cls := v.ClassName(); cls { + case "NilClass", "TrueClass", "FalseClass", "Integer", "Float", "Complex", "String", "Symbol", "Time": + return dfValue(v.Go()) + default: + return nil, argError("the block returned a %s for row %d: a column holds nil, booleans, numbers, strings, symbols and Times", cls, row) } - return dfValue(v) } func (e *dfEnv) resample(c *rb.Call) (any, error) { @@ -1520,7 +1524,7 @@ func (e *dfEnv) seriesMap(c *rb.Call) (any, error) { blockErr = err return nil } - out, err := blockResult(v.Go(), row) + out, err := blockResult(v, row) if err != nil { blockErr = err } diff --git a/dfvalue_test.go b/dfvalue_test.go index 300ff9e..300c2bd 100644 --- a/dfvalue_test.go +++ b/dfvalue_test.go @@ -60,22 +60,36 @@ func TestMapAndApplyRefuseAnArrayResultBeforeConverting(t *testing.T) { eval(t, in, `cyc = []; cyc << cyc deep = 0; 70.times { deep = [deep] } b = (1..64).to_a -big = DataFrame::Series.new((1..200_000).to_a) +big = DataFrame::Series.new((1..20_000).to_a) +bigdf = DataFrame.new(x: (1..20_000).to_a) +h = {}; 1000.times { |i| h[i] = i } df = DataFrame.new(x: [1, 2], y: [3, 4]) s = DataFrame::Series.new([1, 2, 3])`) for _, src := range []string{`s.map { cyc }`, `s.map { deep }`, `s.map { [cyc, 1] }`, `s.map { [1] }`, `df.apply { cyc }`, `df.apply { [1] }`} { - evalErr(t, in, src, "ArgumentError", "returned an Array for row 0") + evalErr(t, in, src, "ArgumentError", "returned a Array for row 0") } - evalErr(t, in, `s.map { |x| x == 2 ? [x] : x }`, "ArgumentError", "returned an Array for row 1") - var before, after runtime.MemStats - runtime.ReadMemStats(&before) - evalErr(t, in, `big.map { b }`, "ArgumentError", "returned an Array for row 0") - runtime.ReadMemStats(&after) - if got := after.TotalAlloc - before.TotalAlloc; got > 8<<20 { - t.Errorf("refusing allocated %d MiB, want under 8", got>>20) + evalErr(t, in, `s.map { |x| x == 2 ? [x] : x }`, "ArgumentError", "returned a Array for row 1") + evalErr(t, in, `s.map { h }`, "ArgumentError", "returned a Hash for row 0") + evalErr(t, in, `df.apply { h }`, "ArgumentError", "returned a Hash for row 0") + evalErr(t, in, `s.map { s }`, "ArgumentError", "for row 0") + evalErr(t, in, `s.map { Object.new }`, "ArgumentError", "returned a Object for row 0") + for _, src := range []string{`big.map { b }`, `big.map { h }`, `bigdf.apply { h }`, `big.map { big }`} { + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + evalErr(t, in, src, "ArgumentError", "for row 0") + runtime.ReadMemStats(&after) + if got := after.TotalAlloc - before.TotalAlloc; got > 16<<20 { + t.Errorf("refusing %s allocated %d MiB, want under 16", src, got>>20) + } } - // Scalar results still map. - eval(t, in, `raise "bad" unless s.map { |x| x * 2 }.to_a == [2, 4, 6]`) + // Scalar, nil, Symbol and Time results still map. + eval(t, in, `raise "bad" unless s.map { |x| x * 2 }.to_a == [2, 4, 6] +raise "bad" unless s.map { |x| x == 2 ? nil : x }.to_a == [1, nil, 3] +raise "bad" unless s.map { |x| x.odd? }.to_a == [true, false, true] +raise "bad" unless s.map { |x| x * 1.5 }.to_a == [1.5, 3.0, 4.5] +raise "bad" unless s.map { |x| :a }.to_a == ["a", "a", "a"] +raise "bad" unless s.map { |x| x.to_s }.to_a == ["1", "2", "3"] +s.map { |x| Time.at(x) }`) } // An Array shared at several places is converted once: 21 doublings are 2^21