lion-core 0.3.0

Lion microkernel — production types, state machine, and kernel API
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
// Copyright (C) 2026 HaiyangLi
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Lion Step Kernel Operations
//!
//! Corresponds to: Lion/Step/KernelOp.lean
//!
//! Kernel-internal operations (trusted TCB).

use crate::state::State;
use crate::types::{ActorId, ThreadId, WorkflowId};

use super::{KernelOpError, StepError};

/// Kernel-internal operations (no external trigger)
///
/// Corresponds to Lean: `inductive KernelOp`
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use = "kernel operations must be executed"]
pub enum KernelOp {
    /// Deliver one message to actor
    ///
    /// Corresponds to Lean: `| route_one (dst : ActorId)`
    RouteOne {
        /// Destination actor to receive the message
        dst: ActorId,
    },

    /// Advance workflow
    ///
    /// Corresponds to Lean: `| workflow_tick (w : WorkflowId)`
    WorkflowTick {
        /// Workflow to advance
        wid: WorkflowId,
    },

    /// Increment global time
    ///
    /// Corresponds to Lean: `| time_tick`
    TimeTick,

    /// Unblock actor waiting to send
    ///
    /// Corresponds to Lean: `| unblock_send (dst : ActorId)`
    UnblockSend {
        /// Destination actor to unblock
        dst: ActorId,
    },

    /// Context switch between threads
    ///
    /// Corresponds to Lean: `| thread_switch (from_ to_ : ThreadId)`
    ThreadSwitch {
        /// Thread to switch from
        from: ThreadId,
        /// Thread to switch to
        to: ThreadId,
    },
}

impl KernelOp {
    /// Execute the kernel operation
    ///
    /// Corresponds to Lean: `def KernelExecInternal`
    ///
    /// Each operation modifies only its designated state component:
    /// - route_one: moves message from pending to mailbox
    /// - time_tick: increments global time
    /// - workflow_tick: advances workflow state
    /// - unblock_send: clears blockedOn for actor
    ///
    /// # Errors
    ///
    /// Returns `StepError::ActorNotFound` if the destination actor does not exist (RouteOne, UnblockSend).
    /// Returns `StepError::KernelOpFailed` if the actor has no pending messages or its mailbox is full (RouteOne).
    /// Returns `StepError::KernelOpFailed` if the workflow is not found or is not running (WorkflowTick).
    pub fn execute(&self, state: &State) -> Result<State, StepError> {
        match self {
            KernelOp::RouteOne { dst } => execute_route_one(state, *dst),
            KernelOp::WorkflowTick { wid } => execute_workflow_tick(state, *wid),
            KernelOp::TimeTick => execute_time_tick(state),
            KernelOp::UnblockSend { dst } => execute_unblock_send(state, *dst),
            KernelOp::ThreadSwitch { from, to } => execute_thread_switch(state, *from, *to),
        }
    }

    /// Execute the kernel operation (mutating version).
    ///
    /// Same validation as `execute` but modifies `&mut State` in place.
    pub fn execute_mut(&self, state: &mut State) -> Result<(), StepError> {
        match self {
            KernelOp::RouteOne { dst } => execute_route_one_mut(state, *dst),
            KernelOp::WorkflowTick { wid } => execute_workflow_tick_mut(state, *wid),
            KernelOp::TimeTick => execute_time_tick_mut(state),
            KernelOp::UnblockSend { dst } => execute_unblock_send_mut(state, *dst),
            KernelOp::ThreadSwitch { from, to } => execute_thread_switch_mut(state, *from, *to),
        }
    }
}

/// Execute route_one
///
/// Move first message from pending to mailbox (if pending non-empty).
/// Scheduler ensures mailbox doesn't exceed capacity.
///
/// Corresponds to Lean: `KernelExecInternal .route_one`
fn execute_route_one(state: &State, dst: ActorId) -> Result<State, StepError> {
    let actor = state.get_actor(dst).ok_or(StepError::ActorNotFound(dst))?;

    // Check pending queue has messages
    if actor.pending_len() == 0 {
        return Err(StepError::KernelOpFailed(
            KernelOpError::NoPendingMessages { dst },
        ));
    }

    // Check mailbox has space
    if actor.mailbox_len() >= actor.capacity() {
        return Err(StepError::KernelOpFailed(
            KernelOpError::MailboxAtCapacity { dst },
        ));
    }

    // Deliver message
    let mut new_state = state.clone();
    if let Some(actor) = new_state.get_actor_mut(dst) {
        let _ = actor.deliver_mut();
    }

    Ok(new_state)
}

