holochain_state 0.7.0-dev.22

Holochain persisted state datatypes and functions
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
use super::*;
use crate::here;
use crate::prelude::mutations_helpers::insert_valid_integrated_op;
use crate::prelude::*;
use holo_hash::fixt::AgentPubKeyFixturator;
use holo_hash::fixt::EntryHashFixturator;
use holochain_trace;
use holochain_types::db::DbWrite;
use holochain_types::record::SignedActionHashedExt;
use std::vec::IntoIter;

#[derive(Clone)]
struct TestData {
    link_add: CreateLink,
    link_remove: DeleteLink,
    base_hash: EntryHash,
    zome_index: ZomeIndex,
    link_type: LinkType,
    tag: LinkTag,
    expected_link: Link,
    env: DbWrite<DbKindDht>,
    scratch: Scratch,
    query: GetLinksQuery,
    query_no_tag: GetLinksQuery,
}

fn fixtures(env: DbWrite<DbKindDht>, n: usize) -> Vec<TestData> {
    let mut tag_fix = BytesFixturator::new(Predictable);
    let mut data = Vec::new();
    let mut agent_pub_key_fixt = AgentPubKeyFixturator::new(Predictable);
    let mut base_hash_fixt = EntryHashFixturator::new(Predictable);
    let mut target_hash_fixt = EntryHashFixturator::new(Unpredictable);
    for i in 0..n {
        // Create a known link add
        let base_address = base_hash_fixt.next().unwrap();
        let target_address = target_hash_fixt.next().unwrap();
        let agent_pub_key = agent_pub_key_fixt.next().unwrap();

        let tag = LinkTag::new(tag_fix.next().unwrap());
        let zome_index = ZomeIndex(i as u8);
        let link_type = LinkType(i as u8);

        let link_add = KnownCreateLink {
            author: agent_pub_key.clone(),
            base_address: base_address.clone().into(),
            target_address: target_address.clone().into(),
            zome_index,
            link_type,
            tag: tag.clone(),
        };

        let link_add = CreateLinkFixturator::new(link_add).next().unwrap();

        // Create the expected link result
        let (_, link_add_hash): (_, ActionHash) =
            ActionHashed::from_content_sync(Action::CreateLink(link_add.clone())).into();

        let expected_link = Link {
            author: agent_pub_key,
            create_link_hash: link_add_hash.clone(),
            base: link_add.base_address.clone(),
            target: target_address.clone().into(),
            zome_index,
            link_type,
            timestamp: link_add.timestamp,
            tag: tag.clone(),
        };

        let link_remove = KnownDeleteLink {
            link_add_address: link_add_hash,
            base_address: link_add.base_address.clone(),
        };
        let link_remove = DeleteLinkFixturator::new(link_remove).next().unwrap();
        let query = GetLinksQuery::new(
            link_add.base_address.clone(),
            LinkTypeFilter::single_dep(zome_index),
            Some(link_add.tag.clone()),
            GetLinksFilter::default(),
        );
        let query_no_tag = GetLinksQuery::base(link_add.base_address.clone(), vec![zome_index]);

        let td = TestData {
            link_add,
            link_remove,
            base_hash: base_address.clone(),
            zome_index,
            link_type,
            tag,
            expected_link,
            env: env.clone(),
            scratch: Scratch::new(),
            query,
            query_no_tag,
        };
        data.push(td);
    }
    data
}

impl TestData {
    /// Create the same test data with a new timestamp
    fn with_same_keys(mut td: Self) -> Self {
        td.link_add.timestamp = holochain_zome_types::prelude::Timestamp::now();
        let link_add_hash =
            ActionHashed::from_content_sync(Action::CreateLink(td.link_add.clone())).into_hash();
        td.link_remove.link_add_address = link_add_hash.clone();
        td.expected_link.timestamp = td.link_add.timestamp;
        td.expected_link.create_link_hash = link_add_hash;
        td
    }

    async fn empty(&self, test: &'static str) {
        let val = self
            .env
            .read_async({
                let query = self.query.clone();
                let scratch = self.scratch.clone();

                move |txn| -> DatabaseResult<bool> {
                    Ok(query
                        .run(DbScratch::new(&[txn], &scratch))
                        .unwrap()
                        .is_empty())
                }
            })
            .await
            .unwrap();
        assert!(val, "{}", test);
    }

