-
Notifications
You must be signed in to change notification settings - Fork 154
/
window.go
479 lines (436 loc) · 11.8 KB
/
window.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
package universe
import (
"fmt"
"math"
"github.com/influxdata/flux"
"github.com/influxdata/flux/execute"
"github.com/influxdata/flux/plan"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
"github.com/pkg/errors"
)
const WindowKind = "window"
type WindowOpSpec struct {
Every flux.Duration `json:"every"`
Period flux.Duration `json:"period"`
Offset flux.Duration `json:"offset"`
TimeColumn string `json:"timeColumn"`
StopColumn string `json:"stopColumn"`
StartColumn string `json:"startColumn"`
CreateEmpty bool `json:"createEmpty"`
}
var infinityVar = values.NewDuration(math.MaxInt64)
func init() {
windowSignature := flux.FunctionSignature(
map[string]semantic.PolyType{
"every": semantic.Duration,
"period": semantic.Duration,
"offset": semantic.Duration,
"timeColumn": semantic.String,
"startColumn": semantic.String,
"stopColumn": semantic.String,
"createEmpty": semantic.Bool,
},
nil,
)
flux.RegisterPackageValue("universe", WindowKind, flux.FunctionValue(WindowKind, createWindowOpSpec, windowSignature))
flux.RegisterOpSpec(WindowKind, newWindowOp)
flux.RegisterPackageValue("universe", "inf", infinityVar)
plan.RegisterProcedureSpec(WindowKind, newWindowProcedure, WindowKind)
plan.RegisterPhysicalRules(WindowTriggerPhysicalRule{})
execute.RegisterTransformation(WindowKind, createWindowTransformation)
}
func createWindowOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) {
if err := a.AddParentFromArgs(args); err != nil {
return nil, err
}
spec := new(WindowOpSpec)
every, everySet, err := args.GetDuration("every")
if err != nil {
return nil, err
}
if everySet {
spec.Every = flux.Duration(every)
}
period, periodSet, err := args.GetDuration("period")
if err != nil {
return nil, err
}
if periodSet {
spec.Period = period
}
if offset, ok, err := args.GetDuration("offset"); err != nil {
return nil, err
} else if ok {
spec.Offset = offset
}
if !everySet && !periodSet {
return nil, errors.New(`window function requires at least one of "every" or "period" to be set`)
}
if label, ok, err := args.GetString("timeColumn"); err != nil {
return nil, err
} else if ok {
spec.TimeColumn = label
} else {
spec.TimeColumn = execute.DefaultTimeColLabel
}
if label, ok, err := args.GetString("startColumn"); err != nil {
return nil, err
} else if ok {
spec.StartColumn = label
} else {
spec.StartColumn = execute.DefaultStartColLabel
}
if label, ok, err := args.GetString("stopColumn"); err != nil {
return nil, err
} else if ok {
spec.StopColumn = label
} else {
spec.StopColumn = execute.DefaultStopColLabel
}
if createEmpty, ok, err := args.GetBool("createEmpty"); err != nil {
return nil, err
} else if ok {
spec.CreateEmpty = createEmpty
} else {
spec.CreateEmpty = false
}
// Apply defaults
if !everySet {
spec.Every = spec.Period
}
if !periodSet {
spec.Period = spec.Every
}
return spec, nil
}
func newWindowOp() flux.OperationSpec {
return new(WindowOpSpec)
}
func (s *WindowOpSpec) Kind() flux.OperationKind {
return WindowKind
}
type WindowProcedureSpec struct {
plan.DefaultCost
Window plan.WindowSpec
TimeColumn,
StartColumn,
StopColumn string
CreateEmpty bool
}
func newWindowProcedure(qs flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) {
s, ok := qs.(*WindowOpSpec)
if !ok {
return nil, fmt.Errorf("invalid spec type %T", qs)
}
p := &WindowProcedureSpec{
Window: plan.WindowSpec{
Every: s.Every,
Period: s.Period,
Offset: s.Offset,
},
TimeColumn: s.TimeColumn,
StartColumn: s.StartColumn,
StopColumn: s.StopColumn,
CreateEmpty: s.CreateEmpty,
}
return p, nil
}
func (s *WindowProcedureSpec) Kind() plan.ProcedureKind {
return WindowKind
}
func (s *WindowProcedureSpec) Copy() plan.ProcedureSpec {
ns := new(WindowProcedureSpec)
ns.Window = s.Window
return ns
}
func createWindowTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*WindowProcedureSpec)
if !ok {
return nil, nil, fmt.Errorf("invalid spec type %T", spec)
}
cache := execute.NewTableBuilderCache(a.Allocator())
d := execute.NewDataset(id, mode, cache)
bounds := a.StreamContext().Bounds()
if bounds == nil {
return nil, nil, errors.New("nil bounds passed to window")
}
t := NewFixedWindowTransformation(
d,
cache,
*bounds,
execute.NewWindow(
execute.Duration(s.Window.Every),
execute.Duration(s.Window.Period),
execute.Duration(s.Window.Offset)),
s.TimeColumn,
s.StartColumn,
s.StopColumn,
s.CreateEmpty,
)
return t, d, nil
}
type fixedWindowTransformation struct {
d execute.Dataset
cache execute.TableBuilderCache
w execute.Window
bounds execute.Bounds
allBounds []execute.Bounds
timeCol,
startCol,
stopCol string
createEmpty bool
}
func NewFixedWindowTransformation(
d execute.Dataset,
cache execute.TableBuilderCache,
bounds execute.Bounds,
w execute.Window,
timeCol,
startCol,
stopCol string,
createEmpty bool,
) execute.Transformation {
t := &fixedWindowTransformation{
d: d,
cache: cache,
w: w,
bounds: bounds,
timeCol: timeCol,
startCol: startCol,
stopCol: stopCol,
createEmpty: createEmpty,
}
if createEmpty {
t.generateWindowsWithinBounds()
}
return t
}
func (t *fixedWindowTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) (err error) {
panic("not implemented")
}
func (t *fixedWindowTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
timeIdx := execute.ColIdx(t.timeCol, tbl.Cols())
if timeIdx < 0 {
return fmt.Errorf("missing time column %q", t.timeCol)
}
newCols := make([]flux.ColMeta, 0, len(tbl.Cols())+2)
keyCols := make([]flux.ColMeta, 0, len(tbl.Cols())+2)
keyColMap := make([]int, 0, len(tbl.Cols())+2)
startColIdx := -1
stopColIdx := -1
for j, c := range tbl.Cols() {
keyIdx := execute.ColIdx(c.Label, tbl.Key().Cols())
keyed := keyIdx >= 0
if c.Label == t.startCol {
startColIdx = j
keyed = true
}
if c.Label == t.stopCol {
stopColIdx = j
keyed = true
}
newCols = append(newCols, c)
if keyed {
keyCols = append(keyCols, c)
keyColMap = append(keyColMap, keyIdx)
}
}
if startColIdx == -1 {
startColIdx = len(newCols)
c := flux.ColMeta{
Label: t.startCol,
Type: flux.TTime,
}
newCols = append(newCols, c)
keyCols = append(keyCols, c)
keyColMap = append(keyColMap, len(keyColMap))
}
if stopColIdx == -1 {
stopColIdx = len(newCols)
c := flux.ColMeta{
Label: t.stopCol,
Type: flux.TTime,
}
newCols = append(newCols, c)
keyCols = append(keyCols, c)
keyColMap = append(keyColMap, len(keyColMap))
}
// Abort processing if no data will match bounds
if t.bounds.IsEmpty() {
return nil
}
for _, bnds := range t.allBounds {
key := t.newWindowGroupKey(tbl, keyCols, bnds, keyColMap)
builder, created := t.cache.TableBuilder(key)
if created {
for _, c := range newCols {
_, err := builder.AddCol(c)
if err != nil {
return err
}
}
}
}
return tbl.Do(func(cr flux.ColReader) error {
l := cr.Len()
for i := 0; i < l; i++ {
tm := values.Time(cr.Times(timeIdx).Value(i))
bounds := t.getWindowBounds(tm)
for _, bnds := range bounds {
key := t.newWindowGroupKey(tbl, keyCols, bnds, keyColMap)
builder, created := t.cache.TableBuilder(key)
if created {
for _, c := range newCols {
_, err := builder.AddCol(c)
if err != nil {
return err
}
}
}
for j, c := range builder.Cols() {
switch c.Label {
case t.startCol:
if err := builder.AppendTime(startColIdx, bnds.Start); err != nil {
return err
}
case t.stopCol:
if err := builder.AppendTime(stopColIdx, bnds.Stop); err != nil {
return err
}
default:
if err := builder.AppendValue(j, execute.ValueForRow(cr, i, j)); err != nil {
return err
}
}
}
}
}
return nil
})
}
func (t *fixedWindowTransformation) newWindowGroupKey(tbl flux.Table, keyCols []flux.ColMeta, bnds execute.Bounds, keyColMap []int) flux.GroupKey {
cols := make([]flux.ColMeta, len(keyCols))
vs := make([]values.Value, len(keyCols))
for j, c := range keyCols {
cols[j] = c
switch c.Label {
case t.startCol:
vs[j] = values.NewTime(bnds.Start)
case t.stopCol:
vs[j] = values.NewTime(bnds.Stop)
default:
vs[j] = tbl.Key().Value(keyColMap[j])
}
}
return execute.NewGroupKey(cols, vs)
}
func (t *fixedWindowTransformation) clipBounds(bs []execute.Bounds) {
for i := range bs {
bs[i] = t.bounds.Intersect(bs[i])
}
}
func (t *fixedWindowTransformation) getWindowBounds(tm execute.Time) []execute.Bounds {
if t.w.Every == infinityVar.Duration() {
return []execute.Bounds{t.bounds}
}
bs := t.w.GetOverlappingBounds(execute.Bounds{Start: tm, Stop: tm + 1})
t.clipBounds(bs)
return bs
}
func (t *fixedWindowTransformation) generateWindowsWithinBounds() {
if t.w.Every == infinityVar.Duration() {
t.allBounds = []execute.Bounds{
{Start: execute.MinTime, Stop: execute.MaxTime},
}
return
}
bs := t.w.GetOverlappingBounds(t.bounds)
t.clipBounds(bs)
t.allBounds = bs
}
func (t *fixedWindowTransformation) UpdateWatermark(id execute.DatasetID, mark execute.Time) error {
return t.d.UpdateWatermark(mark)
}
func (t *fixedWindowTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *fixedWindowTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
}
// WindowTriggerPhysicalRule rewrites a physical window operation
// to use a narrow trigger if certain conditions are met.
type WindowTriggerPhysicalRule struct{}
func (WindowTriggerPhysicalRule) Name() string {
return "WindowTriggerPhysicalRule"
}
// Pattern matches the physical operator pattern consisting of a window
// operator with a single predecessor of any kind.
func (WindowTriggerPhysicalRule) Pattern() plan.Pattern {
return plan.PhysPat(WindowKind, plan.Any())
}
// Rewrite modifies a window's trigger spec so long as it doesn't have any
// window descendents that occur earlier in the plan and as long as none
// of its descendents merge multiple streams together like union and join.
func (WindowTriggerPhysicalRule) Rewrite(window plan.Node) (plan.Node, bool, error) {
// This rule's pattern ensures us only one predecessor
if !hasValidPredecessors(window.Predecessors()[0]) {
return window, false, nil
}
// This rule's pattern ensures us a physical operator
ppn := window.(*plan.PhysicalPlanNode)
if ppn.TriggerSpec != nil {
return ppn, false, nil
}
ppn.TriggerSpec = plan.NarrowTransformationTriggerSpec{}
return ppn, true, nil
}
func hasValidPredecessors(node plan.Node) bool {
pred := node.Predecessors()
// Source nodes might not produce uniform time bounds for all
// tables in which case we can't optimize window. However if a
// source is a BoundsAwareProcedureSpec then it must produce
// bounded data in which case we can perform the optimization.
if len(pred) == 0 {
s := node.ProcedureSpec()
n, ok := s.(plan.BoundsAwareProcedureSpec)
return ok && n.TimeBounds(nil) != nil
}
kind := node.Kind()
switch kind {
// Range gives the same static time bounds to the entire stream,
// so no need to recurse.
case RangeKind:
return true
case ColumnsKind,
CumulativeSumKind,
DerivativeKind,
DifferenceKind,
DistinctKind,
FilterKind,
FirstKind,
GroupKind,
KeyValuesKind,
KeysKind,
LastKind,
LimitKind,
MaxKind,
MinKind,
ExactQuantileSelectKind,
SampleKind,
DropKind,
KeepKind,
DuplicateKind,
RenameKind,
ShiftKind,
SortKind,
StateTrackingKind,
UniqueKind:
default:
return false
}
if len(pred) == 1 {
return hasValidPredecessors(pred[0])
}
return false
}