sedimentree_core 0.6.0

Sedimentree: a hash-linked CRDT storage structure with fragments, commits, and content-addressed blobs
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
//! Internal commit DAG representation for Sedimentree operations.
//!
//! This module provides an adjacency representation of a commit DAG,
//! used internally for operations like [`Sedimentree::minimize`] and [`Sedimentree::heads`].
//! It is not part of the public API.
//!
//! [`Sedimentree::minimize`]: super::Sedimentree::minimize
//! [`Sedimentree::heads`]: super::Sedimentree::heads

use alloc::{vec, vec::Vec};

use crate::{
    collections::{Map, Set},
    crypto::digest::Digest,
    depth::{DepthMetric, MAX_STRATA_DEPTH},
    fragment::Fragment,
    loose_commit::LooseCommit,
};

// An adjacency list based representation of a commit DAG except that we use indexes into the
// `nodes` and `edges` vectors instead of pointers in order to please the borrow checker.
#[derive(Debug, Clone)]
pub(crate) struct CommitDag {
    nodes: Vec<Node>,
    node_map: Map<Digest<LooseCommit>, NodeIdx>,
    edges: Vec<Edge>,
}

#[derive(Debug, Clone)]
struct Node {
    hash: Digest<LooseCommit>,
    parents: Option<EdgeIdx>,
    children: Option<EdgeIdx>,
}

#[derive(Debug, Clone)]
struct Edge {
    source: NodeIdx,
    next: Option<EdgeIdx>,
}

#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
struct NodeIdx(usize);

#[derive(Debug, Clone, Copy)]
struct EdgeIdx(usize);

impl CommitDag {
    pub(crate) fn from_commits<'a, I: Iterator<Item = &'a LooseCommit> + Clone>(
        commits: I,
    ) -> Self {
        let nodes = commits
            .clone()
            .map(|c| Node {
                hash: Digest::hash(c),
                parents: None,
                children: None,
            })
            .collect::<Vec<_>>();
        let node_map = nodes
            .iter()
            .enumerate()
            .map(|(idx, node)| (node.hash, NodeIdx(idx)))
            .collect::<Map<_, _>>();

        let mut dag = CommitDag {
            nodes,
            node_map,
            edges: Vec::new(),
        };

        for commit in commits {
            #[allow(clippy::expect_used)]
            let child_idx = *dag
                .node_map
                .get(&Digest::hash(commit))
                .expect("commit digest not in node_map");

            for parent in commit.parents() {
                if let Some(parent) = dag.node_map.get(parent) {
                    dag.add_edge(*parent, child_idx);
                }
            }
        }
        dag
    }

    fn add_edge(&mut self, source: NodeIdx, target: NodeIdx) {
        // Add an edge in the child node
        let new_edge_idx = EdgeIdx(self.edges.len());
        let new_edge = Edge { source, next: None };
        self.edges.push(new_edge);

        #[allow(clippy::expect_used)]
        let target_node = self
            .nodes
            .get_mut(target.0)
            .expect("NodeId not in self.nodes");

        if let Some(edge_idx) = target_node.parents {
            #[allow(clippy::expect_used)]
            let mut edge = self
                .edges
                .get_mut(edge_idx.0)
                .expect("NodeId not in self.nodes");

            #[allow(clippy::expect_used)]
            while let Some(next) = edge.next {
                edge = self
                    .edges
                    .get_mut(next.0)
                    .expect("NodeId not in self.nodes");
            }
            edge.next = Some(new_edge_idx);
        } else {
            target_node.parents = Some(new_edge_idx);
        }

        // Now add an edge in the parent node
        let new_edge_idx = EdgeIdx(self.edges.len());
        let new_edge = Edge { source, next: None };
        self.edges.push(new_edge);

        #[allow(clippy::expect_used)]
        let source_node = self
            .nodes
            .get_mut(source.0)
            .expect("NodeId not in self.nodes");
        if let Some(edge_idx) = source_node.children {
            #[allow(clippy::expect_used)]
            let mut edge = self
                .edges
                .get_mut(edge_idx.0)
                .expect("NodeId not in self.nodes");

            #[allow(clippy::expect_used)]
            while let Some(next) = edge.next {
                edge = self
                    .edges
                    .get_mut(next.0)
                    .expect("next NodeId not in self.nodes");
            }
            edge.next = Some(new_edge_idx);
        } else {
            source_node.children = Some(new_edge_idx);
        }
    }

