File: vector_run_end_test.go

package info (click to toggle)
golang-github-apache-arrow-go 18.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 32,200 kB
  • sloc: asm: 477,547; ansic: 5,369; cpp: 759; sh: 585; makefile: 319; python: 190; sed: 5
file content (423 lines) | stat: -rw-r--r-- 13,709 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build go1.18

package compute_test

import (
	"context"
	"fmt"
	"math"
	"strings"
	"testing"

	"github.com/apache/arrow-go/v18/arrow"
	"github.com/apache/arrow-go/v18/arrow/array"
	"github.com/apache/arrow-go/v18/arrow/bitutil"
	"github.com/apache/arrow-go/v18/arrow/compute"
	"github.com/apache/arrow-go/v18/arrow/compute/exec"
	"github.com/apache/arrow-go/v18/arrow/internal/testing/gen"
	"github.com/apache/arrow-go/v18/arrow/memory"
	"github.com/stretchr/testify/suite"
)

var runEndTypes = []arrow.DataType{
	arrow.PrimitiveTypes.Int16,
	arrow.PrimitiveTypes.Int32,
	arrow.PrimitiveTypes.Int64,
}

type RunEndEncodeDecodeSuite struct {
	suite.Suite
	mem *memory.CheckedAllocator

	runEndType arrow.DataType
	valueType  arrow.DataType
	jsonData   []string

	expected compute.Datum
	input    compute.Datum

	ctx context.Context
}

func (suite *RunEndEncodeDecodeSuite) SetupTest() {
	suite.mem = memory.NewCheckedAllocator(memory.DefaultAllocator)
	suite.ctx = compute.WithAllocator(context.Background(), suite.mem)

	switch len(suite.jsonData) {
	case 1:
		expected, _, err := array.FromJSON(suite.mem,
			arrow.RunEndEncodedOf(suite.runEndType, suite.valueType),
			strings.NewReader(suite.jsonData[0]))
		suite.Require().NoError(err)
		defer expected.Release()

		input, _, err := array.FromJSON(suite.mem, suite.valueType, strings.NewReader(suite.jsonData[0]))
		suite.Require().NoError(err)
		defer input.Release()

		suite.expected = compute.NewDatum(expected)
		suite.input = compute.NewDatum(input)
	default:
		var err error
		exChunks := make([]arrow.Array, len(suite.jsonData))
		inputChunks := make([]arrow.Array, len(suite.jsonData))
		for i, data := range suite.jsonData {
			exChunks[i], _, err = array.FromJSON(suite.mem,
				arrow.RunEndEncodedOf(suite.runEndType, suite.valueType),
				strings.NewReader(data))
			suite.Require().NoError(err)
			defer exChunks[i].Release()

			inputChunks[i], _, err = array.FromJSON(suite.mem,
				suite.valueType, strings.NewReader(data))
			suite.Require().NoError(err)
			defer inputChunks[i].Release()
		}

		chunked := arrow.NewChunked(exChunks[0].DataType(), exChunks)
		suite.expected = &compute.ChunkedDatum{Value: chunked}
		chunked = arrow.NewChunked(inputChunks[0].DataType(), inputChunks)
		suite.input = &compute.ChunkedDatum{Value: chunked}
	}
}

func (suite *RunEndEncodeDecodeSuite) TearDownTest() {
	suite.expected.Release()
	suite.input.Release()
	suite.mem.AssertSize(suite.T(), 0)
}

func (suite *RunEndEncodeDecodeSuite) TestEncodeArray() {
	result, err := compute.RunEndEncode(suite.ctx,
		compute.RunEndEncodeOptions{RunEndType: suite.runEndType}, suite.input)
	suite.Require().NoError(err)
	defer result.Release()

	assertDatumsEqual(suite.T(), suite.expected, result, nil, nil)
}

func (suite *RunEndEncodeDecodeSuite) TestDecodeArray() {
	result, err := compute.RunEndDecode(suite.ctx, suite.expected)
	suite.Require().NoError(err)
	defer result.Release()

	assertDatumsEqual(suite.T(), suite.input, result, nil, nil)
}

