-
Notifications
You must be signed in to change notification settings - Fork 153
/
join.go
600 lines (520 loc) · 14.5 KB
/
join.go
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package experimental
import (
"context"
"sort"
"sync"
"github.com/influxdata/flux"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/compiler"
"github.com/influxdata/flux/execute"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/interpreter"
"github.com/influxdata/flux/memory"
"github.com/influxdata/flux/plan"
"github.com/influxdata/flux/runtime"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
)
const joinKind = "experimental.join"
func init() {
signature := runtime.MustLookupBuiltinType("experimental", "join")
runtime.RegisterPackageValue("experimental", "join", flux.MustValue(flux.FunctionValue("join", createJoinOpSpec, signature)))
flux.RegisterOpSpec(joinKind, newJoinOp)
plan.RegisterProcedureSpec(joinKind, newMergeJoinProcedure, joinKind)
execute.RegisterTransformation(joinKind, createMergeJoinTransformation)
}
type JoinOpSpec struct {
Left flux.OperationID `json:"left"`
Right flux.OperationID `json:"right"`
Fn interpreter.ResolvedFunction `json:"fn"`
l, r *flux.TableObject
}
func (s *JoinOpSpec) IDer(ider flux.IDer) {
s.Left = ider.ID(s.l)
s.Right = ider.ID(s.r)
}
func createJoinOpSpec(args flux.Arguments, p *flux.Administration) (flux.OperationSpec, error) {
l, ok := args.Get("left")
if !ok {
return nil, errors.New(codes.Invalid, "argument 'left' not present")
}
// TODO(josh): The type system should ensure that this
// assertion is redundant. Unfortunately it does not.
// Remove this check when type inference is fixed.
//
left, ok := l.(*flux.TableObject)
if !ok {
return nil, errors.New(codes.Invalid, "argument 'left' must be a table stream")
}
p.AddParent(left)
r, ok := args.Get("right")
if !ok {
return nil, errors.New(codes.Invalid, "argument 'right' not present")
}
// Same comment as above. The type system should ensure
// that the folowing cast never panics.
//
right, ok := r.(*flux.TableObject)
if !ok {
return nil, errors.New(codes.Invalid, "argument 'right' must be a table stream")
}
p.AddParent(right)
f, err := args.GetRequiredFunction("fn")
if err != nil {
return nil, err
}
fn, err := interpreter.ResolveFunction(f)
if err != nil {
return nil, err
}
return &JoinOpSpec{
Fn: fn,
l: left,
r: right,
}, nil
}
func newJoinOp() flux.OperationSpec {
return new(JoinOpSpec)
}
func (s *JoinOpSpec) Kind() flux.OperationKind {
return joinKind
}
type MergeJoinProcedureSpec struct {
plan.DefaultCost
Fn interpreter.ResolvedFunction `json:"fn"`
}
func newMergeJoinProcedure(spec flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) {
s, ok := spec.(*JoinOpSpec)
if !ok {
return nil, errors.Newf(codes.Internal, "invalid spec type %T", spec)
}
return &MergeJoinProcedureSpec{Fn: s.Fn}, nil
}
func (s *MergeJoinProcedureSpec) Kind() plan.ProcedureKind {
return joinKind
}
func (s *MergeJoinProcedureSpec) Copy() plan.ProcedureSpec {
return &MergeJoinProcedureSpec{Fn: s.Fn.Copy()}
}
func createMergeJoinTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*MergeJoinProcedureSpec)
if !ok {
return nil, nil, errors.Newf(codes.Internal, "invalid spec type %T", spec)
}
parents := a.Parents()
c := NewMergeJoinCache(a.Context(), a.Allocator(), s.Fn, parents[0], parents[1])
d := execute.NewDataset(id, mode, c)
t := NewMergeJoinTransformation(d, c)
return t, d, nil
}
type mergeJoinTransformation struct {
execute.ExecutionNode
mu sync.Mutex
d execute.Dataset
cache *mergeJoinCache
done bool
}
func NewMergeJoinTransformation(d execute.Dataset, cache *mergeJoinCache) *mergeJoinTransformation {
return &mergeJoinTransformation{
d: d,
cache: cache,
}
}
func (t *mergeJoinTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
t.mu.Lock()
defer t.mu.Unlock()
columns := tbl.Cols()
timeCol := execute.ColIdx(execute.DefaultTimeColLabel, columns)
if timeCol == -1 {
return errors.New(codes.Invalid, "no _time column found")
}
var readers []flux.ColReader
if err := tbl.Do(func(cr flux.ColReader) error {
cr.Retain()
readers = append(readers, cr)
return nil
}); err != nil {
return err
}
t.cache.insert(id, tbl.Key(), NewRowIterator(columns, readers, timeCol))
return nil
}
func (t *mergeJoinTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return errors.New(codes.Unimplemented)
}
func (t *mergeJoinTransformation) UpdateWatermark(id execute.DatasetID, mark execute.Time) error {
t.mu.Lock()
defer t.mu.Unlock()
return t.d.UpdateWatermark(mark)
}
func (t *mergeJoinTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
t.mu.Lock()
defer t.mu.Unlock()
return t.d.UpdateProcessingTime(pt)
}
func (t *mergeJoinTransformation) Finish(id execute.DatasetID, err error) {
t.mu.Lock()
defer t.mu.Unlock()
if err != nil || t.done {
t.d.Finish(err)
t.cache.clean()
}
t.done = true
}
func NewMergeJoinCache(ctx context.Context, alloc *memory.Allocator, fn interpreter.ResolvedFunction, left, right execute.DatasetID) *mergeJoinCache {
return &mergeJoinCache{
left: left,
right: right,
fn: newRowJoinFn(fn.Fn, compiler.ToScope(fn.Scope)),
data: execute.NewGroupLookup(),
ctx: ctx,
alloc: alloc,
}
}
type mergeJoinCache struct {
left, right execute.DatasetID
fn *rowJoinFn
data *execute.GroupLookup
spec plan.TriggerSpec
ctx context.Context
alloc *memory.Allocator
}
type cacheEntry struct {
l, r *RowIterator
}
func (e *cacheEntry) ready() bool {
return e.l != nil && e.r != nil && e.l.len != 0 && e.r.len != 0
}
func (c *mergeJoinCache) insert(id execute.DatasetID, key flux.GroupKey, iter *RowIterator) {
if entry, ok := c.data.Lookup(key); ok {
switch id {
case c.left:
entry.(*cacheEntry).l = iter
case c.right:
entry.(*cacheEntry).r = iter
}
} else {
switch id {
case c.left:
c.data.Set(key, &cacheEntry{l: iter})
case c.right:
c.data.Set(key, &cacheEntry{r: iter})
}
}
}
func (c *mergeJoinCache) delete(key flux.GroupKey) {
if entry, ok := c.data.Delete(key); ok {
t := entry.(*cacheEntry)
if t.l != nil {
for _, reader := range t.l.readers {
reader.Release()
}
}
if t.r != nil {
for _, reader := range t.r.readers {
reader.Release()
}
}
}
}
func (c *mergeJoinCache) clean() {
var keys []flux.GroupKey
c.data.Range(func(key flux.GroupKey, value interface{}) {
keys = append(keys, key)
})
for _, key := range keys {
c.delete(key)
}
}
func (c *mergeJoinCache) Table(key flux.GroupKey) (flux.Table, error) {
entry, ok := c.data.Lookup(key)
if !ok {
return nil, errors.Newf(codes.Internal, "no entry for group key %v in cache", key)
}
t := entry.(*cacheEntry)
if t.l == nil || t.r == nil {
return nil, errors.Newf(codes.Internal, "no entry for group key %v in cache", key)
}
return c.join(key, t.l, t.r)
}
func (c *mergeJoinCache) ForEach(f func(flux.GroupKey)) {
c.data.Range(func(key flux.GroupKey, value interface{}) {
if value.(*cacheEntry).ready() {
f(key)
}
})
}
func (c *mergeJoinCache) ForEachWithContext(f func(flux.GroupKey, execute.Trigger, execute.TableContext)) {
c.data.Range(func(key flux.GroupKey, value interface{}) {
if value.(*cacheEntry).ready() {
f(key, execute.NewTriggerFromSpec(c.spec), execute.TableContext{
Key: key,
})
}
})
}
func (c *mergeJoinCache) DiscardTable(key flux.GroupKey) {
c.delete(key)
}
func (c *mergeJoinCache) ExpireTable(key flux.GroupKey) {
c.delete(key)
}
func (c *mergeJoinCache) SetTriggerSpec(spec plan.TriggerSpec) {
c.spec = spec
}
func (c *mergeJoinCache) join(key flux.GroupKey, a, b *RowIterator) (flux.Table, error) {
// Compile row fn for the input rows
if err := c.fn.Prepare(a.columns, b.columns); err != nil {
return nil, err
}
// Create a table builder for the output of the join
builder := execute.NewColListTableBuilder(key, c.alloc)
firstRow := true
i, j := 0, 0
NEXT:
ta := a.time(i)
tb := b.time(j)
if ta == -1 || tb == -1 {
goto DONE
}
if ta < tb {
i++
goto NEXT
}
if ta > tb {
j++
goto NEXT
}
// There may be multiple rows of b that match with single row of a.
// The following loop joins all such rows.
//
// Note there may be multiple rows of a that match with a single
// row of b. This is accounted for as the current index of b (j)
// is reset after the loop, while the current index of a (i) is
// incremented by one.
//
for k := j; ta == b.time(k); k++ {
// Evaluate fn over both input rows
obj, err := c.fn.Eval(c.ctx, a.record(i), b.record(k))
if err != nil {
return nil, err
}
// Build schema if this is the first row being joined
if firstRow {
if err := buildSchema(builder, obj); err != nil {
return nil, err
}
firstRow = false
}
// Check fn does not update the group key values.
// TODO(josh): This should be caught during planning.
// Remove this when the planner is made schema aware.
if ok := objContainsKey(obj, key); !ok {
return nil, errors.New(codes.Invalid, "argument 'fn' may not modify group key")
}
// The record obtained from calling fn may be added to output
if err := appendRowToBuilder(builder, obj); err != nil {
return nil, err
}
}
i++
goto NEXT
DONE:
return builder.Table()
}
// objContainsKey checks if an object contains a specific group key
func objContainsKey(obj values.Object, key flux.GroupKey) bool {
for _, col := range key.Cols() {
if v, ok := obj.Get(col.Label); !ok || !v.Equal(key.LabelValue(col.Label)) {
return false
}
}
return true
}
// buildSchema adds a schema defined by an object to an empty builder
func buildSchema(builder *execute.ColListTableBuilder, obj values.Object) error {
schema := make([]flux.ColMeta, 0, obj.Len())
obj.Range(func(name string, v values.Value) {
schema = append(schema, flux.ColMeta{
Label: name,
Type: execute.ConvertFromKind(v.Type().Nature()),
})
})
sort.Slice(schema, func(i, j int) bool {
return schema[i].Label < schema[j].Label
})
for _, col := range schema {
if _, err := builder.AddCol(col); err != nil {
return err
}
}
return nil
}
func appendRowToBuilder(builder *execute.ColListTableBuilder, obj values.Object) error {
var err error
obj.Range(func(name string, v values.Value) {
idx := execute.ColIdx(name, builder.Cols())
if idx < 0 {
err = errors.Newf(codes.NotFound, "column %s not found", name)
return
}
if err = builder.AppendValue(idx, v); err != nil {
return
}
})
return err
}
func NewRowIterator(columns []flux.ColMeta, readers []flux.ColReader, timeCol int) *RowIterator {
offsets, l := make([]int, len(readers)), 0
for i, r := range readers {
offsets[i] = l
l += r.Len()
}
return &RowIterator{
row: make(map[string]values.Value),
len: l,
columns: columns,
readers: readers,
offsets: offsets,
timeCol: timeCol,
}
}
// RowIterator iterates over the rows of several column readers
type RowIterator struct {
len int
row map[string]values.Value
timeCol int
offsets []int
readers []flux.ColReader
columns []flux.ColMeta
}
// time returns the time at index idx
func (iter *RowIterator) time(idx int) int64 {
for i := len(iter.readers) - 1; i >= 0; i-- {
o := iter.offsets[i]
r := iter.readers[i]
if idx >= o {
if idx-o >= r.Len() {
return -1
}
return r.Times(iter.timeCol).Value(idx - o)
}
}
return -1
}
// record returns the row at index idx
func (iter *RowIterator) record(idx int) map[string]values.Value {
for k := range iter.row {
delete(iter.row, k)
}
for i := len(iter.readers) - 1; i >= 0; i-- {
o := iter.offsets[i]
r := iter.readers[i]
if idx >= o {
for j, col := range r.Cols() {
iter.row[col.Label] = execute.ValueForRow(r, idx-o, j)
}
break
}
}
return iter.row
}
// rowJoinFn is equivalent to the lambda function (a, b) => ...
// Parameters a and b as well as the return value are all record types.
type rowJoinFn struct {
fn *semantic.FunctionExpression
scope compiler.Scope
preparedFn compiler.Func
}
func newRowJoinFn(fn *semantic.FunctionExpression, scope compiler.Scope) *rowJoinFn {
return &rowJoinFn{
fn: fn,
scope: scope,
}
}
func (fn *rowJoinFn) Prepare(left, right []flux.ColMeta) error {
// Check the left and right types to make sure required properties are
// columns in their respective ColMeta.
fntype := fn.fn.TypeOf()
fnarguments, err := fntype.SortedArguments()
if err != nil {
return err
}
leftarguments, err := fnarguments[0].TypeOf()
if err != nil {
return err
}
leftproperties, err := leftarguments.SortedProperties()
if err == nil {
// MonoType is a record, so we can check the properties are columns.
for _, property := range leftproperties {
name := property.Name()
found := false
for _, column := range left {
if column.Label == name {
found = true
break
}
}
if !found {
return errors.Newf(codes.Invalid, "left is missing label %s", name)
}
}
}
rightarguments, err := fnarguments[1].TypeOf()
if err != nil {
return err
}
rightproperties, err := rightarguments.SortedProperties()
if err == nil {
// MonoType is a record, so we can check the properties are columns.
for _, property := range rightproperties {
name := property.Name()
found := false
for _, column := range right {
if column.Label == name {
found = true
break
}
}
if !found {
return errors.Newf(codes.Invalid, "right is missing label %s", name)
}
}
}
l := make([]semantic.PropertyType, len(left))
for j, col := range left {
l[j] = semantic.PropertyType{
Key: []byte(col.Label),
Value: flux.SemanticType(col.Type),
}
}
r := make([]semantic.PropertyType, len(right))
for j, col := range right {
r[j] = semantic.PropertyType{
Key: []byte(col.Label),
Value: flux.SemanticType(col.Type),
}
}
in := semantic.NewObjectType([]semantic.PropertyType{
{Key: []byte("left"), Value: semantic.NewObjectType(l)},
{Key: []byte("right"), Value: semantic.NewObjectType(r)},
})
f, err := compiler.Compile(fn.scope, fn.fn, in)
if err != nil {
return err
}
fn.preparedFn = f
return nil
}
func (fn *rowJoinFn) Eval(ctx context.Context, left, right map[string]values.Value) (values.Object, error) {
// TODO(jsternberg): This is not memory performant and should be updated.
obj, err := fn.preparedFn.Eval(ctx, values.NewObjectWithValues(map[string]values.Value{
"left": values.NewObjectWithValues(left),
"right": values.NewObjectWithValues(right),
}))
if err != nil {
return nil, err
}
return obj.Object(), nil
}