gitiverse-cob 0.2.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
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
use std::collections::BTreeMap;

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

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

pub const PATCH_KIND: &str = "patch";

/// Reviewer verdict kind for a patch revision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum VerdictKind {
    Approve,
    RequestChanges,
    Comment,
}

/// Lifecycle state of a pull-request / patch COB.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PatchStatus {
    Open,
    Merged {
        merge_commit: String,
        merged_by: ActorId,
    },
    Closed,
}

/// Operations on a patch / pull-request CRDT.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PatchAction {
    Propose {
        title: String,
        description: String,
        base_ref: String,
        base_commit: String,
        head_commit: String,
    },
    UpdateRevision {
        revision_commit: String,
        base_commit: Option<String>,
        summary: Option<String>,
    },
    ReviewComment {
        path: String,
        line: u32,
        commit: String,
        body: String,
    },
    ReviewVerdict {
        verdict: VerdictKind,
        commit: String,
        body: Option<String>,
    },
    Merge {
        merge_commit: String,
        merged_by: ActorId,
    },
    Close,
}

/// Recorded revision in a patch's history.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PatchRevision {
    pub id: OpId,
    pub author: ActorId,
    pub commit: String,
    pub summary: Option<String>,
    pub lamport: u64,
    pub timestamp: u64,
}

/// Inline review comment attached to a file, line, and commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PatchReviewComment {
    pub id: OpId,
    pub author: ActorId,
    pub path: String,
    pub line: u32,
    pub commit: String,
    pub body: String,
    pub lamport: u64,
    pub timestamp: u64,
}

/// Signed review verdict on a patch commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PatchReviewVerdict {
    pub id: OpId,
    pub author: ActorId,
    pub verdict: VerdictKind,
    pub commit: String,
    pub body: Option<String>,
    pub lamport: u64,
    pub timestamp: u64,
}

/// Materialised patch / pull-request state with Strong Eventual Consistency.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PatchState {
    pub id: OpId,
    pub repo_id: RepoId,
    pub author: ActorId,
    pub title: String,
    pub description: String,
    pub base_ref: String,
    pub base_commit: String,
    pub head_commit: String,
    pub revisions: Vec<PatchRevision>,
    pub status: PatchStatus,
    pub review_comments: Vec<PatchReviewComment>,
    pub verdicts_by_reviewer: BTreeMap<ActorId, PatchReviewVerdict>,
    pub all_verdicts: Vec<PatchReviewVerdict>,
    pub created_at: u64,
    pub updated_at: u64,
}

struct PatchAccum {
    id: OpId,
    repo_id: RepoId,
    author: ActorId,
    title: String,
    description: String,
    base_ref: String,
    base_commit: Lww<String>,
    head_commit: Lww<String>,
    revisions: BTreeMap<(u64, OpId), PatchRevision>,
    status: Lww<PatchStatus>,
    review_comments: BTreeMap<(u64, OpId), PatchReviewComment>,
    verdicts_by_reviewer: BTreeMap<ActorId, Lww<PatchReviewVerdict>>,
    all_verdicts: BTreeMap<(u64, OpId), PatchReviewVerdict>,
    created_at: u64,
    updated_at: u64,
}

