aranya_runtime/client/
transaction.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
use alloc::collections::{BTreeMap, VecDeque};
use core::{marker::PhantomData, mem};

use aranya_buggy::{bug, BugExt};

use crate::{
    Address, ClientError, Command, CommandId, CommandRecall, Engine, EngineError, GraphId,
    Location, MergeIds, PeerCache, Perspective, Policy, PolicyId, Prior, Revertable, Segment, Sink,
    Storage, StorageError, StorageProvider, MAX_COMMAND_LENGTH,
};

/// Transaction used to receive many commands at once.
///
/// The transaction allows us to have many temporary heads at once, so we don't
/// need as many merges when adding commands. When the transaction is committed,
/// we will merge all temporary heads and the storage head, and then commit the
/// result as the new storage head.
pub struct Transaction<SP: StorageProvider, E> {
    /// The ID of the associated storage
    storage_id: GraphId,
    /// Current working perspective
    perspective: Option<SP::Perspective>,
    /// Head of the current perspective
    phead: Option<CommandId>,
    /// Written but not committed heads
    heads: BTreeMap<Address, Location>,
    /// Tag for associated engine
    _engine: PhantomData<E>,
}

impl<SP: StorageProvider, E> Transaction<SP, E> {
    pub(super) const fn new(storage_id: GraphId) -> Self {
        Self {
            storage_id,
            perspective: None,
            phead: None,
            heads: BTreeMap::new(),
            _engine: PhantomData,
        }
    }
}

impl<SP: StorageProvider, E: Engine> Transaction<SP, E> {
    /// Find a given id if reachable within this transaction.
    ///
    /// Does not search `self.perspective`, which should be written out beforehand.
    fn locate(
        &self,
        storage: &mut SP::Storage,
        address: Address,
    ) -> Result<Option<Location>, ClientError> {
        // Search from committed head.
        if let Some(found) = storage.get_location(address)? {
            return Ok(Some(found));
        }
        // Search from our temporary heads.
        for &head in self.heads.values() {
            if let Some(found) = storage.get_location_from(head, address)? {
                return Ok(Some(found));
            }
        }
        Ok(None)
    }

    /// Write current perspective, merge transaction heads, and commit to graph.
    pub(super) fn commit(
        &mut self,
        provider: &mut SP,
        engine: &mut E,
        sink: &mut impl Sink<E::Effect>,
    ) -> Result<(), ClientError> {
        let storage = provider.get_storage(self.storage_id)?;

        // Write out current perspective.
        if let Some(p) = Option::take(&mut self.perspective) {
            self.phead = None;
            let segment = storage.write(p)?;
            let head = segment.head()?;
            self.heads.insert(head.address()?, segment.head_location());
        }

        // Merge heads pairwise until single head left, then commit.
        // TODO(#370): Merge deterministically
        let mut heads: VecDeque<_> = mem::take(&mut self.heads).into_iter().collect();
        let mut merging_head = false;
        while let Some((left_id, mut left_loc)) = heads.pop_front() {
            if let Some((right_id, mut right_loc)) = heads.pop_front() {
                let (policy, policy_id) = choose_policy(storage, engine, left_loc, right_loc)?;

                let mut buffer = [0u8; MAX_COMMAND_LENGTH];
                let merge_ids = MergeIds::new(left_id, right_id).assume("merging different ids")?;
                if left_id > right_id {
                    mem::swap(&mut left_loc, &mut right_loc);
                }
                let command = policy.merge(&mut buffer, merge_ids)?;

                let (braid, last_common_ancestor) =
                    make_braid_segment::<_, E>(storage, left_loc, right_loc, sink, policy)?;

                let mut perspective = storage
                    .new_merge_perspective(
                        left_loc,
                        right_loc,
                        last_common_ancestor,
                        policy_id,
                        braid,
                    )?
                    .assume("trx heads should exist in storage")?;
                perspective.add_command(&command)?;

                let segment = storage.write(perspective)?;
                let head = segment.head()?;

                heads.push_back((head.address()?, segment.head_location()));
            } else {
                let segment = storage.get_segment(left_loc)?;
                // Try to commit. If it fails with `HeadNotAncestor`, we know we
                // need to merge with the graph head.
                match storage.commit(segment) {
                    Ok(()) => break,
                    Err(StorageError::HeadNotAncestor) => {
                        if merging_head {
                            bug!("merging with graph head again, would loop");
                        }

                        merging_head = true;

                        heads.push_back((left_id, left_loc));

                        let head_loc = storage.get_head()?;
                        let segment = storage.get_segment(head_loc)?;
                        let head = segment.head()?;
                        heads.push_back((head.address()?, segment.head_location()));
                    }
                    Err(e) => return Err(e.into()),
                }
            }
        }

        Ok(())
    }

