Skip to main content

kian_core/
invariants.rs

1//! The six semantic invariants (DESIGN §2.3) plus NoHalfTerminated, as
2//! checkable predicates over event streams/projections, and the resident
3//! assertion-macro family for `debug_assert!`s and test assertions.
4//!
5//! Each predicate checks the invariant's **event-stream-visible**
6//! consequence; the store- and orchestrator-owned halves (CAS fencing,
7//! inbox rebuild, lease TTL) are verified in their own crates.
8//! Predicates are linear scans — safe to keep resident as debug_asserts.
9
10use crate::events::{EndReason, Event, EventKind};
11use crate::model::Epoch;
12use crate::state::{ProjectionError, SessionState, project};
13
14/// A violated invariant, named per predicate. Resident predicates return
15/// these so `debug_assert!`s and test failures name the exact invariant.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
17pub enum InvariantViolation {
18    /// The stream does not project at all; no invariant can be stated
19    /// over it.
20    #[error(transparent)]
21    NotProjectable(#[from] ProjectionError),
22    /// Invariant 1: a reply arrived without its persisted request, or a
23    /// tool result without its logged call, at event index `at`.
24    #[error("invariant 1 (durable before execute) violated at event {at}: {what}")]
25    DurableBeforeExecute { at: usize, what: &'static str },
26    /// Invariant 2: a later snapshot is not an append-only extension of
27    /// the earlier one — work was lost.
28    #[error("invariant 2 (no lost work) violated: streams diverge at index {at}")]
29    EventsNotAppendOnly { at: usize },
30    /// Invariant 3: a turn boundary landed inside an in-flight provider
31    /// turn (between `step/request` and its `assistant/message`).
32    #[error("invariant 3 (promote only at safe boundaries) violated at event {at}")]
33    PromoteInsideProviderTurn { at: usize },
34    /// Invariant 4: rewriting the fencing epochs changed the projected
35    /// state — state must depend on event kinds, never on drain identity.
36    #[error(
37        "invariant 4 (drain has no durable identity) violated: {with_epochs:?} vs {without_epochs:?}"
38    )]
39    DrainIdentityRelevant {
40        with_epochs: SessionState,
41        without_epochs: SessionState,
42    },
43    /// Invariant 5: an interrupted/failed end write arrived while no
44    /// drain owned the session.
45    #[error("invariant 5 (interrupt targets the active chain) violated at event {at}")]
46    InterruptFromInactiveChain { at: usize },
47    /// Invariant 6: drain activity after an aborted end without a new
48    /// claim taking ownership.
49    #[error("invariant 6 (settle on abort) violated at event {at}: work without a new claim")]
50    WorkWithoutReclaim { at: usize },
51    /// NoHalfTerminated: a terminal projection must be produced by
52    /// exactly one terminal `session/ended` event, with nothing after it.
53    #[error(
54        "NoHalfTerminated violated: terminal projection produced by {terminal_end_writes} terminal end writes"
55    )]
56    TerminalNotProducedByExactlyOneEnd { terminal_end_writes: usize },
57}
58
59/// **NoHalfTerminated** (constraint 4): a terminal projection is produced
60/// by exactly one `session/ended` event — the last event of the stream —
61/// and no event follows it. By construction (the atomic end write), the
62/// projection is terminal *exactly when* the last event is a terminal
63/// end write; this predicate keeps that checkable.
64pub fn no_half_terminated(events: &[Event]) -> Result<(), InvariantViolation> {
65    let state = project(events)?;
66    let terminal_ends = events
67        .iter()
68        .filter(|e| {
69            matches!(
70                e.kind,
71                EventKind::SessionEnded {
72                    reason: EndReason::Completed | EndReason::Cancelled
73                }
74            )
75        })
76        .count();
77    let ok = match state {
78        SessionState::Completed | SessionState::Cancelled => {
79            terminal_ends == 1
80                && events.last().is_some_and(|e| {
81                    matches!(
82                        e.kind,
83                        EventKind::SessionEnded {
84                            reason: EndReason::Completed | EndReason::Cancelled
85                        }
86                    )
87                })
88        }
89        _ => terminal_ends == 0,
90    };
91    if ok {
92        Ok(())
93    } else {
94        Err(InvariantViolation::TerminalNotProducedByExactlyOneEnd {
95            terminal_end_writes: terminal_ends,
96        })
97    }
98}
99
100/// Invariant 1 (**durable before execute**): every `assistant/message`
101/// replies to a persisted `step/request` (persist-what-you-send, A2), and
102/// every `tool/result` answers a logged `tool/call`. Positional matching
103/// over opaque payloads; resolution (a call with no result yet) is not a
104/// violation — the stream may be mid-flight or crashed.
105pub fn durable_before_execute(events: &[Event]) -> Result<(), InvariantViolation> {
106    let mut open_request = false;
107    let mut pending_calls: u32 = 0;
108    for (at, ev) in events.iter().enumerate() {
109        match ev.kind {
110            EventKind::StepRequest => open_request = true,
111            EventKind::AssistantMessage => {
112                if !open_request {
113                    return Err(InvariantViolation::DurableBeforeExecute {
114                        at,
115                        what: "assistant/message without a preceding step/request",
116                    });
117                }
118                open_request = false;
119            }
120            EventKind::ToolCall => pending_calls += 1,
121            EventKind::ToolResult => {
122                if pending_calls == 0 {
123                    return Err(InvariantViolation::DurableBeforeExecute {
124                        at,
125                        what: "tool/result without a preceding tool/call",
126                    });
127                }
128                pending_calls -= 1;
129            }
130            _ => {}
131        }
132    }
133    Ok(())
134}
135
136/// Invariant 2 (**wake is advisory / NoLostWork**), event-stream side:
137/// history is append-only, so a restart snapshot (`after`) must extend
138/// the pre-crash snapshot (`before`) as a prefix. The inbox-rebuild half
139/// is owned by the store/orchestrator.
140pub fn no_lost_work(before: &[Event], after: &[Event]) -> Result<(), InvariantViolation> {
141    for (at, (b, a)) in before.iter().zip(after.iter()).enumerate() {
142        if b != a {
143            return Err(InvariantViolation::EventsNotAppendOnly { at });
144        }
145    }
146    if before.len() > after.len() {
147        return Err(InvariantViolation::EventsNotAppendOnly { at: after.len() });
148    }
149    Ok(())
150}
151
152/// Invariant 3 (**promote only at safe boundaries**): no `turn/start` or
153/// `turn/end` may land inside an in-flight provider turn — the window
154/// opened by `step/request` and closed by its `assistant/message`. An
155/// ownership change (`drain/claimed`, takeover after a crash) or a
156/// session end legitimately closes an abandoned window; slot fallbacks,
157/// compaction and tool traffic are mid-turn activity by design.
158pub fn promote_at_safe_boundaries(events: &[Event]) -> Result<(), InvariantViolation> {
159    let mut in_provider_turn = false;
160    for (at, ev) in events.iter().enumerate() {
161        match ev.kind {
162            EventKind::StepRequest => in_provider_turn = true,
163            EventKind::AssistantMessage
164            | EventKind::DrainClaimed
165            | EventKind::SessionEnded { .. } => in_provider_turn = false,
166            EventKind::TurnStart | EventKind::TurnEnd if in_provider_turn => {
167                return Err(InvariantViolation::PromoteInsideProviderTurn { at });
168            }
169            _ => {}
170        }
171    }
172    Ok(())
173}
174
175/// Invariant 4 (**drain has no durable identity**): the projection must
176/// be a function of event kinds alone — rewriting every fencing epoch to
177/// arbitrary values must not change the projected state.
178pub fn drain_has_no_durable_identity(events: &[Event]) -> Result<(), InvariantViolation> {
179    let base = project(events)?;
180    let rewritten: Vec<Event> = events
181        .iter()
182        .enumerate()
183        .map(|(i, ev)| {
184            let mut e = ev.clone();
185            // arbitrary, deliberately non-monotone values
186            e.epoch = Epoch((i as u64 * 2_654_435_761) % 97 + 1);
187            e
188        })
189        .collect();
190    let other = project(&rewritten)?;
191    if base == other {
192        Ok(())
193    } else {
194        Err(InvariantViolation::DrainIdentityRelevant {
195            with_epochs: base,
196            without_epochs: other,
197        })
198    }
199}
200
201/// Invariant 5 (**interrupt targets only the active ownership chain**):
202/// an `interrupted`/`failed` end write may only arrive while a drain
203/// holds the session (since the last claim). Honesty (`interrupted ≠
204/// failed`) is carried structurally by [`EndReason`].
205pub fn interrupt_targets_active_chain(events: &[Event]) -> Result<(), InvariantViolation> {
206    let mut in_claim = false;
207    for (at, ev) in events.iter().enumerate() {
208        match ev.kind {
209            EventKind::DrainClaimed => in_claim = true,
210            EventKind::SessionEnded { reason } => {
211                if matches!(reason, EndReason::Interrupted | EndReason::Failed) && !in_claim {
212                    return Err(InvariantViolation::InterruptFromInactiveChain { at });
213                }
214                in_claim = false;
215            }
216            _ => {}
217        }
218    }
219    Ok(())
220}
221
222/// Invariant 6 (**settle on abort**): after an `interrupted`/`failed`
223/// end, no drain activity may appear until a new claim has taken
224/// ownership. `input/admitted` is a control-plane inbox write, not work,
225/// and stays legal in an idle (aborted) session.
226pub fn settle_on_abort(events: &[Event]) -> Result<(), InvariantViolation> {
227    use crate::state::TransitionTrigger;
228    let mut aborted = false;
229    for (at, ev) in events.iter().enumerate() {
230        match TransitionTrigger::from_event_kind(&ev.kind) {
231            TransitionTrigger::Claimed => aborted = false,
232            TransitionTrigger::Ended(reason) => {
233                aborted = matches!(reason, EndReason::Interrupted | EndReason::Failed);
234            }
235            TransitionTrigger::DrainActivity if aborted => {
236                return Err(InvariantViolation::WorkWithoutReclaim { at });
237            }
238            _ => {}
239        }
240    }
241    Ok(())
242}
243
244/// Runs the full resident assertion family over one event stream:
245/// projection legality, NoHalfTerminated and every single-stream
246/// invariant predicate. Panics with the violated invariant's name — for
247/// tests and for hard assertions in debug tooling.
248#[macro_export]
249macro_rules! assert_session_invariants {
250    ($events:expr $(,)?) => {{
251        let events: &[$crate::events::Event] = $events;
252        $crate::invariants::no_half_terminated(events)
253            .unwrap_or_else(|v| panic!("session invariants: {v}"));
254        $crate::invariants::durable_before_execute(events)
255            .unwrap_or_else(|v| panic!("session invariants: {v}"));
256        $crate::invariants::promote_at_safe_boundaries(events)
257            .unwrap_or_else(|v| panic!("session invariants: {v}"));
258        $crate::invariants::drain_has_no_durable_identity(events)
259            .unwrap_or_else(|v| panic!("session invariants: {v}"));
260        $crate::invariants::interrupt_targets_active_chain(events)
261            .unwrap_or_else(|v| panic!("session invariants: {v}"));
262        $crate::invariants::settle_on_abort(events)
263            .unwrap_or_else(|v| panic!("session invariants: {v}"));
264    }};
265}
266
267/// [`assert_session_invariants!`] gated to debug builds — the resident
268/// `debug_assert!` form intended for drain/store code paths.
269#[macro_export]
270macro_rules! debug_assert_session_invariants {
271    ($events:expr $(,)?) => {
272        if cfg!(debug_assertions) {
273            $crate::assert_session_invariants!($events);
274        }
275    };
276}
277
278#[cfg(test)]
279mod tests {
280    use crate::events::{EndReason, EventKind};
281    use crate::state::test_support::{StreamBuilder, legal_stream};
282
283    use super::{
284        InvariantViolation, drain_has_no_durable_identity, durable_before_execute,
285        interrupt_targets_active_chain, no_half_terminated, no_lost_work,
286        promote_at_safe_boundaries, settle_on_abort,
287    };
288
289    #[test]
290    fn all_predicates_hold_on_generated_legal_streams_and_prefixes() {
291        for seed in 1..=40u64 {
292            let events = legal_stream(seed, 60);
293            for n in 1..=events.len() {
294                let prefix = &events[..n];
295                no_half_terminated(prefix)
296                    .unwrap_or_else(|v| panic!("seed {seed} prefix {n} no_half_terminated: {v}"));
297                durable_before_execute(prefix)
298                    .unwrap_or_else(|v| panic!("seed {seed} prefix {n}: {v}"));
299                promote_at_safe_boundaries(prefix)
300                    .unwrap_or_else(|v| panic!("seed {seed} prefix {n}: {v}"));
301                drain_has_no_durable_identity(prefix)
302                    .unwrap_or_else(|v| panic!("seed {seed} prefix {n}: {v}"));
303                interrupt_targets_active_chain(prefix)
304                    .unwrap_or_else(|v| panic!("seed {seed} prefix {n}: {v}"));
305                settle_on_abort(prefix).unwrap_or_else(|v| panic!("seed {seed} prefix {n}: {v}"));
306            }
307        }
308    }
309
310    #[test]
311    fn no_half_terminated_accepts_terminal_stream_with_single_end() {
312        let mut b = StreamBuilder::new(101);
313        b.push(EventKind::SessionCreated)
314            .claim()
315            .push(EventKind::StepRequest)
316            .push(EventKind::AssistantMessage)
317            .push(EventKind::SessionEnded {
318                reason: EndReason::Completed,
319            });
320        assert_eq!(no_half_terminated(&b.build()), Ok(()));
321    }
322
323    /// A stream with a second terminal end write cannot project cleanly;
324    /// the predicate must surface a violation either way — that is the
325    /// point of keeping it resident.
326    #[test]
327    fn no_half_terminated_rejects_second_terminal_end() {
328        let mut b = StreamBuilder::new(102);
329        b.push(EventKind::SessionCreated)
330            .claim()
331            .push(EventKind::SessionEnded {
332                reason: EndReason::Completed,
333            })
334            .push(EventKind::SessionEnded {
335                reason: EndReason::Cancelled,
336            });
337        assert!(no_half_terminated(&b.build()).is_err());
338    }
339
340    #[test]
341    fn durable_before_execute_flags_reply_without_persisted_request() {
342        let mut b = StreamBuilder::new(103);
343        b.push(EventKind::SessionCreated)
344            .claim()
345            .push(EventKind::AssistantMessage); // reply with no step/request
346        assert_eq!(
347            durable_before_execute(&b.build()),
348            Err(InvariantViolation::DurableBeforeExecute {
349                at: 2,
350                what: "assistant/message without a preceding step/request",
351            })
352        );
353    }
354
355    #[test]
356    fn durable_before_execute_flags_orphan_tool_result() {
357        let mut b = StreamBuilder::new(104);
358        b.push(EventKind::SessionCreated)
359            .claim()
360            .push(EventKind::ToolResult); // result with no logged call
361        assert_eq!(
362            durable_before_execute(&b.build()),
363            Err(InvariantViolation::DurableBeforeExecute {
364                at: 2,
365                what: "tool/result without a preceding tool/call",
366            })
367        );
368    }
369
370    #[test]
371    fn no_lost_work_accepts_prefix_growth_and_flags_dropped_event() {
372        let events = legal_stream(105, 40);
373        let before = events[..events.len() / 2].to_vec();
374        assert_eq!(no_lost_work(&before, &events), Ok(()));
375
376        // a restart that "loses" a middle event is a corruption
377        let mut holed = events.clone();
378        holed.remove(2);
379        assert_eq!(
380            no_lost_work(&events, &holed),
381            Err(InvariantViolation::EventsNotAppendOnly { at: 2 })
382        );
383    }
384
385    /// The stream is projection-legal here (turn/start is state-preserving
386    /// in running) — only the invariant predicate catches the promote
387    /// violation. This is why the predicates exist beyond the table.
388    #[test]
389    fn promote_at_safe_boundaries_flags_turn_start_inside_provider_turn() {
390        let mut b = StreamBuilder::new(106);
391        b.push(EventKind::SessionCreated)
392            .claim()
393            .push(EventKind::StepRequest)
394            .push(EventKind::TurnStart) // inside the provider-turn window
395            .push(EventKind::AssistantMessage);
396        assert_eq!(
397            promote_at_safe_boundaries(&b.build()),
398            Err(InvariantViolation::PromoteInsideProviderTurn { at: 3 })
399        );
400    }
401
402    /// After a crash mid-provider-turn, a takeover claim legitimately
403    /// appears inside the abandoned window: ownership change closes the
404    /// window; only turn boundaries inside a live window are violations.
405    #[test]
406    fn promote_at_safe_boundaries_accepts_takeover_closing_the_window() {
407        let mut b = StreamBuilder::new(107);
408        b.push(EventKind::SessionCreated)
409            .claim()
410            .push(EventKind::StepRequest)
411            .claim() // crash + takeover
412            .push(EventKind::StepRequest)
413            .push(EventKind::AssistantMessage);
414        assert_eq!(promote_at_safe_boundaries(&b.build()), Ok(()));
415    }
416
417    #[test]
418    fn drain_identity_is_irrelevant_under_epoch_rewrites() {
419        let events = legal_stream(108, 50);
420        assert_eq!(drain_has_no_durable_identity(&events), Ok(()));
421    }
422
423    #[test]
424    fn interrupt_targets_active_chain_flags_end_without_claim() {
425        let mut b = StreamBuilder::new(109);
426        b.push(EventKind::SessionCreated)
427            .push(EventKind::SessionEnded {
428                reason: EndReason::Interrupted,
429            });
430        assert_eq!(
431            interrupt_targets_active_chain(&b.build()),
432            Err(InvariantViolation::InterruptFromInactiveChain { at: 1 })
433        );
434    }
435
436    #[test]
437    fn settle_on_abort_flags_work_before_reclaim() {
438        let mut b = StreamBuilder::new(110);
439        b.push(EventKind::SessionCreated)
440            .claim()
441            .push(EventKind::SessionEnded {
442                reason: EndReason::Interrupted,
443            })
444            .push(EventKind::TurnStart); // work without a new claim
445        assert_eq!(
446            settle_on_abort(&b.build()),
447            Err(InvariantViolation::WorkWithoutReclaim { at: 3 })
448        );
449    }
450
451    #[test]
452    fn assert_session_invariants_macro_passes_on_legal_stream() {
453        let events = legal_stream(111, 40);
454        crate::assert_session_invariants!(&events);
455    }
456
457    #[test]
458    #[should_panic(expected = "durable before execute")]
459    fn assert_session_invariants_macro_panics_on_violation() {
460        let mut b = StreamBuilder::new(112);
461        b.push(EventKind::SessionCreated)
462            .claim()
463            .push(EventKind::ToolResult);
464        crate::assert_session_invariants!(&b.build());
465    }
466
467    #[test]
468    fn debug_assert_macro_compiles_and_is_silent() {
469        // Runs the full family under debug builds; nothing to observe on
470        // a legal stream. (Under release the call compiles away.)
471        let events = legal_stream(113, 30);
472        crate::debug_assert_session_invariants!(&events);
473        crate::assert_session_invariants!(&events);
474    }
475}