-
Notifications
You must be signed in to change notification settings - Fork 118
/
mod.rs
2813 lines (2609 loc) · 104 KB
/
mod.rs
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
//! Datalog program.
//!
//! The client constructs a `struct Program` that describes Datalog relations and rules and
//! calls `Program::run()` to instantiate the program. The method returns an error or an
//! instance of `RunningProgram` that can be used to interact with the program at runtime.
//! Interactions include starting, committing or rolling back a transaction and modifying input
//! relations. The engine invokes user-provided callbacks as records are added or removed from
//! relations. `RunningProgram::stop()` terminates the Datalog program destroying all its state.
//! If not invoked manually (which allows for manual error handling), `RunningProgram::stop`
//! will be called when the program object leaves scope.
// TODO: namespace cleanup
// TODO: single input relation
pub mod arrange;
pub mod config;
mod timestamp;
mod update;
mod worker;
use crate::{
ddval::*,
record::Mutator,
render::{
arrange_by::{ArrangeBy, ArrangementKind},
RenderContext,
},
};
use abomonation_derive::Abomonation;
pub use arrange::diff_distinct;
use arrange::{
antijoin_arranged, Arrangement as DataflowArrangement, ArrangementFlavor, Arrangements,
};
use config::SelfProfilingRig;
pub use config::{Config, ProfilingConfig};
use crossbeam_channel::{Receiver, Sender};
use ddlog_profiler::{
with_prof_context, ArrangementDebugInfo, DDlogSourceCode, OperatorDebugInfo, ProfMsg, Profile,
RuleDebugInfo, SourcePosition,
};
use fnv::{FnvHashMap, FnvHashSet};
use num::{One, Zero};
use std::{
any::Any,
borrow::Cow,
cmp,
collections::{hash_map, BTreeSet},
fmt::{self, Debug, Formatter},
iter::{self, Cycle, Skip},
ops::{Add, AddAssign, Mul, Neg, Range},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
thread::JoinHandle,
};
use timestamp::ToTupleTS;
pub use timestamp::{TSNested, TupleTS, TS};
use triomphe::Arc as ThinArc;
pub use update::Update;
use worker::DDlogWorker;
use differential_dataflow::difference::*;
use differential_dataflow::lattice::Lattice;
use differential_dataflow::operators::arrange::arrangement::Arranged;
use differential_dataflow::operators::arrange::*;
use differential_dataflow::operators::*;
use differential_dataflow::trace::implementations::ord::OrdKeySpine as DefaultKeyTrace;
use differential_dataflow::trace::implementations::ord::OrdValSpine as DefaultValTrace;
use differential_dataflow::trace::wrappers::enter::TraceEnter;
use differential_dataflow::trace::{BatchReader, Cursor, TraceReader};
use differential_dataflow::Collection;
use dogsdogsdogs::{
altneu::AltNeu,
calculus::{Differentiate, Integrate},
operators::lookup_map,
};
use timely::communication::{initialize::WorkerGuards, Allocator};
use timely::dataflow::scopes::*;
use timely::order::TotalOrder;
use timely::progress::{timestamp::Refines, PathSummary, Timestamp};
use timely::worker::Worker;
type ValTrace<S> = DefaultValTrace<DDValue, DDValue, S, Weight, u32>;
type KeyTrace<S> = DefaultKeyTrace<DDValue, S, Weight, u32>;
type TValAgent<S> = TraceAgent<ValTrace<S>>;
type TKeyAgent<S> = TraceAgent<KeyTrace<S>>;
type TValEnter<P, T> = TraceEnter<TValAgent<P>, T>;
type TKeyEnter<P, T> = TraceEnter<TKeyAgent<P>, T>;
#[derive(Abomonation, Copy, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, Clone)]
#[repr(transparent)]
pub struct CheckedWeight {
pub value: i32,
}
impl Semigroup for CheckedWeight {
fn is_zero(&self) -> bool {
self.value == 0
}
}
impl<'a> AddAssign<&'a Self> for CheckedWeight {
fn add_assign(&mut self, other: &'a Self) {
// intentional panic on overflow
self.value = self
.value
.checked_add(other.value)
.expect("Weight overflow");
}
}
impl Add for CheckedWeight {
type Output = Self;
fn add(self, other: Self) -> Self {
// intentional panic on overflow
Self {
value: self
.value
.checked_add(other.value)
.expect("Weight overflow"),
}
}
}
impl Mul for CheckedWeight {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
// intentional panic on overflow
Self {
value: self.value.checked_mul(rhs.value).expect("Weight overflow"),
}
}
}
impl Neg for CheckedWeight {
type Output = Self;
fn neg(self) -> Self::Output {
// intentional panic on overflow
Self {
value: self.value.checked_neg().expect("Weight overflow"),
}
}
}
impl Monoid for CheckedWeight {
fn zero() -> Self {
Self { value: 0 }
}
}
impl One for CheckedWeight {
fn one() -> Self {
Self { value: 1 }
}
}
impl Zero for CheckedWeight {
fn zero() -> Self {
Self { value: 0 }
}
fn is_zero(&self) -> bool {
self.value == 0
}
}
impl From<i32> for CheckedWeight {
fn from(item: i32) -> Self {
Self { value: item }
}
}
impl From<CheckedWeight> for i64 {
fn from(item: CheckedWeight) -> Self {
item.value as i64
}
}
/// Weight is a diff associated with records in differential dataflow
#[cfg(feature = "checked_weights")]
pub type Weight = CheckedWeight;
/// Weight is a diff associated with records in differential dataflow
#[cfg(not(feature = "checked_weights"))]
pub type Weight = i32;
/// Message buffer for profiling messages
const PROF_MSG_BUF_SIZE: usize = 10_000;
/// Result type returned by this library
pub type Response<X> = Result<X, String>;
/// Unique identifier of a DDlog relation.
// TODO: Newtype this for type-safety
pub type RelId = usize;
/// Unique identifier of an index.
// TODO: Newtype this for type-safety
pub type IdxId = usize;
/// Unique identifier of an arranged relation.
/// The first element of the tuple identifies relation; the second is the index
/// of arrangement for the given relation.
// TODO: Newtype this for type-safety
pub type ArrId = (RelId, usize);
/// Function type used to map the content of a relation
/// (see `XFormCollection::Map`).
pub type MapFunc = fn(DDValue) -> DDValue;
/// Function type used to extract join key from a relation
/// (see `XFormCollection::StreamJoin`).
pub type KeyFunc = fn(&DDValue) -> Option<DDValue>;
/// (see `XFormCollection::FlatMap`).
pub type FlatMapFunc = fn(DDValue) -> Option<Box<dyn Iterator<Item = DDValue>>>;
/// Function type used to filter a relation
/// (see `XForm*::Filter`).
pub type FilterFunc = fn(&DDValue) -> bool;
/// Function type used to simultaneously filter and map a relation
/// (see `XFormCollection::FilterMap`).
pub type FilterMapFunc = fn(DDValue) -> Option<DDValue>;
/// Function type used to inspect a relation
/// (see `XFormCollection::InspectFunc`)
pub type InspectFunc = fn(&DDValue, TupleTS, Weight) -> ();
/// Function type used to arrange a relation into key-value pairs
/// (see `XFormArrangement::Join`, `XFormArrangement::Antijoin`).
pub type ArrangeFunc = fn(DDValue) -> Option<(DDValue, DDValue)>;
/// Function type used to assemble the result of a join into a value.
/// Takes join key and a pair of values from the two joined relations
/// (see `XFormArrangement::Join`).
pub type JoinFunc = fn(&DDValue, &DDValue, &DDValue) -> Option<DDValue>;
/// Similar to JoinFunc, but only takes values from the two joined
/// relations, and not the key (`XFormArrangement::StreamJoin`).
pub type ValJoinFunc = fn(&DDValue, &DDValue) -> Option<DDValue>;
/// Function type used to assemble the result of a semijoin into a value.
/// Takes join key and value (see `XFormArrangement::Semijoin`).
pub type SemijoinFunc = fn(&DDValue, &DDValue, &()) -> Option<DDValue>;
/// Similar to SemijoinFunc, but only takes one value.
/// (see `XFormCollection::StreamSemijoin`).
pub type StreamSemijoinFunc = fn(&DDValue) -> Option<DDValue>;
/// Aggregation function: aggregates multiple values into a single value.
pub type AggFunc = fn(&DDValue, &[(&DDValue, Weight)]) -> Option<DDValue>;
// TODO: add validating constructor for Program:
// - relation id's are unique
// - rules only refer to previously declared relations or relations in the local scc
// - input relations do not occur in LHS of rules
// - all references to arrangements are valid
/// A Datalog program is a vector of nodes representing
/// individual non-recursive relations and strongly connected components
/// comprised of one or more mutually recursive relations.
/// * `delayed_rels` - delayed relations used in the program.
/// * `init_data` - initial relation contents.
#[derive(Clone)]
pub struct Program {
pub nodes: Vec<ProgNode>,
pub delayed_rels: Vec<DelayedRelation>,
pub init_data: Vec<(RelId, DDValue)>,
}
type TransformerMap<'a> =
FnvHashMap<RelId, Collection<Child<'a, Worker<Allocator>, TS>, DDValue, Weight>>;
/// Represents a dataflow fragment implemented outside of DDlog directly in differential-dataflow.
///
/// Takes the set of already constructed collections and modifies this
/// set, adding new collections. Note that the transformer can only be applied in the top scope
/// (`Child<'a, Worker<Allocator>, TS>`), as we currently don't have a way to ensure that the
/// transformer is monotonic and thus it may not converge if used in a nested scope.
pub type TransformerFuncRes = Box<dyn for<'a> Fn(&mut TransformerMap<'a>)>;
/// A function returning a dataflow fragment implemented in differential-dataflow
pub type TransformerFunc = fn() -> TransformerFuncRes;
/// Program node is either an individual non-recursive relation, a transformer application or
/// a vector of one or more mutually recursive relations.
#[derive(Clone)]
pub enum ProgNode {
Rel {
rel: Relation,
},
Apply {
transformer: Cow<'static, str>,
source_pos: SourcePosition,
tfun: TransformerFunc,
},
Scc {
rels: Vec<RecursiveRelation>,
},
}
/// Relation computed in a nested scope as a fixed point.
///
/// The `distinct` flag indicates that the `distinct` operator should be applied
/// to the relation before closing the loop to enforce convergence of the fixed
/// point computation.
#[derive(Clone)]
pub struct RecursiveRelation {
pub rel: Relation,
pub distinct: bool,
}
pub trait RelationCallback: Fn(RelId, &DDValue, Weight) + Send + Sync {
fn clone_boxed(&self) -> Box<dyn RelationCallback>;
}
impl<T> RelationCallback for T
where
T: Fn(RelId, &DDValue, Weight) + Clone + Send + Sync + ?Sized + 'static,
{
fn clone_boxed(&self) -> Box<dyn RelationCallback> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn RelationCallback> {
fn clone(&self) -> Self {
self.clone_boxed()
}
}
/// Caching mode for input relations only
///
/// `NoCache` - don't cache the contents of the relation.
/// `CacheSet` - cache relation as a set. Duplicate inserts are
/// ignored (for relations without a key) or fail (for relations
/// with key).
/// `CacheMultiset` - cache relation as a generalized multiset with
/// integer weights.
#[derive(Clone)]
pub enum CachingMode {
Stream,
Set,
Multiset,
}
/// Datalog relation.
///
/// defines a set of rules and a set of arrangements with which this relation is used in
/// rules. The set of rules can be empty (if this is a ground relation); the set of arrangements
/// can also be empty if the relation is not used in the RHS of any rules.
#[derive(Clone)]
pub struct Relation {
/// Relation name; does not have to be unique
pub name: Cow<'static, str>,
/// Location of relation declaration.
pub source_pos: SourcePosition,
/// `true` if this is an input relation. Input relations are populated by the client
/// of the library via `RunningProgram::insert()`, `RunningProgram::delete()` and `RunningProgram::apply_updates()` methods.
pub input: bool,
/// Apply distinct_total() to this relation after concatenating all its rules
pub distinct: bool,
/// Caching mode (for input relations only).
pub caching_mode: CachingMode,
/// If `key_func` is present, this indicates that the relation is indexed with a unique
/// key computed by key_func
pub key_func: Option<fn(&DDValue) -> DDValue>,
/// Unique relation id
pub id: RelId,
/// Rules that define the content of the relation.
/// Input relations cannot have rules.
/// Rules can only refer to relations introduced earlier in the program as well as relations in the same strongly connected
/// component.
pub rules: Vec<Rule>,
/// Arrangements of the relation used to compute other relations. Index in this vector
/// along with relation id uniquely identifies the arrangement (see `ArrId`).
pub arrangements: Vec<Arrangement>,
/// Callback invoked when an element is added or removed from relation.
pub change_cb: Option<Arc<dyn RelationCallback + 'static>>,
}
impl Relation {
pub fn name(&self) -> &str {
&*self.name
}
}
/// `DelayedRelation` refers to the contents of a given base relation from
/// `delay` epochs ago.
///
/// The use of delayed relations in rules comes with an additional constraint.
/// A delayed relation produces outputs ahead of time, e.g., at time `ts` it
/// can yield values labeled `ts + delay`. In DDlog we don't want to see these
/// values until we explicitly advance the epoch to `ts + delay`. We apply the
/// `consolidate` operator before `probe`, which guarantees that any
/// output can only be produced once DD knows that it should not expect any more
/// changes for the given timstamp. So as long as each output relation depends on
/// at least one regular (not delayed) relation, we shouldn't observe any values
/// generated ahead of time. It is up to the compiler to enforce this
/// constraint.
#[derive(Clone)]
pub struct DelayedRelation {
/// Source code locations where this delayed relation is used in rules.
pub used_at: Vec<SourcePosition>,
/// Unique id of this delayed relation. Delayed and regular relation ids live in the
/// same name space and therefore cannot clash.
pub id: RelId,
/// Id of the base relation that this DelayedRelation is a delayed version of.
pub rel_id: RelId,
/// The number of epochs to delay by. Must be greater than 0.
pub delay: TS,
// /// We don't have a use case for this, and this is not exposed through the DDlog syntax (since
// /// delayed relations are currently only used with streams), but we could in principle have
// /// shared arrangements of delayed relations.
// pub arrangements: Vec<Arrangement>,
}
/// A Datalog relation or rule can depend on other relations and their
/// arrangements.
#[derive(Copy, PartialEq, Eq, Hash, Debug, Clone)]
pub enum Dep {
Rel(RelId),
Arr(ArrId),
}
impl Dep {
pub fn relid(&self) -> RelId {
match self {
Dep::Rel(relid) => *relid,
Dep::Arr((relid, _)) => *relid,
}
}
}
/// Transformations, such as maps, flatmaps, filters, joins, etc. are the building blocks of
/// DDlog rules.
///
/// Different kinds of transformations can be applied only to flat collections,
/// only to arranged collections, or both. We therefore use separate types to represent
/// collection and arrangement transformations.
///
/// Note that differential sometimes allows the same kind of transformation to be applied to both
/// collections and arrangements; however the former is implemented on top of the latter and incurs
/// the additional cost of arranging the collection. We only support the arranged version of these
/// transformations, forcing the user to explicitly arrange the collection if necessary (or, as much
/// as possible, keep the data arranged throughout the chain of transformations).
///
/// `XFormArrangement` - arrangement transformation.
#[derive(Clone)]
pub enum XFormArrangement {
/// FlatMap arrangement into a collection
FlatMap {
debug_info: OperatorDebugInfo,
fmfun: FlatMapFunc,
/// Transformation to apply to resulting collection.
/// `None` terminates the chain of transformations.
next: Box<Option<XFormCollection>>,
},
FilterMap {
debug_info: OperatorDebugInfo,
fmfun: FilterMapFunc,
/// Transformation to apply to resulting collection.
/// `None` terminates the chain of transformations.
next: Box<Option<XFormCollection>>,
},
/// Aggregate
Aggregate {
debug_info: OperatorDebugInfo,
/// Filter arrangement before grouping
ffun: Option<FilterFunc>,
/// Aggregation to apply to each group.
aggfun: AggFunc,
/// Apply transformation to the resulting collection.
next: Box<Option<XFormCollection>>,
},
/// Join
Join {
debug_info: OperatorDebugInfo,
/// Filter arrangement before joining
ffun: Option<FilterFunc>,
/// Arrangement to join with.
arrangement: ArrId,
/// Function used to put together ouput value.
jfun: JoinFunc,
/// Join returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
/// Semijoin
Semijoin {
debug_info: OperatorDebugInfo,
/// Filter arrangement before joining
ffun: Option<FilterFunc>,
/// Arrangement to semijoin with.
arrangement: ArrId,
/// Function used to put together ouput value.
jfun: SemijoinFunc,
/// Join returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
/// Return a subset of values that correspond to keys not present in `arrangement`.
Antijoin {
debug_info: OperatorDebugInfo,
/// Filter arrangement before joining
ffun: Option<FilterFunc>,
/// Arrangement to antijoin with
arrangement: ArrId,
/// Antijoin returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
/// Streaming join: join arrangement with a collection.
/// This outputs a collection obtained by matching each value
/// in the input collection against the arrangement without
/// arranging the collection first.
StreamJoin {
debug_info: OperatorDebugInfo,
/// Filter arrangement before join.
ffun: Option<FilterFunc>,
/// Relation to join with.
rel: RelId,
/// Extract join key from the _collection_.
kfun: KeyFunc,
/// Function used to put together ouput value. The first argument comes
/// from the arrangement, the second from the collection.
jfun: ValJoinFunc,
/// Join returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
/// Streaming semijoin.
StreamSemijoin {
debug_info: OperatorDebugInfo,
/// Filter arrangement before join.
ffun: Option<FilterFunc>,
/// Relation to join with.
rel: RelId,
/// Extract join key from the relation.
kfun: KeyFunc,
/// Function used to put together ouput value.
jfun: StreamSemijoinFunc,
/// Join returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
}
impl XFormArrangement {
pub(super) fn dependencies(&self) -> FnvHashSet<Dep> {
match self {
XFormArrangement::FlatMap { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormArrangement::FilterMap { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormArrangement::Aggregate { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormArrangement::Join {
arrangement, next, ..
} => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Arr(*arrangement));
deps
}
XFormArrangement::Semijoin {
arrangement, next, ..
} => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Arr(*arrangement));
deps
}
XFormArrangement::Antijoin {
arrangement, next, ..
} => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Arr(*arrangement));
deps
}
XFormArrangement::StreamJoin { rel, next, .. } => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Rel(*rel));
deps
}
XFormArrangement::StreamSemijoin { rel, next, .. } => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Rel(*rel));
deps
}
}
}
}
/// `XFormCollection` - collection transformation.
#[derive(Clone)]
pub enum XFormCollection {
/// Arrange the collection, apply `next` transformation to the resulting collection.
Arrange {
debug_info: OperatorDebugInfo,
afun: ArrangeFunc,
next: Box<XFormArrangement>,
},
/// The `Differentiate` operator subtracts the previous value
/// of the collection from its current value, `C' = C - (C_-1)`.
/// Can be used to transform a stream into a relation that stores
/// the new values in the stream for each timestamp.
Differentiate {
debug_info: OperatorDebugInfo,
next: Box<Option<XFormCollection>>,
},
/// Apply `mfun` to each element in the collection
Map {
debug_info: OperatorDebugInfo,
mfun: MapFunc,
next: Box<Option<XFormCollection>>,
},
/// FlatMap
FlatMap {
debug_info: OperatorDebugInfo,
fmfun: FlatMapFunc,
next: Box<Option<XFormCollection>>,
},
/// Filter collection
Filter {
debug_info: OperatorDebugInfo,
ffun: FilterFunc,
next: Box<Option<XFormCollection>>,
},
/// Map and filter
FilterMap {
debug_info: OperatorDebugInfo,
fmfun: FilterMapFunc,
next: Box<Option<XFormCollection>>,
},
/// Inspector
Inspect {
debug_info: OperatorDebugInfo,
ifun: InspectFunc,
next: Box<Option<XFormCollection>>,
},
/// Streaming join: join collection with an arrangement.
/// This outputs a collection obtained by matching each value
/// in the input collection against the arrangement without
/// arranging the collection first.
StreamJoin {
debug_info: OperatorDebugInfo,
/// Function to arrange collection into key/value pairs.
afun: ArrangeFunc,
/// Arrangement to join with.
arrangement: ArrId,
/// Function used to put together ouput values (the first argument
/// comes from the collection, the second -- from the arrangement).
jfun: ValJoinFunc,
/// Join returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
/// Streaming semijoin.
StreamSemijoin {
debug_info: OperatorDebugInfo,
/// Function to arrange collection into key/value pairs.
afun: ArrangeFunc,
/// Arrangement to join with.
arrangement: ArrId,
/// Function used to put together ouput values (the first argument
/// comes from the collection, the second -- from the arrangement).
jfun: StreamSemijoinFunc,
/// Join returns a collection: apply `next` transformation to it.
next: Box<Option<XFormCollection>>,
},
/// Applies `xform` to the stream (i.e., to changes to the collection in
/// the last timestamp) and produces the result while discarding any
/// intermediate arrangements used to construct the result.
/// Example: `xform` may arrange and aggregate the collection. This
/// will output the aggregate of values added at the current timestamp
/// after each transaction. Since the arrangement is instantly cleared,
/// the old value of the aggregate will not get retracted during the next
/// transaction.
///
/// Stream xforms are currently only supported in the top-level contents.
///
/// This transformation is implemented using the "calculus" feature of DD:
/// it constructs an `AltNeu` scope, moves the collection into it using the
/// `calculus::differentiate` operator, applies `xform` and extracts the
/// result using `calculus:integrate`.
/// NOTE: This is an experimental feature. We currently don't
/// have real use cases for it (stream joins are already more efficiently
/// implemented using `lookup_map`, stream aggregation does not sound like
/// a very useful feature to me, stream antijoins might be the killer app
/// here), and the implementation is ugly.
/// It might go away if we don't find what it's good for.
StreamXForm {
debug_info: OperatorDebugInfo,
xform: Box<Option<XFormCollection>>,
next: Box<Option<XFormCollection>>,
},
}
impl XFormCollection {
pub fn dependencies(&self) -> FnvHashSet<Dep> {
match self {
XFormCollection::Arrange { next, .. } => next.dependencies(),
XFormCollection::Differentiate { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormCollection::Map { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormCollection::FlatMap { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormCollection::Filter { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormCollection::FilterMap { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormCollection::Inspect { next, .. } => match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
},
XFormCollection::StreamJoin {
arrangement, next, ..
} => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Arr(*arrangement));
deps
}
XFormCollection::StreamSemijoin {
arrangement, next, ..
} => {
let mut deps = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps.insert(Dep::Arr(*arrangement));
deps
}
XFormCollection::StreamXForm { xform, next, .. } => {
let deps1 = match **xform {
None => FnvHashSet::default(),
Some(ref x) => x.dependencies(),
};
let deps2 = match **next {
None => FnvHashSet::default(),
Some(ref n) => n.dependencies(),
};
deps1.union(&deps2).cloned().collect()
}
}
}
}
/// Datalog rule (more precisely, the body of a rule) starts with a collection
/// or arrangement and applies a chain of transformations to it.
#[derive(Clone)]
pub enum Rule {
CollectionRule {
debug_info: RuleDebugInfo,
rel: RelId,
xform: Option<XFormCollection>,
},
ArrangementRule {
debug_info: RuleDebugInfo,
arr: ArrId,
xform: XFormArrangement,
},
}
impl Rule {
fn dependencies(&self) -> FnvHashSet<Dep> {
match self {
Rule::CollectionRule { rel, xform, .. } => {
let mut deps = match xform {
None => FnvHashSet::default(),
Some(ref x) => x.dependencies(),
};
deps.insert(Dep::Rel(*rel));
deps
}
Rule::ArrangementRule { arr, xform, .. } => {
let mut deps = xform.dependencies();
deps.insert(Dep::Arr(*arr));
deps
}
}
}
}
/// Describes arrangement of a relation.
#[derive(Clone)]
pub enum Arrangement {
/// Arrange into (key,value) pairs
Map {
debug_info: ArrangementDebugInfo,
/// Function used to produce arrangement.
afun: ArrangeFunc,
/// The arrangement can be queried using `RunningProgram::query_arrangement`
/// and `RunningProgram::dump_arrangement`.
queryable: bool,
},
/// Arrange into a set of values
Set {
debug_info: ArrangementDebugInfo,
/// Function used to produce arrangement.
fmfun: FilterMapFunc,
/// Apply distinct_total() before arranging filtered collection.
/// This is necessary if the arrangement is to be used in an antijoin.
distinct: bool,
},
}
impl Arrangement {
fn arrange_by(&self) -> &Cow<'static, str> {
match self {
Arrangement::Map { debug_info, .. } => &debug_info.arrange_by,
Arrangement::Set { debug_info, .. } => &debug_info.arrange_by,
}
}
fn used_at(&self) -> &[SourcePosition] {
match self {
Arrangement::Map { debug_info, .. } => debug_info.used_at.as_slice(),
Arrangement::Set { debug_info, .. } => debug_info.used_at.as_slice(),
}
}
fn used_in_indexes(&self) -> &[Cow<'static, str>] {
match self {
Arrangement::Map { debug_info, .. } => debug_info.used_in_indexes.as_slice(),
Arrangement::Set { debug_info, .. } => debug_info.used_in_indexes.as_slice(),
}
}
fn queryable(&self) -> bool {
match *self {
Arrangement::Map { queryable, .. } => queryable,
Arrangement::Set { .. } => false,
}
}
pub fn set_debug_info(mut self, dbg_info: ArrangementDebugInfo) -> Self {
match self {
Self::Map {
ref mut debug_info, ..
} => *debug_info = dbg_info,
Self::Set {
ref mut debug_info, ..
} => *debug_info = dbg_info,
};
self
}
fn build_arrangement_root<S>(
&self,
render_context: &RenderContext,
collection: &Collection<S, DDValue, Weight>,
) -> DataflowArrangement<S, Weight, TValAgent<S::Timestamp>, TKeyAgent<S::Timestamp>>
where
S: Scope,
Collection<S, DDValue, Weight>: ThresholdTotal<S, DDValue, Weight>,
S::Timestamp: Lattice + Ord + TotalOrder,
{
let kind = match *self {
Arrangement::Map { afun, .. } => ArrangementKind::Map {
value_function: afun,
},
Arrangement::Set {
fmfun, distinct, ..
} => {
// TODO: We don't currently produce a `None` as the key extraction
// function, but doing so will simplify the dataflow graph
// in instances where a function isn't needed
ArrangementKind::Set {
key_function: Some(fmfun),
distinct,
}
}
};
ArrangeBy {
kind,
target_relation: self.arrange_by().clone(),
}
.render_root(render_context, collection)
}
fn build_arrangement<S>(
&self,
render_context: &RenderContext,
collection: &Collection<S, DDValue, Weight>,
) -> DataflowArrangement<S, Weight, TValAgent<S::Timestamp>, TKeyAgent<S::Timestamp>>
where
S: Scope,
S::Timestamp: Lattice + Ord,
{
let kind = match *self {
Arrangement::Map { afun, .. } => ArrangementKind::Map {
value_function: afun,
},
Arrangement::Set {
fmfun, distinct, ..
} => {
// TODO: We don't currently produce a `None` as the key extraction
// function, but doing so will simplify the dataflow graph
// in instances where a function isn't needed
ArrangementKind::Set {
key_function: Some(fmfun),
distinct,
}
}
};
ArrangeBy {
kind,
target_relation: self.arrange_by().clone(),
}
.render(render_context, collection)
}
}
/// Set relation content.
pub type ValSet = FnvHashSet<DDValue>;
/// Multiset relation content.
pub type ValMSet = DeltaSet;
/// Indexed relation content.
pub type IndexedValSet = FnvHashMap<DDValue, DDValue>;
/// Relation delta
pub type DeltaSet = FnvHashMap<DDValue, isize>;
/// Runtime representation of a datalog program.
///
/// The program will be automatically stopped when the object goes out
/// of scope. Error occurring as part of that operation are silently
/// ignored. If you want to handle such errors, call `stop` manually.
pub struct RunningProgram {
/// Producer sides of channels used to send commands to workers.
/// We use async channels to avoid deadlocks when workers are blocked
/// in `step_or_park`.
senders: Vec<Sender<Msg>>,
/// Channels to receive replies from worker threads. We could use a single
/// channel with multiple senders, but use many channels instead to avoid
/// deadlocks when one of the workers has died, but `recv` blocks instead
/// of failing, since the channel is still considered alive.
reply_recv: Vec<Receiver<Reply>>,
relations: FnvHashMap<RelId, RelationInstance>,
worker_guards: Option<WorkerGuards<Result<(), String>>>,
transaction_in_progress: bool,
need_to_flush: bool,
timestamp: TS,
/// CPU profiling enabled (can be expensive).
profile_cpu: Option<ThinArc<AtomicBool>>,
/// Consume timely_events and output them to CSV file. Can be expensive.
profile_timely: Option<ThinArc<AtomicBool>>,
/// Change profiling enabled.
profile_change: Option<ThinArc<AtomicBool>>,
/// Profiling thread.
prof_thread_handle: Option<JoinHandle<()>>,
/// Profiling statistics.
pub profile: Option<ThinArc<Mutex<Profile>>>,
worker_round_robbin: Skip<Cycle<Range<usize>>>,
}
// Right now this Debug implementation is more or less a short cut.
// Ideally we would want to implement Debug for `RelationInstance`, but
// that quickly gets very cumbersome.
impl Debug for RunningProgram {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("RunningProgram")