    /// Attempt to store the `command` in the graph with `storage_id`. Effects will be
    /// emitted to the `sink`. This interface is used when syncing with another device
    /// and integrating the new commands.
    pub(super) fn add_commands(
        &mut self,
        commands: &[impl Command],
        provider: &mut SP,
        engine: &mut E,
        sink: &mut impl Sink<E::Effect>,
        request_heads: &mut PeerCache,
    ) -> Result<usize, ClientError> {
        let mut commands = commands.iter();
        let mut count: usize = 0;

        // Get storage or try to initialize with first command.
        let storage = match provider.get_storage(self.storage_id) {
            Ok(s) => s,
            Err(StorageError::NoSuchStorage) => {
                let command = commands.next().ok_or(ClientError::InitError)?;
                count = count.checked_add(1).assume("must not overflow")?;
                self.init(command, engine, provider, sink)?
            }
            Err(e) => return Err(e.into()),
        };

        // Handle remaining commands.
        for command in commands {
            if self
                .perspective
                .as_ref()
                .is_some_and(|p| p.includes(command.id()))
            {
                // Command in current perspective.
                continue;
            }
            if let Some(loc) = self.locate(storage, command.address()?)? {
                request_heads.add_command(storage, command.address()?, loc)?;
                // Command already added.
                continue;
            }
            match command.parent() {
                Prior::None => {
                    if command.id().into_id() == self.storage_id.into_id() {
                        // Graph already initialized, extra init just spurious
                    } else {
                        bug!("init command does not belong in graph");
                    }
                }
                Prior::Single(parent) => {
                    self.add_single(storage, engine, sink, command, parent)?;
                    count = count.checked_add(1).assume("must not overflow")?;
                }
                Prior::Merge(left, right) => {
                    self.add_merge(storage, engine, sink, command, left, right)?;
                    count = count.checked_add(1).assume("must not overflow")?;
                }
            };
            if let Some(loc) = self.locate(storage, command.address()?)? {
                request_heads.add_command(storage, command.address()?, loc)?;
            }
        }
        let head_location = storage.get_head()?;
        let cmd_seg = storage.get_segment(head_location)?;
        let command = cmd_seg.head()?;
        request_heads.add_command(storage, command.address()?, head_location)?;

        Ok(count)
    }

    fn add_single(
        &mut self,
        storage: &mut <SP as StorageProvider>::Storage,
        engine: &mut E,
        sink: &mut impl Sink<E::Effect>,
        command: &impl Command,
        parent: Address,
    ) -> Result<(), ClientError> {
        let perspective = self.get_perspective(parent, storage)?;

        let policy_id = perspective.policy();
        let policy = engine.get_policy(policy_id)?;

        // Try to run command, or revert if failed.
        sink.begin();
        let checkpoint = perspective.checkpoint();
        if let Err(e) = policy.call_rule(command, perspective, sink, CommandRecall::None) {
            perspective.revert(checkpoint)?;
            sink.rollback();
            return Err(e.into());
        }
        perspective.add_command(command)?;
        sink.commit();

        self.phead = Some(command.id());

        Ok(())
    }

