gitiverse-cob 0.3.0

Content-addressed Git-backed DAG CRDTs for repository governance, issues, and patches in gitiverse
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
use std::collections::{BTreeMap, BTreeSet};

use gitiverse_core::ids::{ActorId, RepoId};
use serde::{Deserialize, Serialize};

use crate::dag::{CobError, Dag, Lww, OpId, require_root};

pub const ISSUE_KIND: &str = "issue";

/// Lifecycle state of an issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueStatus {
    Open,
    Closed,
}

/// Operations on an issue CRDT.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueAction {
    Open {
        title: String,
        body: String,
        labels: Vec<String>,
    },
    Edit {
        title: Option<String>,
        body: Option<String>,
    },
    SetState(IssueStatus),
    AddLabel(String),
    RemoveLabel(String),
    Comment {
        body: String,
    },
    EditComment {
        comment_id: OpId,
        body: String,
    },
}

/// Resolved comment on an issue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IssueComment {
    pub id: OpId,
    pub author: ActorId,
    pub body: String,
    pub created_at: u64,
    pub updated_at: u64,
    pub lamport: u64,
}

/// Materialised issue state with Strong Eventual Consistency via causal LWW registers and add-wins OR-Set labels.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IssueState {
    pub id: OpId,
    pub repo_id: RepoId,
    pub author: ActorId,
    pub title: String,
    pub body: String,
    pub status: IssueStatus,
    pub labels: BTreeSet<String>,
    pub comments: Vec<IssueComment>,
    pub created_at: u64,
    pub updated_at: u64,
}

struct CommentAccum {
    id: OpId,
    author: ActorId,
    body: Lww<String>,
    created_at: u64,
    updated_at: Lww<u64>,
    lamport: u64,
}

struct IssueAccum {
    id: OpId,
    repo_id: RepoId,
    author: ActorId,
    title: Lww<String>,
    body: Lww<String>,
    status: Lww<IssueStatus>,
    label_adds: BTreeMap<String, BTreeSet<OpId>>,
    label_tombstones: BTreeMap<String, BTreeSet<OpId>>,
    comments: BTreeMap<OpId, CommentAccum>,
    created_at: u64,
    updated_at: u64,
}

