//! Native session/job state machines with no dependency on Emacs runtime values. //! //! A session owns one model worker. A job moves from pending to one immutable //! terminal result. Cancellation and session closure suppress undelivered work. //! Every shared reference names either a cancellation flag or channel endpoint; //! model tensors never cross the worker boundary after loading. use std::cell::RefCell; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; use std::thread; use std::time::Duration; use lispm_llm::{ engine::ModelEngine, episodic::EpisodicMemory, model::ModelError, runtime::{self, RuntimeError}, }; use serde::Serialize; use serde_json::Value; use thiserror::Error; /// Recoverable native lifecycle/configuration failures, before FFI conversion. #[derive(Debug, Error)] pub(crate) enum NativeError { /// The model artifact location must not depend on process working directory. #[error("the native model directory must be an absolute path")] RelativeDirectory, /// Shared process-wide seed/thread coordination failed. #[error(transparent)] Runtime(#[from] RuntimeError), /// An explicitly closed or garbage-collected session accepts no new jobs. #[error("the native model session is closed")] Closed, /// A disconnected worker cannot leave its jobs pending indefinitely. #[error("the native model worker stopped before returning a result")] WorkerStopped, /// Creating the background thread failed. #[error("could not start the native model worker: {0}")] Spawn(#[source] std::io::Error), /// Model loading retains its typed root cause in the native core. #[error(transparent)] Model(#[from] ModelError), /// Serializing a terminal result failed. #[error(transparent)] Json(#[from] serde_json::Error), /// A reentrant poll/cancel cannot borrow the same job state simultaneously. #[error("the native inference job is already being observed")] JobBorrowed, } /// Only this transport enum is serialized across the native/Lisp boundary. #[derive(Debug, Serialize)] #[serde(tag = "status", rename_all = "lowercase")] enum Outcome { /// A proposal from the existing typed action renderer. Ready { proposal: Value }, /// A syntax, intent or confidence refusal, distinct from infrastructure errors. Refused { message: String }, /// A loading, worker or native tensor failure. Error { message: String }, /// Pending delivery was cancelled without applying any action. Cancelled, } impl Outcome { /// Convert an explicit lifecycle/load failure at the transport boundary. fn error(error: &NativeError) -> Self { Self::Error { message: error.to_string(), } } } /// The worker owns its predictor; this boundary also allows deterministic tests. trait Predictor { /// Return one bounded proposal, refusal or infrastructure failure. fn predict(&mut self, instruction: &str) -> Outcome; /// Score `instruction` with optional originating-buffer major modes. fn predict_in_modes(&mut self, instruction: &str, _active_modes: Option<&[String]>) -> Outcome { self.predict(instruction) } } /// Real model state is constructed and used exclusively inside its worker. struct LoadedModel { /// Polymorphic closed-set or open bi-encoder engine. engine: ModelEngine, /// Optional workspace episodic file consulted before neural scoring. episodic_path: Option, /// Optional workspace catalog file hot-reloaded on SHA-256 change. catalog_path: Option, } impl Predictor for LoadedModel { fn predict(&mut self, instruction: &str) -> Outcome { self.predict_in_modes(instruction, None) } fn predict_in_modes(&mut self, instruction: &str, active_modes: Option<&[String]>) -> Outcome { if let Some(cat_path) = &self.catalog_path && let Err(message) = self.engine.refresh_catalog_optional(cat_path) { return Outcome::Error { message }; } let open_cat = if self.engine.is_open() { Some(self.engine.catalog()) } else { None }; let episodic = match &self.episodic_path { Some(path) => match EpisodicMemory::load_optional_with_catalog(path, open_cat) { Ok(memory) => Some(memory), Err(error) => { return Outcome::Error { message: error.to_string(), }; } }, None => None, }; match self.engine.predict(instruction, episodic.as_ref(), active_modes) { Ok(program) => Outcome::Ready { proposal: program.to_json(), }, Err(error) if error.is_refusal() => Outcome::Refused { message: error.to_string(), }, Err(error) => Outcome::Error { message: error.to_string(), }, } } } /// An owned queue message, containing no Emacs pointer or borrowed input. enum Work { /// One job's input, optional active modes, completion sender and cancellation identity. Predict { instruction: String, active_modes: Option>, reply: Sender, cancelled: Arc, }, /// Stop after the active prediction finishes; queued jobs observe closure. Stop, } /// A GC-owned handle whose destruction never waits for native computation. pub(crate) struct Session { /// Queue endpoint used only to enqueue owned work or the stop message. sender: Sender, /// Closure is shared with worker and jobs so suppression is immediate. closed: Arc, } /// A GC-owned request handle with a nonblocking completion receiver. pub(crate) struct Job { /// The worker's sole result channel; disconnect is itself a terminal failure. receiver: Receiver, /// Cancellation identity shared with this job's queued or active work. cancelled: Arc, /// Session closure cancels pending results even before its worker wakes. session_closed: Arc, /// Exact JSON last returned to Lisp; terminal polling is idempotent. terminal: RefCell>, } /// Configure the native process exactly once, before a session worker starts. fn configure_threads(requested: i64) -> Result<(), NativeError> { let requested = i32::try_from(requested).map_err(|_| RuntimeError::InvalidThreads)?; Ok(runtime::configure_threads(requested)?) } /// Wait only on the worker for exclusive RNG access, observing session closure. /// /// A busy training run is temporary: keep the model factory untouched until the /// runtime guard is available. Closing a waiting session suppresses construction. fn initialize_when_available

