Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 107 additions & 19 deletions dataframe.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,10 @@ func indexOf(list []string, s string) int {
// value as dfValue makes it, the others convert as for every binding.
func dfArg(x any, t reflect.Type) (reflect.Value, error) {
if t.Kind() == reflect.Interface {
v := dfValue(x)
v, err := dfValue(x)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(&v).Elem(), nil
}
return convert(x, t)
Expand All @@ -380,24 +383,64 @@ func dfArg(x any, t reflect.Type) (reflect.Value, error) {
// dfValue is a Ruby value as go-dataframe takes data and scalars: a Symbol
// is a string, a Time a time.Time, an Array a []any of such values; the rest
// (numbers, strings, booleans, nil, NDArrays, Series) is the value itself.
func dfValue(x any) any {
//
// Arrays nest to at most dfMaxDepth levels: a self-containing Array, or one
// nested deeper, is an ArgumentError rather than a stack overflow, which no
// recover can catch.
//
// An Array shared at several places (a = [a, a] repeated) is converted once and
// the result reused, so the work follows the distinct Arrays, not the paths to
// them. A sub-Array met again while it is still being converted is a cycle.
func dfValue(x any) (any, error) { return dfValueAt(x, 0, dfMemo{}) }

// dfMaxDepth is far deeper than any table and far shallower than the stack.
const dfMaxDepth = 64

// dfKey is an Array's identity: its first element's address and its length.
type dfKey struct {
first *any
n int
}

// dfMemo maps an Array to its conversion, nil while it is in progress.
type dfMemo map[dfKey][]any

func dfValueAt(x any, depth int, memo dfMemo) (any, error) {
switch v := x.(type) {
case rb.Symbol:
return string(v)
return string(v), nil
case []any:
if depth >= dfMaxDepth {
return nil, argError("an Array nested more than %d levels deep (a cycle?)", dfMaxDepth)
}
out := make([]any, len(v))
k := dfKey{n: len(v)} // all empty Arrays are one key: no cycle passes through one
if len(v) > 0 {
k.first = &v[0]
}
if done, seen := memo[k]; seen {
if done == nil {
return nil, argError("an Array containing itself")
}
return done, nil
}
memo[k] = nil
for i, e := range v {
out[i] = dfValue(e)
var err error
if out[i], err = dfValueAt(e, depth+1, memo); err != nil {
return nil, err
}
}
return out
memo[k] = out
return out, nil
case rb.Value:
if v.ClassName() == "Time" {
s, _ := v.Call("to_i")
ns, _ := v.Call("nsec")
return time.Unix(s.Go().(int64), ns.Go().(int64)).UTC()
return time.Unix(s.Go().(int64), ns.Go().(int64)).UTC(), nil
}
}
return x
return x, nil
}

// results converts what a Go method returned (see out).
Expand Down Expand Up @@ -538,7 +581,11 @@ func (e *dfEnv) fromPairs(c *rb.Call) (any, error) {
if err != nil {
return nil, err
}
cols[i] = dataframe.Col(name, dfValue(p[1]))
data, err := dfValue(p[1])
if err != nil {
return nil, err
}
cols[i] = dataframe.Col(name, data)
}
return e.results(reflect.ValueOf(dataframe.New).Call(colValues(cols)))
}
Expand Down Expand Up @@ -984,7 +1031,9 @@ func valueMap(x map[any]any) (map[string]any, error) {
if err != nil {
return nil, err
}
out[s] = dfValue(v)
if out[s], err = dfValue(v); err != nil {
return nil, err
}
}
return out, nil
}
Expand Down Expand Up @@ -1017,7 +1066,11 @@ func (e *dfEnv) fillNA(c *rb.Call) (any, error) {
if err := plExact(c, 1); err != nil {
return nil, err
}
return frameOf(c).FillNA(dfValue(c.Args[0].Go())), nil
v, err := dfValue(c.Args[0].Go())
if err != nil {
return nil, err
}
return frameOf(c).FillNA(v), nil
}

func (e *dfEnv) asType(c *rb.Call) (any, error) {
Expand Down Expand Up @@ -1138,7 +1191,10 @@ func exprArgs(c *rb.Call) (string, []map[string]any, error) {
if len(c.Kwargs) > 0 {
m := map[string]any{}
for k, v := range c.Kwargs {
m[k] = dfValue(v.Go())
var err error
if m[k], err = dfValue(v.Go()); err != nil {
return "", nil, err
}
}
vars = append(vars, m)
}
Expand Down Expand Up @@ -1188,7 +1244,11 @@ func selector(x any, positional bool) (dataframe.Selector, error) {
}
return dataframe.Pos(p.Interface().([]int)...), nil
}
return dataframe.Labels(dfValue(v).([]any)...), nil
labels, err := dfValue(v)
if err != nil {
return dataframe.Selector{}, err
}
return dataframe.Labels(labels.([]any)...), nil
case int64:
if positional {
return dataframe.Pos(int(v)), nil
Expand All @@ -1201,7 +1261,8 @@ func selector(x any, positional bool) (dataframe.Selector, error) {
if positional {
return dataframe.Selector{}, typeError(x, "a position, an Array, a Range or a mask")
}
return dataframe.Labels(dfValue(x)), nil
label, _ := dfValue(x) // x is not an Array here (that case returned above): no error
return dataframe.Labels(label), nil
}

// rangeSelector reads a Range: positions (an exclusive or inclusive end, nil
Expand All @@ -1215,7 +1276,15 @@ func rangeSelector(r rb.Value, positional bool) (dataframe.Selector, error) {
if ex.Go() == true {
return dataframe.Selector{}, argError("a label range includes its end: use a..b, not a...b")
}
return dataframe.LabelRange(dfValue(lo), dfValue(hi)), nil
from, err := dfValue(lo)
if err != nil {
return dataframe.Selector{}, err
}
to, err := dfValue(hi)
if err != nil {
return dataframe.Selector{}, err
}
return dataframe.LabelRange(from, to), nil
}
start := int64(0)
if lo != nil {
Expand Down Expand Up @@ -1310,7 +1379,11 @@ func (e *dfEnv) apply(c *rb.Call) (any, error) {
blockErr = err
return nil
}
return dfValue(v.Go())
out, err := dfValue(v.Go())
if err != nil {
blockErr = err
}
return out
})
if blockErr != nil {
return nil, blockErr
Expand Down Expand Up @@ -1344,7 +1417,11 @@ func newIndexArg(x any) (*dataframe.Index, error) {
if ix, ok := x.(*dataframe.Index); ok {
return ix, nil
}
ix, err := dataframe.NewIndex("", dfValue(x))
labels, err := dfValue(x)
if err != nil {
return nil, err
}
ix, err := dataframe.NewIndex("", labels)
if err != nil {
return nil, goError(err)
}
Expand All @@ -1366,7 +1443,10 @@ func (e *dfEnv) newSeries(c *rb.Call) (any, error) {
}
name = s
}
data := dfValue(c.Args[0].Go())
data, err := dfValue(c.Args[0].Go())
if err != nil {
return nil, err
}
if ixv, ok := c.Kwargs["index"]; ok {
ix, err := newIndexArg(ixv.Go())
if err != nil {
Expand Down Expand Up @@ -1425,7 +1505,11 @@ func (e *dfEnv) seriesMap(c *rb.Call) (any, error) {
blockErr = err
return nil
}
return dfValue(v.Go())
out, err := dfValue(v.Go())
if err != nil {
blockErr = err
}
return out
})
if blockErr != nil {
return nil, blockErr
Expand Down Expand Up @@ -1543,7 +1627,11 @@ func (e *dfEnv) newIndex(c *rb.Call) (any, error) {
}
name = s
}
return e.result(dataframe.NewIndex(name, dfValue(c.Args[0].Go())))
labels, err := dfValue(c.Args[0].Go())
if err != nil {
return nil, err
}
return e.result(dataframe.NewIndex(name, labels))
}

func (e *dfEnv) rangeIndex(c *rb.Call) (any, error) {
Expand Down
118 changes: 118 additions & 0 deletions dfvalue_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package ruby

import (
"runtime"
"runtime/debug"
"strings"
"testing"
)

// dfValue recurses over Arrays: a self-containing one, or one nested too deep,
// is an ArgumentError from every entry point that reaches it, never a stack
// overflow (which kills the host, recover or not).
func TestDataFrameNestedArraysAreRefused(t *testing.T) {
in := newInterp(t)
eval(t, in, `cyc = []; cyc << cyc
deep = 0; 70.times { deep = [deep] }
df = DataFrame.new(x: [1, 2], y: ["a", "b"])
s = DataFrame::Series.new([1, 2], name: "s")
str = DataFrame::Series.new(["Lyon", "Rome"])`)
// A label Range's ends are values too; Array ends compare in Ruby, so a
// too-deep one reaches dfValue (a cyclic one is not built: comparing it
// is the interpreter's affair).
eval(t, in, `deep2 = [deep]`)
evalErr(t, in, `df.loc(deep..deep2)`, "ArgumentError", "nested more than 64 levels")
evalErr(t, in, `df.loc([1]..deep)`, "ArgumentError", "nested more than 64 levels")
// Only the begin is too deep: Arrays of different nesting still compare.
eval(t, in, `mk = ->(n) { a = []; n.times { a = [a] }; a }`)
evalErr(t, in, `df.loc(mk[70]..mk[60])`, "ArgumentError", "nested more than 64 levels")
for _, call := range []string{
`DataFrame.new(x: ARG)`,
`DataFrame.new("x" => ARG)`,
`DataFrame::Series.new(ARG)`,
`DataFrame::Series.new([1, 2], index: ARG)`,
`DataFrame::Index.new(ARG)`,
`df.fillna(ARG)`,
`df.fillna(x: ARG)`,
`df.fillna("x" => ARG)`,
`df.query("x > 0", v: ARG)`,
`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{
"cyc": "containing itself", "deep": "nested more than 64 levels", "[cyc, 1]": "containing itself",
} {
src := strings.ReplaceAll(call, "ARG", arg)
evalErr(t, in, src, "ArgumentError", msg)
}
}
}

// 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
// keys or rows there are. The allocation is measured, whatever the outcome.
func TestDataFrameSharedArraysAreConvertedOnce(t *testing.T) {
defer debug.SetMemoryLimit(debug.SetMemoryLimit(1 << 30))
in := newInterp(t)
eval(t, in, `a = 1; 21.times { a = [a, a] }
kw = {}; 8.times { |i| kw[:"k#{i}"] = a }
df = DataFrame.new(x: [1, 2])
s8 = DataFrame::Series.new((1..8).to_a)`)
for _, src := range []string{
`DataFrame::Series.new([a])`,
`df.query("x > 0", **kw)`,
`s8.map { a }`,
`DataFrame.new(**kw)`,
} {
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
_, _ = in.Eval(src, "test.rb", 1) // an error or a value: only the allocation is asserted
runtime.ReadMemStats(&after)
if got := after.TotalAlloc - before.TotalAlloc; got > 64<<20 {
t.Errorf("%s allocated %d MiB, want under 64", src, got>>20)
}
}
// A flat column of ordinary size converts: there is no amplification.
eval(t, in, `DataFrame::Series.new((1..4_200_000).to_a)`)
}

// Sharing is by identity: one conversion for a repeated Array, one result
// reused, and a cycle (an Array met again while in progress) refused.
func TestDfValueMemoizesByIdentity(t *testing.T) {
inner := []any{1, 2}
got, err := dfValue([]any{inner, inner, []any{}, []any{}})
if err != nil {
t.Fatal(err)
}
l := got.([]any)
if &l[0].([]any)[0] != &l[1].([]any)[0] {
t.Error("a shared Array was converted twice")
}
cyc := make([]any, 1)
cyc[0] = cyc
if _, err := dfValue(cyc); err == nil || !strings.Contains(err.Error(), "containing itself") {
t.Errorf("cycle: %v", err)
}
}

// The depth limit is exact: dfMaxDepth levels convert, one more is refused.
func TestDfValueDepthIsExact(t *testing.T) {
nest := func(n int) any {
var a any = 1
for ; n > 0; n-- {
a = []any{a}
}
return a
}
if _, err := dfValue(nest(dfMaxDepth)); err != nil {
t.Errorf("%d levels: %v", dfMaxDepth, err)
}
if _, err := dfValue(nest(dfMaxDepth + 1)); err == nil {
t.Errorf("%d levels converted", dfMaxDepth+1)
}
}
Loading