impl PatchState {
    /// Resolves a patch DAG into a deterministic [`PatchState`].
    pub fn from_dag(dag: &Dag<PatchAction>) -> Result<Self, CobError> {
        let accum: Option<PatchAccum> =
            dag.fold(None, |state, op_id, op, _ancestors| match &op.payload {
                PatchAction::Propose {
                    title,
                    description,
                    base_ref,
                    base_commit,
                    head_commit,
                } => {
                    if state.is_some() {
                        return Err(CobError::InvalidOp(
                            "duplicate patch Propose operation".to_owned(),
                        ));
                    }
                    if !op.parents.is_empty() {
                        return Err(CobError::InvalidOp(
                            "patch Propose operation must have no parents".to_owned(),
                        ));
                    }
                    let mut revisions = BTreeMap::new();
                    revisions.insert(
                        (op.lamport, op_id),
                        PatchRevision {
                            id: op_id,
                            author: op.author,
                            commit: head_commit.clone(),
                            summary: Some("initial revision".to_owned()),
                            lamport: op.lamport,
                            timestamp: op.timestamp,
                        },
                    );
                    *state = Some(PatchAccum {
                        id: op_id,
                        repo_id: op.repo_id,
                        author: op.author,
                        title: title.clone(),
                        description: description.clone(),
                        base_ref: base_ref.clone(),
                        base_commit: Lww::new(op.lamport, op_id, base_commit.clone()),
                        head_commit: Lww::new(op.lamport, op_id, head_commit.clone()),
                        revisions,
                        status: Lww::new(op.lamport, op_id, PatchStatus::Open),
                        review_comments: BTreeMap::new(),
                        verdicts_by_reviewer: BTreeMap::new(),
                        all_verdicts: BTreeMap::new(),
                        created_at: op.timestamp,
                        updated_at: op.timestamp,
                    });
                    Ok(())
                }
                PatchAction::UpdateRevision {
                    revision_commit,
                    base_commit,
                    summary,
                } => {
                    let acc = require_root(state, PATCH_KIND, op_id)?;
                    acc.head_commit
                        .update(op.lamport, op_id, revision_commit.clone());
                    if let Some(base) = base_commit {
                        acc.base_commit.update(op.lamport, op_id, base.clone());
                    }
                    acc.revisions.insert(
                        (op.lamport, op_id),
                        PatchRevision {
                            id: op_id,
                            author: op.author,
                            commit: revision_commit.clone(),
                            summary: summary.clone(),
                            lamport: op.lamport,
                            timestamp: op.timestamp,
                        },
                    );
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                PatchAction::ReviewComment {
                    path,
                    line,
                    commit,
                    body,
                } => {
                    let acc = require_root(state, PATCH_KIND, op_id)?;
                    acc.review_comments.insert(
                        (op.lamport, op_id),
                        PatchReviewComment {
                            id: op_id,
                            author: op.author,
                            path: path.clone(),
                            line: *line,
                            commit: commit.clone(),
                            body: body.clone(),
                            lamport: op.lamport,
                            timestamp: op.timestamp,
                        },
                    );
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                PatchAction::ReviewVerdict {
                    verdict,
                    commit,
                    body,
                } => {
                    let acc = require_root(state, PATCH_KIND, op_id)?;
                    let entry = PatchReviewVerdict {
                        id: op_id,
                        author: op.author,
                        verdict: *verdict,
                        commit: commit.clone(),
                        body: body.clone(),
                        lamport: op.lamport,
                        timestamp: op.timestamp,
                    };
                    acc.all_verdicts.insert((op.lamport, op_id), entry.clone());
                    match acc.verdicts_by_reviewer.get_mut(&op.author) {
                        Some(lww) => lww.update(op.lamport, op_id, entry),
                        None => {
                            acc.verdicts_by_reviewer
                                .insert(op.author, Lww::new(op.lamport, op_id, entry));
                        }
                    }
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                PatchAction::Merge {
                    merge_commit,
                    merged_by,
                } => {
                    let acc = require_root(state, PATCH_KIND, op_id)?;
                    acc.status.update(
                        op.lamport,
                        op_id,
                        PatchStatus::Merged {
                            merge_commit: merge_commit.clone(),
                            merged_by: *merged_by,
                        },
                    );
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
                PatchAction::Close => {
                    let acc = require_root(state, PATCH_KIND, op_id)?;
                    acc.status.update(op.lamport, op_id, PatchStatus::Closed);
                    acc.updated_at = acc.updated_at.max(op.timestamp);
                    Ok(())
                }
            })?;

        let acc = accum.ok_or_else(|| CobError::InvalidOp("empty patch DAG".to_owned()))?;
        Ok(PatchState {
            id: acc.id,
            repo_id: acc.repo_id,
            author: acc.author,
            title: acc.title,
            description: acc.description,
            base_ref: acc.base_ref,
            base_commit: acc.base_commit.value,
            head_commit: acc.head_commit.value,
            revisions: acc.revisions.into_values().collect(),
            status: acc.status.value,
            review_comments: acc.review_comments.into_values().collect(),
            verdicts_by_reviewer: acc
                .verdicts_by_reviewer
                .into_iter()
                .map(|(k, v)| (k, v.value))
                .collect(),
            all_verdicts: acc.all_verdicts.into_values().collect(),
            created_at: acc.created_at,
            updated_at: acc.updated_at,
        })
    }

    /// Returns maintainers whose latest verdict approves the current `head_commit`.
    #[must_use]
    pub fn maintainer_approvals(&self, maintainers: &[ActorId]) -> Vec<ActorId> {
        self.verdicts_by_reviewer
            .iter()
            .filter_map(|(actor, verdict)| {
                if maintainers.contains(actor)
                    && verdict.verdict == VerdictKind::Approve
                    && verdict.commit == self.head_commit
                {
                    Some(*actor)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Returns `true` if any maintainer currently requests changes on the current `head_commit`.
    #[must_use]
    pub fn has_blocking_changes(&self, maintainers: &[ActorId]) -> bool {
        self.verdicts_by_reviewer.iter().any(|(actor, verdict)| {
            maintainers.contains(actor)
                && verdict.verdict == VerdictKind::RequestChanges
                && verdict.commit == self.head_commit
        })
    }

    /// Returns `true` when maintainer approvals meet `quorum` and no maintainer requests changes.
    #[must_use]
    pub fn meets_quorum(&self, quorum: u32, maintainers: &[ActorId]) -> bool {
        !self.has_blocking_changes(maintainers)
            && self.maintainer_approvals(maintainers).len() >= quorum as usize
    }
}

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

    #[tokio::test]
    async fn patch_tracks_revisions_verdicts_quorum_and_merge() {
        let author = NodeIdentity::generate_ed25519();
        let reviewer = NodeIdentity::generate_es256();
        let repo_id = RepoId::from_bytes([0x66; 32]);
        let reviewer_id = ActorId(*reviewer.device_id());

        let c1 = "1".repeat(40);
        let c2 = "2".repeat(40);
        let c_merge = "3".repeat(40);

        let propose = DagOp::sign_new(
            repo_id,
            PATCH_KIND,
            vec![],
            1,
            100,
            PatchAction::Propose {
                title: "Add COB patch CRDT".to_owned(),
                description: "Implements SEC patch flow".to_owned(),
                base_ref: "refs/heads/main".to_owned(),
                base_commit: "0".repeat(40),
                head_commit: c1.clone(),
            },
            &author,
        )
        .await
        .unwrap();
        let propose_id = propose.op_id().unwrap();

        let req_changes = DagOp::sign_new(
            repo_id,
            PATCH_KIND,
            vec![propose_id],
            2,
            101,
            PatchAction::ReviewVerdict {
                verdict: VerdictKind::RequestChanges,
                commit: c1.clone(),
                body: Some("needs test".to_owned()),
            },
            &reviewer,
        )
        .await
        .unwrap();

        let rev2 = DagOp::sign_new(
            repo_id,
            PATCH_KIND,
            vec![propose_id],
            2,
            102,
            PatchAction::UpdateRevision {
                revision_commit: c2.clone(),
                base_commit: None,
                summary: Some("added test".to_owned()),
            },
            &author,
        )
        .await
        .unwrap();
        let rev2_id = rev2.op_id().unwrap();

        let approve = DagOp::sign_new(
            repo_id,
            PATCH_KIND,
            vec![rev2_id],
            3,
            103,
            PatchAction::ReviewVerdict {
                verdict: VerdictKind::Approve,
                commit: c2.clone(),
                body: Some("LGTM".to_owned()),
            },
            &reviewer,
        )
        .await
        .unwrap();
        let approve_id = approve.op_id().unwrap();

        let merge = DagOp::sign_new(
            repo_id,
            PATCH_KIND,
            vec![approve_id],
            4,
            104,
            PatchAction::Merge {
                merge_commit: c_merge.clone(),
                merged_by: reviewer_id,
            },
            &reviewer,
        )
        .await
        .unwrap();

        let mut dag = Dag::new();
        for op in [merge, approve, rev2, req_changes, propose] {
            dag.insert_verified(op, &author, Some(&repo_id), Some(PATCH_KIND))
                .await
                .unwrap();
        }
        let state = PatchState::from_dag(&dag).unwrap();
        assert_eq!(state.head_commit, c2);
        assert!(state.meets_quorum(1, &[reviewer_id]));
        assert_eq!(
            state.status,
            PatchStatus::Merged {
                merge_commit: c_merge,
                merged_by: reviewer_id,
            }
        );
    }

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

                let c1 = "a".repeat(40);
                let c2 = "b".repeat(40);

                let propose = DagOp::sign_new(
                    repo_id,
                    PATCH_KIND,
                    vec![],
                    1,
                    10,
                    PatchAction::Propose {
                        title: "Fix".to_owned(),
                        description: "desc".to_owned(),
                        base_ref: "refs/heads/main".to_owned(),
                        base_commit: "0".repeat(40),
                        head_commit: c1.clone(),
                    },
                    &alice,
                ).await.unwrap();
                let id_propose = propose.op_id().unwrap();

                let comment = DagOp::sign_new(
                    repo_id, PATCH_KIND, vec![id_propose], 2, 11,
                    PatchAction::ReviewComment {
                        path: "src/lib.rs".to_owned(),
                        line: 12,
                        commit: c1.clone(),
                        body: "nit".to_owned(),
                    },
                    &bob,
                ).await.unwrap();
                let rev2 = DagOp::sign_new(
                    repo_id, PATCH_KIND, vec![id_propose], 2, 12,
                    PatchAction::UpdateRevision {
                        revision_commit: c2.clone(),
                        base_commit: None,
                        summary: Some("addressed nit".to_owned()),
                    },
                    &alice,
                ).await.unwrap();
                let id_rev2 = rev2.op_id().unwrap();

                let verdict_req = DagOp::sign_new(
                    repo_id, PATCH_KIND, vec![id_propose], 2, 13,
                    PatchAction::ReviewVerdict {
                        verdict: VerdictKind::RequestChanges,
                        commit: c1,
                        body: None,
                    },
                    &bob,
                ).await.unwrap();
                let verdict_ok = DagOp::sign_new(
                    repo_id, PATCH_KIND, vec![id_rev2], 3, 14,
                    PatchAction::ReviewVerdict {
                        verdict: VerdictKind::Approve,
                        commit: c2.clone(),
                        body: Some("nice".to_owned()),
                    },
                    &bob,
                ).await.unwrap();
                let merge_op = DagOp::sign_new(
                    repo_id, PATCH_KIND, vec![verdict_ok.op_id().unwrap()], 4, 15,
                    PatchAction::Merge {
                        merge_commit: "c".repeat(40),
                        merged_by: ActorId(*bob.device_id()),
                    },
                    &bob,
                ).await.unwrap();
                let close_op = DagOp::sign_new(
                    repo_id, PATCH_KIND, vec![id_rev2], 3, 16,
                    PatchAction::Close,
                    &alice,
                ).await.unwrap();

                let all_ops = vec![
                    propose, comment, rev2, verdict_req, verdict_ok, merge_op, close_op,
                ];

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

                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 dag_b = Dag::new();
                for idx in indices {
                    dag_b.insert_unchecked(all_ops[idx].clone()).unwrap();
                }
                for dup in dups {
                    dag_b.insert_unchecked(all_ops[dup % all_ops.len()].clone()).unwrap();
                }
                let actual = PatchState::from_dag(&dag_b).unwrap();
                assert_eq!(actual, expected);
                assert_eq!(dag_b.len(), all_ops.len());
            });
        }
    }
}