( closed: &AtomicBool, factory: impl FnOnce() -> Result, ) -> Result { loop { if closed.load(Ordering::Acquire) { return Err(NativeError::Closed); } match runtime::try_acquire() { Ok(_guard) => { if closed.load(Ordering::Acquire) { return Err(NativeError::Closed); } return factory(); } Err(RuntimeError::Busy) => thread::sleep(Duration::from_millis(10)), Err(error) => return Err(error.into()), } } } impl Session { /// Create a native model session; artifact loading occurs in its worker. pub(crate) fn open(directory: String, threads: i64) -> Result { Self::open_with_files(directory, threads, None, None) } /// Create a native model session bound to an explicit workspace episodic file. pub(crate) fn open_episodic( directory: String, threads: i64, episodic_file: String, ) -> Result { let episodic_path = PathBuf::from(episodic_file); if !episodic_path.is_absolute() { return Err(NativeError::RelativeDirectory); } Self::open_with_files(directory, threads, Some(episodic_path), None) } /// Create a native session bound to optional episodic and open-catalog files. pub(crate) fn open_workspace( directory: String, threads: i64, episodic_file: Option, catalog_file: Option, ) -> Result { let episodic_path = match episodic_file { Some(path) => { let p = PathBuf::from(path); if !p.is_absolute() { return Err(NativeError::RelativeDirectory); } Some(p) } None => None, }; let catalog_path = match catalog_file { Some(path) => { let p = PathBuf::from(path); if !p.is_absolute() { return Err(NativeError::RelativeDirectory); } Some(p) } None => None, }; Self::open_with_files(directory, threads, episodic_path, catalog_path) } /// Shared constructor validating paths before spawning the model worker. fn open_with_files( directory: String, threads: i64, episodic_path: Option, catalog_path: Option, ) -> Result { let directory = PathBuf::from(directory); if !directory.is_absolute() { return Err(NativeError::RelativeDirectory); } configure_threads(threads)?; Self::spawn(move |closed| { initialize_when_available(closed, || { Ok(LoadedModel { engine: ModelEngine::load(directory)?, episodic_path, catalog_path, }) }) }) } /// Start one worker from a single-use predictor constructor. fn spawn(factory: F) -> Result where P: Predictor + 'static, F: FnOnce(&AtomicBool) -> Result + Send + 'static, { let (sender, receiver) = channel(); let closed = Arc::new(AtomicBool::new(false)); let worker_closed = Arc::clone(&closed); thread::Builder::new() .name("lispm-model".into()) .spawn(move || { // A dependency panic must not cross the FFI boundary or strand jobs. // Unwinding drops the receiver and each reply sender: poll then emits // WorkerStopped. The JoinHandle is deliberately detached, never joined. let _ = catch_unwind(AssertUnwindSafe(|| { run_worker(factory, receiver, worker_closed) })); }) .map_err(NativeError::Spawn)?; Ok(Self { sender, closed }) } /// Enqueue an instruction without waiting for model loading or inference. pub(crate) fn submit(&self, instruction: String) -> Result { self.submit_with_modes(instruction, None) } /// Enqueue an instruction scoped to JSON-encoded active major-mode names. pub(crate) fn submit_modes( &self, instruction: String, modes_json: String, ) -> Result { let modes: Vec = serde_json::from_str(&modes_json)?; self.submit_with_modes(instruction, Some(modes)) } /// Enqueue an instruction with optional active major-mode names. fn submit_with_modes( &self, instruction: String, active_modes: Option>, ) -> Result { if self.closed.load(Ordering::Acquire) { return Err(NativeError::Closed); } let (reply, receiver) = channel(); let cancelled = Arc::new(AtomicBool::new(false)); self.sender .send(Work::Predict { instruction, active_modes, reply, cancelled: Arc::clone(&cancelled), }) .map_err(|_| NativeError::WorkerStopped)?; Ok(Job { receiver, cancelled, session_closed: Arc::clone(&self.closed), terminal: RefCell::new(None), }) } /// Mark the session closed and wake its worker without blocking the caller. pub(crate) fn close(&self) { if !self.closed.swap(true, Ordering::AcqRel) { // Disconnection means the worker already ended, which also satisfies close. let _ = self.sender.send(Work::Stop); } } } impl Drop for Session { /// GC only signals closure; the worker releases tensor storage on its thread. fn drop(&mut self) { self.close(); } } /// Load exactly once, then serve serial predictions until closure or disconnect. fn run_worker(factory: F, receiver: Receiver, closed: Arc) where P: Predictor, F: FnOnce(&AtomicBool) -> Result, { let mut predictor = factory(&closed); while let Ok(work) = receiver.recv() { match work { Work::Stop => break, Work::Predict { instruction, active_modes, reply, cancelled, } => { let outcome = if delivery_cancelled(&closed, &cancelled) { Outcome::Cancelled } else { match &mut predictor { Ok(predictor) => { predictor.predict_in_modes(&instruction, active_modes.as_deref()) } Err(error) => Outcome::error(error), } }; let delivered = if delivery_cancelled(&closed, &cancelled) { Outcome::Cancelled } else { outcome }; // A dropped job intentionally discards its owned result. let _ = reply.send(delivered); } } } } /// Cancellation is a session-or-job predicate, checked before and after compute. fn delivery_cancelled(closed: &AtomicBool, cancelled: &AtomicBool) -> bool { closed.load(Ordering::Acquire) || cancelled.load(Ordering::Acquire) } impl Job { /// Observe without waiting, freezing the first terminal JSON result. pub(crate) fn poll(&self) -> Result, NativeError> { let mut terminal = self .terminal .try_borrow_mut() .map_err(|_| NativeError::JobBorrowed)?; if let Some(value) = terminal.as_ref() { return Ok(Some(value.to_owned())); } let outcome = if delivery_cancelled(&self.session_closed, &self.cancelled) { Some(Outcome::Cancelled) } else { match self.receiver.try_recv() { Ok(value) => Some(value), Err(TryRecvError::Empty) => None, Err(TryRecvError::Disconnected) => { Some(Outcome::error(&NativeError::WorkerStopped)) } } }; match outcome { None => Ok(None), Some(outcome) => { let encoded = serde_json::to_string(&outcome)?; *terminal = Some(encoded.to_owned()); Ok(Some(encoded)) } } } /// Cancel an unobserved result while leaving observed terminal data immutable. pub(crate) fn cancel(&self) -> Result<(), NativeError> { let mut terminal = self .terminal .try_borrow_mut() .map_err(|_| NativeError::JobBorrowed)?; self.cancelled.store(true, Ordering::Release); if terminal.is_none() { *terminal = Some(serde_json::to_string(&Outcome::Cancelled)?); } Ok(()) } } impl Drop for Job { /// GC cancellation is constant-time and never waits for an active kernel. fn drop(&mut self) { self.cancelled.store(true, Ordering::Release); } } #[cfg(test)] #[path = "worker_tests.rs"] mod tests;