func (suite *RunEndEncodeDecodeSuite) TestEncodeWithOffset() {
	// skip chunked examples for ease of testing
	expected, ok := suite.expected.(*compute.ArrayDatum)
	if !ok {
		suite.T().SkipNow()
	}

	input := suite.input.(*compute.ArrayDatum)

	if input.Len() == 0 {
		// skip 0 len arrays for this test
		suite.T().SkipNow()
	}

	expectedOffset := array.NewSliceData(expected.Value, 1, expected.Len())
	defer expectedOffset.Release()
	inputOffset := array.NewSliceData(input.Value, 1, input.Len())
	defer inputOffset.Release()

	result, err := compute.RunEndEncode(suite.ctx,
		compute.RunEndEncodeOptions{RunEndType: suite.runEndType},
		&compute.ArrayDatum{Value: inputOffset})
	suite.Require().NoError(err)
	defer result.Release()

	assertDatumsEqual(suite.T(), &compute.ArrayDatum{Value: expectedOffset}, result, nil, nil)
}

func (suite *RunEndEncodeDecodeSuite) TestDecodeWithOffset() {
	// skip chunked examples for ease of testing
	expected, ok := suite.expected.(*compute.ArrayDatum)
	if !ok {
		suite.T().SkipNow()
	}

	input := suite.input.(*compute.ArrayDatum)

	if input.Len() == 0 {
		// skip 0 len arrays for this test
		suite.T().SkipNow()
	}

	expectedOffset := array.NewSliceData(expected.Value, 1, expected.Len())
	defer expectedOffset.Release()
	inputOffset := array.NewSliceData(input.Value, 1, input.Len())
	defer inputOffset.Release()

	result, err := compute.RunEndDecode(suite.ctx, &compute.ArrayDatum{Value: expectedOffset})
	suite.Require().NoError(err)
	defer result.Release()

	assertDatumsEqual(suite.T(), &compute.ArrayDatum{Value: inputOffset}, result, nil, nil)
}

func (suite *RunEndEncodeDecodeSuite) TestDecodeWithChildOffset() {
	// artificially add a bunch of nulls to the values child of the
	// run-end encoded array both before and after the data and then
	// replace it with a slice. Then make sure it still decodes
	// correctly.

	// skip chunked
	expected, ok := suite.expected.(*compute.ArrayDatum)
	if !ok {
		suite.T().SkipNow()
	}

	const offset = 100

	var newValuesData arrow.ArrayData
	valuesData := expected.Value.Children()[1]
	newLength := offset + int64(valuesData.Len()) + offset
	byteLen := bitutil.BytesForBits(newLength)

	validity, values := memory.NewResizableBuffer(suite.mem), memory.NewResizableBuffer(suite.mem)
	defer validity.Release()
	defer values.Release()

	validity.Resize(int(byteLen))
	if valuesData.Len() > 0 {
		bitutil.CopyBitmap(valuesData.Buffers()[0].Buf(), valuesData.Offset(), valuesData.Len(),
			validity.Buf(), offset)
	}

	switch dt := valuesData.DataType().(type) {
	case *arrow.BooleanType:
		values.Resize(int(byteLen))

		if valuesData.Len() > 0 {
			bitutil.CopyBitmap(valuesData.Buffers()[1].Buf(), valuesData.Offset(), valuesData.Len(),
				values.Buf(), offset)
		}

		newValuesData = array.NewData(valuesData.DataType(), valuesData.Len(),
			[]*memory.Buffer{validity, values}, nil, valuesData.NullN(), offset)
	case *arrow.StringType, *arrow.BinaryType:
		values.Resize(int(newLength+1) * int(arrow.Int32SizeBytes))
		copy(values.Bytes()[offset*arrow.Int32SizeBytes:], valuesData.Buffers()[1].Bytes())
		tail := values.Bytes()[(offset+valuesData.Len())*arrow.Int32SizeBytes:]
		for j := arrow.Int32SizeBytes; j < len(tail); j *= 2 {
			copy(tail[j:], tail[:j])
		}

		newValuesData = array.NewData(valuesData.DataType(), valuesData.Len(),
			[]*memory.Buffer{validity, values, valuesData.Buffers()[2]}, nil, valuesData.NullN(), offset)
	case *arrow.LargeStringType, *arrow.LargeBinaryType:
		values.Resize(int(newLength+1) * int(arrow.Int64SizeBytes))
		copy(values.Bytes()[offset*arrow.Int64SizeBytes:], valuesData.Buffers()[1].Bytes())
		tail := values.Bytes()[(offset+valuesData.Len())*arrow.Int64SizeBytes:]
		for j := arrow.Int64SizeBytes; j < len(tail); j *= 2 {
			copy(tail[j:], tail[:j])
		}

		newValuesData = array.NewData(valuesData.DataType(), valuesData.Len(),
			[]*memory.Buffer{validity, values, valuesData.Buffers()[2]}, nil, valuesData.NullN(), offset)
	case arrow.FixedWidthDataType:
		width := dt.Bytes()
		values.Resize(int(newLength) * width)
		if valuesData.Len() > 0 {
			copy(values.Bytes()[offset*width:], valuesData.Buffers()[1].Bytes())
		}
		newValuesData = array.NewData(valuesData.DataType(), valuesData.Len(),
			[]*memory.Buffer{validity, values}, nil, valuesData.NullN(), offset)
	}

	withOffset := expected.Value.(*array.Data).Copy()
	withOffset.Children()[1].Release()
	withOffset.Children()[1] = newValuesData
	defer withOffset.Release()

	result, err := compute.RunEndDecode(suite.ctx, &compute.ArrayDatum{Value: withOffset})
	suite.Require().NoError(err)
	defer result.Release()

	assertDatumsEqual(suite.T(), suite.input, result, nil, nil)
}