    fn add_merge(
        &mut self,
        storage: &mut <SP as StorageProvider>::Storage,
        engine: &mut E,
        sink: &mut impl Sink<E::Effect>,
        command: &impl Command,
        left: Address,
        right: Address,
    ) -> Result<bool, ClientError> {
        // Must always start a new perspective for merges.
        if let Some(p) = Option::take(&mut self.perspective) {
            let seg = storage.write(p)?;
            let head = seg.head()?;
            self.heads.insert(head.address()?, seg.head_location());
        }

        let left_loc = self
            .locate(storage, left)?
            .ok_or(ClientError::NoSuchParent(left.id))?;
        let right_loc = self
            .locate(storage, right)?
            .ok_or(ClientError::NoSuchParent(right.id))?;

        let (policy, policy_id) = choose_policy(storage, engine, left_loc, right_loc)?;

        // Braid commands from left and right into an ordered sequence.
        let (braid, last_common_ancestor) =
            make_braid_segment::<_, E>(storage, left_loc, right_loc, sink, policy)?;

        let mut perspective = storage
            .new_merge_perspective(left_loc, right_loc, last_common_ancestor, policy_id, braid)?
            .assume(
                "we already found left and right locations above and we only call this with merge command",
            )?;
        perspective.add_command(command)?;

        // These are no longer heads of the transaction, since they are both covered by the merge
        self.heads.remove(&left);
        self.heads.remove(&right);

        self.perspective = Some(perspective);
        self.phead = Some(command.id());

        Ok(true)
    }

    /// Get a perspective to which we can add a command with the given parant.
    ///
    /// If parent is the head of the current perspective, we can just use it.
    /// Otherwise, we must write out the perspective and get a new one.
    fn get_perspective(
        &mut self,
        parent: Address,
        storage: &mut <SP as StorageProvider>::Storage,
    ) -> Result<&mut <SP as StorageProvider>::Perspective, ClientError> {
        if self.phead == Some(parent.id) {
            // Command will append to current perspective.
            return Ok(self
                .perspective
                .as_mut()
                .assume("trx has perspective when has phead")?);
        }

        // Write out the current perspective.
        if let Some(p) = Option::take(&mut self.perspective) {
            self.phead = None;
            let seg = storage.write(p)?;
            let head = seg.head()?;
            self.heads.insert(head.address()?, seg.head_location());
        }

        let loc = self
            .locate(storage, parent)?
            .ok_or(ClientError::NoSuchParent(parent.id))?;

        // Get a new perspective and store it in the transaction.
        let p = self.perspective.insert(
            storage
                .get_linear_perspective(loc)?
                .assume("location should already be in storage")?,
        );

        self.phead = Some(parent.id);
        self.heads.remove(&parent);

        Ok(p)
    }

    fn init<'sp>(
        &mut self,
        command: &impl Command,
        engine: &mut E,
        provider: &'sp mut SP,
        sink: &mut impl Sink<E::Effect>,
    ) -> Result<&'sp mut <SP as StorageProvider>::Storage, ClientError> {
        // Storage ID is the id of the init command by definition.
        if self.storage_id.into_id() != command.id().into_id() {
            return Err(ClientError::InitError);
        }

        // The init command must not have a parent.
        if !matches!(command.parent(), Prior::None) {
            return Err(ClientError::InitError);
        }

        // The graph must have policy to start with.
        let Some(policy_data) = command.policy() else {
            return Err(ClientError::InitError);
        };

        let policy_id = engine.add_policy(policy_data)?;
        let policy = engine.get_policy(policy_id)?;

        // Get an empty perspective and run the init command.
        let mut perspective = provider.new_perspective(policy_id);
        sink.begin();
        if let Err(e) = policy.call_rule(command, &mut perspective, sink, CommandRecall::None) {
            sink.rollback();
            // We don't need to revert perspective since we just drop it.
            return Err(e.into());
        }
        perspective.add_command(command)?;

        let (_, storage) = provider.new_storage(perspective)?;

        // Wait to commit until we are absolutely sure we've initialized.
        sink.commit();

        Ok(storage)
    }
}