    pub(crate) fn simplify<S: DepthMetric>(&self, fragments: &[Fragment], strategy: &S) -> Self {
        // The work here is to identify which parts of a commit DAG can be
        // discarded based on the strata we have. This is a little bit fiddly.
        // Imagine this graph:
        //
        //        ┌─┐
        //        │A│
        //   ┌────┴─┴────┐
        //   │           │
        //   │           │
        //  ┌▼┐         ┌▼┐          ┌─┐
        //  │B│         │C│          │D│
        //  └┬┘         └┬┘          └┬┘
        //   │           │            │
        //   │           └─────┬──────┘
        //  ┌▼┐                │
        //  │I│               ┌▼┐
        //  └─┘               │E│
        //                    └┬┘
        //                     │
        //                     │
        //                    ┌▼┐
        //               ┌────┤F├────┐
        //               │    └─┘    │
        //               │           │
        //               │           │
        //               │           │
        //              ┌▼┐         ┌▼┐
        //              │G│         │H│
        //              └─┘         └─┘
        //
        // Let's say we have a checkpoint commit at F, D, I, and A and we have
        // strata containing A and F, which commits can we discard? Well, we
        // can't discard G or H because they are not in any blocks. We can't
        // discard I or B because they are not in any blocks that we have strata
        // for.
        //
        // The invariant we must maintain is that we always have a path from
        // some commit back to the last checkpoint commit (a commit with two
        // leading zeros). How do we identify the commits that can be discarded?
        //
        // If we start from the heads of the graph then we can walk up the graph
        // in a (reverse) depth first topological sort. First, this allows us to
        // easily identify which commits are not in a block (a range of commits
        // bounded by checkpoint commits) - it's all the commits which we
        // encounter in this traversal before we have ever encountered a
        // checkpoint commit. This same technique also allows us to identify all
        // the blocks in the graph and which commits are in each block (note
        // that a commit can be in multiple blocks).
        //
        // Now, which commits can be discarded? It is any commit which is only
        // in a block which is covered by at least one stratum in the tree.

        // Identify blocks by their end hash and store a mapping from commit hash to block end hash
        let mut commits_to_blocks = Map::new();
        let mut blockless_commits = Set::new();

        let mut tips = self.tips().collect::<Vec<_>>();
        tips.sort_by_key(|idx| {
            #[allow(clippy::expect_used)]
            self.nodes
                .get(idx.0)
                .expect("NodeId not in self.nodes")
                .hash
        });

        for tip in tips {
            let mut block: Option<(Digest<LooseCommit>, Vec<Digest<LooseCommit>>)> = None;
            for hash in self.reverse_topo(tip) {
                let depth = strategy.to_depth(hash);
                if depth >= MAX_STRATA_DEPTH {
                    // We're in a block and we just found a checkpoint, this must be the start hash
                    // for the block we're in. Flush the current block and start a new one.
                    if let Some((block, commits)) = block.take() {
                        for commit in commits {
                            blockless_commits.remove(&commit);
                            commits_to_blocks
                                .entry(commit)
                                .or_insert_with(Vec::new)
                                .push(block);
                        }
                    }
                    block = Some((hash, vec![hash]));
                }
                if let Some((_, commits)) = &mut block {
                    if depth < MAX_STRATA_DEPTH {
                        commits.push(hash);
                    }
                } else if !commits_to_blocks.contains_key(&hash) && depth < MAX_STRATA_DEPTH {
                    blockless_commits.insert(hash);
                }
            }
            // We never found a start hash for this block, so the start must be the root hash
            if let Some((end, commits)) = block.take() {
                commits_to_blocks
                    .entry(end)
                    .or_insert_with(Vec::new)
                    .push(end);
                for commit in commits {
                    commits_to_blocks
                        .entry(commit)
                        .or_insert_with(Vec::new)
                        .push(end);
                }
            }
        }

        // The commits we can discard are the ones where the blocks they are in are all supported
        let remaining_commits = commits_to_blocks
            .into_iter()
            .filter_map(|(commit, blocks)| {
                if blocks
                    .iter()
                    .all(|&b| fragments.iter().any(|s| s.supports_block(b)))
                {
                    None
                } else {
                    Some(commit)
                }
            })
            .chain(blockless_commits)
            .collect::<Vec<_>>();

        let nodes = remaining_commits
            .iter()
            .map(|&c| Node {
                hash: c,
                parents: None,
                children: None,
            })
            .collect::<Vec<_>>();
        let node_map = nodes
            .iter()
            .enumerate()
            .map(|(idx, node)| (node.hash, NodeIdx(idx)))
            .collect::<Map<_, _>>();

        let mut dag = CommitDag {
            nodes,
            node_map,
            edges: Vec::new(),
        };

        for (child_idx, commit) in remaining_commits.into_iter().enumerate() {
            for parent in self.parents_of_hash(commit) {
                if let Some(parent) = dag.node_map.get(&parent) {
                    dag.add_edge(*parent, NodeIdx(child_idx));
                }
            }
        }
        dag
    }