func TestRunEndFunctions(t *testing.T) {
	// base64 encoded for testing fixed size binary
	const (
		valAba = `YWJh`
		valAbc = `YWJj`
		valAbd = `YWJk`
	)

	tests := []struct {
		name      string
		data      []string
		valueType arrow.DataType
	}{
		{"simple int32", []string{`[1, 1, 0, -5, -5, -5, 255, 255]`}, arrow.PrimitiveTypes.Int32},
		{"uint32 with nulls", []string{`[null, 1, 1, null, null, 5]`}, arrow.PrimitiveTypes.Uint32},
		{"boolean", []string{`[true, true, true, false, false]`}, arrow.FixedWidthTypes.Boolean},
		{"boolean no runs", []string{`[true, false, true, false, true, false, true, false, true]`}, arrow.FixedWidthTypes.Boolean},
		{"float64 len=1", []string{`[1.0]`}, arrow.PrimitiveTypes.Float64},
		{"bool chunks", []string{`[true, true]`, `[true, false, null, null, false]`, `[null, null]`}, arrow.FixedWidthTypes.Boolean},
		{"float32 chunked", []string{`[1, 1, 0, -5, -5]`, `[-5, 255, 255]`}, arrow.PrimitiveTypes.Float32},
		{"str", []string{`["foo", "foo", "foo", "bar", "bar", "baz", "bar", "bar", "foo", "foo"]`}, arrow.BinaryTypes.String},
		{"large str", []string{`["foo", "foo", "foo", "bar", "bar", "baz", "bar", "bar", "foo", "foo"]`}, arrow.BinaryTypes.LargeString},
		{"str chunked", []string{`["foo", "foo", null]`, `["foo", "bar", "bar"]`, `[null, null, "baz"]`, `[null]`}, arrow.BinaryTypes.String},
		{"empty arrs", []string{`[]`}, arrow.PrimitiveTypes.Float32},
		{"empty str array", []string{`[]`}, arrow.BinaryTypes.String},
		{"empty chunked", []string{`[]`, `[]`, `[]`}, arrow.FixedWidthTypes.Boolean},
		{"fsb", []string{`["` + valAba + `", "` + valAba + `", null, "` + valAbc + `", "` + valAbd + `", "` + valAbd + `", "` + valAbd + `"]`}, &arrow.FixedSizeBinaryType{ByteWidth: 3}},
		{"fsb chunked", []string{`["` + valAba + `", "` + valAba + `", null]`, `["` + valAbc + `", "` + valAbd + `", "` + valAbd + `", "` + valAbd + `"]`, `[]`}, &arrow.FixedSizeBinaryType{ByteWidth: 3}}}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			for _, runEndType := range runEndTypes {
				t.Run("run_ends="+runEndType.String(), func(t *testing.T) {
					suite.Run(t, &RunEndEncodeDecodeSuite{
						runEndType: runEndType,
						valueType:  tt.valueType,
						jsonData:   tt.data,
					})
				})
			}
		})
	}
}