/// Run the braid algorithm and evaluate the sequence to create a braided fact index.
fn make_braid_segment<S: Storage, E: Engine>(
    storage: &mut S,
    left: Location,
    right: Location,
    sink: &mut impl Sink<E::Effect>,
    policy: &E::Policy,
) -> Result<(S::FactIndex, (Location, usize)), ClientError> {
    let order = super::braid(storage, left, right)?;
    let last_common_ancestor = super::last_common_ancestor(storage, left, right)?;

    let (&first, rest) = order.split_first().assume("braid is non-empty")?;

    let mut braid_perspective = storage.get_fact_perspective(first)?;

    sink.begin();

    for &location in rest {
        let segment = storage.get_segment(location)?;
        let command = segment
            .get_command(location)
            .assume("braid only contains existing commands")?;

        let result = policy.call_rule(
            &command,
            &mut braid_perspective,
            sink,
            CommandRecall::OnCheck,
        );

        // If the command failed in an uncontrolled way, rollback
        if let Err(e) = result {
            if e != EngineError::Check {
                sink.rollback();
                return Err(e.into());
            }
        }
    }

    let braid = storage.write_facts(braid_perspective)?;

    sink.commit();

    Ok((braid, last_common_ancestor))
}

/// Select the policy from two locations with the greatest serial value.
fn choose_policy<'a, E: Engine>(
    storage: &impl Storage,
    engine: &'a E,
    left: Location,
    right: Location,
) -> Result<(&'a E::Policy, PolicyId), ClientError> {
    Ok(core::cmp::max_by_key(
        get_policy(storage, engine, left)?,
        get_policy(storage, engine, right)?,
        |(p, _)| p.serial(),
    ))
}

fn get_policy<'a, E: Engine>(
    storage: &impl Storage,
    engine: &'a E,
    location: Location,
) -> Result<(&'a E::Policy, PolicyId), ClientError> {
    let segment = storage.get_segment(location)?;
    let policy_id = segment.policy();
    let policy = engine.get_policy(policy_id)?;
    Ok((policy, policy_id))
}

#[cfg(test)]
mod test {
    use aranya_buggy::Bug;
    use test_log::test;

    use super::*;
    use crate::{memory::MemStorageProvider, ClientState, Keys, MergeIds, Priority};

    struct SeqEngine;

    /// [`SeqPolicy`] is a very simple policy which appends the id of each
    /// command to a fact named `b"seq"`. At each point in the graph, the value
    /// of this fact should be equal to the ids in braid order of all facts up
    /// to that point.
    struct SeqPolicy;

    struct SeqCommand {
        id: CommandId,
        prior: Prior<Address>,
        data: Box<str>,
        max_cut: usize,
    }

    impl Engine for SeqEngine {
        type Policy = SeqPolicy;
        type Effect = ();

        fn add_policy(&mut self, _policy: &[u8]) -> Result<PolicyId, EngineError> {
            Ok(PolicyId::new(0))
        }

        fn get_policy(&self, _id: PolicyId) -> Result<&Self::Policy, EngineError> {
            Ok(&SeqPolicy)
        }
    }

    impl Policy for SeqPolicy {
        type Action<'a> = &'a str;
        type Effect = ();
        type Command<'a> = SeqCommand;

        fn serial(&self) -> u32 {
            0
        }

        fn call_rule(
            &self,
            command: &impl Command,
            facts: &mut impl crate::FactPerspective,
            _sink: &mut impl Sink<Self::Effect>,
            _recall: CommandRecall,
        ) -> Result<(), EngineError> {
            assert!(
                !matches!(command.parent(), Prior::Merge { .. }),
                "merges shouldn't be evaluated"
            );

            // For init and basic commands, append the id to the seq fact.
            let data = command.bytes();
            if let Some(seq) = facts.query("seq", &Keys::default())?.as_deref() {
                facts.insert(
                    "seq".into(),
                    Keys::default(),
                    [seq, b":", data].concat().into(),
                );
            } else {
                facts.insert("seq".into(), Keys::default(), data.into());
            };
            Ok(())
        }