    fn tips(&self) -> impl Iterator<Item = NodeIdx> + '_ {
        self.nodes.iter().enumerate().filter_map(|(idx, node)| {
            if node.children.is_none() {
                Some(NodeIdx(idx))
            } else {
                None
            }
        })
    }

    fn parents(&self, node: NodeIdx) -> impl Iterator<Item = NodeIdx> + '_ {
        Parents::new(self, node)
    }

    fn parents_of_hash(
        &self,
        hash: Digest<LooseCommit>,
    ) -> impl Iterator<Item = Digest<LooseCommit>> + '_ {
        self.node_map
            .get(&hash)
            .map(|idx| {
                self.parents(*idx).map(|i| {
                    #[allow(clippy::expect_used)]
                    self.nodes
                        .get(i.0)
                        .expect("nodeId wasn't in self.nodes")
                        .hash
                })
            })
            .into_iter()
            .flatten()
    }

    fn reverse_topo(&self, start: NodeIdx) -> impl Iterator<Item = Digest<LooseCommit>> + '_ {
        ReverseTopo::new(self, start)
    }

    pub(crate) fn contains_commit(&self, commit: &Digest<LooseCommit>) -> bool {
        self.node_map.contains_key(commit)
    }

    pub(crate) fn heads(&self) -> impl Iterator<Item = Digest<LooseCommit>> + '_ {
        self.nodes.iter().filter_map(|node| {
            if node.children.is_none() {
                Some(node.hash)
            } else {
                None
            }
        })
    }

    #[cfg(test)]
    fn commit_hashes(&self) -> impl Iterator<Item = Digest<LooseCommit>> + '_ {
        self.nodes.iter().map(|node| node.hash)
    }
}

struct ReverseTopo<'a> {
    dag: &'a CommitDag,
    stack: Vec<NodeIdx>,
    visited: Set<NodeIdx>,
}

impl<'a> ReverseTopo<'a> {
    fn new(dag: &'a CommitDag, start: NodeIdx) -> Self {
        let stack = vec![start];
        ReverseTopo {
            dag,
            stack,
            visited: Set::new(),
        }
    }
}

impl Iterator for ReverseTopo<'_> {
    type Item = Digest<LooseCommit>;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(node) = self.stack.pop() {
            if self.visited.contains(&node) {
                continue;
            }
            self.visited.insert(node);
            let mut parents = self.dag.parents(node).collect::<Vec<_>>();
            parents.sort_by_key(|p| {
                #[allow(clippy::expect_used)]
                self.dag.nodes.get(p.0).expect("node is not in DAG").hash
            });
            self.stack.extend(parents);
            return Some(self.dag.nodes.get(node.0)?.hash);
        }
        None
    }
}

struct Parents<'a> {
    dag: &'a CommitDag,
    edge: Option<EdgeIdx>,
}

impl<'a> Parents<'a> {
    fn new(dag: &'a CommitDag, node: NodeIdx) -> Self {
        Parents {
            dag,
            edge: dag.nodes.get(node.0).and_then(|x| x.parents),
        }
    }
}

