Skip to main content

ouisync/protocol/
root_node.rs

1use std::cmp::Ordering;
2
3use super::{NodeState, Proof, Summary};
4use crate::{crypto::sign::PublicKey, ord};
5
6pub(crate) type SnapshotId = u32;
7
8#[derive(Clone, Eq, PartialEq, Debug)]
9pub struct RootNode {
10    pub snapshot_id: SnapshotId,
11    pub proof: Proof,
12    pub summary: Summary,
13}
14
15/// Kind of root node.
16#[derive(Eq, PartialEq, Debug)]
17pub(crate) enum RootNodeKind {
18    /// Published nodes have their version vector strictly greater than any previous node
19    /// in the same branch. Only published nodes are announced to other replicas.
20    Published,
21    /// Draft nodes have their version vector equal to that of the previous node in the same
22    /// branch. Draft nodes are neither announced to nor accepted from other replicas.
23    Draft,
24}
25
26/// What kind of nodes to load and/or create.
27pub(crate) enum RootNodeFilter {
28    /// Only published nodes.
29    Published,
30    /// Published and draft nodes.
31    Any,
32}
33
34/// Sort the nodes into two groups: those that are up-to-date and should be kept and those that are
35/// outdated and should be pruned.
36///
37/// The decision into which group a node belongs to depends on its version vector, state and whether
38/// the node belongs to the local branch.
39///
40/// Note that nodes from the local branch can end up in the outdated group (see `compare_for_prune`
41/// for details). It's the responsibility of the caller to never prune the local branch.
42pub(crate) fn prune(
43    nodes: Vec<RootNode>,
44    local_writer_id: &PublicKey,
45) -> (Vec<RootNode>, Vec<RootNode>) {
46    ord::partial_partition_by(nodes, |a, b| compare_for_prune(a, b, local_writer_id))
47}
48
49// Compare the nodes for the purpose of pruning according to their version vectors, whether they are
50// local and whether they are approved. This is a product order of these three properties:
51//
52// 1. Node compares greater than the other one if its version vector happens-after or is equal to
53//    the other one's, it's local or the other one isn't, and it's approved or the other one isn't,
54//    and at least one of these is strict (and vice versa for less).
55//
56// 2. If all three properties are the same, break ties by comparing by writer id (arbitrary, but
57//    consistent across replicas), then by snapshot id (assigned sequentially, so within the same
58//    branch the greater one is the newer one).
59//
60// 3. Otherwise they are uncomparable.
61//
62// Additionally, two non-approved nodes from different branches are always uncomparable, regardless
63// of their version vectors. This is because a non-approved node might never become approved (e.g.,
64// due to the peer disconnecting before we receive all its nodes) so it can't be considered to
65// supersede a node from another branch. As a consequence, a node is pruned only if there is an
66// approved node greater than it, so when a whole branch is pruned, all its snapshots (including the
67// older approved ones) are superseded by an approved node.
68//
69// Note this means an older approved node is kept when its branch has a newer, non-approved one. Both
70// are pruned only when there is an approved node that is newer than both of them, either in the
71// same branch or in a different one.
72//
73// Only approved nodes from the local branch are considered local. Local snapshots are always created
74// fully in a single db transaction and the quota is not applied to the local branch, so they are
75// normally always approved. A non-approved node with the local writer id can still exist though, for
76// example when it's received from another replica that uses the same writer id. Such node is
77// treated as non-local.
78fn compare_for_prune(a: &RootNode, b: &RootNode, local_id: &PublicKey) -> Option<Ordering> {
79    fn is_approved(node: &RootNode) -> bool {
80        node.summary.state == NodeState::Approved
81    }
82
83    fn is_local(node: &RootNode, local_id: &PublicKey) -> bool {
84        node.proof.writer_id == *local_id && is_approved(node)
85    }
86
87    if !is_approved(a) && !is_approved(b) && a.proof.writer_id != b.proof.writer_id {
88        return None;
89    }
90
91    let orderings = [
92        a.proof
93            .version_vector
94            .partial_cmp(&b.proof.version_vector)?,
95        is_local(a, local_id).cmp(&is_local(b, local_id)),
96        is_approved(a).cmp(&is_approved(b)),
97    ];
98
99    match (
100        orderings.contains(&Ordering::Greater),
101        orderings.contains(&Ordering::Less),
102    ) {
103        (true, true) => None,
104        (true, false) => Some(Ordering::Greater),
105        (false, true) => Some(Ordering::Less),
106        (false, false) => Some(
107            a.proof
108                .writer_id
109                .cmp(&b.proof.writer_id)
110                .then_with(|| a.snapshot_id.cmp(&b.snapshot_id)),
111        ),
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use std::{array, sync::LazyLock};
118
119    use proptest::collection::vec;
120    use test_strategy::proptest;
121
122    use super::*;
123    use crate::{
124        VersionVector,
125        crypto::sign::Keypair,
126        protocol::{MultiBlockPresence, NodeState},
127    };
128
129    #[test]
130    fn prune_sanity_check() {
131        let l_id = PublicKey::random();
132        let a_id = PublicKey::random();
133        let b_id = PublicKey::random();
134
135        let a = make_root_node(a_id, VersionVector::first(a_id), NodeState::Approved);
136        let b = make_root_node(b_id, VersionVector::first(b_id), NodeState::Approved);
137
138        assert_eq!(
139            prune(vec![a.clone(), b.clone()], &l_id),
140            (vec![a, b], vec![])
141        );
142    }
143
144    #[test]
145    fn prune_different_branches_keeps_approved_when_newer_is_not_approved() {
146        let l_id = PublicKey::random();
147        let a_id = PublicKey::random();
148        let b_id = PublicKey::random();
149
150        let vv0 = VersionVector::first(a_id);
151        let vv1 = vv0.clone().incremented(b_id);
152
153        let a = make_root_node(a_id, vv0, NodeState::Approved);
154        let b = make_root_node(b_id, vv1, NodeState::Incomplete);
155
156        assert_eq!(
157            prune(vec![a.clone(), b.clone()], &l_id),
158            (vec![a.clone(), b.clone()], vec![])
159        );
160        assert_eq!(
161            prune(vec![b.clone(), a.clone()], &l_id),
162            (vec![b, a], vec![])
163        );
164    }
165
166    #[test]
167    fn prune_same_branch_keeps_older_approved_when_newer_is_not_approved() {
168        let l_id = PublicKey::random();
169        let r_id = PublicKey::random();
170
171        let vv0 = VersionVector::first(r_id);
172        let vv1 = vv0.clone().incremented(r_id);
173
174        let a = make_root_node(r_id, vv0, NodeState::Approved);
175        let b = make_root_node(r_id, vv1, NodeState::Incomplete);
176
177        assert_eq!(
178            prune(vec![a.clone(), b.clone()], &l_id),
179            (vec![a.clone(), b.clone()], vec![])
180        );
181        assert_eq!(
182            prune(vec![b.clone(), a.clone()], &l_id),
183            (vec![b, a], vec![])
184        );
185    }
186
187    #[test]
188    fn prune_same_branch_keeps_newer_when_at_least_as_approved() {
189        let l_id = PublicKey::random();
190        let r_id = PublicKey::random();
191
192        let vv0 = VersionVector::first(r_id);
193        let vv1 = vv0.clone().incremented(r_id);
194
195        for (old_state, new_state) in [
196            (NodeState::Approved, NodeState::Approved),
197            (NodeState::Incomplete, NodeState::Approved),
198            (NodeState::Incomplete, NodeState::Incomplete),
199        ] {
200            let a = make_root_node(r_id, vv0.clone(), old_state);
201            let b = make_root_node(r_id, vv1.clone(), new_state);
202
203            assert_eq!(
204                prune(vec![a.clone(), b.clone()], &l_id),
205                (vec![b.clone()], vec![a.clone()])
206            );
207            assert_eq!(prune(vec![b.clone(), a.clone()], &l_id), (vec![b], vec![a]));
208        }
209    }
210
211    #[test]
212    fn prune_newer_approved_node_prunes_older_approved_and_newer_unapproved() {
213        let l_id = PublicKey::random();
214        let r_id = PublicKey::random();
215        let s_id = PublicKey::random();
216
217        let vv0 = VersionVector::first(r_id);
218        let vv1 = vv0.clone().incremented(r_id);
219
220        // The newer approved node is either local, from another remote branch or from the same
221        // branch.
222        for c_id in [l_id, s_id, r_id] {
223            let vv2 = vv1.clone().incremented(c_id);
224
225            let a = make_root_node(r_id, vv0.clone(), NodeState::Approved);
226            let b = make_root_node(r_id, vv1.clone(), NodeState::Incomplete);
227            let c = make_root_node(c_id, vv2, NodeState::Approved);
228
229            for nodes in [
230                vec![a.clone(), b.clone(), c.clone()],
231                vec![c.clone(), b.clone(), a.clone()],
232                vec![b.clone(), c.clone(), a.clone()],
233            ] {
234                let (uptodate, outdated) = prune(nodes, &l_id);
235
236                assert_eq!(uptodate, vec![c.clone()]);
237                assert_eq!(outdated.len(), 2);
238                assert!(outdated.contains(&a));
239                assert!(outdated.contains(&b));
240            }
241        }
242    }
243
244    #[test]
245    fn prune_local_with_same_version_vector_keeps_newer() {
246        let l_id = PublicKey::random();
247        let vv = VersionVector::first(l_id);
248
249        let a = make_root_node(l_id, vv.clone(), NodeState::Approved);
250        let b = make_root_node(l_id, vv, NodeState::Approved);
251        assert!(b.snapshot_id > a.snapshot_id);
252
253        assert_eq!(
254            prune(vec![a.clone(), b.clone()], &l_id),
255            (vec![b.clone()], vec![a.clone()])
256        );
257        assert_eq!(prune(vec![b.clone(), a.clone()], &l_id), (vec![b], vec![a]));
258    }
259
260    #[test]
261    fn prune_treats_unapproved_local_node_as_non_local() {
262        let l_id = PublicKey::random();
263        let r_id = PublicKey::random();
264
265        let vv0 = VersionVector::first(l_id);
266        let vv1 = vv0.clone().incremented(r_id);
267
268        // Would be kept if it was considered local.
269        let a = make_root_node(l_id, vv0, NodeState::Incomplete);
270        let b = make_root_node(r_id, vv1, NodeState::Approved);
271
272        assert_eq!(
273            prune(vec![a.clone(), b.clone()], &l_id),
274            (vec![b.clone()], vec![a.clone()])
275        );
276        assert_eq!(prune(vec![b.clone(), a.clone()], &l_id), (vec![b], vec![a]));
277    }
278
279    #[test]
280    fn prune_different_branches_keeps_unapproved_when_newer_is_not_approved() {
281        let l_id = PublicKey::random();
282        let a_id = PublicKey::random();
283        let b_id = PublicKey::random();
284
285        let vv0 = VersionVector::first(a_id);
286        let vv1 = vv0.clone().incremented(b_id);
287
288        for a_state in [NodeState::Incomplete, NodeState::Complete] {
289            for b_state in [NodeState::Incomplete, NodeState::Complete] {
290                let a = make_root_node(a_id, vv0.clone(), a_state);
291                let b = make_root_node(b_id, vv1.clone(), b_state);
292
293                assert_eq!(
294                    prune(vec![a.clone(), b.clone()], &l_id),
295                    (vec![a.clone(), b.clone()], vec![])
296                );
297                assert_eq!(
298                    prune(vec![b.clone(), a.clone()], &l_id),
299                    (vec![b, a], vec![])
300                );
301            }
302        }
303    }
304
305    #[test]
306    fn prune_remote_with_same_writer_and_version_vector_keeps_newer() {
307        let l_id = PublicKey::random();
308        let r_id = PublicKey::random();
309        let vv = VersionVector::first(r_id);
310
311        for state in [NodeState::Approved, NodeState::Incomplete] {
312            let a = make_root_node(r_id, vv.clone(), state);
313            let b = make_root_node(r_id, vv.clone(), state);
314            assert!(b.snapshot_id > a.snapshot_id);
315
316            assert_eq!(
317                prune(vec![a.clone(), b.clone()], &l_id),
318                (vec![b.clone()], vec![a.clone()])
319            );
320            assert_eq!(prune(vec![b.clone(), a.clone()], &l_id), (vec![b], vec![a]));
321        }
322    }
323
324    #[proptest]
325    fn compare_for_prune_is_partial_order(
326        #[strategy(vec((0..3usize, vec(0..3u64, 3), 0..2usize), 1..10))] specs: Vec<(
327            usize,
328            Vec<u64>,
329            usize,
330        )>,
331    ) {
332        // Writer 0 is the local one.
333        let writer_ids: [PublicKey; 3] = array::from_fn(|_| PublicKey::random());
334        let local_id = writer_ids[0];
335
336        let nodes: Vec<_> = specs
337            .into_iter()
338            .enumerate()
339            .map(|(snapshot_id, (writer_index, versions, state_index))| {
340                let version_vector: VersionVector = writer_ids
341                    .iter()
342                    .copied()
343                    .zip(versions)
344                    .filter(|(_, version)| *version > 0)
345                    .collect();
346                let state = [NodeState::Approved, NodeState::Incomplete][state_index];
347
348                let mut node = make_root_node(writer_ids[writer_index], version_vector, state);
349                node.snapshot_id = snapshot_id as SnapshotId;
350                node
351            })
352            .collect();
353
354        let cmp = |a, b| compare_for_prune(a, b, &local_id);
355
356        for a in &nodes {
357            // Reflexivity
358            assert_eq!(cmp(a, a), Some(Ordering::Equal), "a = {a:?}");
359
360            for b in &nodes {
361                // Antisymmetry (also implies the duality of `Less` and `Greater`)
362                assert_eq!(
363                    cmp(a, b),
364                    cmp(b, a).map(Ordering::reverse),
365                    "a = {a:?}, b = {b:?}"
366                );
367
368                if cmp(a, b) == Some(Ordering::Equal) {
369                    assert_eq!(a, b);
370                }
371
372                for c in &nodes {
373                    // Transitivity
374                    match (cmp(a, b), cmp(b, c)) {
375                        (Some(Ordering::Less), Some(Ordering::Less | Ordering::Equal))
376                        | (Some(Ordering::Equal), Some(Ordering::Less)) => {
377                            assert_eq!(
378                                cmp(a, c),
379                                Some(Ordering::Less),
380                                "a = {a:?}, b = {b:?}, c = {c:?}"
381                            );
382                        }
383                        (Some(Ordering::Greater), Some(Ordering::Greater | Ordering::Equal))
384                        | (Some(Ordering::Equal), Some(Ordering::Greater)) => {
385                            assert_eq!(
386                                cmp(a, c),
387                                Some(Ordering::Greater),
388                                "a = {a:?}, b = {b:?}, c = {c:?}"
389                            );
390                        }
391                        (Some(Ordering::Equal), Some(Ordering::Equal)) => {
392                            assert_eq!(
393                                cmp(a, c),
394                                Some(Ordering::Equal),
395                                "a = {a:?}, b = {b:?}, c = {c:?}"
396                            );
397                        }
398                        _ => (),
399                    }
400                }
401            }
402        }
403    }
404
405    fn make_root_node(
406        writer_id: PublicKey,
407        version_vector: VersionVector,
408        state: NodeState,
409    ) -> RootNode {
410        use std::sync::atomic::{self, AtomicU32};
411
412        static NEXT_SNAPSHOT_ID: AtomicU32 = AtomicU32::new(0);
413        static WRITE_KEYS: LazyLock<Keypair> = LazyLock::new(Keypair::random);
414
415        RootNode {
416            snapshot_id: NEXT_SNAPSHOT_ID.fetch_add(1, atomic::Ordering::Relaxed),
417            proof: Proof::new(writer_id, version_vector, rand::random(), &WRITE_KEYS),
418            summary: Summary {
419                state,
420                block_presence: MultiBlockPresence::Full,
421            },
422        }
423    }
424}