diff --git a/crates/loader/src/services/task_fixture.rs b/crates/loader/src/services/task_fixture.rs index 5e0db50..7560138 100644 --- a/crates/loader/src/services/task_fixture.rs +++ b/crates/loader/src/services/task_fixture.rs @@ -60,6 +60,16 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(u64::from(tasks.queue.dispatch_work(now))) }); + let background = Arc::clone(state); + registry.register(MODULE, "DispatchFixtureBackground", move |_, cpu, _| { + let now = Duration::from_millis(background.uptime_millis()); + let mut tasks = background.task_fixture.lock().expect("fixture task queue"); + match tasks.queue.dispatch_background(now) { + Ok(started) => Ok(u64::from(started)), + Err(_) => background.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0), + } + }); + let completion = Arc::clone(state); registry.register( MODULE, @@ -83,6 +93,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc TaskResult::Finished(Err(error)) => (error, 0), TaskResult::Cancelled => (995, 0), TaskResult::TimedOut => (1460, 0), + TaskResult::WorkerPanicked => (31, 0), }; let mut record = [0; COMPLETION_SIZE]; record[..8].copy_from_slice(&id.raw().to_le_bytes()); diff --git a/crates/loader/src/tasks.rs b/crates/loader/src/tasks.rs index 0a17d91..4fc7d13 100644 --- a/crates/loader/src/tasks.rs +++ b/crates/loader/src/tasks.rs @@ -4,6 +4,7 @@ //! The caller supplies monotonic time, allowing deterministic dispatch in tests. use std::collections::VecDeque; +use std::thread::JoinHandle; use std::time::Duration; /// Identifier issued by a task queue and never reused within that queue. @@ -33,6 +34,7 @@ pub enum TaskResult { Finished(Result), Cancelled, TimedOut, + WorkerPanicked, } type Work = Box Result + Send>; @@ -51,12 +53,19 @@ struct Completion { callback: Callback, } +struct Worker { + id: TaskId, + callback: Callback, + thread: JoinHandle>, +} + /// A manual task queue whose capacity covers pending work and undelivered completions. pub struct TaskQueue { capacity: usize, last_id: u64, pending: VecDeque>, completions: VecDeque>, + worker: Option>, } impl TaskQueue { @@ -66,6 +75,7 @@ impl TaskQueue { last_id: 0, pending: VecDeque::new(), completions: VecDeque::new(), + worker: None, } } @@ -76,7 +86,9 @@ impl TaskQueue { work: impl FnOnce() -> Result + Send + 'static, callback: impl FnOnce(TaskId, TaskResult) + Send + 'static, ) -> Result { - if self.pending.len() + self.completions.len() >= self.capacity { + if self.pending.len() + self.completions.len() + usize::from(self.worker.is_some()) + >= self.capacity + { return Err(SubmitError::Full); } self.last_id = self @@ -112,6 +124,10 @@ impl TaskQueue { /// Run one queued operation. An expired operation completes without running. pub fn dispatch_work(&mut self, now: Duration) -> bool { + self.collect_worker(); + if self.worker.is_some() { + return false; + } let Some(task) = self.pending.pop_front() else { return false; }; @@ -130,12 +146,109 @@ impl TaskQueue { /// Invoke one callback on the caller's thread. pub fn dispatch_completion(&mut self) -> bool { + self.collect_worker(); let Some(completion) = self.completions.pop_front() else { return false; }; (completion.callback)(completion.id, completion.result); true } + + fn collect_worker(&mut self) { + if self + .worker + .as_ref() + .is_some_and(|worker| worker.thread.is_finished()) + { + let worker = self.worker.take().expect("finished worker"); + let result = worker + .thread + .join() + .map_or(TaskResult::WorkerPanicked, TaskResult::Finished); + self.completions.push_back(Completion { + id: worker.id, + result, + callback: worker.callback, + }); + } + } +} + +impl TaskQueue { + /// Start one background operation. At most one worker runs per queue. + pub fn dispatch_background(&mut self, now: Duration) -> std::io::Result { + self.collect_worker(); + if self.worker.is_some() { + return Ok(false); + } + let Some(task) = self.pending.front() else { + return Ok(false); + }; + if task.deadline.is_some_and(|deadline| now >= deadline) { + return Ok(self.dispatch_work(now)); + } + let (send, receive) = std::sync::mpsc::channel::>(); + // Start the thread before removing the task so spawn failure leaves it queued. + let thread = std::thread::Builder::new() + .name("xenora-task".into()) + .spawn(move || receive.recv().expect("worker receives one operation")())?; + let task = self.pending.pop_front().expect("pending task"); + assert!(send.send(task.work).is_ok()); + self.worker = Some(Worker { + id: task.id, + callback: task.callback, + thread, + }); + Ok(true) + } +} + +impl Drop for TaskQueue { + fn drop(&mut self) { + if let Some(worker) = self.worker.take() { + let _ = worker.thread.join(); + } + } +} + +#[cfg(test)] +#[test] +fn background_worker_preserves_capacity_and_manual_completion() { + use std::sync::mpsc::channel; + use std::time::Instant; + + let mut queue = TaskQueue::::new(1); + let (release, gate) = channel(); + let (completed, results) = channel(); + let id = queue + .submit( + None, + move || { + gate.recv_timeout(Duration::from_secs(2)).unwrap(); + Ok(17) + }, + move |id, result| completed.send((id, result)).unwrap(), + ) + .unwrap(); + assert!(queue.dispatch_background(Duration::ZERO).unwrap()); + assert!(!queue.dispatch_background(Duration::ZERO).unwrap()); + assert!(!queue.cancel(id)); + assert!(!queue.dispatch_completion()); + assert_eq!( + queue.submit(None, || Ok(0), |_, _| {}), + Err(SubmitError::Full) + ); + release.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while !queue.dispatch_completion() { + assert!(Instant::now() < deadline, "worker did not complete"); + std::thread::yield_now(); + } + assert_eq!( + results.try_recv().unwrap(), + (id, TaskResult::Finished(Ok(17))) + ); + assert!(!queue.dispatch_completion()); } #[cfg(test)] diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 7d6fb02..4f8dc1e 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1160,6 +1160,22 @@ fn guest_manual_tasks_deliver_results_once_through_imports() { assert_eq!(memory.read_u64(output + 16).unwrap(), expected_value); } assert_eq!(value("DispatchFixtureCompletion", &[output]), 0); + let background = value("SubmitFixtureTask", &[11, 0]); + assert_eq!(value("DispatchFixtureBackground", &[]), 1); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let result = call("DispatchFixtureCompletion", &[output]); + if result.execution.final_state.get(Register::Rax) == 1 { + assert_eq!(result.image.memory.read_u64(output).unwrap(), background); + assert_eq!(result.image.memory.read_u64(output + 16).unwrap(), 121); + break; + } + assert!( + std::time::Instant::now() < deadline, + "guest worker did not complete" + ); + std::thread::yield_now(); + } } #[test]