Skip to main content

lex_vcs/
gate.rs

1//! Write-time type-check gate (#130).
2//!
3//! Wraps [`apply`](crate::apply::apply) with a type-checker pass.
4//! When this gate is the only path that advances a branch head,
5//! the store's invariant becomes "every accepted operation
6//! produces a program that typechecks." The cascading-breakage
7//! failure mode that breaks agentic workflows — agent A commits a
8//! typing-broken stage, agent B reads it and builds work
9//! assuming the broken stage, hours pass, CI catches the bug —
10//! becomes impossible by construction.
11//!
12//! Effect violations surface here too: `lex-types::check_program`
13//! reports an undeclared-effect call as a `TypeError` variant, so
14//! a single rejection envelope covers both type and effect bugs.
15//!
16//! ## Performance
17//!
18//! The gate runs `lex_types::check_program` against the *candidate*
19//! program — the sequence of `Stage`s that would exist after the
20//! op is applied. Computing that sequence is the caller's job
21//! (typically `Store::publish_program`, which already has it in
22//! memory). The gate itself does not load anything from disk; it
23//! just runs the type checker.
24//!
25//! Performance budget from #130: <50 ms p99 for a single-function
26//! op on a 1000-stage store. This module doesn't validate that —
27//! the budget belongs to the caller's candidate-assembly path
28//! plus `lex_types::check_program`. We'll measure once the gate
29//! is wired into a real `Store::publish_program` flow.
30
31use lex_ast::Stage;
32use lex_types::{check_program, TypeError};
33
34use crate::apply::{apply, ApplyError, NewHead};
35use crate::op_log::OpLog;
36use crate::operation::{OpId, Operation, StageTransition};
37
38#[derive(Debug, thiserror::Error)]
39pub enum GateError {
40    /// The operation's parent or merge structure is wrong.
41    /// Pass-through from [`ApplyError`]; same shape so callers
42    /// already handling stale-parent / unknown-merge-parent on the
43    /// raw apply path can keep their existing match arms.
44    #[error(transparent)]
45    Apply(#[from] ApplyError),
46    /// The candidate program — i.e. the state that would exist
47    /// after applying the op — doesn't typecheck. The op is *not*
48    /// persisted; the branch head is unchanged.
49    ///
50    /// `op_id` is the would-be op_id (computed before the apply
51    /// path persisted anything). Lets callers correlate the
52    /// rejection with the op they submitted, even though no
53    /// `<root>/ops/<op_id>.json` file exists.
54    ///
55    /// `errors` is the structured envelope `lex check` already
56    /// emits. Effect violations show up here as a `TypeError`
57    /// variant; the gate doesn't model them as a separate kind
58    /// because the type checker doesn't either.
59    #[error("type errors after applying op {op_id}: {} error(s)", errors.len())]
60    TypeError {
61        op_id: OpId,
62        errors: Vec<TypeError>,
63    },
64}
65
66/// Apply an operation only if the resulting candidate program
67/// typechecks. Otherwise return [`GateError::TypeError`] with the
68/// structured error envelope; nothing is persisted.
69///
70/// `candidate` is the sequence of `Stage`s that would exist after
71/// the op is applied. The caller computes it — typically by
72/// applying the op's [`StageTransition`] to the program it just
73/// loaded from source. The gate does not assemble it from the
74/// store; the cost of "load every stage" is on the caller, where
75/// it can be amortized across the full publish flow.
76pub fn check_and_apply(
77    op_log: &OpLog,
78    head_op: Option<&OpId>,
79    op: Operation,
80    transition: StageTransition,
81    candidate: &[Stage],
82) -> Result<NewHead, GateError> {
83    if let Err(errors) = check_program(candidate) {
84        return Err(GateError::TypeError {
85            op_id: op.op_id(),
86            errors,
87        });
88    }
89    Ok(apply(op_log, head_op, op, transition)?)
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::operation::OperationKind;
96    use std::collections::BTreeSet;
97
98    fn fac_op_and_transition() -> (Operation, StageTransition) {
99        let op = Operation::new(
100            OperationKind::AddFunction {
101                sig_id: "fac".into(),
102                stage_id: "s1".into(),
103                effects: BTreeSet::new(),
104                budget_cost: None,
105                in_file: None,
106            },
107            [],
108        );
109        let t = StageTransition::Create {
110            sig_id: "fac".into(),
111            stage_id: "s1".into(),
112        };
113        (op, t)
114    }
115
116    fn parse(src: &str) -> Vec<Stage> {
117        let prog = lex_syntax::parse_source(src).expect("parse");
118        lex_ast::canonicalize_program(&prog)
119    }
120
121    #[test]
122    fn clean_program_is_accepted_and_persisted() {
123        let tmp = tempfile::tempdir().unwrap();
124        let log = OpLog::open(tmp.path()).unwrap();
125        let candidate = parse(
126            "fn factorial(n :: Int) -> Int { match n { 0 => 1, _ => n * factorial(n - 1) } }\n",
127        );
128        let (op, t) = fac_op_and_transition();
129        let head = check_and_apply(&log, None, op, t, &candidate).unwrap();
130        assert!(log.get(&head.op_id).unwrap().is_some());
131    }
132
133    #[test]
134    fn type_error_is_rejected_and_nothing_persisted() {
135        let tmp = tempfile::tempdir().unwrap();
136        let log = OpLog::open(tmp.path()).unwrap();
137        // `not_defined` is referenced but never declared — the type
138        // checker emits an `UnknownIdentifier` error.
139        let candidate =
140            parse("fn broken(x :: Int) -> Int { not_defined(x) }\n");
141        let (op, t) = fac_op_and_transition();
142        let expected_op_id = op.op_id();
143        let err = check_and_apply(&log, None, op, t, &candidate)
144            .expect_err("expected TypeError");
145        match err {
146            GateError::TypeError { op_id, errors } => {
147                assert_eq!(op_id, expected_op_id);
148                assert!(!errors.is_empty(), "expected at least one TypeError");
149            }
150            other => panic!("expected TypeError, got {other:?}"),
151        }
152        // The op record was NOT persisted on the rejection path —
153        // the store's "always-valid HEAD" invariant holds.
154        assert!(log.get(&expected_op_id).unwrap().is_none());
155    }
156
157    #[test]
158    fn arity_mismatch_is_rejected() {
159        // Calling `add` with one arg when it takes two should
160        // produce an `ArityMismatch`. Verifies that several
161        // `TypeError` variants flow through the gate, not just
162        // unknown-identifier.
163        let tmp = tempfile::tempdir().unwrap();
164        let log = OpLog::open(tmp.path()).unwrap();
165        let candidate = parse(
166            "fn add(x :: Int, y :: Int) -> Int { x + y }\nfn caller() -> Int { add(1) }\n",
167        );
168        let (op, t) = fac_op_and_transition();
169        let err = check_and_apply(&log, None, op, t, &candidate)
170            .expect_err("expected TypeError");
171        assert!(matches!(err, GateError::TypeError { .. }));
172    }
173
174    #[test]
175    fn parent_check_still_runs_when_program_is_clean() {
176        // Pass a clean candidate but a stale-parent op. The gate
177        // shouldn't accept it just because typechecking passed —
178        // structural rejection still wins.
179        let tmp = tempfile::tempdir().unwrap();
180        let log = OpLog::open(tmp.path()).unwrap();
181        let candidate = parse(
182            "fn factorial(n :: Int) -> Int { match n { 0 => 1, _ => n * factorial(n - 1) } }\n",
183        );
184        // First op lands cleanly so head_op is set.
185        let (op1, t1) = fac_op_and_transition();
186        let head1 = check_and_apply(&log, None, op1, t1, &candidate).unwrap();
187        // Second op declares a wrong parent.
188        let bogus = Operation::new(
189            OperationKind::ModifyBody {
190                sig_id: "fac".into(),
191                from_stage_id: "s1".into(),
192                to_stage_id: "s2".into(),
193                from_budget: None,
194                to_budget: None,
195            },
196            ["someone-else".into()],
197        );
198        let t = StageTransition::Replace {
199            sig_id: "fac".into(),
200            from: "s1".into(),
201            to: "s2".into(),
202        };
203        let err = check_and_apply(&log, Some(&head1.op_id), bogus, t, &candidate)
204            .expect_err("expected Apply(StaleParent)");
205        match err {
206            GateError::Apply(ApplyError::StaleParent { .. }) => {}
207            other => panic!("expected Apply(StaleParent), got {other:?}"),
208        }
209    }
210}