forked from mit-pdos/noria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintegration.rs
2961 lines (2511 loc) · 96.3 KB
/
integration.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
use crate::controller::recipe::Recipe;
use crate::controller::sql::SqlIncorporator;
use crate::{Builder, Handle};
use dataflow::node::special::Base;
use dataflow::ops::grouped::aggregate::Aggregation;
use dataflow::ops::identity::Identity;
use dataflow::ops::join::JoinSource::*;
use dataflow::ops::join::{Join, JoinSource, JoinType};
use dataflow::ops::project::Project;
use dataflow::ops::union::Union;
use dataflow::{DurabilityMode, PersistenceParameters};
use noria::consensus::LocalAuthority;
use noria::DataType;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use std::{env, thread};
const DEFAULT_SETTLE_TIME_MS: u64 = 200;
const DEFAULT_SHARDING: usize = 2;
// PersistenceParameters with a log_name on the form of `prefix` + timestamp,
// avoiding collisions between separate test runs (in case an earlier panic causes clean-up to
// fail).
fn get_persistence_params(prefix: &str) -> PersistenceParameters {
let mut params = PersistenceParameters::default();
params.mode = DurabilityMode::DeleteOnExit;
params.log_prefix = String::from(prefix);
params
}
// Builds a local worker with the given log prefix.
pub async fn start_simple(prefix: &str) -> Handle<LocalAuthority> {
build(prefix, Some(DEFAULT_SHARDING), false).await
}
#[allow(dead_code)]
pub async fn start_simple_unsharded(prefix: &str) -> Handle<LocalAuthority> {
build(prefix, None, false).await
}
#[allow(dead_code)]
pub async fn start_simple_logging(prefix: &str) -> Handle<LocalAuthority> {
build(prefix, Some(DEFAULT_SHARDING), true).await
}
async fn build(prefix: &str, sharding: Option<usize>, log: bool) -> Handle<LocalAuthority> {
use crate::logger_pls;
let mut builder = Builder::default();
if log {
builder.log_with(logger_pls());
}
builder.set_sharding(sharding);
builder.set_persistence(get_persistence_params(prefix));
builder.start_local().await.unwrap().0
}
fn get_settle_time() -> Duration {
let settle_time: u64 = match env::var("SETTLE_TIME") {
Ok(value) => value.parse().unwrap(),
Err(_) => DEFAULT_SETTLE_TIME_MS,
};
Duration::from_millis(settle_time)
}
// Sleeps for either DEFAULT_SETTLE_TIME_MS milliseconds, or
// for the value given through the SETTLE_TIME environment variable.
async fn sleep() {
tokio::time::delay_for(get_settle_time()).await;
}
#[tokio::test(threaded_scheduler)]
async fn it_works_basic() {
let mut g = start_simple("it_works_basic").await;
let _ = g
.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::new(vec![]).with_key(vec![0]));
let b = mig.add_base("b", &["a", "b"], Base::new(vec![]).with_key(vec![0]));
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
emits.insert(b, vec![0, 1]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["a", "b"], u);
mig.maintain_anonymous(c, &[0]);
(a, b, c)
})
.await;
let mut cq = g.view("c").await.unwrap();
let mut muta = g.table("a").await.unwrap();
let mut mutb = g.table("b").await.unwrap();
let id: DataType = 1.into();
assert_eq!(muta.table_name(), "a");
assert_eq!(muta.columns(), &["a", "b"]);
// send a value on a
muta.insert(vec![id.clone(), 2.into()]).await.unwrap();
// give it some time to propagate
sleep().await;
// send a query to c
assert_eq!(
cq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![1.into(), 2.into()]]
);
// update value again
mutb.insert(vec![id.clone(), 4.into()]).await.unwrap();
// give it some time to propagate
sleep().await;
// check that value was updated again
let res = cq.lookup(&[id.clone()], true).await.unwrap();
assert!(res.iter().any(|r| r == &vec![id.clone(), 2.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 4.into()]));
// check that looking up columns by name works
assert!(res.iter().all(|r| r.get::<i32>("a").unwrap() == 1));
assert!(res.iter().any(|r| r.get::<i32>("b").unwrap() == 2));
assert!(res.iter().any(|r| r.get::<i32>("b").unwrap() == 4));
// same with index
assert!(res.iter().all(|r| r["a"] == id));
assert!(res.iter().any(|r| r["b"] == 2.into()));
assert!(res.iter().any(|r| r["b"] == 4.into()));
// Delete first record
muta.delete(vec![id.clone()]).await.unwrap();
// give it some time to propagate
sleep().await;
// send a query to c
assert_eq!(
cq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![1.into(), 4.into()]]
);
// Update second record
// TODO(malte): disabled until we have update support on bases; the current way of doing this
// is incompatible with bases' enforcement of the primary key uniqueness constraint.
//mutb.update(vec![id.clone(), 6.into()]).await.unwrap();
// give it some time to propagate
//sleep().await;
// send a query to c
//assert_eq!(cq.lookup(&[id.clone()], true).await, Ok(vec![vec![1.into(), 6.into()]]));
}
#[tokio::test(threaded_scheduler)]
async fn it_completes() {
let mut builder = Builder::default();
builder.set_sharding(Some(DEFAULT_SHARDING));
builder.set_persistence(get_persistence_params("it_completes"));
let (g, done) = builder.start_local().await.unwrap();
{
let mut g = g;
// do some stuff (== it_works_basic)
let _ = g
.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::new(vec![]).with_key(vec![0]));
let b = mig.add_base("b", &["a", "b"], Base::new(vec![]).with_key(vec![0]));
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
emits.insert(b, vec![0, 1]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["a", "b"], u);
mig.maintain_anonymous(c, &[0]);
(a, b, c)
})
.await;
let mut cq = g.view("c").await.unwrap();
let mut muta = g.table("a").await.unwrap();
let mut mutb = g.table("b").await.unwrap();
let id: DataType = 1.into();
assert_eq!(muta.table_name(), "a");
assert_eq!(muta.columns(), &["a", "b"]);
muta.insert(vec![id.clone(), 2.into()]).await.unwrap();
sleep().await;
assert_eq!(
cq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![1.into(), 2.into()]]
);
mutb.insert(vec![id.clone(), 4.into()]).await.unwrap();
sleep().await;
let res = cq.lookup(&[id.clone()], true).await.unwrap();
assert!(res.iter().any(|r| r == &vec![id.clone(), 2.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 4.into()]));
muta.delete(vec![id.clone()]).await.unwrap();
sleep().await;
assert_eq!(
cq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![1.into(), 4.into()]]
);
} // ensure that all handles and such are dropped
// wait for exit
done.await;
}
#[tokio::test(threaded_scheduler)]
async fn sharded_shuffle() {
let mut g = start_simple("sharded_shuffle").await;
// in this test, we have a single sharded base node that is keyed on one column, and a sharded
// reader that is keyed by a different column. this requires a shuffle. we want to make sure
// that that shuffle happens correctly.
g.migrate(|mig| {
let a = mig.add_base(
"base",
&["id", "non_id"],
Base::new(vec![]).with_key(vec![0]),
);
mig.maintain_anonymous(a, &[1]);
})
.await;
eprintln!("{}", g.graphviz().await.unwrap());
let mut base = g.table("base").await.unwrap();
let mut view = g.view("base").await.unwrap();
// make sure there is data on >1 shard, and that we'd get multiple rows by querying the reader
// for a single key.
base.perform_all((0..100).map(|i| vec![i.into(), DataType::Int(1)]))
.await
.unwrap();
sleep().await;
// moment of truth
let rows = view.lookup(&[DataType::Int(1)], true).await.unwrap();
assert_eq!(rows.len(), 100);
}
#[tokio::test(threaded_scheduler)]
async fn broad_recursing_upquery() {
let nshards = 16;
let mut g = build("bru", Some(nshards), false).await;
// our goal here is to have a recursive upquery such that both levels of the upquery require
// contacting _all_ shards. in this setting, any miss at the leaf requires the upquery to go to
// all shards of the intermediate operator, and each miss there requires an upquery to each
// shard of the top level. as a result, we would expect every base to receive 2 upqueries for
// the same key, and a total of n^2+n upqueries. crucially, what we want to test is that the
// partial logic correctly manages all these requests, and the resulting responses (especially
// at the shard mergers). to achieve this, we're going to use this layout:
//
// base x base y [sharded by a]
// | |
// +----+----+ [lookup by b]
// |
// join [sharded by b]
// |
// reader [sharded by c]
//
// we basically _need_ a join in order to get this layout, since only joins allow us to
// introduce a new sharding without also dropping all columns that are not the sharding column
// (like aggregations would). with an aggregation for example, the downstream view could not be
// partial, since it would have no way to know the partial key to upquery for given a miss,
// since the miss would be on an _output_ column of the aggregation. we _could_ use a
// multi-column aggregation group by, but those have their own problems that we do not want to
// exercise here.
//
// we're also going to make the join a left join so that we know the upquery will go to base_x.
g.migrate(|mig| {
// bases, both sharded by their first column
let x = mig.add_base(
"base_x",
&["base_col", "join_col", "reader_col"],
Base::new(vec![]).with_key(vec![0]),
);
let y = mig.add_base("base_y", &["id"], Base::new(vec![]).with_key(vec![0]));
// join, sharded by the join column, which is be the second column on x
let join = mig.add_ingredient(
"join",
&["base_col", "join_col", "reader_col"],
Join::new(x, y, JoinType::Left, vec![L(0), B(1, 0), L(2)]),
);
// reader, sharded by the lookup column, which is the third column on x
mig.maintain("reader".to_string(), join, &[2]);
})
.await;
eprintln!("{}", g.graphviz().await.unwrap());
let mut base_x = g.table("base_x").await.unwrap();
let mut reader = g.view("reader").await.unwrap();
// we want to make sure that all the upqueries recurse all the way to cause maximum headache
// for the partial logic. we do this by ensuring that every shard at every operator has at
// least one record. we also ensure that we can get _all_ the rows by querying a single key on
// the reader.
let n = 10_000;
base_x
.perform_all((0..n).map(|i| {
vec![
DataType::Int(i),
DataType::Int(i % nshards as i32),
DataType::Int(1),
]
}))
.await
.unwrap();
sleep().await;
// moment of truth
let rows = reader.lookup(&[DataType::Int(1)], true).await.unwrap();
assert_eq!(rows.len(), n as usize);
for i in 0..n {
assert!(rows
.iter()
.any(|row| row.get::<i32>("base_col").unwrap() == i));
}
}
#[tokio::test(threaded_scheduler)]
async fn base_mutation() {
use noria::{Modification, Operation};
let mut g = start_simple("base_mutation").await;
g.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::new(vec![]).with_key(vec![0]));
mig.maintain_anonymous(a, &[0]);
})
.await;
let mut read = g.view("a").await.unwrap();
let mut write = g.table("a").await.unwrap();
// insert a new record
write.insert(vec![1.into(), 2.into()]).await.unwrap();
sleep().await;
assert_eq!(
read.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 2.into()]]
);
// update that record in place (set)
write
.update(vec![1.into()], vec![(1, Modification::Set(3.into()))])
.await
.unwrap();
sleep().await;
assert_eq!(
read.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 3.into()]]
);
// update that record in place (add)
write
.update(
vec![1.into()],
vec![(1, Modification::Apply(Operation::Add, 1.into()))],
)
.await
.unwrap();
sleep().await;
assert_eq!(
read.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 4.into()]]
);
// insert or update should update
write
.insert_or_update(
vec![1.into(), 2.into()],
vec![(1, Modification::Apply(Operation::Add, 1.into()))],
)
.await
.unwrap();
sleep().await;
assert_eq!(
read.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 5.into()]]
);
// delete should, well, delete
write.delete(vec![1.into()]).await.unwrap();
sleep().await;
assert!(read.lookup(&[1.into()], true).await.unwrap().is_empty());
// insert or update should insert
write
.insert_or_update(
vec![1.into(), 2.into()],
vec![(1, Modification::Apply(Operation::Add, 1.into()))],
)
.await
.unwrap();
sleep().await;
assert_eq!(
read.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 2.into()]]
);
}
#[tokio::test(threaded_scheduler)]
async fn shared_interdomain_ancestor() {
// set up graph
let mut g = start_simple("shared_interdomain_ancestor").await;
let _ = g
.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::default());
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
let u = Union::new(emits.clone());
let b = mig.add_ingredient("b", &["a", "b"], u);
mig.maintain_anonymous(b, &[0]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["a", "b"], u);
mig.maintain_anonymous(c, &[0]);
(a, b, c)
})
.await;
let mut bq = g.view("b").await.unwrap();
let mut cq = g.view("c").await.unwrap();
let mut muta = g.table("a").await.unwrap();
let id: DataType = 1.into();
// send a value on a
muta.insert(vec![id.clone(), 2.into()]).await.unwrap();
sleep().await;
assert_eq!(
bq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![id.clone(), 2.into()]]
);
assert_eq!(
cq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![id.clone(), 2.into()]]
);
// update value again
let id: DataType = 2.into();
muta.insert(vec![id.clone(), 4.into()]).await.unwrap();
sleep().await;
assert_eq!(
bq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![id.clone(), 4.into()]]
);
assert_eq!(
cq.lookup(&[id.clone()], true).await.unwrap(),
vec![vec![id.clone(), 4.into()]]
);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_w_mat() {
// set up graph
let mut g = start_simple("it_works_w_mat").await;
let _ = g
.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::default());
let b = mig.add_base("b", &["a", "b"], Base::default());
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
emits.insert(b, vec![0, 1]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["a", "b"], u);
mig.maintain_anonymous(c, &[0]);
(a, b, c)
})
.await;
let mut cq = g.view("c").await.unwrap();
let mut muta = g.table("a").await.unwrap();
let mut mutb = g.table("b").await.unwrap();
let id: DataType = 1.into();
// send a few values on a
muta.insert(vec![id.clone(), 1.into()]).await.unwrap();
muta.insert(vec![id.clone(), 2.into()]).await.unwrap();
muta.insert(vec![id.clone(), 3.into()]).await.unwrap();
// give them some time to propagate
sleep().await;
// send a query to c
// we should see all the a values
let res = cq.lookup(&[id.clone()], true).await.unwrap();
assert_eq!(res.len(), 3);
assert!(res.iter().any(|r| r == &vec![id.clone(), 1.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 2.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 3.into()]));
// update value again (and again send some secondary updates)
mutb.insert(vec![id.clone(), 4.into()]).await.unwrap();
mutb.insert(vec![id.clone(), 5.into()]).await.unwrap();
mutb.insert(vec![id.clone(), 6.into()]).await.unwrap();
// give it some time to propagate
sleep().await;
// check that value was updated again
let res = cq.lookup(&[id.clone()], true).await.unwrap();
assert_eq!(res.len(), 6);
assert!(res.iter().any(|r| r == &vec![id.clone(), 1.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 2.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 3.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 4.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 5.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 6.into()]));
}
#[tokio::test(threaded_scheduler)]
async fn it_works_w_partial_mat() {
// set up graph
let mut g = start_simple("it_works_w_partial_mat").await;
let (a, b) = g
.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::default());
let b = mig.add_base("b", &["a", "b"], Base::default());
(a, b)
})
.await;
let mut muta = g.table("a").await.unwrap();
let id: DataType = 1.into();
// send a few values on a
muta.insert(vec![id.clone(), 1.into()]).await.unwrap();
muta.insert(vec![id.clone(), 2.into()]).await.unwrap();
muta.insert(vec![id.clone(), 3.into()]).await.unwrap();
// give it some time to propagate
sleep().await;
let _ = g
.migrate(move |mig| {
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
emits.insert(b, vec![0, 1]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["a", "b"], u);
mig.maintain_anonymous(c, &[0]);
c
})
.await;
// give it some time to propagate
sleep().await;
let mut cq = g.view("c").await.unwrap();
// because the reader is partial, we should have no key until we read
assert_eq!(cq.len().await.unwrap(), 0);
// now do some reads
let res = cq.lookup(&[id.clone()], true).await.unwrap();
assert_eq!(res.len(), 3);
assert!(res.iter().any(|r| r == &vec![id.clone(), 1.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 2.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 3.into()]));
// should have one key in the reader now
assert_eq!(cq.len().await.unwrap(), 1);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_w_partial_mat_below_empty() {
// set up graph with all nodes added in a single migration. The base tables are therefore empty
// for now.
let mut g = start_simple("it_works_w_partial_mat_below_empty").await;
let _ = g
.migrate(|mig| {
let a = mig.add_base("a", &["a", "b"], Base::default());
let b = mig.add_base("b", &["a", "b"], Base::default());
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
emits.insert(b, vec![0, 1]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["a", "b"], u);
mig.maintain_anonymous(c, &[0]);
(a, b, c)
})
.await;
let mut muta = g.table("a").await.unwrap();
let id: DataType = 1.into();
// send a few values on a
muta.insert(vec![id.clone(), 1.into()]).await.unwrap();
muta.insert(vec![id.clone(), 2.into()]).await.unwrap();
muta.insert(vec![id.clone(), 3.into()]).await.unwrap();
// give it some time to propagate
sleep().await;
let mut cq = g.view("c").await.unwrap();
// despite the empty base tables, we'll make the reader partial and therefore we should have no
// key until we read
assert_eq!(cq.len().await.unwrap(), 0);
// now do some reads
let res = cq.lookup(&[id.clone()], true).await.unwrap();
assert_eq!(res.len(), 3);
assert!(res.iter().any(|r| r == &vec![id.clone(), 1.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 2.into()]));
assert!(res.iter().any(|r| r == &vec![id.clone(), 3.into()]));
// should have one key in the reader now
assert_eq!(cq.len().await.unwrap(), 1);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_deletion() {
// set up graph
let mut g = start_simple("it_works_deletion").await;
let _ = g
.migrate(|mig| {
let a = mig.add_base("a", &["x", "y"], Base::new(vec![]).with_key(vec![1]));
let b = mig.add_base("b", &["_", "x", "y"], Base::new(vec![]).with_key(vec![2]));
let mut emits = HashMap::new();
emits.insert(a, vec![0, 1]);
emits.insert(b, vec![1, 2]);
let u = Union::new(emits);
let c = mig.add_ingredient("c", &["x", "y"], u);
mig.maintain_anonymous(c, &[0]);
(a, b, c)
})
.await;
let mut cq = g.view("c").await.unwrap();
let mut muta = g.table("a").await.unwrap();
let mut mutb = g.table("b").await.unwrap();
// send a value on a
muta.insert(vec![1.into(), 2.into()]).await.unwrap();
sleep().await;
assert_eq!(
cq.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 2.into()]]
);
// send a value on b
mutb.insert(vec![0.into(), 1.into(), 4.into()])
.await
.unwrap();
sleep().await;
let res = cq.lookup(&[1.into()], true).await.unwrap();
assert_eq!(res.len(), 2);
assert!(res.contains(&vec![1.into(), 2.into()]));
assert!(res.contains(&vec![1.into(), 4.into()]));
// delete first value
muta.delete(vec![2.into()]).await.unwrap();
sleep().await;
assert_eq!(
cq.lookup(&[1.into()], true).await.unwrap(),
vec![vec![1.into(), 4.into()]]
);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_with_sql_recipe() {
let mut g = start_simple("it_works_with_sql_recipe").await;
let sql = "
CREATE TABLE Car (id int, brand varchar(255), PRIMARY KEY(id));
QUERY CountCars: SELECT COUNT(*) FROM Car WHERE brand = ?;
";
g.install_recipe(sql).await.unwrap();
let mut mutator = g.table("Car").await.unwrap();
let mut getter = g.view("CountCars").await.unwrap();
assert_eq!(mutator.table_name(), "Car");
assert_eq!(mutator.columns(), &["id", "brand"]);
let brands = vec!["Volvo", "Volvo", "Volkswagen"];
for (i, &brand) in brands.iter().enumerate() {
mutator.insert(vec![i.into(), brand.into()]).await.unwrap();
}
// Let writes propagate:
sleep().await;
// Retrieve the result of the count query:
let result = getter.lookup(&["Volvo".into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0][0], 2.into());
}
#[tokio::test(threaded_scheduler)]
async fn it_works_with_vote() {
let mut g = start_simple("it_works_with_vote").await;
let sql = "
# base tables
CREATE TABLE Article (id int, title varchar(255), PRIMARY KEY(id));
CREATE TABLE Vote (article_id int, user int);
# read queries
QUERY ArticleWithVoteCount: SELECT Article.id, title, VoteCount.votes AS votes \
FROM Article \
LEFT JOIN (SELECT Vote.article_id, COUNT(user) AS votes \
FROM Vote GROUP BY Vote.article_id) AS VoteCount \
ON (Article.id = VoteCount.article_id) WHERE Article.id = ?;
";
g.install_recipe(sql).await.unwrap();
let mut article = g.table("Article").await.unwrap();
let mut vote = g.table("Vote").await.unwrap();
let mut awvc = g.view("ArticleWithVoteCount").await.unwrap();
article
.insert(vec![0i64.into(), "Article".into()])
.await
.unwrap();
article
.insert(vec![1i64.into(), "Article".into()])
.await
.unwrap();
vote.insert(vec![0i64.into(), 0.into()]).await.unwrap();
sleep().await;
let rs = awvc.lookup(&[0i64.into()], true).await.unwrap();
assert_eq!(rs.len(), 1);
assert_eq!(rs[0], vec![0i64.into(), "Article".into(), 1.into()]);
let empty = awvc.lookup(&[1i64.into()], true).await.unwrap();
assert_eq!(empty.len(), 1);
assert_eq!(
empty[0],
vec![1i64.into(), "Article".into(), DataType::None]
);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_with_identical_queries() {
let mut g = start_simple("it_works_with_identical_queries").await;
let sql = "
CREATE TABLE Article (aid int, PRIMARY KEY(aid));
QUERY aq1: SELECT Article.* FROM Article WHERE Article.aid = ?;
QUERY aq2: SELECT Article.* FROM Article WHERE Article.aid = ?;
";
g.install_recipe(sql).await.unwrap();
let mut article = g.table("Article").await.unwrap();
let mut aq1 = g.view("aq1").await.unwrap();
let mut aq2 = g.view("aq2").await.unwrap();
let aid = 1u64;
assert!(aq1.lookup(&[aid.into()], true).await.unwrap().is_empty());
assert!(aq2.lookup(&[aid.into()], true).await.unwrap().is_empty());
article.insert(vec![aid.into()]).await.unwrap();
sleep().await;
let result = aq2.lookup(&[aid.into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0], vec![aid.into()]);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_with_double_query_through() {
let mut g = start_simple_unsharded("it_works_with_double_query_through").await;
let sql = "
# base tables
CREATE TABLE A (aid int, other int, PRIMARY KEY(aid));
CREATE TABLE B (bid int, PRIMARY KEY(bid));
# read queries
QUERY ReadJoin: SELECT J.aid, J.other \
FROM B \
LEFT JOIN (SELECT A.aid, A.other FROM A \
WHERE A.other = 5) AS J \
ON (J.aid = B.bid) \
WHERE J.aid = ?;
";
g.install_recipe(sql).await.unwrap();
let mut a = g.table("A").await.unwrap();
let mut b = g.table("B").await.unwrap();
let mut getter = g.view("ReadJoin").await.unwrap();
a.insert(vec![1i64.into(), 5.into()]).await.unwrap();
a.insert(vec![2i64.into(), 10.into()]).await.unwrap();
b.insert(vec![1i64.into()]).await.unwrap();
sleep().await;
let rs = getter.lookup(&[1i64.into()], true).await.unwrap();
assert_eq!(rs.len(), 1);
assert_eq!(rs[0], vec![1i64.into(), 5.into()]);
let empty = getter.lookup(&[2i64.into()], true).await.unwrap();
assert_eq!(empty.len(), 0);
}
#[tokio::test(threaded_scheduler)]
async fn it_works_with_reads_before_writes() {
let mut g = start_simple("it_works_with_reads_before_writes").await;
let sql = "
CREATE TABLE Article (aid int, PRIMARY KEY(aid));
CREATE TABLE Vote (aid int, uid int, PRIMARY KEY(aid, uid));
QUERY ArticleVote: SELECT Article.aid, Vote.uid \
FROM Article, Vote \
WHERE Article.aid = Vote.aid AND Article.aid = ?;
";
g.install_recipe(sql).await.unwrap();
let mut article = g.table("Article").await.unwrap();
let mut vote = g.table("Vote").await.unwrap();
let mut awvc = g.view("ArticleVote").await.unwrap();
let aid = 1;
let uid = 10;
assert!(awvc.lookup(&[aid.into()], true).await.unwrap().is_empty());
article.insert(vec![aid.into()]).await.unwrap();
sleep().await;
vote.insert(vec![aid.into(), uid.into()]).await.unwrap();
sleep().await;
let result = awvc.lookup(&[aid.into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0], vec![aid.into(), uid.into()]);
}
#[tokio::test(threaded_scheduler)]
async fn forced_shuffle_despite_same_shard() {
// XXX: this test doesn't currently *fail* despite
// multiple trailing replay responses that are simply ignored...
let mut g = start_simple("forced_shuffle_despite_same_shard").await;
let sql = "
CREATE TABLE Car (cid int, pid int, PRIMARY KEY(pid));
CREATE TABLE Price (pid int, price int, PRIMARY KEY(pid));
QUERY CarPrice: SELECT cid, price FROM Car \
JOIN Price ON Car.pid = Price.pid WHERE cid = ?;
";
g.install_recipe(sql).await.unwrap();
let mut car_mutator = g.table("Car").await.unwrap();
let mut price_mutator = g.table("Price").await.unwrap();
let mut getter = g.view("CarPrice").await.unwrap();
let cid = 1;
let pid = 1;
let price = 100;
price_mutator
.insert(vec![pid.into(), price.into()])
.await
.unwrap();
car_mutator
.insert(vec![cid.into(), pid.into()])
.await
.unwrap();
// Let writes propagate:
sleep().await;
// Retrieve the result of the count query:
let result = getter.lookup(&[cid.into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0][1], price.into());
}
#[tokio::test(threaded_scheduler)]
async fn double_shuffle() {
let mut g = start_simple("double_shuffle").await;
let sql = "
CREATE TABLE Car (cid int, pid int, PRIMARY KEY(cid));
CREATE TABLE Price (pid int, price int, PRIMARY KEY(pid));
QUERY CarPrice: SELECT cid, price FROM Car \
JOIN Price ON Car.pid = Price.pid WHERE cid = ?;
";
g.install_recipe(sql).await.unwrap();
let mut car_mutator = g.table("Car").await.unwrap();
let mut price_mutator = g.table("Price").await.unwrap();
let mut getter = g.view("CarPrice").await.unwrap();
let cid = 1;
let pid = 1;
let price = 100;
price_mutator
.insert(vec![pid.into(), price.into()])
.await
.unwrap();
car_mutator
.insert(vec![cid.into(), pid.into()])
.await
.unwrap();
// Let writes propagate:
sleep().await;
// Retrieve the result of the count query:
let result = getter.lookup(&[cid.into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0][1], price.into());
}
#[tokio::test(threaded_scheduler)]
async fn it_works_with_arithmetic_aliases() {
let mut g = start_simple("it_works_with_arithmetic_aliases").await;
let sql = "
CREATE TABLE Price (pid int, cent_price int, PRIMARY KEY(pid));
ModPrice: SELECT pid, cent_price / 100 AS price FROM Price;
QUERY AltPrice: SELECT pid, price FROM ModPrice WHERE pid = ?;
";
g.install_recipe(sql).await.unwrap();
let mut price_mutator = g.table("Price").await.unwrap();
let mut getter = g.view("AltPrice").await.unwrap();
let pid = 1;
let price = 10000;
price_mutator
.insert(vec![pid.into(), price.into()])
.await
.unwrap();
// Let writes propagate:
sleep().await;
// Retrieve the result of the count query:
let result = getter.lookup(&[pid.into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0][1], (price / 100).into());
}
#[tokio::test(threaded_scheduler)]
async fn it_recovers_persisted_bases() {
let authority = Arc::new(LocalAuthority::new());
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("it_recovers_persisted_bases");
let persistence_params = PersistenceParameters::new(
DurabilityMode::Permanent,
Duration::from_millis(1),
Some(path.to_string_lossy().into()),
1,
);
{
let mut g = Builder::default();
g.set_persistence(persistence_params.clone());
let (mut g, done) = g.start(authority.clone()).await.unwrap();
{
let sql = "
CREATE TABLE Car (id int, price int, PRIMARY KEY(id));
QUERY CarPrice: SELECT price FROM Car WHERE id = ?;
";
g.install_recipe(sql).await.unwrap();
let mut mutator = g.table("Car").await.unwrap();
for i in 1..10 {
let price = i * 10;
mutator.insert(vec![i.into(), price.into()]).await.unwrap();
}
}
// Let writes propagate:
sleep().await;
drop(g);
done.await;
}
let mut g = Builder::default();
g.set_persistence(persistence_params);
let (mut g, done) = g.start(authority.clone()).await.unwrap();
{
let mut getter = g.view("CarPrice").await.unwrap();
// Make sure that the new graph contains the old writes
for i in 1..10 {
let price = i * 10;
let result = getter.lookup(&[i.into()], true).await.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0][0], price.into());
}
}
drop(g);
done.await;
}