Skip to main content

lex_vcs/
apply.rs

1//! The apply gate. Validates an operation's parents against a known
2//! branch head, then persists it via [`OpLog`]. Issue #129 keeps this
3//! narrow: no type checking, no effect verification — those are #130.
4
5use crate::op_log::OpLog;
6use crate::operation::{OpId, Operation, OperationRecord, StageTransition};
7use std::io;
8
9#[derive(Debug)]
10pub struct NewHead {
11    pub op_id: OpId,
12    pub record: OperationRecord,
13}
14
15#[derive(Debug, thiserror::Error)]
16pub enum ApplyError {
17    #[error("stale parent: branch head is {expected:?} but op's parents are {op_parents:?}")]
18    StaleParent {
19        expected: Option<OpId>,
20        op_parents: Vec<OpId>,
21    },
22    #[error("merge op references unknown second parent {0}")]
23    UnknownMergeParent(OpId),
24    #[error(transparent)]
25    Persist(#[from] io::Error),
26}
27
28/// Apply an operation against a branch head and persist it.
29///
30/// Validates parents:
31/// - If `op.parents.is_empty()`: `head_op` must be `None` (genesis op
32///   on an empty branch).
33/// - If `op.parents.len() == 1`: that parent must equal `head_op`.
34/// - If `op.parents.len() == 2`: one parent must equal `head_op`, and
35///   the other must already exist in the log (a merge op's
36///   second-parent ancestry must be reachable).
37/// - All other arities are rejected as `StaleParent`.
38pub fn apply(
39    op_log: &OpLog,
40    head_op: Option<&OpId>,
41    op: Operation,
42    transition: StageTransition,
43) -> Result<NewHead, ApplyError> {
44    match (op.parents.len(), head_op) {
45        (0, None) => {}
46        (1, Some(h)) if op.parents[0] == *h => {}
47        (2, Some(h)) => {
48            if op.parents[0] == op.parents[1] {
49                return Err(ApplyError::StaleParent {
50                    expected: head_op.cloned(),
51                    op_parents: op.parents.clone(),
52                });
53            }
54            if op.parents[0] != *h && op.parents[1] != *h {
55                return Err(ApplyError::StaleParent {
56                    expected: head_op.cloned(),
57                    op_parents: op.parents.clone(),
58                });
59            }
60            // The non-head parent must exist in the log.
61            let other = if op.parents[0] == *h { &op.parents[1] } else { &op.parents[0] };
62            if op_log.get(other)?.is_none() {
63                return Err(ApplyError::UnknownMergeParent(other.clone()));
64            }
65        }
66        _ => {
67            return Err(ApplyError::StaleParent {
68                expected: head_op.cloned(),
69                op_parents: op.parents.clone(),
70            });
71        }
72    }
73
74    let record = OperationRecord::new(op, transition);
75    op_log.put(&record)?;
76    Ok(NewHead { op_id: record.op_id.clone(), record })
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use crate::operation::{OperationKind, StageTransition};
83    use std::collections::BTreeSet;
84
85    fn add_fac() -> (Operation, StageTransition) {
86        let op = Operation::new(
87            OperationKind::AddFunction {
88                sig_id: "fac".into(),
89                stage_id: "s1".into(),
90                effects: BTreeSet::new(),
91                budget_cost: None,
92                in_file: None,
93            },
94            [],
95        );
96        let t = StageTransition::Create {
97            sig_id: "fac".into(),
98            stage_id: "s1".into(),
99        };
100        (op, t)
101    }
102
103    #[test]
104    fn parentless_op_against_empty_head_succeeds() {
105        let tmp = tempfile::tempdir().unwrap();
106        let log = OpLog::open(tmp.path()).unwrap();
107        let (op, t) = add_fac();
108        let head = apply(&log, None, op, t).unwrap();
109        assert!(log.get(&head.op_id).unwrap().is_some());
110    }
111
112    #[test]
113    fn parentless_op_against_non_empty_head_is_stale() {
114        let tmp = tempfile::tempdir().unwrap();
115        let log = OpLog::open(tmp.path()).unwrap();
116        let (op1, t1) = add_fac();
117        let head1 = apply(&log, None, op1, t1).unwrap();
118        let (op2, t2) = add_fac(); // parentless again
119        let err = apply(&log, Some(&head1.op_id), op2, t2).unwrap_err();
120        match err {
121            ApplyError::StaleParent { expected, op_parents } => {
122                assert_eq!(expected.as_deref(), Some(head1.op_id.as_str()));
123                assert!(op_parents.is_empty());
124            }
125            other => panic!("expected StaleParent, got {other:?}"),
126        }
127    }
128
129    #[test]
130    fn single_parent_matching_head_succeeds() {
131        let tmp = tempfile::tempdir().unwrap();
132        let log = OpLog::open(tmp.path()).unwrap();
133        let (op1, t1) = add_fac();
134        let head1 = apply(&log, None, op1, t1).unwrap();
135        let modify = Operation::new(
136            OperationKind::ModifyBody {
137                sig_id: "fac".into(),
138                from_stage_id: "s1".into(),
139                to_stage_id: "s2".into(),
140                from_budget: None,
141                to_budget: None,
142            },
143            [head1.op_id.clone()],
144        );
145        let t = StageTransition::Replace {
146            sig_id: "fac".into(),
147            from: "s1".into(),
148            to: "s2".into(),
149        };
150        let head2 = apply(&log, Some(&head1.op_id), modify, t).unwrap();
151        assert_ne!(head2.op_id, head1.op_id);
152    }
153
154    #[test]
155    fn single_parent_not_matching_head_is_stale() {
156        let tmp = tempfile::tempdir().unwrap();
157        let log = OpLog::open(tmp.path()).unwrap();
158        let (op1, t1) = add_fac();
159        let head1 = apply(&log, None, op1, t1).unwrap();
160        let bogus = Operation::new(
161            OperationKind::ModifyBody {
162                sig_id: "fac".into(),
163                from_stage_id: "s1".into(),
164                to_stage_id: "s2".into(),
165                from_budget: None,
166                to_budget: None,
167            },
168            ["someone-else".into()],
169        );
170        let t = StageTransition::Replace {
171            sig_id: "fac".into(),
172            from: "s1".into(),
173            to: "s2".into(),
174        };
175        let err = apply(&log, Some(&head1.op_id), bogus, t).unwrap_err();
176        match err {
177            ApplyError::StaleParent { expected, op_parents } => {
178                assert_eq!(expected.as_deref(), Some(head1.op_id.as_str()));
179                assert_eq!(op_parents, vec!["someone-else".to_string()]);
180            }
181            other => panic!("expected StaleParent, got {other:?}"),
182        }
183    }
184
185    #[test]
186    fn merge_op_with_known_second_parent_succeeds() {
187        let tmp = tempfile::tempdir().unwrap();
188        let log = OpLog::open(tmp.path()).unwrap();
189        let (op_a, t_a) = add_fac();
190        let head_a = apply(&log, None, op_a, t_a).unwrap();
191        let other = Operation::new(
192            OperationKind::AddFunction {
193                sig_id: "double".into(),
194                stage_id: "d1".into(),
195                effects: BTreeSet::new(),
196                budget_cost: None,
197                in_file: None,
198            },
199            [],
200        );
201        let head_b = apply(&log, None, other, StageTransition::Create {
202            sig_id: "double".into(), stage_id: "d1".into(),
203        }).unwrap();
204        // Merge op: parents = [head_a, head_b].
205        let merge = Operation::new(
206            OperationKind::Merge { resolved: 1 },
207            [head_a.op_id.clone(), head_b.op_id.clone()],
208        );
209        let t = StageTransition::Merge {
210            entries: std::iter::once(("double".to_string(), Some("d1".to_string())))
211                .collect(),
212        };
213        let merged = apply(&log, Some(&head_a.op_id), merge, t).unwrap();
214        assert!(log.get(&merged.op_id).unwrap().is_some());
215    }
216
217    #[test]
218    fn merge_op_with_unknown_second_parent_fails() {
219        let tmp = tempfile::tempdir().unwrap();
220        let log = OpLog::open(tmp.path()).unwrap();
221        let (op_a, t_a) = add_fac();
222        let head_a = apply(&log, None, op_a, t_a).unwrap();
223        let merge = Operation::new(
224            OperationKind::Merge { resolved: 0 },
225            [head_a.op_id.clone(), "ghost".into()],
226        );
227        let t = StageTransition::Merge { entries: Default::default() };
228        let err = apply(&log, Some(&head_a.op_id), merge, t).unwrap_err();
229        match err {
230            ApplyError::UnknownMergeParent(id) => {
231                assert_eq!(id, "ghost");
232            }
233            other => panic!("expected UnknownMergeParent, got {other:?}"),
234        }
235    }
236
237    #[test]
238    fn three_parent_op_is_stale() {
239        // Catch-all arm: any arity > 2 is rejected.
240        let tmp = tempfile::tempdir().unwrap();
241        let log = OpLog::open(tmp.path()).unwrap();
242        let (op_a, t_a) = add_fac();
243        let head_a = apply(&log, None, op_a, t_a).unwrap();
244
245        // Hand-construct an Operation with three parents (Operation::new
246        // dedups but accepts arbitrary count).
247        let weird = Operation::new(
248            OperationKind::ModifyBody {
249                sig_id: "fac".into(),
250                from_stage_id: "s1".into(),
251                to_stage_id: "s2".into(),
252                from_budget: None,
253                to_budget: None,
254            },
255            [head_a.op_id.clone(), "p2".into(), "p3".into()],
256        );
257        let t = StageTransition::Replace {
258            sig_id: "fac".into(), from: "s1".into(), to: "s2".into(),
259        };
260        let err = apply(&log, Some(&head_a.op_id), weird, t).unwrap_err();
261        assert!(matches!(err, ApplyError::StaleParent { .. }));
262    }
263
264    #[test]
265    fn single_parent_against_empty_head_is_stale() {
266        // Catch-all arm: 1 parent + None head is rejected.
267        let tmp = tempfile::tempdir().unwrap();
268        let log = OpLog::open(tmp.path()).unwrap();
269        let modify = Operation::new(
270            OperationKind::ModifyBody {
271                sig_id: "fac".into(),
272                from_stage_id: "s1".into(),
273                to_stage_id: "s2".into(),
274                from_budget: None,
275                to_budget: None,
276            },
277            ["claimed-parent".into()],
278        );
279        let t = StageTransition::Replace {
280            sig_id: "fac".into(), from: "s1".into(), to: "s2".into(),
281        };
282        let err = apply(&log, None, modify, t).unwrap_err();
283        match err {
284            ApplyError::StaleParent { expected, op_parents } => {
285                assert_eq!(expected, None);
286                assert_eq!(op_parents, vec!["claimed-parent".to_string()]);
287            }
288            other => panic!("expected StaleParent, got {other:?}"),
289        }
290    }
291
292    #[test]
293    fn self_merge_is_stale() {
294        // Direct deserialization could produce parents = [h, h] which
295        // bypasses Operation::new's dedup. The gate must still reject.
296        let tmp = tempfile::tempdir().unwrap();
297        let log = OpLog::open(tmp.path()).unwrap();
298        let (op_a, t_a) = add_fac();
299        let head_a = apply(&log, None, op_a, t_a).unwrap();
300
301        // Construct an Operation with two equal parents *without* going
302        // through `new` (which dedups). Use serde_json round-trip.
303        let json = serde_json::json!({
304            "op": "merge",
305            "resolved": 0,
306            "parents": [head_a.op_id.clone(), head_a.op_id.clone()],
307        });
308        let weird: Operation = serde_json::from_value(json).unwrap();
309        assert_eq!(weird.parents.len(), 2,
310            "round-trip should preserve duplicates if Operation deserialization doesn't dedup");
311        let t = StageTransition::Merge { entries: Default::default() };
312        let err = apply(&log, Some(&head_a.op_id), weird, t).unwrap_err();
313        assert!(matches!(err, ApplyError::StaleParent { .. }));
314    }
315}