impl IssueState {
    /// Resolves an issue DAG into a deterministic [`IssueState`].
    pub fn from_dag(dag: &Dag<IssueAction>) -> Result<Self, CobError> {
        let accum: Option<IssueAccum> = dag.fold(None, |state, op_id, op, ancestors| {
            match &op.payload {
                IssueAction::Open {
                    title,
                    body,
                    labels,
                } => {
                    if state.is_some() {
                        return Err(CobError::InvalidOp(
                            "duplicate issue Open operation".to_owned(),
                        ));
                    }
                    if !op.parents.is_empty() {
                        return Err(CobError::InvalidOp(
                            "issue Open operation must have no parents".to_owned(),
                        ));
                    }
                    let mut label_adds: BTreeMap<String, BTreeSet<OpId>> = BTreeMap::new();
                    for label in labels {
                        label_adds.entry(label.clone()).or_default().insert(op_id);
                    }
                    *state = Some(IssueAccum {
                        id: op_id,
                        repo_id: op.repo_id,
                        author: op.author,
                        title: Lww::new(op.lamport, op_id, title.clone()),
                        body: Lww::new(op.lamport, op_id, body.clone()),
                        status: Lww::new(op.lamport, op_id, IssueStatus::Open),
                        label_adds,
                        label_tombstones: BTreeMap::new(),
                        comments: BTreeMap::new(),
                        created_at: op.timestamp,
                        updated_at: op.timestamp,
                    });
                    Ok(())
                }
                IssueAction::Edit { title, body } => {
                    let acc = require_root(state, ISSUE_KIND, op_id)?;
                    if let Some(t) = title {
                        acc.title.update(op.lamport, op_id, t.clone());
                    }
                    if let Some(b) = body {
                        acc.body.update(op.lamport, op_id, b.clone());
                    }
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                IssueAction::SetState(next) => {
                    let acc = require_root(state, ISSUE_KIND, op_id)?;
                    acc.status.update(op.lamport, op_id, *next);
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                IssueAction::AddLabel(label) => {
                    let acc = require_root(state, ISSUE_KIND, op_id)?;
                    acc.label_adds
                        .entry(label.clone())
                        .or_default()
                        .insert(op_id);
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                IssueAction::RemoveLabel(label) => {
                    let acc = require_root(state, ISSUE_KIND, op_id)?;
                    // Add-wins OR-Set: remove only add tags observed in this op's causal past.
                    if let Some(add_ids) = acc.label_adds.get(label) {
                        let observed: Vec<OpId> = add_ids
                            .iter()
                            .copied()
                            .filter(|add_id| ancestors.contains(add_id))
                            .collect();
                        if !observed.is_empty() {
                            acc.label_tombstones
                                .entry(label.clone())
                                .or_default()
                                .extend(observed);
                        }
                    }
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                IssueAction::Comment { body } => {
                    let acc = require_root(state, ISSUE_KIND, op_id)?;
                    acc.comments.insert(
                        op_id,
                        CommentAccum {
                            id: op_id,
                            author: op.author,
                            body: Lww::new(op.lamport, op_id, body.clone()),
                            created_at: op.timestamp,
                            updated_at: Lww::new(op.lamport, op_id, op.timestamp),
                            lamport: op.lamport,
                        },
                    );
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                IssueAction::EditComment { comment_id, body } => {
                    let acc = require_root(state, ISSUE_KIND, op_id)?;
                    let Some(comment) = acc.comments.get_mut(comment_id) else {
                        return Err(CobError::InvalidOp(format!(
                            "EditComment references unknown comment {comment_id}"
                        )));
                    };
                    if comment.author != op.author {
                        return Err(CobError::Unauthorised {
                            actor: op.author,
                            op_id,
                            reason: "only the comment author may edit their comment".to_owned(),
                        });
                    }
                    comment.body.update(op.lamport, op_id, body.clone());
                    comment.updated_at.update(op.lamport, op_id, op.timestamp);
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
            }
        })?;

        let acc = accum.ok_or_else(|| CobError::InvalidOp("empty issue DAG".to_owned()))?;
        let mut labels = BTreeSet::new();
        for (label, add_ids) in acc.label_adds {
            let tombstoned = acc.label_tombstones.get(&label);
            let live = add_ids
                .iter()
                .any(|id| tombstoned.is_none_or(|t| !t.contains(id)));
            if live {
                labels.insert(label);
            }
        }

        let mut comments: Vec<IssueComment> = acc
            .comments
            .into_values()
            .map(|c| IssueComment {
                id: c.id,
                author: c.author,
                body: c.body.value,
                created_at: c.created_at,
                updated_at: c.updated_at.value,
                lamport: c.lamport,
            })
            .collect();
        comments.sort_by_key(|c| (c.lamport, c.id));

        Ok(IssueState {
            id: acc.id,
            repo_id: acc.repo_id,
            author: acc.author,
            title: acc.title.value,
            body: acc.body.value,
            status: acc.status.value,
            labels,
            comments,
            created_at: acc.created_at,
            updated_at: acc.updated_at,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dag::DagOp;
    use gitiverse_core::ids::RepoId;
    use proptest::prelude::*;
    use wire_mesh_core::adapters::NodeIdentity;

    #[tokio::test]
    async fn concurrent_add_wins_label_and_comment_edit_resolve_deterministically() {
        let alice = NodeIdentity::generate_ed25519();
        let bob = NodeIdentity::generate_es256();
        let repo_id = RepoId::from_bytes([0x21; 32]);

        let open = DagOp::sign_new(
            repo_id,
            ISSUE_KIND,
            vec![],
            1,
            100,
            IssueAction::Open {
                title: "Initial bug".to_owned(),
                body: "Needs fix".to_owned(),
                labels: vec!["bug".to_owned()],
            },
            &alice,
        )
        .await
        .unwrap();
        let open_id = open.op_id().unwrap();

        // Bob removes "bug" while Alice concurrently adds "bug" again.
        let bob_remove = DagOp::sign_new(
            repo_id,
            ISSUE_KIND,
            vec![open_id],
            2,
            101,
            IssueAction::RemoveLabel("bug".to_owned()),
            &bob,
        )
        .await
        .unwrap();
        let alice_readd = DagOp::sign_new(
            repo_id,
            ISSUE_KIND,
            vec![open_id],
            2,
            102,
            IssueAction::AddLabel("bug".to_owned()),
            &alice,
        )
        .await
        .unwrap();

        let comment = DagOp::sign_new(
            repo_id,
            ISSUE_KIND,
            vec![open_id],
            2,
            103,
            IssueAction::Comment {
                body: "draft".to_owned(),
            },
            &alice,
        )
        .await
        .unwrap();
        let comment_id = comment.op_id().unwrap();
        let edit_comment = DagOp::sign_new(
            repo_id,
            ISSUE_KIND,
            vec![comment_id],
            3,
            104,
            IssueAction::EditComment {
                comment_id,
                body: "final comment".to_owned(),
            },
            &alice,
        )
        .await
        .unwrap();

        let mut d1 = Dag::new();
        for op in [
            edit_comment.clone(),
            bob_remove.clone(),
            alice_readd.clone(),
            comment.clone(),
            open.clone(),
        ] {
            d1.insert_verified(op, &alice, Some(&repo_id), Some(ISSUE_KIND))
                .await
                .unwrap();
        }
        let mut d2 = Dag::new();
        for op in [open, comment, alice_readd, bob_remove, edit_comment] {
            d2.insert_verified(op, &bob, Some(&repo_id), Some(ISSUE_KIND))
                .await
                .unwrap();
        }

        let s1 = IssueState::from_dag(&d1).unwrap();
        let s2 = IssueState::from_dag(&d2).unwrap();
        assert_eq!(s1, s2);
        assert!(s1.labels.contains("bug"));
        assert_eq!(s1.comments.len(), 1);
        assert_eq!(s1.comments[0].body, "final comment");
    }

    proptest! {
        #[test]
        fn prop_issue_crdt_commutes_is_idempotent_and_converges(
            perm in prop::collection::vec(0usize..100, 1..20),
            dups in prop::collection::vec(0usize..12, 0..10),
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let alice = NodeIdentity::from_ed25519_secret(&[1u8; 32]).unwrap();
                let bob = NodeIdentity::from_ed25519_secret(&[2u8; 32]).unwrap();
                let repo_id = RepoId::from_bytes([0x55; 32]);

                let open = DagOp::sign_new(
                    repo_id,
                    ISSUE_KIND,
                    vec![],
                    1,
                    10,
                    IssueAction::Open {
                        title: "t0".to_owned(),
                        body: "b0".to_owned(),
                        labels: vec!["triage".to_owned()],
                    },
                    &alice,
                ).await.unwrap();
                let id_open = open.op_id().unwrap();

                let edit_a = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![id_open], 2, 11,
                    IssueAction::Edit { title: Some("t-a".to_owned()), body: None }, &alice,
                ).await.unwrap();
                let edit_b = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![id_open], 2, 12,
                    IssueAction::Edit { title: Some("t-b".to_owned()), body: Some("b-b".to_owned()) }, &bob,
                ).await.unwrap();
                let rm_triage = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![id_open], 2, 13,
                    IssueAction::RemoveLabel("triage".to_owned()), &bob,
                ).await.unwrap();
                let add_triage = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![id_open], 2, 14,
                    IssueAction::AddLabel("triage".to_owned()), &alice,
                ).await.unwrap();
                let add_perf = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![edit_a.op_id().unwrap()], 3, 15,
                    IssueAction::AddLabel("perf".to_owned()), &alice,
                ).await.unwrap();
                let close_op = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![edit_b.op_id().unwrap()], 3, 16,
                    IssueAction::SetState(IssueStatus::Closed), &bob,
                ).await.unwrap();
                let reopen_op = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![close_op.op_id().unwrap()], 4, 17,
                    IssueAction::SetState(IssueStatus::Open), &alice,
                ).await.unwrap();
                let comment_a = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![id_open], 2, 18,
                    IssueAction::Comment { body: "first".to_owned() }, &alice,
                ).await.unwrap();
                let comment_id = comment_a.op_id().unwrap();
                let edit_comment = DagOp::sign_new(
                    repo_id, ISSUE_KIND, vec![comment_id], 3, 19,
                    IssueAction::EditComment { comment_id, body: "edited".to_owned() }, &alice,
                ).await.unwrap();

                let all_ops = vec![
                    open, edit_a, edit_b, rm_triage, add_triage,
                    add_perf, close_op, reopen_op, comment_a, edit_comment,
                ];

                let mut canonical_dag = Dag::new();
                for op in &all_ops {
                    canonical_dag.insert_unchecked(op.clone()).unwrap();
                }
                let expected = IssueState::from_dag(&canonical_dag).unwrap();

                // Build an arbitrary permutation + duplicates arrival order.
                let mut indices: Vec<usize> = (0..all_ops.len()).collect();
                for (i, &swap_seed) in perm.iter().enumerate() {
                    let a = i % all_ops.len();
                    let b = swap_seed % all_ops.len();
                    indices.swap(a, b);
                }
                let mut peer_dag = Dag::new();
                for idx in indices {
                    peer_dag.insert_unchecked(all_ops[idx].clone()).unwrap();
                }
                for dup in dups {
                    let op = &all_ops[dup % all_ops.len()];
                    peer_dag.insert_unchecked(op.clone()).unwrap();
                }

                let actual = IssueState::from_dag(&peer_dag).unwrap();
                assert_eq!(actual, expected);
                assert_eq!(peer_dag.len(), all_ops.len());
            });
        }
    }
}