/// Execute workflow_tick
///
/// Advance workflow state (must preserve has-work invariant).
///
/// Corresponds to Lean: `KernelExecInternal .workflow_tick`
///
/// PERF NOTE: Currently a no-op that validates preconditions and clones state.
/// The actual workflow advancement is abstracted in the formal model. A concrete
/// implementation would advance node states based on dependencies and avoid the
/// identity clone. The clone is retained for API uniformity with other kernel ops.
fn execute_workflow_tick(state: &State, wid: WorkflowId) -> Result<State, StepError> {
    let workflow = state.get_workflow(wid).ok_or(StepError::KernelOpFailed(
        KernelOpError::WorkflowNotFound { wid },
    ))?;

    // Check workflow is running
    if !workflow.is_running() {
        return Err(StepError::KernelOpFailed(
            KernelOpError::WorkflowNotRunning { wid },
        ));
    }

    // Abstract tick: validates preconditions, returns state unchanged.
    // A concrete implementation would advance node states based on dependencies.
    Ok(state.clone())
}

/// Execute time_tick
///
/// Increment time and kernel time.
///
/// Corresponds to Lean: `KernelExecInternal .time_tick`
fn execute_time_tick(state: &State) -> Result<State, StepError> {
    let mut new_state = state.clone();
    new_state
        .tick()
        .map_err(|e| StepError::KernelOpFailed(KernelOpError::CounterOverflow(e.to_string())))?;
    Ok(new_state)
}

/// Execute unblock_send
///
/// Clear blockedOn for the destination actor.
///
/// Corresponds to Lean: `KernelExecInternal .unblock_send`
fn execute_unblock_send(state: &State, dst: ActorId) -> Result<State, StepError> {
    let _actor = state.get_actor(dst).ok_or(StepError::ActorNotFound(dst))?;

    let mut new_state = state.clone();
    if let Some(actor) = new_state.get_actor_mut(dst) {
        actor.unblock_mut();
    }

    Ok(new_state)
}

/// Execute thread_switch
///
/// Context switch between threads: save `from` registers, restore `to` and
/// make it running. Requires threads/scheduler in State (Phase 3).
///
/// Corresponds to Lean: `KernelExecInternal (.thread_switch from_ to_)`
///
/// NOTE: State does not yet include threads/scheduler fields (Phase 3 extension).
/// This stub returns an error until the State type is extended.
fn execute_thread_switch(
    _state: &State,
    _from: ThreadId,
    _to: ThreadId,
) -> Result<State, StepError> {
    Err(StepError::KernelOpFailed(KernelOpError::NotImplemented {
        operation: "thread_switch",
    }))
}

// ============== MUTATING VARIANTS ==============

fn execute_route_one_mut(state: &mut State, dst: ActorId) -> Result<(), StepError> {
    let actor = state.get_actor(dst).ok_or(StepError::ActorNotFound(dst))?;

    if actor.pending_len() == 0 {
        return Err(StepError::KernelOpFailed(
            KernelOpError::NoPendingMessages { dst },
        ));
    }

    if actor.mailbox_len() >= actor.capacity() {
        return Err(StepError::KernelOpFailed(
            KernelOpError::MailboxAtCapacity { dst },
        ));
    }

    if let Some(actor) = state.get_actor_mut(dst) {
        let _ = actor.deliver_mut();
    }

    Ok(())
}

fn execute_workflow_tick_mut(state: &mut State, wid: WorkflowId) -> Result<(), StepError> {
    let workflow = state.get_workflow(wid).ok_or(StepError::KernelOpFailed(
        KernelOpError::WorkflowNotFound { wid },
    ))?;

    if !workflow.is_running() {
        return Err(StepError::KernelOpFailed(
            KernelOpError::WorkflowNotRunning { wid },
        ));
    }

    // Abstract tick: validates preconditions, state unchanged.
    Ok(())
}