        fn call_action(
            &self,
            _action: Self::Action<'_>,
            _facts: &mut impl Perspective,
            _sink: &mut impl Sink<Self::Effect>,
        ) -> Result<(), EngineError> {
            unimplemented!()
        }

        fn merge<'a>(
            &self,
            _target: &'a mut [u8],
            ids: MergeIds,
        ) -> Result<Self::Command<'a>, EngineError> {
            let (left, right): (Address, Address) = ids.into();
            let mut buf = [0u8; 128];
            buf[..64].copy_from_slice(left.id.as_bytes());
            buf[64..].copy_from_slice(right.id.as_bytes());
            let id = CommandId::hash_for_testing_only(&buf);

            Ok(SeqCommand::new(
                id,
                Prior::Merge(left, right),
                left.max_cut
                    .max(right.max_cut)
                    .checked_add(1)
                    .assume("must not overflow")?,
            ))
        }
    }

    impl SeqCommand {
        fn new(id: CommandId, prior: Prior<Address>, max_cut: usize) -> Self {
            let data = id.short_b58().into_boxed_str();
            Self {
                id,
                prior,
                data,
                max_cut,
            }
        }
    }

    impl Command for SeqCommand {
        fn priority(&self) -> Priority {
            match self.prior {
                Prior::None => Priority::Init,
                Prior::Single(_) => {
                    // Use the last byte of the ID as priority, just so we can
                    // properly see the effects of braiding
                    let id = self.id.as_bytes();
                    let priority = u32::from(*id.last().unwrap());
                    Priority::Basic(priority)
                }
                Prior::Merge(_, _) => Priority::Merge,
            }
        }

        fn id(&self) -> CommandId {
            self.id
        }

        fn parent(&self) -> Prior<Address> {
            self.prior
        }

        fn policy(&self) -> Option<&[u8]> {
            // We don't actually need any policy bytes, but the
            // transaction/storage requires it on init commands.
            match self.prior {
                Prior::None { .. } => Some(b""),
                _ => None,
            }
        }

        fn bytes(&self) -> &[u8] {
            self.data.as_bytes()
        }

        fn max_cut(&self) -> Result<usize, Bug> {
            Ok(self.max_cut)
        }
    }

    struct NullSink;
    impl<E> Sink<E> for NullSink {
        fn begin(&mut self) {}
        fn consume(&mut self, _: E) {}
        fn rollback(&mut self) {}
        fn commit(&mut self) {}
    }

    /// [`GraphBuilder`] and the associated macro [`graph`] provide an easy way
    /// to create a graph with a specific structure.
    struct GraphBuilder<SP: StorageProvider> {
        client: ClientState<SeqEngine, SP>,
        trx: Transaction<SP, SeqEngine>,
    }

    impl<SP: StorageProvider> GraphBuilder<SP> {
        pub fn init(mut client: ClientState<SeqEngine, SP>, ids: &[CommandId]) -> Self {
            let mut trx = Transaction::new(GraphId::from(ids[0].into_id()));
            let mut prior: Prior<Address> = Prior::None;
            for &id in ids {
                let cmd = SeqCommand::new(id, prior, 0);
                trx.add_commands(
                    &[cmd],
                    &mut client.provider,
                    &mut client.engine,
                    &mut NullSink,
                    &mut PeerCache::new(),
                )
                .unwrap();
                prior = Prior::Single(Address { id, max_cut: 0 });
            }
            Self { client, trx }
        }

        pub fn line(&mut self, mut prev: Address, ids: &[CommandId]) {
            for &id in ids {
                let max_cut = prev.max_cut.checked_add(1).unwrap();
                let cmd = SeqCommand::new(id, Prior::Single(prev), max_cut);
                self.trx
                    .add_commands(
                        &[cmd],
                        &mut self.client.provider,
                        &mut self.client.engine,
                        &mut NullSink,
                        &mut PeerCache::new(),
                    )
                    .unwrap();
                prev = Address { id, max_cut };
            }
        }

        pub fn merge(&mut self, (left, right): (Address, Address), ids: &[CommandId]) {
            let prior = Prior::Merge(left, right);
            let mergecmd = SeqCommand::new(ids[0], prior, prior.next_max_cut().unwrap());
            let mut prev = Address {
                id: mergecmd.id,
                max_cut: mergecmd.max_cut,
            };
            self.trx
                .add_commands(
                    &[mergecmd],
                    &mut self.client.provider,
                    &mut self.client.engine,
                    &mut NullSink,
                    &mut PeerCache::new(),
                )
                .unwrap();
            for &id in &ids[1..] {
                let cmd = SeqCommand::new(
                    id,
                    Prior::Single(prev),
                    prev.max_cut.checked_add(1).expect("must not overflow"),
                );
                prev = Address {
                    id: cmd.id,
                    max_cut: cmd.max_cut,
                };
                self.trx
                    .add_commands(
                        &[cmd],
                        &mut self.client.provider,
                        &mut self.client.engine,
                        &mut NullSink,
                        &mut PeerCache::new(),
                    )
                    .unwrap();
            }
        }

        pub fn flush(&mut self) {
            if let Some(p) = Option::take(&mut self.trx.perspective) {
                self.trx.phead = None;
                let seg = self
                    .client
                    .provider
                    .get_storage(self.trx.storage_id)
                    .unwrap()
                    .write(p)
                    .unwrap();
                let head = seg.head().unwrap();
                self.trx.heads.insert(
                    head.address().expect("address must exist"),
                    seg.head_location(),
                );
            }
        }

        pub fn commit(&mut self) {
            self.trx
                .commit(
                    &mut self.client.provider,
                    &mut self.client.engine,
                    &mut NullSink,
                )
                .unwrap();
        }
    }

    fn mkid(x: &str) -> CommandId {
        x.parse().unwrap()
    }

    /// See tests for usage.
    macro_rules! graph {
        ( $client:expr ; $init:literal $($inits:literal )* ; $($rest:tt)*) => {{
            let mut gb = GraphBuilder::init($client, &[mkid($init), $(mkid($inits)),*]);
            graph!(@ gb, $($rest)*);
            gb
        }};
        (@ $gb:ident, $prev:literal $prev_max_cut:literal < $($id:literal)+; $($rest:tt)*) => {
            $gb.line(Address {id: mkid($prev), max_cut: $prev_max_cut}, &[$(mkid($id)),+]);
            graph!(@ $gb, $($rest)*);
        };
        (@ $gb:ident, $l:literal $l_max_cut:literal $r:literal $r_max_cut:literal < $($id:literal)+; $($rest:tt)*) => {
            $gb.merge((Address {id: mkid($l), max_cut: $l_max_cut}, Address {id: mkid($r), max_cut: $r_max_cut}), &[$(mkid($id)),+]);
            graph!(@ $gb, $($rest)*);
        };
        (@ $gb:ident, commit; $($rest:tt)*) => {
            $gb.commit();
            graph!(@ $gb, $($rest)*);
        };
        (@ $gb:ident, ) => {
            $gb.flush();
        };
    }

    fn lookup(storage: &impl Storage, name: &str) -> Option<Box<[u8]>> {
        use crate::Query;
        let head = storage.get_head().unwrap();
        let p = storage.get_fact_perspective(head).unwrap();
        p.query(name, &Keys::default()).unwrap()
    }

    #[test]
    fn test_simple() -> Result<(), StorageError> {
        let mut gb = graph! {
            ClientState::new(SeqEngine, MemStorageProvider::new());
            "a";
            "a" 0 < "b";
            "a" 0 < "c";
            "b" 1 "c" 1 < "ma";
            "b" 1 < "d";
            "ma" 2 "d" 2 < "mb";
            commit;
        };
        let g = gb
            .client
            .provider
            .get_storage("a".parse().unwrap())
            .unwrap();

        #[cfg(feature = "graphviz")]
        crate::storage::memory::graphviz::dot(g, "simple");

        assert_eq!(g.get_head().unwrap(), Location::new(5, 0));

        let seq = lookup(g, "seq").unwrap();
        let seq = std::str::from_utf8(&seq).unwrap();
        assert_eq!(seq, "a:b:d:c");

        Ok(())
    }

    #[test]
    fn test_complex() -> Result<(), StorageError> {
        let mut gb = graph! {
            ClientState::new(SeqEngine, MemStorageProvider::new());
            "a";
            "a" 0 < "1" "2" "3";
            "3" 3 < "4" "6" "7";
            "3" 3 < "5" "8";
            "6" 5 "8" 5 < "9" "aa"; commit;
            "7" 6 < "a1" "a2";
            "aa" 7 "a2" 8 < "a3";
            "a3" 9 < "a6" "a4";
            "a3" 9 < "a7" "a5";
            "a4" 11 "a5" 11 < "a8";
            "9" 6 < "42" "43";
            "42" 7 < "45" "46";
            "45" 8 < "47" "48";
            commit;
        };

        let g = gb
            .client
            .provider
            .get_storage("a".parse().unwrap())
            .unwrap();

        #[cfg(feature = "graphviz")]
        crate::storage::memory::graphviz::dot(g, "complex");

        assert_eq!(g.get_head().unwrap(), Location::new(15, 0));

        let seq = lookup(g, "seq").unwrap();
        let seq = std::str::from_utf8(&seq).unwrap();
        assert_eq!(
            seq,
            "a:1:2:3:5:8:4:6:42:45:47:48:46:43:aa:7:a1:a2:a7:a6:a5:a4"
        );

        Ok(())
    }

    #[test]
    fn test_duplicates() {
        let mut gb = graph! {
            ClientState::new(SeqEngine, MemStorageProvider::new());
            "a";
            "a" 0 < "b" "c";
            "a" 0 < "b";
            "b" 1 < "c";
            "c" 2 < "d";
            commit;
            "a" 0 < "b";
            "b" 1 < "c";
            "d" 3 < "e";
            commit;
        };

        let g = gb
            .client
            .provider
            .get_storage("a".parse().unwrap())
            .unwrap();

        #[cfg(feature = "graphviz")]
        crate::storage::memory::graphviz::dot(g, "duplicates");

        assert_eq!(g.get_head().unwrap(), Location::new(2, 0));

        let seq = lookup(g, "seq").unwrap();
        let seq = std::str::from_utf8(&seq).unwrap();
        assert_eq!(seq, "a:b:c:d:e");
    }

    #[test]
    fn test_mid_braid_1() {
        let mut gb = graph! {
            ClientState::new(SeqEngine, MemStorageProvider::new());
            "a";
            commit;
            "a" 0 < "b" "c" "d" "e" "f" "g";
            "d" 3 < "h" "i" "j";
            commit;
        };

        let g = gb
            .client
            .provider
            .get_storage("a".parse().unwrap())
            .unwrap();

        #[cfg(feature = "graphviz")]
        crate::storage::memory::graphviz::dot(g, "mid_braid_1");

        assert_eq!(g.get_head().unwrap(), Location::new(3, 0));

        let seq = lookup(g, "seq").unwrap();
        let seq = std::str::from_utf8(&seq).unwrap();
        assert_eq!(seq, "a:b:c:d:h:i:j:e:f:g");
    }

    #[test]
    fn test_mid_braid_2() {
        let mut gb = graph! {
            ClientState::new(SeqEngine, MemStorageProvider::new());
            "a";
            commit;
            "a" 0 < "b" "c" "d" "h" "i" "j";
            "d" 3 < "e" "f" "g";
            commit;
        };

        let g = gb
            .client
            .provider
            .get_storage("a".parse().unwrap())
            .unwrap();

        #[cfg(feature = "graphviz")]
        crate::storage::memory::graphviz::dot(g, "mid_braid_2");

        assert_eq!(g.get_head().unwrap(), Location::new(3, 0));

        let seq = lookup(g, "seq").unwrap();
        let seq = std::str::from_utf8(&seq).unwrap();
        assert_eq!(seq, "a:b:c:d:h:i:j:e:f:g");
    }
}