lispm-llm / emacs-module /src /worker_tests.rs
Ryan.K
Publish open-vocabulary bi-encoder, continual learning, and technical paper
4a54697 unverified
Raw History Blame Contribute Delete
13.3 kB
//! Deterministic lifecycle witnesses plus the real published-model boundary.
use super::*;
use serde_json::json;
use std::sync::atomic::AtomicUsize;
use std::time::{Duration, Instant};
/// Explicit test-adapter failures distinguish timeout from a failed native API.
#[derive(Debug, Error)]
enum TestError {
/// A native configuration or lifecycle operation failed unexpectedly.
#[error(transparent)]
Native(#[from] NativeError),
/// Acquiring the shared runtime failed before a test operation started.
#[error(transparent)]
Runtime(#[from] RuntimeError),
/// A terminal result was malformed JSON.
#[error(transparent)]
Json(#[from] serde_json::Error),
/// The bounded test wait ended before worker progress.
#[error("test worker timed out")]
Timeout,
/// A channel required by the test fixture disconnected unexpectedly.
#[error("test synchronization disconnected")]
Disconnected,
}
/// Return one fixed valid proposal so lifecycle tests do not tune model behavior.
fn ready() -> Outcome {
Outcome::Ready {
proposal: json!({"actions": [{"action": "save-buffer"}]}),
}
}
/// A predictor records how many jobs really reached its computation boundary.
struct CountingPredictor {
/// Shared observation count, independent of the worker's lifecycle state.
predictions: Arc<AtomicUsize>,
}
impl Predictor for CountingPredictor {
fn predict(&mut self, instruction: &str) -> Outcome {
self.predictions.fetch_add(1, Ordering::AcqRel);
match instruction {
"refuse" => Outcome::Refused {
message: "unsupported fixture request".into(),
},
_ => ready(),
}
}
}
/// A gate exposes an active native operation without depending on timing sleeps.
struct GatedPredictor {
/// Signals that the single test operation started.
entered: Sender<()>,
/// The test controls completion of the active operation.
release: Receiver<()>,
/// Records jobs that were actually computed rather than cancelled in queue.
predictions: Arc<AtomicUsize>,
}
impl Predictor for GatedPredictor {
fn predict(&mut self, _: &str) -> Outcome {
self.predictions.fetch_add(1, Ordering::AcqRel);
let _ = self.entered.send(());
match self.release.recv() {
Ok(()) => ready(),
Err(_) => Outcome::Error {
message: "test gate disconnected".into(),
},
}
}
}
/// Wait for a real terminal result with a finite failure bound.
fn terminal(job: &Job) -> Result<String, TestError> {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Some(value) = job.poll()? {
return Ok(value);
}
if Instant::now() >= deadline {
return Err(TestError::Timeout);
}
thread::sleep(Duration::from_millis(1));
}
}
/// Decode the observable protocol status, not implementation state.
fn status(text: &str) -> Result<String, TestError> {
let value: Value = serde_json::from_str(text)?;
Ok(value
.get("status")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned())
}
/// Bound test-only waiting when an independent model integration test owns RNG.
fn runtime_guard() -> Result<runtime::RuntimeGuard, TestError> {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
match runtime::try_acquire() {
Ok(guard) => return Ok(guard),
Err(RuntimeError::Busy) if Instant::now() < deadline => {
thread::sleep(Duration::from_millis(1));
}
Err(RuntimeError::Busy) => return Err(TestError::Timeout),
Err(error) => return Err(error.into()),
}
}
}
#[test]
fn one_session_loads_once_and_retains_distinct_refusal_results() -> Result<(), TestError> {
let loads = Arc::new(AtomicUsize::new(0));
let predictions = Arc::new(AtomicUsize::new(0));
let observed_loads = Arc::clone(&loads);
let observed_predictions = Arc::clone(&predictions);
let session = Session::spawn(move |_| {
observed_loads.fetch_add(1, Ordering::AcqRel);
Ok(CountingPredictor {
predictions: observed_predictions,
})
})?;
let first = session.submit("save".into())?;
let second = session.submit("refuse".into())?;
let result = terminal(&first)?;
assert_eq!(status(&result)?, "ready");
assert_eq!(first.poll()?, Some(result.to_owned()));
first.cancel()?;
assert_eq!(first.poll()?, Some(result));
assert_eq!(status(&terminal(&second)?)?, "refused");
assert_eq!(loads.load(Ordering::Acquire), 1);
assert_eq!(predictions.load(Ordering::Acquire), 2);
session.close();
session.close();
assert!(matches!(
session.submit("later".into()),
Err(NativeError::Closed)
));
Ok(())
}
#[test]
fn cancel_and_close_do_not_wait_for_an_active_operation() -> Result<(), TestError> {
let (entered_sender, entered) = channel();
let (release, release_receiver) = channel();
let predictions = Arc::new(AtomicUsize::new(0));
let observed_predictions = Arc::clone(&predictions);
let session = Session::spawn(move |_| {
Ok(GatedPredictor {
entered: entered_sender,
release: release_receiver,
predictions: observed_predictions,
})
})?;
let active = session.submit("first".into())?;
entered
.recv_timeout(Duration::from_secs(5))
.map_err(|_| TestError::Timeout)?;
let queued = session.submit("second".into())?;
active.cancel()?;
active.cancel()?;
assert_eq!(status(&terminal(&active)?)?, "cancelled");
session.close();
assert_eq!(status(&terminal(&queued)?)?, "cancelled");
// The gate is still closed: reaching here proves neither operation joined.
assert_eq!(predictions.load(Ordering::Acquire), 1);
release.send(()).map_err(|_| TestError::Disconnected)?;
assert_eq!(status(&terminal(&active)?)?, "cancelled");
Ok(())
}
#[test]
fn dropping_a_job_suppresses_queued_computation() -> Result<(), TestError> {
let (entered_sender, entered) = channel();
let (release, release_receiver) = channel();
let predictions = Arc::new(AtomicUsize::new(0));
let observed_predictions = Arc::clone(&predictions);
let session = Session::spawn(move |_| {
Ok(GatedPredictor {
entered: entered_sender,
release: release_receiver,
predictions: observed_predictions,
})
})?;
let active = session.submit("first".into())?;
entered
.recv_timeout(Duration::from_secs(5))
.map_err(|_| TestError::Timeout)?;
drop(session.submit("discarded".into())?);
release.send(()).map_err(|_| TestError::Disconnected)?;
assert_eq!(status(&terminal(&active)?)?, "ready");
session.close();
assert_eq!(predictions.load(Ordering::Acquire), 1);
Ok(())
}
#[test]
fn loading_failure_is_an_error_instead_of_a_refusal() -> Result<(), TestError> {
let session = Session::spawn::<CountingPredictor, _>(|_| Err(NativeError::RelativeDirectory))?;
let job = session.submit("save".into())?;
let value: Value = serde_json::from_str(&terminal(&job)?)?;
assert_eq!(value.get("status").and_then(Value::as_str), Some("error"));
assert!(
value
.get("message")
.and_then(Value::as_str)
.is_some_and(|text| text.contains("absolute"))
);
Ok(())
}
#[test]
fn unexpected_worker_unwind_cannot_leave_a_job_pending() -> Result<(), TestError> {
let (entered_sender, entered) = channel();
let (release, release_receiver) = channel();
let session = Session::spawn::<CountingPredictor, _>(move |_| {
let _ = entered_sender.send(());
let _ = release_receiver.recv();
std::panic::resume_unwind(Box::new("simulated dependency unwind"))
})?;
entered
.recv_timeout(Duration::from_secs(5))
.map_err(|_| TestError::Timeout)?;
let job = session.submit("save".into())?;
release.send(()).map_err(|_| TestError::Disconnected)?;
let result = terminal(&job)?;
assert_eq!(status(&result)?, "error");
assert!(result.contains("worker stopped"));
Ok(())
}
/// Serialize process-wide thread-pool configuration tests against each other.
static THREAD_POOL_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn actual_published_model_returns_typed_action_and_unsupported_refusal() -> Result<(), TestError> {
let _pool_serial = THREAD_POOL_TEST.lock().unwrap_or_else(|e| e.into_inner());
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
let session = Session::open(root.to_string_lossy().into_owned(), 2)?;
let save = session.submit("save the current buffer".into())?;
let duplicate = session.submit("duplicate the current browser tab".into())?;
let value: Value = serde_json::from_str(&terminal(&save)?)?;
assert_eq!(
value,
json!({"status": "ready", "proposal": {"actions": [{"action": "save-buffer"}]}})
);
assert_eq!(status(&terminal(&duplicate)?)?, "refused");
assert!(matches!(
Session::open("relative/path".into(), 2),
Err(NativeError::RelativeDirectory)
));
assert!(matches!(
Session::open_episodic(root.to_string_lossy().into_owned(), 2, "relative/episodic.json".into()),
Err(NativeError::RelativeDirectory)
));
assert!(matches!(
configure_threads(0),
Err(NativeError::Runtime(RuntimeError::InvalidThreads))
));
assert!(matches!(
configure_threads(3),
Err(NativeError::Runtime(
RuntimeError::ThreadCountChanged { .. }
))
));
Ok(())
}
#[test]
fn model_factory_waits_for_training_rng_and_closed_waiters_never_initialize()
-> Result<(), TestError> {
let guard = runtime_guard()?;
let loads = Arc::new(AtomicUsize::new(0));
let observed_loads = Arc::clone(&loads);
let (entered_sender, entered) = channel();
let (exited_sender, exited) = channel();
let cancelled = Session::spawn(move |closed| {
let _ = entered_sender.send(());
let result = initialize_when_available(closed, || {
observed_loads.fetch_add(1, Ordering::AcqRel);
Ok(CountingPredictor {
predictions: Arc::new(AtomicUsize::new(0)),
})
});
let _ = exited_sender.send(());
result
})?;
let job = cancelled.submit("save".into())?;
entered
.recv_timeout(Duration::from_secs(5))
.map_err(|_| TestError::Timeout)?;
assert!(job.poll()?.is_none());
assert_eq!(loads.load(Ordering::Acquire), 0);
cancelled.close();
exited
.recv_timeout(Duration::from_secs(5))
.map_err(|_| TestError::Timeout)?;
assert_eq!(loads.load(Ordering::Acquire), 0);
assert_eq!(status(&terminal(&job)?)?, "cancelled");
// The second waiter must eventually initialize, rather than caching Busy.
let observed_loads = Arc::clone(&loads);
let resumed = Session::spawn(move |closed| {
initialize_when_available(closed, || {
observed_loads.fetch_add(1, Ordering::AcqRel);
Ok(CountingPredictor {
predictions: Arc::new(AtomicUsize::new(0)),
})
})
})?;
let job = resumed.submit("save".into())?;
assert!(job.poll()?.is_none());
assert_eq!(loads.load(Ordering::Acquire), 0);
drop(guard);
assert_eq!(status(&terminal(&job)?)?, "ready");
assert_eq!(loads.load(Ordering::Acquire), 1);
Ok(())
}
#[test]
fn episodic_session_learns_live_without_reloading_or_claiming_runtime_guard()
-> Result<(), TestError> {
let _pool_serial = THREAD_POOL_TEST.lock().unwrap_or_else(|e| e.into_inner());
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
let episodic_file =
std::env::temp_dir().join(format!("lispm-worker-episodic-{}.json", std::process::id()));
let _ = std::fs::remove_file(&episodic_file);
let session = Session::open_episodic(
root.to_string_lossy().into_owned(),
2,
episodic_file.to_string_lossy().into_owned(),
)?;
// Warm up model load before claiming the runtime guard (simulating active background training).
let warmup = session.submit("save the current buffer".into())?;
assert_eq!(status(&terminal(&warmup)?)?, "ready");
let training_lock = runtime_guard()?;
let before = session.submit("beam into dossier \"notes.el\"".into())?;
assert_eq!(status(&terminal(&before)?)?, "refused");
std::fs::write(
&episodic_file,
serde_json::to_vec(&json!({
"format_version": 1,
"entries": {"beam into dossier name": "find-file"}
}))?,
)
.expect("write episodic fixture");
let after = session.submit("beam into dossier \"notes.el\"".into())?;
let decoded: Value = serde_json::from_str(&terminal(&after)?)?;
let _ = std::fs::remove_file(&episodic_file);
drop(training_lock);
assert_eq!(
decoded,
json!({"status": "ready", "proposal": {"actions": [{"action": "find-file", "path": "notes.el"}]}})
);
Ok(())
}