fn execute_time_tick_mut(state: &mut State) -> Result<(), StepError> {
    state
        .tick()
        .map_err(|e| StepError::KernelOpFailed(KernelOpError::CounterOverflow(e.to_string())))?;
    Ok(())
}

fn execute_unblock_send_mut(state: &mut State, dst: ActorId) -> Result<(), StepError> {
    let _actor = state.get_actor(dst).ok_or(StepError::ActorNotFound(dst))?;

    if let Some(actor) = state.get_actor_mut(dst) {
        actor.unblock_mut();
    }

    Ok(())
}

fn execute_thread_switch_mut(
    _state: &mut State,
    _from: ThreadId,
    _to: ThreadId,
) -> Result<(), StepError> {
    Err(StepError::KernelOpFailed(KernelOpError::NotImplemented {
        operation: "thread_switch",
    }))
}

// ============== FRAME THEOREMS ==============
//
// These correspond to Lean's comprehensive frame theorems.
// In Rust, we verify these properties through tests.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{ActorRuntime, Message, PluginState, WorkflowInstance};
    use crate::types::SecurityLevel;

    fn make_test_message(id: u128) -> Message {
        Message::new(id, 1, 2, SecurityLevel::Public, vec![1, 2, 3])
    }

    #[test]
    fn test_time_tick_increments_time() {
        let state = State::empty();
        assert_eq!(state.time(), 0);

        let op = KernelOp::TimeTick;
        let new_state = op.execute(&state).expect("time_tick should succeed");

        assert_eq!(new_state.time(), 1);
    }

    #[test]
    fn test_time_tick_preserves_plugins() {
        // Corresponds to Lean: time_tick_comprehensive_frame (plugins unchanged)
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 100));

        let op = KernelOp::TimeTick;
        let new_state = op.execute(&state).expect("time_tick should succeed");

        // Plugins should be unchanged
        assert!(new_state.get_plugin(1).is_some());
        assert_eq!(
            new_state.get_plugin(1).map(|p| p.memory_bounds()),
            Some(100)
        );
    }

    #[test]
    fn test_time_tick_preserves_actors() {
        // Corresponds to Lean: time_tick_comprehensive_frame (actors unchanged)
        let mut state = State::empty();
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let op = KernelOp::TimeTick;
        let new_state = op.execute(&state).expect("time_tick should succeed");

        // Actors should be unchanged
        assert!(new_state.get_actor(1).is_some());
        assert_eq!(new_state.get_actor(1).map(|a| a.capacity()), Some(10));
    }

    #[test]
    fn test_route_one_moves_message() {
        let mut state = State::empty();
        let mut actor = ActorRuntime::empty(10);
        actor.enqueue_pending_mut(make_test_message(42));
        state.insert_actor(1, actor).unwrap();

        assert_eq!(state.get_actor(1).map(|a| a.pending_len()), Some(1));
        assert_eq!(state.get_actor(1).map(|a| a.mailbox_len()), Some(0));

        let op = KernelOp::RouteOne { dst: 1 };
        let new_state = op.execute(&state).expect("route_one should succeed");

        assert_eq!(new_state.get_actor(1).map(|a| a.pending_len()), Some(0));
        assert_eq!(new_state.get_actor(1).map(|a| a.mailbox_len()), Some(1));
    }

    #[test]
    fn test_route_one_preserves_other_actors() {
        // Corresponds to Lean: route_one_comprehensive_frame (other actors unchanged)
        let mut state = State::empty();

        let mut actor1 = ActorRuntime::empty(10);
        actor1.enqueue_pending_mut(make_test_message(1));
        state.insert_actor(1, actor1).unwrap();

        let actor2 = ActorRuntime::empty(5);
        state.insert_actor(2, actor2).unwrap();

        let op = KernelOp::RouteOne { dst: 1 };
        let new_state = op.execute(&state).expect("route_one should succeed");

        // Actor 2 should be unchanged
        assert_eq!(new_state.get_actor(2).map(|a| a.capacity()), Some(5));
        assert_eq!(new_state.get_actor(2).map(|a| a.pending_len()), Some(0));
    }

    #[test]
    fn test_route_one_preserves_plugins() {
        // Corresponds to Lean: route_one_memory_unchanged
        let mut state = State::empty();

        let mut actor = ActorRuntime::empty(10);
        actor.enqueue_pending_mut(make_test_message(1));
        state.insert_actor(1, actor).unwrap();

        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Secret, 1024));

        let op = KernelOp::RouteOne { dst: 1 };
        let new_state = op.execute(&state).expect("route_one should succeed");

        // Plugin should be unchanged
        assert_eq!(new_state.plugin_level(1), Some(SecurityLevel::Secret));
    }

    #[test]
    fn test_route_one_no_pending_fails() {
        let mut state = State::empty();
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let op = KernelOp::RouteOne { dst: 1 };
        let result = op.execute(&state);

        assert!(matches!(result, Err(StepError::KernelOpFailed(_))));
    }

    #[test]
    fn test_route_one_mailbox_full_fails() {
        let mut state = State::empty();

        // Create actor with capacity 1, full mailbox
        let mut actor = ActorRuntime::empty(1);
        actor.enqueue_pending_mut(make_test_message(1));
        let _ = actor.deliver_mut(); // Fill mailbox
        actor.enqueue_pending_mut(make_test_message(2)); // Add another pending
        state.insert_actor(1, actor).unwrap();

        let op = KernelOp::RouteOne { dst: 1 };
        let result = op.execute(&state);

        assert!(matches!(result, Err(StepError::KernelOpFailed(_))));
    }

    #[test]
    fn test_unblock_send_clears_blocked() {
        let mut state = State::empty();
        let mut actor = ActorRuntime::empty(10);
        actor.set_blocked_mut(42);
        state.insert_actor(1, actor).unwrap();

        assert!(state.get_actor(1).map(|a| a.is_blocked()).unwrap_or(false));

        let op = KernelOp::UnblockSend { dst: 1 };
        let new_state = op.execute(&state).expect("unblock_send should succeed");

        assert!(!new_state
            .get_actor(1)
            .map(|a| a.is_blocked())
            .unwrap_or(true));
    }

    #[test]
    fn test_unblock_send_preserves_mailbox() {
        // Corresponds to Lean: unblock_send_comprehensive_frame
        let mut state = State::empty();
        let mut actor = ActorRuntime::empty(10);
        actor.enqueue_pending_mut(make_test_message(1));
        let _ = actor.deliver_mut();
        actor.set_blocked_mut(42);
        state.insert_actor(1, actor).unwrap();

        let initial_mailbox_len = state.get_actor(1).map(|a| a.mailbox_len()).unwrap_or(0);

        let op = KernelOp::UnblockSend { dst: 1 };
        let new_state = op.execute(&state).expect("unblock_send should succeed");

        let final_mailbox_len = new_state.get_actor(1).map(|a| a.mailbox_len()).unwrap_or(0);
        assert_eq!(initial_mailbox_len, final_mailbox_len);
    }

    #[test]
    fn test_workflow_tick_not_found() {
        let state = State::empty();

        let op = KernelOp::WorkflowTick { wid: 999 };
        let result = op.execute(&state);

        assert!(matches!(result, Err(StepError::KernelOpFailed(_))));
    }

    #[test]
    fn test_workflow_tick_preserves_other_workflows() {
        // Corresponds to Lean: workflow_tick_comprehensive_frame
        let mut state = State::empty();

        let _ = state.insert_workflow(1, WorkflowInstance::running(100));
        let _ = state.insert_workflow(2, WorkflowInstance::running(200));

        let op = KernelOp::WorkflowTick { wid: 1 };
        let new_state = op.execute(&state).expect("workflow_tick should succeed");

        // Workflow 2 should be unchanged
        assert!(new_state
            .get_workflow(2)
            .map(|w| w.is_running())
            .unwrap_or(false));
    }
}