impl Iterator for Parents<'_> {
    type Item = NodeIdx;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(edge) = self.edge {
            let edge: &Edge = self.dag.edges.get(edge.0)?;
            self.edge = edge.next;
            Some(edge.source)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::collections::BTreeSet;

    use super::CommitDag;
    use crate::{
        blob::{Blob, BlobMeta},
        collections::{Map, Set},
        crypto::digest::Digest,
        depth::{Depth, DepthMetric},
        id::SedimentreeId,
        loose_commit::LooseCommit,
    };

    fn make_sedimentree_id(seed: u8) -> SedimentreeId {
        SedimentreeId::new([seed; 32])
    }

    fn make_commit(
        sedimentree_id: SedimentreeId,
        seed: u8,
        parents: BTreeSet<Digest<LooseCommit>>,
    ) -> LooseCommit {
        let blob = Blob::from(&[seed][..]);
        let blob_meta = BlobMeta::new(&blob);
        LooseCommit::new(sedimentree_id, parents, blob_meta)
    }

    /// A mock depth metric that returns predetermined depths for specific digests.
    struct MockDepthMetric {
        depths: Map<Digest<LooseCommit>, Depth>,
    }

    impl MockDepthMetric {
        fn new() -> Self {
            Self { depths: Map::new() }
        }

        fn set_depth(&mut self, digest: Digest<LooseCommit>, depth: Depth) {
            self.depths.insert(digest, depth);
        }
    }

    impl DepthMetric for MockDepthMetric {
        fn to_depth(&self, digest: Digest<LooseCommit>) -> Depth {
            self.depths.get(&digest).copied().unwrap_or(Depth(0))
        }
    }

    /// No fragments: all commits with depth >= threshold remain as block boundaries.
    #[test]
    fn simplify_block_boundaries_without_fragments() {
        let sedimentree_id = make_sedimentree_id(1);

        // Create commits: b is root, a has b as parent
        let b = make_commit(sedimentree_id, 1, BTreeSet::new());
        let b_hash = Digest::hash(&b);
        let a = make_commit(sedimentree_id, 2, BTreeSet::from([b_hash]));
        let a_hash = Digest::hash(&a);

        // Set up mock depths: a=2, b=0
        let mut depth_metric = MockDepthMetric::new();
        depth_metric.set_depth(a_hash, Depth(2));
        depth_metric.set_depth(b_hash, Depth(0));

        let dag = CommitDag::from_commits([&a, &b].into_iter());

        let simplified = dag
            .simplify(&[], &depth_metric)
            .commit_hashes()
            .collect::<Set<_>>();

        // With no fragments, simplify keeps block boundaries + heads
        // Both a and b should remain (a is head, b would be pruned but there's no fragment)
        assert_eq!(simplified, Set::from([a_hash, b_hash]));
    }

    /// Two consecutive block boundary commits (both depth >= threshold).
    #[test]
    fn simplify_consecutive_block_boundary_commits_without_fragments() {
        let sedimentree_id = make_sedimentree_id(1);

        // Create commits: b is root, a has b as parent
        let b = make_commit(sedimentree_id, 1, BTreeSet::new());
        let b_hash = Digest::hash(&b);
        let a = make_commit(sedimentree_id, 2, BTreeSet::from([b_hash]));
        let a_hash = Digest::hash(&a);

        // Set up mock depths: a=2, b=2
        let mut depth_metric = MockDepthMetric::new();
        depth_metric.set_depth(a_hash, Depth(2));
        depth_metric.set_depth(b_hash, Depth(2));

        let dag = CommitDag::from_commits([&a, &b].into_iter());

        let simplified = dag
            .simplify(&[], &depth_metric)
            .commit_hashes()
            .collect::<Set<_>>();

        // Both are block boundaries, both remain
        assert_eq!(simplified, Set::from([a_hash, b_hash]));
    }

    #[test]
    fn test_parents() {
        let sedimentree_id = make_sedimentree_id(1);

        // Create a DAG: a and b are roots, c has both as parents, d has c as parent
        let a = make_commit(sedimentree_id, 1, BTreeSet::new());
        let a_hash = Digest::hash(&a);
        let b = make_commit(sedimentree_id, 2, BTreeSet::new());
        let b_hash = Digest::hash(&b);
        let c = make_commit(sedimentree_id, 3, BTreeSet::from([a_hash, b_hash]));
        let c_hash = Digest::hash(&c);
        let d = make_commit(sedimentree_id, 4, BTreeSet::from([c_hash]));

        let dag = CommitDag::from_commits([&a, &b, &c, &d].into_iter());

        assert_eq!(
            dag.parents_of_hash(c_hash).collect::<Set<_>>(),
            Set::from([a_hash, b_hash])
        );
    }
}