This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
core.zig
1992 lines (1807 loc) · 89.9 KB
/
core.zig
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The core of dida handles all the actual computation.
//! It exposes an api that is maximally flexible but also verbose and error-prone.
//! See ./sugar.zig for a friendlier layer on top of the core.
//!
//! Assume that all struct parameters are owned unless otherwise stated.
//! Assume all function arguments are borrowed unless otherwise stated.
const std = @import("std");
const dida = @import("../dida.zig");
const u = dida.util;
/// The basic unit of data in dida.
pub const Value = union(enum) {
String: []const u8,
Number: f64,
pub fn deinit(self: *Value, allocator: u.Allocator) void {
switch (self.*) {
.String => |string| allocator.free(string),
.Number => {},
}
self.* = undefined;
}
};
/// Every operation takes rows as inputs and produces rows as outputs.
// TODO This will eventually be replaced by raw bytes plus an optional type tag, so that users of dida can use whatever values and serde scheme they want.
pub const Row = struct {
values: []const Value,
pub fn deinit(self: *Row, allocator: u.Allocator) void {
for (self.values) |_value| {
// can't deinit through []const
var value = _value;
value.deinit(allocator);
}
allocator.free(self.values);
self.* = undefined;
}
};
/// A [bag](https://en.wikipedia.org/wiki/Multiset) of rows.
/// The dataflow is a graph of operations, each of which takes one or more bags of rows as inputs and produces a bag of rows as outputs.
pub const Bag = struct {
/// Rows are all borrowed.
rows: u.DeepHashMap(Row, isize),
pub fn init(allocator: u.Allocator) Bag {
return .{
.rows = u.DeepHashMap(Row, isize).init(allocator),
};
}
pub fn deinit(self: *Bag) void {
// rows are all borrowed so no need to free them
self.rows.deinit();
self.* = undefined;
}
pub fn update(self: *Bag, row: Row, diff: isize) !void {
const entry = try self.rows.getOrPutValue(row, 0);
entry.value_ptr.* += diff;
_ = if (entry.value_ptr.* == 0) self.rows.remove(row);
}
};
/// The result of comparing two elements in a [partially ordered set](https://en.wikipedia.org/wiki/Partially_ordered_set).
/// (Field names are weird to be consistent with std.math.Order)
pub const PartialOrder = enum {
lt,
eq,
gt,
none,
pub fn isLessThanOrEqual(self: PartialOrder) bool {
return switch (self) {
.lt, .eq => true,
.gt, .none => false,
};
}
};
/// > Time is what prevents everything from happening all at once.
///
/// Timestamps represent the logical time something happened.
/// The first coord represents the logical time in the dataflow as a whole.
/// Each extra coord represent the iteration number within some enclosing loop in the dataflow (outermost loop first, innermost loop last).
pub const Timestamp = struct {
coords: []const usize,
pub fn initLeast(allocator: u.Allocator, num_coords: usize) !Timestamp {
var coords = try allocator.alloc(usize, num_coords);
for (coords) |*coord| coord.* = 0;
return Timestamp{ .coords = coords };
}
pub fn deinit(self: *Timestamp, allocator: u.Allocator) void {
allocator.free(self.coords);
self.* = undefined;
}
pub fn pushCoord(self: Timestamp, allocator: u.Allocator) !Timestamp {
var new_coords = try allocator.alloc(usize, self.coords.len + 1);
std.mem.copy(usize, new_coords, self.coords);
new_coords[new_coords.len - 1] = 0;
return Timestamp{ .coords = new_coords };
}
pub fn incrementCoord(self: Timestamp, allocator: u.Allocator) !Timestamp {
var new_coords = try allocator.dupe(usize, self.coords[0..self.coords.len]);
new_coords[new_coords.len - 1] += 1;
return Timestamp{ .coords = new_coords };
}
pub fn popCoord(self: Timestamp, allocator: u.Allocator) !Timestamp {
u.assert(self.coords.len > 0, "Tried to call popCoord on a timestamp with length 0", .{});
const new_coords = try allocator.dupe(usize, self.coords[0 .. self.coords.len - 1]);
return Timestamp{ .coords = new_coords };
}
/// A partial ordering on timestamps such that if a change at timestamp A could ever cause a change at timestamp B, then A <= B.
/// This is used to process changes in an order that is guaranteed to converge, and to define the behavior of frontiers.
pub fn causalOrder(self: Timestamp, other: Timestamp) PartialOrder {
u.assert(self.coords.len == other.coords.len, "Tried to compute causalOrder of timestamps with different lengths: {} vs {}", .{ self.coords.len, other.coords.len });
var lt: usize = 0;
var gt: usize = 0;
var eq: usize = 0;
for (self.coords) |self_coord, i| {
const other_coord = other.coords[i];
switch (std.math.order(self_coord, other_coord)) {
.lt => lt += 1,
.eq => eq += 1,
.gt => gt += 1,
}
}
if (eq == self.coords.len) return .eq;
if (lt + eq == self.coords.len) return .lt;
if (gt + eq == self.coords.len) return .gt;
return .none;
}
/// A total ordering on timestamps that is compatible with the causal order.
/// ie If `a.causalOrder(b) != .none` then `a.causalOrder(b) == a.lexicalOrder(b)`.
/// This is useful if you want to sort Timestamps by causal order - standard sorting algorithms don't always work well on partial orders.
pub fn lexicalOrder(self: Timestamp, other: Timestamp) std.math.Order {
u.assert(self.coords.len == other.coords.len, "Tried to compute lexicalOrder of timestamps with different lengths: {} vs {}", .{ self.coords.len, other.coords.len });
for (self.coords) |self_coord, i| {
const other_coord = other.coords[i];
switch (std.math.order(self_coord, other_coord)) {
.lt => return .lt,
.eq => {},
.gt => return .gt,
}
}
return .eq;
}
/// Returns the earliest timestamp that is greater than both the inputs (in the causal ordering).
pub fn leastUpperBound(allocator: u.Allocator, self: Timestamp, other: Timestamp) !Timestamp {
u.assert(self.coords.len == other.coords.len, "Tried to compute leastUpperBound of timestamps with different lengths: {} vs {}", .{ self.coords.len, other.coords.len });
var output_coords = try allocator.alloc(usize, self.coords.len);
for (self.coords) |self_coord, i| {
const other_coord = other.coords[i];
output_coords[i] = u.max(self_coord, other_coord);
}
return Timestamp{ .coords = output_coords };
}
};
/// A frontier represents the earliest timestamps in some set of timestamps (by causal order).
/// It's used to track progress in the dataflow and also to summarize the contents of a change batch.
pub const Frontier = struct {
allocator: u.Allocator,
/// Invariant: timestamps don't overlap - for any two timestamps t1 and t2 in timestamps `t1.causalOrder(t2) == .none`
timestamps: u.DeepHashSet(Timestamp),
pub fn init(allocator: u.Allocator) Frontier {
return Frontier{
.allocator = allocator,
.timestamps = u.DeepHashSet(Timestamp).init(allocator),
};
}
pub fn deinit(self: *Frontier) void {
{
var iter = self.timestamps.iterator();
while (iter.next()) |entry| {
entry.key_ptr.deinit(self.allocator);
}
}
self.timestamps.deinit();
self.* = undefined;
}
/// Compares `timestamp` to `self.timestamps`.
pub fn causalOrder(self: Frontier, timestamp: Timestamp) PartialOrder {
var iter = self.timestamps.iterator();
while (iter.next()) |entry| {
const order = entry.key_ptr.causalOrder(timestamp);
// Since the timestamps in `self.timestamps` are always mututally incomparable, we can never have `t1 < timestamp < t2`.
// So it's safe to return as soon as we find some comparison.
switch (order) {
.lt => return .lt,
.eq => return .eq,
.gt => return .gt,
.none => {},
}
}
return .none;
}
pub const Direction = enum { Later, Earlier };
/// Mutate `self` to a later (or earlier) frontier.
/// Remove any timestamps that are earlier (or later) than `timestamp`.
/// Reports any changes to the frontier into `changes_into`.
pub fn move(self: *Frontier, comptime direction: Direction, timestamp: Timestamp, changes_into: *u.ArrayList(FrontierChange)) !void {
u.assert(changes_into.items.len == 0, "Need to start with an empty changes_into buffer so can use it to remove timestamps", .{});
var iter = self.timestamps.iterator();
while (iter.next()) |entry| {
switch (timestamp.causalOrder(entry.key_ptr.*)) {
.eq, if (direction == .Later) .lt else .gt => {
// Moved in the wrong direction
u.assert(changes_into.items.len == 0, "Frontier timestamps invariant was broken", .{});
return;
},
if (direction == .Later) .gt else .lt => {
try changes_into.append(.{ .timestamp = entry.key_ptr.*, .diff = -1 });
},
.none => {},
}
}
// If we got this far, timestamp is being added to the frontier and might also be replacing some other timestamps that are currently on the frontier
for (changes_into.items) |frontier_change| {
_ = self.timestamps.remove(frontier_change.timestamp);
}
try changes_into.append(.{ .timestamp = try u.deepClone(timestamp, self.allocator), .diff = 1 });
try self.timestamps.put(try u.deepClone(timestamp, self.allocator), {});
}
};
/// Tracks both a bag of timestamps and the frontier of that bag.
/// This is used to incrementally compute the frontiers of each node in the graph as the dataflow progresses.
pub const SupportedFrontier = struct {
allocator: u.Allocator,
support: u.DeepHashMap(Timestamp, usize),
// Invariant: frontier contains exactly the least timestamps from support
frontier: Frontier,
pub fn init(allocator: u.Allocator) !SupportedFrontier {
return SupportedFrontier{
.allocator = allocator,
.support = u.DeepHashMap(Timestamp, usize).init(allocator),
.frontier = Frontier.init(allocator),
};
}
pub fn deinit(self: *SupportedFrontier) void {
{
var iter = self.support.iterator();
while (iter.next()) |entry| entry.key_ptr.deinit(self.allocator);
}
self.support.deinit();
self.frontier.deinit();
self.* = undefined;
}
/// Change the count of `timestamp` by `diff`.
/// Reports any changes to the frontier into `changes_into`.
/// Changes are owned by the caller.
pub fn update(self: *SupportedFrontier, timestamp: Timestamp, diff: isize, changes_into: *u.ArrayList(FrontierChange)) !void {
const support_entry = try self.support.getOrPut(timestamp);
if (!support_entry.found_existing) {
support_entry.key_ptr.* = try u.deepClone(support_entry.key_ptr.*, self.allocator);
support_entry.value_ptr.* = 0;
}
support_entry.value_ptr.* = @intCast(usize, @intCast(isize, support_entry.value_ptr.*) + diff);
if (support_entry.value_ptr.* == 0) {
// Timestamp was just removed, might have been in frontier
if (self.support.fetchRemove(timestamp)) |*remove_entry| {
remove_entry.key.deinit(self.allocator);
}
if (self.frontier.timestamps.fetchRemove(timestamp)) |*remove_entry| {
remove_entry.key.deinit(self.allocator);
// Removed this timestamp from frontier
try changes_into.append(.{ .timestamp = try u.deepClone(timestamp, self.allocator), .diff = -1 });
// Find timestamps in support that might now be on the frontier
var candidates = u.ArrayList(Timestamp).init(self.allocator);
defer candidates.deinit();
var iter = self.support.iterator();
while (iter.next()) |entry| {
if (timestamp.causalOrder(entry.key_ptr.*) == .lt)
try candidates.append(entry.key_ptr.*);
}
// Add in lexical order any candidates that are not past the current frontier (or past any earlier candidates)
std.sort.sort(Timestamp, candidates.items, {}, struct {
fn lessThan(_: void, a: Timestamp, b: Timestamp) bool {
return a.lexicalOrder(b) == .lt;
}
}.lessThan);
for (candidates.items) |candidate| {
if (self.frontier.causalOrder(candidate) == .none) {
try self.frontier.timestamps.put(try u.deepClone(candidate, self.allocator), {});
try changes_into.append(.{ .timestamp = try u.deepClone(candidate, self.allocator), .diff = 1 });
}
}
}
}
if (support_entry.value_ptr.* == diff) {
// Timestamp was just added, might be in frontier
if (self.frontier.causalOrder(timestamp) != .lt) {
// Add to frontier
try self.frontier.timestamps.put(try u.deepClone(timestamp, self.allocator), {});
try changes_into.append(.{ .timestamp = try u.deepClone(timestamp, self.allocator), .diff = 1 });
// Remove any other timestamp that is greater than the new timestamp
var to_remove = u.ArrayList(Timestamp).init(self.allocator);
defer to_remove.deinit();
var iter = self.frontier.timestamps.iterator();
while (iter.next()) |frontier_entry| {
if (frontier_entry.key_ptr.causalOrder(timestamp) == .gt)
try to_remove.append(frontier_entry.key_ptr.*);
}
for (to_remove.items) |other_timestamp| {
_ = self.frontier.timestamps.remove(other_timestamp);
try changes_into.append(.{ .timestamp = other_timestamp, .diff = -1 });
}
}
}
}
};
/// Represents a single change to the set of earliest timestamps in a frontier.
pub const FrontierChange = struct {
timestamp: Timestamp,
diff: isize,
pub fn deinit(self: *FrontierChange, allocator: u.Allocator) void {
self.timestamp.deinit(allocator);
self.* = undefined;
}
};
/// Represents a change to some bag in the dataflow.
/// The count of `row` changed by `diff` at `timestamp`.
pub const Change = struct {
row: Row,
timestamp: Timestamp,
diff: isize,
pub fn deinit(self: *Change, allocator: u.Allocator) void {
self.row.deinit(allocator);
self.timestamp.deinit(allocator);
self.* = undefined;
}
};
pub const ConcatOrder = enum { LeftThenRight, RightThenLeft };
/// A batch of changes, conveniently pre-sorted and de-duplicated.
pub const ChangeBatch = struct {
/// Invariant: for every change in changes, lower_bound.causalOrder(change).isLessThanOrEqual()
lower_bound: Frontier,
/// Invariant: non-empty,
/// Invariant: sorted by row/timestamp
/// Invariant: no two changes with same row/timestamp
// TODO should be `[]const Change`?
changes: []Change,
pub fn empty(allocator: u.Allocator) ChangeBatch {
var empty_changes = [0]Change{};
return ChangeBatch{
.lower_bound = Frontier.init(allocator),
.changes = &empty_changes,
};
}
pub fn deinit(self: *ChangeBatch, allocator: u.Allocator) void {
for (self.changes) |*change| change.deinit(allocator);
allocator.free(self.changes);
self.lower_bound.deinit();
self.* = undefined;
}
/// Find the first row after `from` that starts with `row[0..key_columns]` or, if there is no such row, the position where it would be.
/// IE returns `ix` such that:
/// * `self.changes[ix].row[0..key_columns] >= row[0..key_columns]` (or `ix == self.changes.len`)
/// * `self.changes[ix-1].row[0..key_columns] < row[0..key_columns]` (or `ix == 0`)
/// Uses a binary search with increasing step size.
/// If `from == self.changes.len`, then returns `from`.
pub fn seekRowStart(self: ChangeBatch, from: usize, row: Row, key_columns: usize) usize {
u.assert(
from <= self.changes.len,
"Can't seek to row from a start point that is beyond the end of the batch",
.{},
);
if (from == self.changes.len or
u.deepOrder(
self.changes[from].row.values[0..key_columns],
row.values[0..key_columns],
) != .lt)
return from;
var lo = from;
var skip: usize = 1;
while (true) {
const next = lo + skip;
if (next >= self.changes.len) {
skip = self.changes.len - lo;
break;
}
if (u.deepOrder(
self.changes[next].row.values[0..key_columns],
row.values[0..key_columns],
) != .lt)
break;
lo = next;
skip *= 2;
}
var hi = lo + skip;
// now lo is < row and hi is >= row
u.assert(
u.deepOrder(
self.changes[lo].row.values[0..key_columns],
row.values[0..key_columns],
) == .lt,
"",
.{},
);
u.assert(
hi >= self.changes.len or
u.deepOrder(
self.changes[hi].row.values[0..key_columns],
row.values[0..key_columns],
) != .lt,
"",
.{},
);
while (hi - lo > 1) {
const mid = lo + @divTrunc(hi - lo, 2);
if (u.deepOrder(
self.changes[mid].row.values[0..key_columns],
row.values[0..key_columns],
) == .lt) {
lo = mid;
} else {
hi = mid;
}
}
return hi;
}
/// Find the last row after `from` that starts with `row[0..key_columns]` or, if there is no such row, the position where it would be.
/// IE returns `ix` such that:
/// * `self.changes[ix].row[0..key_columns] > row[0..key_columns]` (or `ix == self.changes.len`)
/// * `self.changes[ix-1].row[0..key_columns] <= row[0..key_columns]` (or `ix == 0`)
/// Uses a linear scan.
/// If `from == self.changes.len`, then returns `from`.
pub fn seekRowEnd(self: ChangeBatch, from: usize, row: Row, key_columns: usize) usize {
u.assert(
from <= self.changes.len,
"Can't seek to row from a start point that is beyond the end of the batch",
.{},
);
if (from == self.changes.len)
return from;
var ix = from;
while (ix < self.changes.len and
u.deepOrder(
self.changes[ix].row.values[0..key_columns],
row.values[0..key_columns],
) != .gt) ix += 1;
return ix;
}
/// Find the last row after `from` that starts with `self.changes[from].row[0..key_columns]`
/// If `from == self.changes.len`, then returns `from`.
pub fn seekCurrentRowEnd(self: ChangeBatch, from: usize, key_columns: usize) usize {
u.assert(
from <= self.changes.len,
"Can't seek to row from a start point that is beyond the end of the batch",
.{},
);
if (from == self.changes.len)
return from;
return self.seekRowEnd(from + 1, self.changes[from].row, key_columns);
}
/// Relational join on the first `key_columns` columns of self and other.
/// Produces rows that look like `self_row ++ other_row[key_columns..]`.
pub fn mergeJoin(
self: ChangeBatch,
self_frontier: Frontier,
other: ChangeBatch,
key_columns: usize,
concat_order: ConcatOrder,
into_builder: *ChangeBatchBuilder,
) !void {
var ix_self: usize = 0;
var ix_other: usize = 0;
while (ix_self < self.changes.len and ix_other < other.changes.len) {
switch (u.deepOrder(
self.changes[ix_self].row.values[0..key_columns],
other.changes[ix_other].row.values[0..key_columns],
)) {
.eq => {
const ix_self_end = self.seekCurrentRowEnd(ix_self, key_columns);
const ix_other_end = other.seekCurrentRowEnd(ix_other, key_columns);
const ix_other_start = ix_other;
while (ix_self < ix_self_end) : (ix_self += 1) {
if (self_frontier.causalOrder(self.changes[ix_self].timestamp) == .gt) {
ix_other = ix_other_start;
while (ix_other < ix_other_end) : (ix_other += 1) {
const change_self = self.changes[ix_self];
const change_other = other.changes[ix_other];
var values = try std.mem.concat(into_builder.allocator, Value, switch (concat_order) {
.LeftThenRight => &[_][]const Value{
change_self.row.values,
change_other.row.values[key_columns..],
},
.RightThenLeft => &[_][]const Value{
change_other.row.values,
change_self.row.values[key_columns..],
},
});
for (values) |*value| {
value.* = try u.deepClone(value.*, into_builder.allocator);
}
try into_builder.changes.append(.{
.row = .{ .values = values },
.timestamp = try Timestamp.leastUpperBound(into_builder.allocator, change_self.timestamp, change_other.timestamp),
.diff = change_self.diff * change_other.diff,
});
}
}
}
// now ix_self and ix_other are both at next row
},
.lt => {
ix_self = self.seekRowStart(ix_self, other.changes[ix_other].row, key_columns);
},
.gt => {
ix_other = other.seekRowStart(ix_other, self.changes[ix_self].row, key_columns);
},
}
}
}
};
/// A helper for building a ChangeBatch.
/// Append to `changes` as you like and call `finishAndReset` to produce a batch.
pub const ChangeBatchBuilder = struct {
allocator: u.Allocator,
changes: u.ArrayList(Change),
pub fn init(allocator: u.Allocator) ChangeBatchBuilder {
return ChangeBatchBuilder{
.allocator = allocator,
.changes = u.ArrayList(Change).init(allocator),
};
}
pub fn deinit(self: *ChangeBatchBuilder) void {
for (self.changes.items) |*change| change.deinit(self.allocator);
self.changes.deinit();
self.* = undefined;
}
/// Coalesce changes with identical rows and timestamps.
pub fn coalesce(self: *ChangeBatchBuilder) void {
if (self.changes.items.len == 0) return;
std.sort.sort(Change, self.changes.items, {}, struct {
fn lessThan(_: void, a: Change, b: Change) bool {
return u.deepOrder(a, b) == .lt;
}
}.lessThan);
var prev_i: usize = 0;
for (self.changes.items[1..]) |*change| {
const prev_change = &self.changes.items[prev_i];
if (u.deepEqual(prev_change.row, change.row) and u.deepEqual(prev_change.timestamp, change.timestamp)) {
prev_change.diff += change.diff;
} else {
if (prev_change.diff != 0) prev_i += 1;
std.mem.swap(Change, &self.changes.items[prev_i], change);
}
}
if (self.changes.items[prev_i].diff != 0) prev_i += 1;
for (self.changes.items[prev_i..]) |*change| change.deinit(self.allocator);
self.changes.shrinkRetainingCapacity(prev_i);
}
/// Produce a change batch.
/// If the batch would have been empty, return null instead.
/// Resets `self` so that it can be used again.
pub fn finishAndReset(self: *ChangeBatchBuilder) !?ChangeBatch {
self.coalesce();
if (self.changes.items.len == 0) return null;
var lower_bound = Frontier.init(self.allocator);
var changes_into = u.ArrayList(FrontierChange).init(self.allocator);
defer changes_into.deinit();
for (self.changes.items) |change| {
try lower_bound.move(.Earlier, change.timestamp, &changes_into);
for (changes_into.items) |*frontier_change| frontier_change.deinit(self.allocator);
try changes_into.resize(0);
}
return ChangeBatch{
.lower_bound = lower_bound,
.changes = self.changes.toOwnedSlice(),
};
}
};
/// Represents the state of a bag at a variety of timestamps.
/// Allows efficiently adding new changes and querying previous changes.
pub const Index = struct {
allocator: u.Allocator,
/// Invariant: each batch is at most half the size of it's left neighbour
change_batches: u.ArrayList(ChangeBatch),
pub fn init(allocator: u.Allocator) Index {
return .{
.allocator = allocator,
.change_batches = u.ArrayList(ChangeBatch).init(allocator),
};
}
pub fn deinit(self: *Index) void {
for (self.change_batches.items) |*change_batch| change_batch.deinit(self.allocator);
self.change_batches.deinit();
self.* = undefined;
}
/// Takes ownership of `change_batch`
// TODO merge incrementally to avoid latency spikes
pub fn addChangeBatch(self: *Index, change_batch: ChangeBatch) !void {
try self.change_batches.append(change_batch);
while (true) {
const len = self.change_batches.items.len;
if (len <= 1 or @divFloor(self.change_batches.items[len - 2].changes.len, 2) >= self.change_batches.items[len - 1].changes.len) break;
var batch_a = self.change_batches.pop();
defer {
batch_a.lower_bound.deinit();
self.allocator.free(batch_a.changes);
}
var batch_b = self.change_batches.pop();
defer {
batch_b.lower_bound.deinit();
self.allocator.free(batch_b.changes);
}
var builder = ChangeBatchBuilder.init(self.allocator);
defer builder.deinit();
try builder.changes.ensureTotalCapacity(batch_a.changes.len + batch_b.changes.len);
try builder.changes.appendSlice(batch_a.changes);
try builder.changes.appendSlice(batch_b.changes);
if (try builder.finishAndReset()) |batch_ab| {
try self.change_batches.append(batch_ab);
}
}
}
/// Relational join on the first `key_columns` columns of self and change_batch.
/// Produces rows that look like:
/// * `self_row ++ other_row[key_columns..]` if `concat_order == .LeftThenRight`
/// * `other_row ++ self_row[key_columns..]` if `concat_order == .RightThenLeft`
// TODO would it be better to merge against a cursor, to avoid touching change_batch multiple times?
pub fn mergeJoin(
self: *const Index,
self_frontier: Frontier,
change_batch: ChangeBatch,
key_columns: usize,
concat_order: ConcatOrder,
into_builder: *ChangeBatchBuilder,
) !void {
for (self.change_batches.items) |self_change_batch| {
try self_change_batch.mergeJoin(self_frontier, change_batch, key_columns, concat_order, into_builder);
}
}
/// Appends every change where `row.values[0..key_columns] == change.row.values[0..key_columns]` into `into_changes`.
/// Changes are borrowed from the index.
pub fn getChangesForKey(self: *Index, row: Row, key_columns: usize, into_changes: *u.ArrayList(Change)) !void {
for (self.change_batches.items) |change_batch| {
var start_ix = change_batch.seekRowStart(0, row, key_columns);
const end_ix = change_batch.seekRowEnd(start_ix, row, key_columns);
while (start_ix < end_ix) : (start_ix += 1)
try into_changes.append(change_batch.changes[start_ix]);
}
}
pub fn getCountForRowAsOf(self: *Index, row: Row, timestamp: Timestamp) isize {
var count: isize = 0;
for (self.change_batches.items) |change_batch| {
var start_ix = change_batch.seekRowStart(0, row, row.values.len);
const end_ix = change_batch.seekRowEnd(start_ix, row, row.values.len);
while (start_ix < end_ix) : (start_ix += 1) {
const change = change_batch.changes[start_ix];
if (change.timestamp.causalOrder(timestamp).isLessThanOrEqual())
count += change.diff;
}
}
return count;
}
};
/// A node in the dataflow graph.
pub const Node = struct {
id: usize,
};
/// One of the input edges to some node in a dataflow graph.
pub const NodeInput = struct {
node: Node,
input_ix: usize,
};
pub const NodeSpecTag = enum {
Input,
Map,
Index,
Join,
Output,
TimestampPush,
TimestampIncrement,
TimestampPop,
Union,
Distinct,
Reduce,
pub fn hasIndex(self: NodeSpecTag) bool {
return switch (self) {
.Index, .Distinct, .Reduce => true,
else => false,
};
}
pub fn needsIndex(self: NodeSpecTag) bool {
return switch (self) {
.Distinct, .Reduce => true,
else => false,
};
}
};
/// Specifies how a node should transform inputs bags into an output bag.
pub const NodeSpec = union(NodeSpecTag) {
Input,
Map: MapSpec,
Index: IndexSpec,
Join: JoinSpec,
Output: OutputSpec,
TimestampPush: TimestampPushSpec,
TimestampIncrement: TimestampIncrementSpec,
TimestampPop: TimestampPopSpec,
Union: UnionSpec,
Distinct: DistinctSpec,
Reduce: ReduceSpec,
pub const MapSpec = struct {
input: Node,
mapper: *Mapper,
pub const Mapper = struct {
map_fn: fn (self: *Mapper, row: Row) error{OutOfMemory}!Row,
};
};
pub const IndexSpec = struct {
input: Node,
};
pub const JoinSpec = struct {
inputs: [2]Node,
key_columns: usize,
};
pub const OutputSpec = struct {
input: Node,
};
pub const TimestampPushSpec = struct {
input: Node,
};
pub const TimestampIncrementSpec = struct {
// Initially null, will be set later to a future edge
input: ?Node,
};
pub const TimestampPopSpec = struct {
input: Node,
};
pub const UnionSpec = struct {
inputs: [2]Node,
};
pub const DistinctSpec = struct {
input: Node,
};
pub const ReduceSpec = struct {
input: Node,
key_columns: usize,
init_value: Value,
reducer: *Reducer,
pub const Reducer = struct {
reduce_fn: fn (self: *Reducer, reduced_value: Value, row: Row, count: usize) error{OutOfMemory}!Value,
};
};
pub fn getInputs(self: *const NodeSpec) []const Node {
return switch (self.*) {
.Input => |_| &[_]Node{},
.Map => |*spec| u.ptrToSlice(Node, &spec.input),
.Index => |*spec| u.ptrToSlice(Node, &spec.input),
.Output => |*spec| u.ptrToSlice(Node, &spec.input),
.TimestampPush => |*spec| u.ptrToSlice(Node, &spec.input),
.TimestampIncrement => |*spec| u.ptrToSlice(Node, &spec.input.?),
.TimestampPop => |*spec| u.ptrToSlice(Node, &spec.input),
.Distinct => |*spec| u.ptrToSlice(Node, &spec.input),
.Reduce => |*spec| u.ptrToSlice(Node, &spec.input),
.Join => |*spec| &spec.inputs,
.Union => |*spec| &spec.inputs,
};
}
};
/// The internal state of a node in a running dataflow.
pub const NodeState = union(enum) {
Input: InputState,
Map,
Index: IndexState,
Join: JoinState,
Output: OutputState,
TimestampPush,
TimestampIncrement,
TimestampPop,
Union,
Distinct: DistinctState,
Reduce: ReduceState,
pub const InputState = struct {
frontier: Frontier,
/// These changes are being buffered.
/// When flushed they will form a change batch.
unflushed_changes: ChangeBatchBuilder,
};
pub const IndexState = struct {
index: Index,
/// These changes are waiting for the frontier to move past them, at which point they will be added to the index.
pending_changes: u.ArrayList(Change),
};
pub const JoinState = struct {
// The input frontier of the input indexes, as of the last ChangeBatch processed from them.
// We use these to ensure we ignore Changes that exist in the index already but haven't yet been processed by this join.
index_input_frontiers: [2]Frontier,
};
pub const OutputState = struct {
unpopped_change_batches: u.Queue(ChangeBatch),
};
pub const DistinctState = struct {
index: Index,
/// These are rows/timestamps at which the output might change even if there is no new input.
/// For example, if a distinct row appears at two different timestamps, then at the leastUpperBound of those timestamps the total count would be 2 and we need to correct that.
/// To calculate:
/// * For each row in the input, take the leastUpperBound of every possible subset of timestamps at which that row changed.
/// * Filter out timestamps that are before the output frontier of this node.
// TODO If Index supported cheap single updates, it would maybe be a suitable data structure here.
pending_corrections: u.DeepHashMap(Row, u.DeepHashSet(Timestamp)),
};
pub const ReduceState = struct {
index: Index,
/// These are keys/timestamps at which the output might change even if there is no new input.
/// For example, if a key appears at two different timestamps, then at the leastUpperBound of those timestamps the there will be two output values and we need to replace that with the correct single output.
/// To calculate:
/// * For each key in the input, take the leastUpperBound of every possible subset of timestamps at which that key changed.
/// * Filter out timestamps that are before the output frontier of this node.
// TODO If Index supported cheap single updates, it would maybe be a suitable data structure here.
pending_corrections: u.DeepHashMap(Row, u.DeepHashSet(Timestamp)),
};
pub fn init(allocator: u.Allocator, node_spec: NodeSpec) NodeState {
return switch (node_spec) {
.Input => .{
.Input = .{
.frontier = Frontier.init(allocator),
.unflushed_changes = ChangeBatchBuilder.init(allocator),
},
},
.Map => .Map,
.Index => .{
.Index = .{
.index = Index.init(allocator),
.pending_changes = u.ArrayList(Change).init(allocator),
},
},
.Join => .{
.Join = .{
.index_input_frontiers = .{
Frontier.init(allocator),
Frontier.init(allocator),
},
},
},
.Output => .{
.Output = .{
.unpopped_change_batches = u.Queue(ChangeBatch).init(allocator),
},
},
.TimestampPush => .TimestampPush,
.TimestampIncrement => .TimestampIncrement,
.TimestampPop => .TimestampPop,
.Union => .Union,
.Distinct => .{
.Distinct = .{
.index = Index.init(allocator),
.pending_corrections = u.DeepHashMap(Row, u.DeepHashSet(Timestamp)).init(allocator),
},
},
.Reduce => .{
.Reduce = .{
.index = Index.init(allocator),
.pending_corrections = u.DeepHashMap(Row, u.DeepHashSet(Timestamp)).init(allocator),
},
},
};
}
pub fn deinit(self: *NodeState, allocator: u.Allocator) void {
switch (self.*) {
.Input => |*input| {
input.frontier.deinit();
input.unflushed_changes.deinit();
},
.Index => |*index| {
index.index.deinit();
for (index.pending_changes.items) |*change| change.deinit(allocator);
index.pending_changes.deinit();
},
.Join => |*join| {
for (join.index_input_frontiers) |*frontier| frontier.deinit();
},
.Output => |*output| {
for (output.unpopped_change_batches.in.items) |*change_batch| change_batch.deinit(allocator);
for (output.unpopped_change_batches.out.items) |*change_batch| change_batch.deinit(allocator);
output.unpopped_change_batches.deinit();
},
.Distinct => |*distinct| {
distinct.index.deinit();
{
var iter = distinct.pending_corrections.iterator();
while (iter.next()) |entry| {
entry.key_ptr.deinit(allocator);
{
var value_iter = entry.value_ptr.iterator();
while (value_iter.next()) |value_entry| {
value_entry.key_ptr.deinit(allocator);
}
}
entry.value_ptr.deinit();
}
}
distinct.pending_corrections.deinit();
},
.Reduce => |*reduce| {
reduce.index.deinit();
{
var iter = reduce.pending_corrections.iterator();
while (iter.next()) |entry| {
entry.key_ptr.deinit(allocator);
{
var value_iter = entry.value_ptr.iterator();
while (value_iter.next()) |value_entry| {
value_entry.key_ptr.deinit(allocator);
}
}
entry.value_ptr.deinit();
}
}
reduce.pending_corrections.deinit();
},
.Map, .TimestampPush, .TimestampIncrement, .TimestampPop, .Union => {},
}
self.* = undefined;
}