func benchRunEndEncode(b *testing.B, sz int, nullProb float64, runEndType, valueType arrow.DataType) {
	b.Run("encode", func(b *testing.B) {
		var (
			mem = memory.NewCheckedAllocator(memory.DefaultAllocator)
			rng = gen.NewRandomArrayGenerator(seed, mem)
		)

		values := rng.ArrayOf(valueType.ID(), int64(sz), nullProb)
		b.Cleanup(func() {
			values.Release()
		})

		var (
			res   compute.Datum
			err   error
			ctx   = compute.WithAllocator(context.Background(), mem)
			input = &compute.ArrayDatum{Value: values.Data()}
			opts  = compute.RunEndEncodeOptions{RunEndType: runEndType}

			byts int64
		)

		for _, buf := range values.Data().Buffers() {
			if buf != nil {
				byts += int64(buf.Len())
			}
		}

		b.SetBytes(byts)
		b.ResetTimer()
		for n := 0; n < b.N; n++ {
			res, err = compute.RunEndEncode(ctx, opts, input)
			b.StopTimer()
			if err != nil {
				b.Fatal(err)
			}
			res.Release()
			b.StartTimer()
		}
	})
}

func benchRunEndDecode(b *testing.B, sz int, nullProb float64, runEndType, valueType arrow.DataType) {
	b.Run("decode", func(b *testing.B) {
		var (
			mem = memory.NewCheckedAllocator(memory.DefaultAllocator)
			rng = gen.NewRandomArrayGenerator(seed, mem)
		)

		values := rng.ArrayOf(valueType.ID(), int64(sz), nullProb)
		b.Cleanup(func() {
			values.Release()
		})

		var (
			res        compute.Datum
			ctx        = compute.WithAllocator(context.Background(), mem)
			opts       = compute.RunEndEncodeOptions{RunEndType: runEndType}
			input, err = compute.RunEndEncode(ctx, opts, &compute.ArrayDatum{Value: values.Data()})
			byts       int64
		)

		if err != nil {
			b.Fatal(err)
		}

		for _, buf := range values.Data().Buffers() {
			if buf != nil {
				byts += int64(buf.Len())
			}
		}

		b.SetBytes(byts)
		b.ResetTimer()
		for n := 0; n < b.N; n++ {
			res, err = compute.RunEndDecode(ctx, input)
			b.StopTimer()
			if err != nil {
				b.Fatal(err)
			}
			res.Release()
			b.StartTimer()
		}
	})
}

func BenchmarkRunEndKernels(b *testing.B) {
	args := []struct {
		sz       int
		nullProb float64
	}{
		{CpuCacheSizes[2], 0},
		{CpuCacheSizes[2], 0.5},
		{CpuCacheSizes[2], 1},
	}

	runEnds := []struct {
		dt     arrow.DataType
		maxLen int
	}{
		{arrow.PrimitiveTypes.Int16, math.MaxInt16},
		{arrow.PrimitiveTypes.Int32, math.MaxInt32},
		{arrow.PrimitiveTypes.Int64, math.MaxInt64},
	}

	for _, a := range args {
		b.Run(fmt.Sprintf("nullprob=%.1f", a.nullProb), func(b *testing.B) {
			for _, runEndType := range runEnds {
				sz := exec.Min(a.sz, runEndType.maxLen)
				b.Run("run_ends_type="+runEndType.dt.String(), func(b *testing.B) {
					for _, valType := range append(numericTypes, arrow.BinaryTypes.String, arrow.FixedWidthTypes.Boolean) {
						b.Run("value_type="+valType.String(), func(b *testing.B) {
							benchRunEndEncode(b, sz, a.nullProb, runEndType.dt, valType)
							benchRunEndDecode(b, sz, a.nullProb, runEndType.dt, valType)
						})
					}
				})
			}
		})
	}
}