    async fn only_on_full_key(&self, test: &'static str) {
        let val = self
            .env
            .read_async({
                let query = self.query_no_tag.clone();
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap();
        assert_eq!(val, std::slice::from_ref(&self.expected_link), "{test}");
    }

    async fn not_on_full_key(&self, test: &'static str) {
        let val = self
            .env
            .read_async({
                let query = self.query.clone();
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap()
            .contains(&self.expected_link);
        assert!(
            !val,
            "LinkMetaVal: {:?} should not be present {}",
            self.expected_link, test
        );
    }

    async fn only_on_base(&self, test: &'static str) {
        let val = self
            .env
            .read_async({
                let query_no_tag = self.query_no_tag.clone();
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query_no_tag.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap();
        assert_eq!(val, std::slice::from_ref(&self.expected_link), "{test}");
    }

    async fn is_on_type(&self, test: &'static str) {
        let query = GetLinksQuery::new(
            self.base_hash.clone().into(),
            LinkTypeFilter::single_type(self.zome_index, self.link_type),
            None,
            GetLinksFilter::default(),
        );

        let val = self
            .env
            .read_async({
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap()
            .contains(&self.expected_link);
        assert!(
            val,
            "Results should contain link: {:?} in test: {}",
            self.expected_link, test
        );
    }

    async fn is_on_type_query(&self, type_query: LinkTypeFilter, test: &'static str) {
        let query = GetLinksQuery::new(
            self.base_hash.clone().into(),
            type_query,
            None,
            GetLinksFilter::default(),
        );

        let val = self
            .env
            .read_async({
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap()
            .contains(&self.expected_link);
        assert!(
            val,
            "Results should contain link: {:?} in test: {}",
            self.expected_link, test
        );
    }

    async fn only_on_half_tag(&self, test: &'static str) {
        let tag_len = self.tag.0.len();
        // Make sure there is at least some tag
        let half_tag = if tag_len > 1 { tag_len / 2 } else { tag_len };
        let half_tag = LinkTag::new(&self.tag.0[..half_tag]);
        let query = GetLinksQuery::new(
            self.base_hash.clone().into(),
            LinkTypeFilter::single_type(self.zome_index, self.link_type),
            Some(half_tag),
            GetLinksFilter::default(),
        );

        let val = self
            .env
            .read_async({
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap();
        assert_eq!(val, std::slice::from_ref(&self.expected_link), "{test}");
    }

    async fn is_on_half_tag(&self, test: &'static str) {
        let tag_len = self.tag.0.len();
        // Make sure there is at least some tag
        let half_tag = if tag_len > 1 { tag_len / 2 } else { tag_len };
        let half_tag = LinkTag::new(&self.tag.0[..half_tag]);
        let query = GetLinksQuery::new(
            self.base_hash.clone().into(),
            LinkTypeFilter::single_type(self.zome_index, self.link_type),
            Some(half_tag),
            GetLinksFilter::default(),
        );

        let val = self
            .env
            .read_async({
                let scratch = self.scratch.clone();

                move |txn| -> StateQueryResult<Vec<Link>> {
                    query.run(DbScratch::new(&[txn], &scratch))
                }
            })
            .await
            .unwrap()
            .contains(&self.expected_link);
        assert!(
            val,
            "Results should contain LinkMetaVal: {:?} in test: {}",
            self.expected_link, test
        );
    }

    async fn add_link(&self) {
        let op = DhtOpHashed::from_content_sync(ChainOp::RegisterAddLink(
            fixt!(Signature),
            self.link_add.clone(),
        ));
        self.env
            .write_async(move |txn| -> StateMutationResult<()> {
                insert_valid_integrated_op(txn, &op)
            })
            .await
            .unwrap();
    }

    fn add_link_scratch(&mut self) {
        let action = SignedActionHashed::from_content_sync(SignedAction::new(
            Action::CreateLink(self.link_add.clone()),
            fixt!(Signature),
        ));
        self.scratch.add_action(action, ChainTopOrdering::default());
    }

    fn add_link_given_scratch(&mut self, scratch: &mut Scratch) {
        let action = SignedActionHashed::from_content_sync(SignedAction::new(
            Action::CreateLink(self.link_add.clone()),
            fixt!(Signature),
        ));
        scratch.add_action(action, ChainTopOrdering::default());
    }

    async fn delete_link(&self) {
        let op = DhtOpHashed::from_content_sync(ChainOp::RegisterRemoveLink(
            fixt!(Signature),
            self.link_remove.clone(),
        ));
        self.env
            .write_async(move |txn| -> StateMutationResult<()> {
                insert_valid_integrated_op(txn, &op)
            })
            .await
            .unwrap();
    }

    fn delete_link_scratch(&mut self) {
        let action = SignedActionHashed::from_content_sync(SignedAction::new(
            Action::DeleteLink(self.link_remove.clone()),
            fixt!(Signature),
        ));
        self.scratch.add_action(action, ChainTopOrdering::default());
    }
    fn clear_scratch(&mut self) {
        self.scratch.drain_actions().for_each(|_| ());
    }

    async fn only_these_on_base(td: &[Self], test: &'static str) {
        // Check all base hash are the same
        for d in td {
            assert_eq!(d.base_hash, td[0].base_hash, "{test}");
        }
        let base_hash = td[0].base_hash.clone();
        let expected = td
            .iter()
            .map(|d| d.expected_link.clone())
            .collect::<Vec<_>>();
        let mut val = Vec::new();
        for d in td {
            let query = GetLinksQuery::new(
                base_hash.clone().into(),
                LinkTypeFilter::single_type(d.zome_index, d.link_type),
                None,
                GetLinksFilter::default(),
            );

            val.extend(
                d.env
                    .read_async({
                        let scratch = d.scratch.clone();

                        move |txn| -> DatabaseResult<IntoIter<Link>> {
                            Ok(query
                                .run(DbScratch::new(&[txn], &scratch))
                                .unwrap()
                                .into_iter())
                        }
                    })
                    .await
                    .unwrap(),
            );
        }
        assert_eq!(val, expected, "{test}");
    }

    async fn only_these_on_query(
        td: &[Self],
        scratch: &Scratch,
        query: impl Into<LinkTypeFilter>,
        test: &str,
    ) {
        // Check all base hash are the same
        for d in td {
            assert_eq!(d.base_hash, td[0].base_hash, "{test}");
        }
        let base_hash = td[0].base_hash.clone();
        let expected = td
            .iter()
            .map(|d| d.expected_link.clone())
            .collect::<HashSet<_>>();
        let query = GetLinksQuery::new(
            base_hash.clone().into(),
            query.into(),
            None,
            GetLinksFilter::default(),
        );

        let val: HashSet<_> = td[0]
            .env
            .clone()
            .read_async({
                let scratch = scratch.clone();

                move |txn| -> DatabaseResult<IntoIter<Link>> {
                    Ok(query
                        .run(DbScratch::new(&[txn], &scratch))
                        .unwrap()
                        .into_iter())
                }
            })
            .await
            .unwrap()
            .collect();
        assert_eq!(val, expected, "{test}");
    }

    async fn only_these_on_full_key(td: &[Self], test: &'static str) {
        // Check all base hash, link type, tag are the same
        for d in td {
            assert_eq!(d.base_hash, td[0].base_hash, "{test}");
            assert_eq!(d.link_type, td[0].link_type, "{test}");
            assert_eq!(d.tag, td[0].tag, "{test}");
        }
        let base_hash = td[0].base_hash.clone();
        let zome_index = td[0].zome_index;
        let tag = td[0].tag.clone();
        let expected = td
            .iter()
            .map(|d| d.expected_link.clone())
            .collect::<Vec<_>>();
        let query = GetLinksQuery::new(
            base_hash.into(),
            LinkTypeFilter::single_dep(zome_index),
            Some(tag),
            GetLinksFilter::default(),
        );
        let mut val = Vec::new();
        for d in td {
            val.extend(
                d.env
                    .read_async({
                        let my_query = query.clone();
                        let scratch = d.scratch.clone();

                        move |txn| -> DatabaseResult<IntoIter<Link>> {
                            Ok(my_query
                                .run(DbScratch::new(&[txn], &scratch))
                                .unwrap()
                                .into_iter())
                        }
                    })
                    .await
                    .unwrap(),
            );
        }
        assert_eq!(val, expected, "{test}");
    }

    async fn only_these_on_half_key(td: &[Self], test: &'static str) {
        let tag_len = td[0].tag.0.len();
        // Make sure there is at least some tag
        let tag_len = if tag_len > 1 { tag_len / 2 } else { tag_len };
        let half_tag = LinkTag::new(&td[0].tag.0[..tag_len]);
        // Check all base hash, zome_index, half tag are the same
        for d in td {
            assert_eq!(d.base_hash, td[0].base_hash, "{test}");
            assert_eq!(d.link_type, td[0].link_type, "{test}");
            assert_eq!(&d.tag.0[..tag_len], &half_tag.0[..], "{test}");
        }
        let base_hash = td[0].base_hash.clone();
        let zome_index = td[0].zome_index;
        let expected = td
            .iter()
            .map(|d| d.expected_link.clone())
            .collect::<Vec<_>>();
        let query = GetLinksQuery::new(
            base_hash.into(),
            LinkTypeFilter::single_dep(zome_index),
            Some(half_tag),
            GetLinksFilter::default(),
        );
        let mut val = Vec::new();
        for d in td {
            val.extend(
                d.env
                    .read_async({
                        let my_query = query.clone();
                        let scratch = d.scratch.clone();

                        move |txn| -> DatabaseResult<IntoIter<Link>> {
                            Ok(my_query
                                .run(DbScratch::new(&[txn], &scratch))
                                .unwrap()
                                .into_iter())
                        }
                    })
                    .await
                    .unwrap(),
            );
        }
        assert_eq!(val, expected, "{test}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn can_add_and_delete_link() {
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 1).into_iter().next().unwrap();

    // Check it's empty
    td.empty(here!("empty at start")).await;

    // Add a link
    // Add
    td.add_link_scratch();
    // Is in scratch
    td.only_on_full_key(here!("add link in scratch")).await;

    // Remove from scratch
    td.delete_link_scratch();

    // Is empty
    td.empty(here!("empty after remove")).await;

    let new_td = TestData::with_same_keys(td.clone());
    td = new_td;

    // Add again
    td.add_link_scratch();

    // Is in scratch again
    td.only_on_full_key(here!("Is still in the scratch")).await;

    // Remove from scratch
    td.delete_link_scratch();

    // Is empty
    td.empty(here!("empty after remove")).await;

    // Check it's in db
    td.clear_scratch();
    td.add_link().await;

    td.only_on_full_key(here!("It's in the db")).await;

    // Remove the link
    td.delete_link().await;
    // Is empty

    td.empty(here!("empty after remove in db")).await;

    // Add a link
    let new_td = TestData::with_same_keys(td.clone());
    td = new_td;
    // Add
    td.add_link_scratch();
    // Is in scratch
    td.only_on_full_key(here!("add link in scratch")).await;
    // No zome, no tag
    td.only_on_base(here!("scratch")).await;
    // Half the tag
    td.only_on_half_tag(here!("scratch")).await;

    td.delete_link_scratch();
    td.empty(here!("empty after remove in db")).await;

    // Partial matching
    td.clear_scratch();
    td.add_link().await;

    td.only_on_full_key(here!("db")).await;
    // No zome, no tag
    td.only_on_base(here!("db")).await;
    // Half the tag
    td.only_on_half_tag(here!("db")).await;
}

#[tokio::test(flavor = "multi_thread")]
async fn multiple_links() {
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 10);

    // Add links
    {
        // Add
        for d in &mut td {
            d.add_link_scratch();
        }
        // Is in scratch
        for d in &mut td {
            d.only_on_full_key(here!("add link in scratch")).await;
        }

        // Remove from scratch
        td[5].delete_link_scratch();

        td[5].not_on_full_key(here!("removed in scratch")).await;

        for d in td[0..5].iter().chain(&td[6..]) {
            d.only_on_full_key(here!("all except 5 scratch")).await;
        }
        // Can't add back the same action because removes are tombstones
        // so add one with the same key
        let new_td = TestData::with_same_keys(td[5].clone());
        td[5] = new_td;
        // Add again
        td[5].add_link_scratch();

        // Is in scratch again
        td[5]
            .only_on_full_key(here!("Is back in the scratch"))
            .await;

        for d in &mut td {
            d.only_on_full_key(here!("add link in scratch")).await;
        }
        for d in &mut td {
            d.clear_scratch();
        }
    }

    {
        for d in &mut td {
            d.add_link().await;
        }
        for d in &mut td {
            d.only_on_full_key(here!("all in db")).await;
        }
        td[0].delete_link().await;

        for d in &td[1..] {
            d.only_on_full_key(here!("all except 0 scratch")).await;
        }

        td[0].not_on_full_key(here!("removed in scratch")).await;
    }

    for d in &td[1..] {
        d.only_on_full_key(here!("all except 0")).await;
    }
    td[0].not_on_full_key(here!("removed in db")).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn duplicate_links() {
    holochain_trace::test_run();
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 10);
    // Add to db then the same to scratch and expect on one result
    {
        // Add
        for d in &mut td {
            d.add_link_scratch();
        }
        // Is in scratch
        for d in &mut td {
            d.only_on_full_key(here!("re add")).await;
            // No zome, no tag
            d.only_on_base(here!("re add")).await;
            // Half the tag
            d.is_on_half_tag(here!("re add")).await;
        }
        // Add Again
        for d in &mut td {
            d.add_link_scratch();
        }
        // Is in scratch
        for d in &mut td {
            d.only_on_full_key(here!("re add")).await;
            // No zome, no tag
            d.only_on_base(here!("re add")).await;
            // Half the tag
            d.is_on_half_tag(here!("re add")).await;
        }
    }
    {
        // Add
        for d in &mut td {
            d.add_link().await;
        }
        // Is in scratch
        for d in &mut td {
            d.only_on_full_key(here!("re add")).await;
            // No zome, no tag
            d.only_on_base(here!("re add")).await;
            // Half the tag
            d.is_on_half_tag(here!("re add")).await;
        }
    }

    for d in &mut td {
        d.clear_scratch();
    }
    // Is in db
    for d in &mut td {
        d.only_on_full_key(here!("re add")).await;
        // No zome, no tag
        d.only_on_base(here!("re add")).await;
        // Half the tag
        d.is_on_half_tag(here!("re add")).await;
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn links_on_same_base() {
    holochain_trace::test_run();
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 2);
    let base_hash = td[0].base_hash.clone();
    let base_hash = &base_hash;
    for d in td.iter_mut() {
        d.base_hash = base_hash.clone();
        d.link_add.base_address = base_hash.clone().into();
        // Create the new hash
        let (_, link_add_hash): (_, ActionHash) =
            ActionHashed::from_content_sync(Action::CreateLink(d.link_add.clone())).into();
        d.expected_link.create_link_hash = link_add_hash.clone();
        d.link_remove.link_add_address = link_add_hash;
        d.link_remove.base_address = base_hash.clone().into();
        d.query = GetLinksQuery::new(
            base_hash.clone().into(),
            LinkTypeFilter::single_dep(d.zome_index),
            Some(d.tag.clone()),
            GetLinksFilter::default(),
        );
        d.query_no_tag = GetLinksQuery::base(base_hash.clone().into(), vec![d.zome_index]);
        d.expected_link.base = d.link_add.base_address.clone();
    }
    {
        // Add
        for d in &mut td {
            d.add_link_scratch();
        }
        // Is in scratch
        for d in &mut td {
            d.only_on_full_key(here!("same base")).await;
            // Half the tag
            d.is_on_half_tag(here!("same base")).await;
        }
        TestData::only_these_on_base(&td, here!("check all return on same base")).await;
    }
    {
        for d in &mut td {
            d.add_link().await;
        }
        // In db
        for d in &mut td {
            d.only_on_full_key(here!("same base")).await;
            // Half the tag
            d.is_on_half_tag(here!("same base")).await;
        }
        TestData::only_these_on_base(&td, here!("check all return on same base")).await;
    }
    {
        for d in &mut td {
            d.clear_scratch();
        }
        // In db
        for d in &mut td {
            d.only_on_full_key(here!("same base")).await;
            // Half the tag
            d.is_on_half_tag(here!("same base")).await;
        }
        TestData::only_these_on_base(&td, here!("check all return on same base")).await;
    }
    // Check removes etc.
    {
        for d in &mut td {
            d.add_link_scratch();
        }
        td[0].delete_link_scratch();
        for d in &td[1..] {
            d.only_on_full_key(here!("same base")).await;
            // Half the tag
            d.is_on_half_tag(here!("same base")).await;
        }
        TestData::only_these_on_base(&td[1..], here!("check all return on same base")).await;
        td[0].not_on_full_key(here!("removed in scratch")).await;
    }
    {
        for d in &mut td {
            d.clear_scratch();
        }
        td[0].delete_link().await;
        for d in &td[1..] {
            d.only_on_full_key(here!("same base")).await;
            d.is_on_half_tag(here!("same base")).await;
        }
        TestData::only_these_on_base(&td[1..], here!("check all return on same base")).await;
        td[0].not_on_full_key(here!("removed in scratch")).await;
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn links_on_same_tag() {
    holochain_trace::test_run();
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 10);
    let base_hash = td[0].base_hash.clone();
    let link_type = td[0].link_type;
    let zome_index = td[0].zome_index;
    let tag = td[0].tag.clone();

    for d in td.iter_mut() {
        d.base_hash = base_hash.clone();
        d.zome_index = zome_index;
        d.link_type = link_type;
        d.tag = tag.clone();
        d.link_add.base_address = base_hash.clone().into();
        d.link_add.zome_index = zome_index;
        d.link_add.link_type = link_type;
        d.link_add.tag = tag.clone();
        d.link_remove.base_address = base_hash.clone().into();

        // Create the new hash
        let (_, link_add_hash): (_, ActionHash) =
            ActionHashed::from_content_sync(Action::CreateLink(d.link_add.clone())).into();
        d.expected_link.create_link_hash = link_add_hash.clone();
        d.expected_link.base = d.link_add.base_address.clone();
        d.expected_link.tag = tag.clone();
        d.expected_link.zome_index = zome_index;
        d.expected_link.link_type = link_type;
        d.link_remove.link_add_address = link_add_hash;

        d.query = GetLinksQuery::new(
            base_hash.clone().into(),
            LinkTypeFilter::single_dep(d.zome_index),
            Some(tag.clone()),
            GetLinksFilter::default(),
        );
        d.query_no_tag = GetLinksQuery::base(base_hash.clone().into(), vec![d.zome_index]);
    }
    {
        // Add
        for d in &mut td {
            d.add_link_scratch();
        }
        TestData::only_these_on_base(&td[..], here!("check all return on same base")).await;
        TestData::only_these_on_full_key(&td[..], here!("check all return on same base")).await;
        TestData::only_these_on_half_key(&td[..], here!("check all return on same base")).await;
    }
    {
        // In db
        TestData::only_these_on_base(&td[..], here!("check all return on same base")).await;
        TestData::only_these_on_full_key(&td[..], here!("check all return on same base")).await;
        TestData::only_these_on_half_key(&td[..], here!("check all return on same base")).await;
    }
    // Check removes etc.
    {
        td[5].delete_link().await;
        td[6].delete_link().await;
        let partial_td = &td[..5].iter().chain(&td[7..]).cloned().collect::<Vec<_>>();
        TestData::only_these_on_base(&partial_td[..], here!("check all return on same base")).await;
        TestData::only_these_on_full_key(&partial_td[..], here!("check all return on same base"))
            .await;
        TestData::only_these_on_half_key(&partial_td[..], here!("check all return on same base"))
            .await;
    }
    {
        let partial_td = &td[..5].iter().chain(&td[7..]).cloned().collect::<Vec<_>>();
        TestData::only_these_on_base(&partial_td[..], here!("check all return on same base")).await;
        TestData::only_these_on_full_key(&partial_td[..], here!("check all return on same base"))
            .await;
        TestData::only_these_on_half_key(&partial_td[..], here!("check all return on same base"))
            .await;
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn links_on_same_type() {
    holochain_trace::test_run();
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 10);
    let base_hash = td[0].base_hash.clone();
    let link_type = td[0].link_type;

    for d in td.iter_mut() {
        d.base_hash = base_hash.clone();
        d.link_type = link_type;
        d.link_add.base_address = base_hash.clone().into();
        d.link_add.link_type = link_type;

        // Create the new hash
        let (_, link_add_hash): (_, ActionHash) =
            ActionHashed::from_content_sync(Action::CreateLink(d.link_add.clone())).into();
        d.expected_link.create_link_hash = link_add_hash.clone();
        d.expected_link.base = d.link_add.base_address.clone();
        d.expected_link.link_type = link_type;
    }

    for d in &mut td {
        d.add_link_scratch();
    }
    for d in &td {
        d.is_on_type(here!("Each link is returned for a type"))
            .await;
        d.is_on_type_query(
            LinkTypeFilter::Dependencies(td.iter().map(|d| d.zome_index).collect()),
            here!("Each link is returned for a type"),
        )
        .await;
        d.is_on_type_query(
            LinkTypeFilter::single_type(d.zome_index, d.link_type),
            here!("Each link is returned for a type"),
        )
        .await;
    }
    for d in &mut td {
        d.add_link().await;
    }
    for d in &td {
        d.is_on_type(here!("Each link is returned for a type"))
            .await;
        d.is_on_type_query(
            LinkTypeFilter::Dependencies(td.iter().map(|d| d.zome_index).collect()),
            here!("Each link is returned for a type"),
        )
        .await;
        d.is_on_type_query(
            LinkTypeFilter::single_type(d.zome_index, d.link_type),
            here!("Each link is returned for a type"),
        )
        .await;
        d.is_on_type_query(
            LinkTypeFilter::Types(vec![(d.zome_index, vec![d.link_type])]),
            here!("Each link is returned for a type"),
        )
        .await;
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn link_type_ranges() {
    holochain_trace::test_run();
    let test_db = test_dht_db();
    let arc = test_db.to_db();

    let mut td = fixtures(arc.clone(), 10);
    let base_hash = td[0].base_hash.clone();
    let mut scratch = Scratch::new();

    for (i, d) in td.iter_mut().enumerate() {
        d.base_hash = base_hash.clone();
        d.link_type = LinkType(i as u8);
        d.link_add.base_address = base_hash.clone().into();
        d.link_add.link_type = LinkType(i as u8);

        // Create the new hash
        let link_add_hash = ActionHash::with_data_sync(&Action::CreateLink(d.link_add.clone()));
        d.expected_link.create_link_hash = link_add_hash.clone();
        d.expected_link.base = d.link_add.base_address.clone();
    }

    // Add
    for d in &mut td {
        d.add_link_given_scratch(&mut scratch);
    }
    TestData::only_these_on_query(
        &td,
        &scratch,
        LinkTypeFilter::Dependencies(td.iter().map(|d| d.zome_index).collect()),
        here!("all return on full range"),
    )
    .await;
    TestData::only_these_on_query(
        &td[0..=0],
        &scratch,
        LinkTypeFilter::single_type(0.into(), 0.into()),
        here!("only single on single range"),
    )
    .await;
    TestData::only_these_on_query(
        &td[4..=9],
        &scratch,
        LinkTypeFilter::Types(vec![
            (4.into(), vec![4.into()]),
            (5.into(), vec![5.into()]),
            (6.into(), vec![6.into()]),
            (7.into(), vec![7.into()]),
            (8.into(), vec![8.into()]),
            (9.into(), vec![9.into()]),
        ]),
        here!("range matches"),
    )
    .await;
    let partial_td = &td[2..5]
        .iter()
        .chain(&td[7..9])
        .cloned()
        .collect::<Vec<_>>();
    TestData::only_these_on_query(
        &partial_td[..],
        &scratch,
        LinkTypeFilter::Types(vec![
            (2.into(), vec![2.into()]),
            (3.into(), vec![3.into()]),
            (8.into(), vec![8.into()]),
            (7.into(), vec![7.into()]),
            (4.into(), vec![4.into()]),
        ]),
        here!("individual types"),
    )
    .await;
    let partial_td = &td[2..5]
        .iter()
        .chain(&td[7..9])
        .cloned()
        .collect::<Vec<_>>();
    TestData::only_these_on_query(
        &partial_td[..],
        &scratch,
        LinkTypeFilter::Types(vec![
            (7.into(), vec![7.into()]),
            (8.into(), vec![8.into()]),
            (2.into(), vec![2.into()]),
            (3.into(), vec![3.into()]),
            (4.into(), vec![4.into()]),
        ]),
        here!("individual types"),
    )
    .await;
    for d in &mut td {
        d.add_link().await;
    }
    TestData::only_these_on_query(
        &td,
        &Scratch::new(),
        LinkTypeFilter::Dependencies(td.iter().map(|d| d.zome_index).collect()),
        here!("all return on full range"),
    )
    .await;
    TestData::only_these_on_query(
        &td[0..=0],
        &Scratch::new(),
        LinkTypeFilter::single_type(0.into(), 0.into()),
        here!("all return on full range"),
    )
    .await;
    let partial_td = &td[2..5]
        .iter()
        .chain(&td[7..9])
        .cloned()
        .collect::<Vec<_>>();
    TestData::only_these_on_query(
        &partial_td[..],
        &scratch,
        LinkTypeFilter::Types(vec![
            (7.into(), vec![7.into()]),
            (8.into(), vec![8.into()]),
            (2.into(), vec![2.into()]),
            (3.into(), vec![3.into()]),
            (4.into(), vec![4.into()]),
        ]),
        here!("individual types"),
    )
    .await;
}