From 8f6fd3d92aa87d693173cad2ba8e541f55b9493b Mon Sep 17 00:00:00 2001 From: Nathan Watkins <8055935+n8watkins@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:05:51 -0800 Subject: [PATCH 1/2] refactor(core): tell a gone engine from an unfilled cell in both workers CoreCell::lookup answers NotFilled, Gone or Ready, and the dictation and note-sync workers find the Core through it. A cell filled and emptied before any dictation job ran used to look unfilled, so the job polled until the channel closed; it is now answered dictation_worker_unavailable, and the note-sync thread ends on the next signal instead of polling. Adds a Core test builder (core::test_core) and a cell-driven test constructor for the dictation worker, with tests for the cell on a real Core, both regressions and the settings-lock assertion on a real command path. Release-note: skip --- crates/scribe-core/src/core.rs | 329 ++++++++++++++++++++- crates/scribe-core/src/dictation_worker.rs | 248 ++++++++++++---- crates/scribe-core/src/note_sync.rs | 153 ++++++++-- 3 files changed, 630 insertions(+), 100 deletions(-) diff --git a/crates/scribe-core/src/core.rs b/crates/scribe-core/src/core.rs index 8d716ed..941f64f 100644 --- a/crates/scribe-core/src/core.rs +++ b/crates/scribe-core/src/core.rs @@ -136,16 +136,55 @@ impl Core { /// note-sync workers), without letting them keep it alive. /// /// The shell makes an empty cell, gives a clone to each worker, builds the -/// `Core` and fills the cell with it. A worker calls [`CoreCell::get`] once -/// per job (or per sync) and drops the `Core` it got when the job ends; it -/// never stores one. The cell holds only a weak reference, so once every -/// `Core` handle is dropped, `get` answers `None` again, the worker senders -/// the `Core` held are dropped with it, and the worker threads end. +/// `Core` and fills the cell with it. A worker calls [`CoreCell::lookup`] +/// once per job (or per sync) and drops the `Core` it got when the job ends; +/// it never stores one. The cell holds only a weak reference, so once every +/// `Core` handle is dropped, `lookup` answers [`CoreLookup::Gone`], for good, +/// and the workers stop: the dictation worker answers every later job +/// `dictation_worker_unavailable`, and the note-sync thread ends at its next +/// signal. #[derive(Clone, Default)] pub struct CoreCell(WeakCell); +/// What a [`CoreCell`] answers, generic so a worker can map the `Core` to +/// what it runs a job with ([`CoreLookup::map`]). +/// +/// The answer moves only forward: `NotFilled`, then `Ready` once the cell is +/// filled, then `Gone` once every `Core` handle is dropped. `Gone` is final: +/// a cell keeps its first fill, and a dropped `Core` never comes back. +#[derive(Debug)] +pub enum CoreLookup { + /// The shell has not built the engine yet: wait for it. + NotFilled, + /// The engine was built and every handle to it is gone: it never comes + /// back. + Gone, + /// The engine. + Ready(C), +} + +impl CoreLookup { + /// The same answer, with `Ready`'s value mapped through `f`. + pub fn map(self, f: impl FnOnce(C) -> D) -> CoreLookup { + match self { + CoreLookup::NotFilled => CoreLookup::NotFilled, + CoreLookup::Gone => CoreLookup::Gone, + CoreLookup::Ready(value) => CoreLookup::Ready(f(value)), + } + } + + /// `Ready`'s value, or `None` for both other answers. + pub fn ready(self) -> Option { + match self { + CoreLookup::Ready(value) => Some(value), + CoreLookup::NotFilled | CoreLookup::Gone => None, + } + } +} + impl CoreCell { - /// An empty cell: [`CoreCell::get`] answers `None` until it is filled. + /// An empty cell: [`CoreCell::lookup`] answers + /// [`CoreLookup::NotFilled`] until it is filled. pub fn new() -> Self { Self::default() } @@ -158,10 +197,18 @@ impl CoreCell { } } + /// The `Core`, or why there is none: not filled yet, or gone for good. + /// One read of the cell, so a fill or a drop that lands meanwhile can + /// never be misread. + pub fn lookup(&self) -> CoreLookup { + self.0.lookup().map(Core) + } + /// The `Core`: `None` before the cell is filled, and again once every - /// `Core` handle has been dropped. + /// `Core` handle has been dropped. A worker that must tell those two + /// apart uses [`CoreCell::lookup`]. pub fn get(&self) -> Option { - self.0.get().map(Core) + self.lookup().ready() } } @@ -187,8 +234,19 @@ impl WeakCell { self.0.set(Arc::downgrade(value)).is_ok() } + fn lookup(&self) -> CoreLookup> { + match self.0.get() { + None => CoreLookup::NotFilled, + Some(weak) => match weak.upgrade() { + Some(value) => CoreLookup::Ready(value), + None => CoreLookup::Gone, + }, + } + } + + #[cfg(test)] fn get(&self) -> Option> { - self.0.get()?.upgrade() + self.lookup().ready() } } @@ -217,8 +275,135 @@ fn shutdown_in_order(host: &dyn Host, dictation_server: Option<&dyn Stop>, warm: warm.stop(); } +/// A real [`Core`] for tests, built the way the shell builds it, on a +/// temporary folder and a [`RecordingHost`]. +/// +/// It has a database and replacements.txt in the folder, a speech engine that +/// loads nothing until asked, no dictation-state server, an empty hotkey +/// runtime, and both workers on the cell it fills. The dictation worker runs +/// each job on a [`TestExecutor`], so no test reaches the microphone, the +/// clipboard or the keyboard. Every test ends with `core.shutdown()`, as +/// every shell must. +#[cfg(test)] +pub(crate) mod test_core { + use super::*; + use crate::app_state::AppStatus; + use crate::data_hygiene::DataDirs; + use crate::db::Database; + use crate::dictation_worker::{DictationCommand, Executor, Outcome}; + use crate::error::CommandError; + use crate::host::RecordingHost; + use std::sync::Mutex; + + /// The built engine and what a test inspects it through. Destructure it + /// to drop the `Core` while keeping the folder (`dir`) alive. + pub(crate) struct TestCore { + pub(crate) core: Core, + /// The cell both workers find the `Core` through, already filled. + pub(crate) cell: CoreCell, + pub(crate) host: Arc, + /// The commands the dictation worker ran, in order (`Debug` text). + pub(crate) ran: Arc>>, + pub(crate) dir: tempfile::TempDir, + } + + impl TestCore { + /// The engine with the production note-sync worker + /// ([`NoteSyncWorker::spawn_with`]). + pub(crate) fn new() -> Self { + Self::with_note_sync(NoteSyncWorker::spawn_with) + } + + /// The engine with the note-sync worker `note_sync` starts on the + /// cell, for a test that needs the worker's thread. + pub(crate) fn with_note_sync(note_sync: impl FnOnce(CoreCell) -> NoteSyncWorker) -> Self { + let dir = tempfile::tempdir().expect("a temporary folder"); + let data = dir.path().join("data"); + let cache = dir.path().join("cache"); + let logs = dir.path().join("logs"); + for folder in [&data, &cache, &logs] { + std::fs::create_dir_all(folder).expect("the test folders"); + } + let host = Arc::new(RecordingHost::new( + Paths::from_parts(data.clone(), cache.clone(), logs, None, None), + Flavor::Stable, + )); + let shared_host: Arc = host.clone(); + + let db = Database::open(data.join("scribe.sqlite3")).expect("the test database"); + let backend = BackendState::new( + db, + cache.join("recordings"), + DataDirs { + data_dir: data.clone(), + cache_dir: cache, + }, + ); + let warm_transcriber = WarmTranscriber::new_with( + shared_host.clone(), + backend.clone(), + crate::speech_engine::measurements_path(&data), + ); + let cell = CoreCell::new(); + let ran = Arc::new(Mutex::new(Vec::new())); + let log = ran.clone(); + let dictation_worker = + DictationWorker::spawn_on_for_tests(cell.clone(), move |core| TestExecutor { + core, + ran: log.clone(), + }) + .expect("the dictation worker thread"); + let parts = CoreParts { + backend, + warm_transcriber, + dictation_server: None, + note_sync: note_sync(cell.clone()), + dictation_worker, + hotkey_runtime: HotkeyRuntimeState::default(), + replacements: Arc::new(ReplacementStore::open(data.join("replacements.txt"), &[])), + }; + let core = Core::new(shared_host, parts); + cell.fill(&core); + Self { + core, + cell, + host, + ran, + dir, + } + } + } + + /// Runs a dictation job against the real `Core`'s state without doing + /// it: reads the status from the dictation state machine, records the + /// command and answers `Done`. + pub(crate) struct TestExecutor { + core: Core, + ran: Arc>>, + } + + impl Executor for TestExecutor { + fn status(&self) -> Result { + Ok(self.core.backend().app_state()?.status().clone()) + } + + fn execute(&self, command: DictationCommand) -> Result { + self.ran + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .push(format!("{command:?}")); + Ok(Outcome::Done) + } + + fn report(&self, error: CommandError) { + log::warn!("Test dictation job failed: {}", error.message); + } + } +} + #[cfg(test)] mod tests { + use super::test_core::TestCore; use super::*; use crate::host::RecordingHost; use std::path::PathBuf; @@ -286,17 +471,135 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } - // No test can build a `Core` yet (docs/CORE-SPLIT.md), so the cell's - // behaviour is pinned on `WeakCell`, the whole of `CoreCell` apart from - // wrapping the `Arc` it hands back in a `Core`. - #[test] fn an_empty_core_cell_has_no_core() { let cell = CoreCell::new(); + assert!(matches!(cell.lookup(), CoreLookup::NotFilled)); assert!(cell.get().is_none()); assert!(cell.clone().get().is_none()); } + #[test] + fn a_core_cell_on_a_real_core_answers_not_filled_then_ready_then_gone() { + let TestCore { + core, + cell: filled, + dir: _dir, + .. + } = TestCore::new(); + + // A cell made before the fill, and every clone of it, sees it. + let cell = CoreCell::new(); + let worker = cell.clone(); + assert!(matches!(worker.lookup(), CoreLookup::NotFilled)); + cell.fill(&core); + let CoreLookup::Ready(found) = worker.lookup() else { + panic!("a filled cell answers Ready"); + }; + assert!(Arc::ptr_eq(&found.0, &core.0)); + assert!(Arc::ptr_eq(&worker.get().unwrap().0, &core.0)); + drop(found); + + // The cell holds no strong reference: the test's handle is the only + // one between jobs. + assert_eq!(Arc::strong_count(&core.0), 1); + + // A second fill keeps the first `Core`. + let other = TestCore::new(); + filled.fill(&other.core); + assert!(Arc::ptr_eq(&filled.get().unwrap().0, &core.0)); + other.core.shutdown(); + drop(other); + + core.shutdown(); + let weak = Arc::downgrade(&core.0); + drop(core); + assert!(weak.upgrade().is_none(), "nothing else holds the engine"); + // Gone, not NotFilled, on every cell that held it, and for good. + for cell in [&cell, &worker, &filled] { + assert!(matches!(cell.lookup(), CoreLookup::Gone)); + assert!(cell.get().is_none()); + } + let late = TestCore::new(); + cell.fill(&late.core); + assert!(matches!(cell.lookup(), CoreLookup::Gone)); + late.core.shutdown(); + } + + #[test] + fn a_lookup_maps_only_a_ready_value() { + assert!(matches!( + CoreLookup::Ready(2).map(|n| n * 10), + CoreLookup::Ready(20) + )); + assert!(matches!( + CoreLookup::::NotFilled.map(|n| n * 10), + CoreLookup::NotFilled + )); + assert!(matches!( + CoreLookup::::Gone.map(|n| n * 10), + CoreLookup::Gone + )); + assert_eq!(CoreLookup::Ready(3).ready(), Some(3)); + assert_eq!(CoreLookup::::Gone.ready(), None); + assert_eq!(CoreLookup::::NotFilled.ready(), None); + } + + /// The panic message of a thread, whichever form the payload took. + fn panic_text(payload: Box) -> String { + match payload.downcast::() { + Ok(text) => *text, + Err(payload) => payload + .downcast::<&'static str>() + .map(|text| text.to_string()) + .unwrap_or_default(), + } + } + + /// A real command path (the window-focus and tray handler's) on a thread + /// named "main" is caught before it takes the settings write lock. + #[cfg(debug_assertions)] + #[test] + fn syncing_launch_at_startup_on_the_main_thread_panics_in_debug_builds() { + let TestCore { + core, + host, + dir: _dir, + .. + } = TestCore::new(); + let on_main = core.clone(); + let panic = std::thread::Builder::new() + .name("main".into()) + .spawn(move || { + let _ = crate::settings_store::sync_launch_at_startup_with(&on_main); + }) + .expect("the thread") + .join() + .unwrap_err(); + assert_eq!( + panic_text(panic), + "the settings write lock must never be taken on the main thread" + ); + // The assertion fires before the lock is taken, so it is not + // poisoned, and no settings were announced. + assert!(core.backend().settings_writes().try_lock().is_ok()); + assert!(!host + .events() + .iter() + .any(|event| event.name() == "scribe:settings-changed")); + + // Off the main thread the same path runs. + let off_main = core.clone(); + std::thread::Builder::new() + .name("launch-at-startup".into()) + .spawn(move || crate::settings_store::sync_launch_at_startup_with(&off_main)) + .expect("the thread") + .join() + .expect("no panic") + .expect("the settings"); + core.shutdown(); + } + #[test] fn a_cell_answers_none_before_it_is_filled_and_the_value_after() { let cell = WeakCell::::default(); diff --git a/crates/scribe-core/src/dictation_worker.rs b/crates/scribe-core/src/dictation_worker.rs index 7c564a5..3d4cf41 100644 --- a/crates/scribe-core/src/dictation_worker.rs +++ b/crates/scribe-core/src/dictation_worker.rs @@ -42,7 +42,7 @@ use tauri::{AppHandle, Manager}; use crate::{ app_state::AppStatus, audio::{self, RecordingResultStatus, RecordingSessionInfo, StartRecordingRequest}, - core::{Core, CoreCell}, + core::{Core, CoreCell, CoreLookup}, dictation, error::CommandError, output::{self, OutputResult}, @@ -299,8 +299,8 @@ fn async_reply() -> (AsyncReply, ReplyFuture) { (AsyncReply(slot.clone()), ReplyFuture(slot)) } -/// Handle to the worker thread, kept in Tauri's managed state. Clones share -/// the one worker (Tauri state and `core::Core` hold the same one). +/// Handle to the worker thread. Clones share the one worker; the `Core` +/// holds one. #[derive(Clone)] pub struct DictationWorker { sender: Sender, @@ -324,52 +324,62 @@ impl DictationWorker { /// worker), so its thread finds the `Core` through the app for each job, /// waiting for it rather than dropping the first jobs. pub fn spawn(app: AppHandle) -> std::io::Result { - Self::spawn_finding(move || { - app.try_state::().map(|core| AppExecutor { + Self::spawn_finding(move || match app.try_state::() { + Some(core) => CoreLookup::Ready(AppExecutor { app: app.clone(), core: core.inner().clone(), - }) + }), + None => CoreLookup::NotFilled, }) } /// Starts the worker for a shell that hands it the `Core` through `cell`, /// which the shell fills right after `Core::new`. /// - /// The worker never keeps the `Core`: it calls [`CoreCell::get`] once per - /// job and drops the `Core` when that job ends. So the `Core`, which holds - /// this worker's sender, can be dropped while the worker exists, and the - /// worker thread then ends with the last sender. Before the cell is - /// filled, jobs wait in arrival order and none is dropped. Once a job has - /// found the `Core` and every `Core` handle is gone, later jobs are - /// answered `dictation_worker_unavailable`. If every `Core` handle is - /// dropped before any job ran, the worker cannot tell that from "not - /// filled yet" ([`CoreCell::get`] answers `None` for both) and keeps - /// polling until its channel closes; step 3 lets it tell them apart. + /// The worker never keeps the `Core`: it calls [`CoreCell::lookup`] once + /// per job and drops the `Core` when that job ends. So the `Core`, which + /// holds this worker's sender, can be dropped while the worker exists, + /// and the worker thread then ends with the last sender. Before the cell + /// is filled, jobs wait in arrival order and none is dropped. Once every + /// `Core` handle is gone, whether or not a job ever ran, the waiting job + /// and every later one are answered `dictation_worker_unavailable`. /// /// Still takes the app, only to pass it on to the other lanes' functions /// a job calls (see [`execute_with`]); P1-4 step 4 removes it. pub fn spawn_on(cell: CoreCell, app: AppHandle) -> std::io::Result { Self::spawn_finding(move || { - cell.get().map(|core| AppExecutor { + cell.lookup().map(|core| AppExecutor { app: app.clone(), core, }) }) } + /// [`DictationWorker::spawn_on`] for tests: finds the `Core` through + /// `cell` the same way and runs each job on the executor `executor_for` + /// builds from it, so no job reaches the microphone or the clipboard. + #[cfg(test)] + pub(crate) fn spawn_on_for_tests( + cell: CoreCell, + executor_for: impl Fn(Core) -> E + Send + 'static, + ) -> std::io::Result { + Self::spawn_finding(move || cell.lookup().map(&executor_for)) + } + /// Starts the worker with an executor that is ready now. #[cfg(test)] pub(crate) fn spawn_with(executor: E) -> std::io::Result { - Self::spawn_finding(move || Some(executor.clone())) + Self::spawn_finding(move || CoreLookup::Ready(executor.clone())) } /// Starts the worker thread. `find_executor` is asked for an executor /// once per job, which runs the job and is dropped with it, so the - /// worker keeps no executor (and no engine) between jobs. Until it first - /// answers, it is asked again every [`EXECUTOR_POLL`] while jobs queue up - /// in order; once it has answered, `None` means the engine is gone. + /// worker keeps no executor (and no engine) between jobs. While it + /// answers `NotFilled`, it is asked again every [`EXECUTOR_POLL`] while + /// jobs queue up in order; `Gone` answers the job + /// `dictation_worker_unavailable`. fn spawn_finding( - find_executor: impl FnMut() -> Option + Send + 'static, + find_executor: impl FnMut() -> CoreLookup + Send + 'static, ) -> std::io::Result { let (sender, receiver) = channel::(); let pending_starts = Arc::new(AtomicUsize::new(0)); @@ -463,12 +473,10 @@ const EXECUTOR_POLL: Duration = Duration::from_millis(50); /// The worker thread: runs every job in arrival order. Ends when every sender /// is gone, which is app shutdown (or the last `Core` dropped). fn worker_loop( - mut find_executor: impl FnMut() -> Option, + mut find_executor: impl FnMut() -> CoreLookup, receiver: &Receiver, pending_starts: &AtomicUsize, ) { - // Whether the executor (the engine) was ever found. - let mut found = false; // Jobs that arrived while the worker waited for its executor, in order. let mut backlog = VecDeque::new(); loop { @@ -479,35 +487,37 @@ fn worker_loop( Err(_) => return, }, }; - let executor = if found { - find_executor() - } else { - let Some(executor) = wait_for_executor(&mut find_executor, receiver, &mut backlog) - else { - // The channel closed while waiting: the app is shutting down. - return; - }; - found = true; - Some(executor) - }; let start = is_start(&job.command); let finished = || { if start { pending_starts.fetch_sub(1, Ordering::SeqCst); } }; - match executor { + match wait_for_executor(&mut find_executor, receiver, &mut backlog) { // The executor, and the engine it holds, is dropped with its job. - Some(executor) => run_job(&executor, job, finished), - None => engine_gone(job, finished), + Found::Ready(executor) => run_job(&executor, job, finished), + Found::Gone => engine_gone(job, finished), + // The channel closed while waiting: the app is shutting down. + // Dropping the waiting jobs tells their callers the worker is + // gone. + Found::Closed => return, } } } -/// A job that arrived after the engine it was found with went away (every -/// `Core` handle was dropped): it cannot run. A waiting caller hears that the -/// worker is gone; a fire-and-forget job is logged, as when the worker thread -/// itself is gone. +/// What [`wait_for_executor`] found. +enum Found { + Ready(E), + /// The engine is gone for good (every `Core` handle was dropped). + Gone, + /// Every sender is gone before the engine came. + Closed, +} + +/// A job that arrived after the engine went away (every `Core` handle was +/// dropped, whether or not a job ever ran on it): it cannot run. A waiting +/// caller hears that the worker is gone; a fire-and-forget job is logged, as +/// when the worker thread itself is gone. fn engine_gone(job: Job, finished: impl FnOnce()) { finished(); log::error!( @@ -519,23 +529,25 @@ fn engine_gone(job: Job, finished: impl FnOnce()) { } } -/// Waits for the executor, which the shell builds after it starts this -/// worker. Jobs that arrive meanwhile join `backlog`, in order, so none is -/// dropped whatever the startup timing. Returns `None` only when the channel -/// closes (the app is shutting down). +/// Finds the executor for one job: asks once, and while the shell has not +/// built the engine yet (`NotFilled`) waits for it, asking again every +/// [`EXECUTOR_POLL`]. Jobs that arrive meanwhile join `backlog`, in order, +/// so none is dropped whatever the startup timing. fn wait_for_executor( - find_executor: &mut impl FnMut() -> Option, + find_executor: &mut impl FnMut() -> CoreLookup, receiver: &Receiver, backlog: &mut VecDeque, -) -> Option { +) -> Found { loop { - if let Some(executor) = find_executor() { - return Some(executor); + match find_executor() { + CoreLookup::Ready(executor) => return Found::Ready(executor), + CoreLookup::Gone => return Found::Gone, + CoreLookup::NotFilled => {} } match receiver.recv_timeout(EXECUTOR_POLL) { Ok(job) => backlog.push_back(job), Err(RecvTimeoutError::Timeout) => {} - Err(RecvTimeoutError::Disconnected) => return None, + Err(RecvTimeoutError::Disconnected) => return Found::Closed, } } } @@ -1108,7 +1120,11 @@ mod tests { let (fake, ready, asked) = (fake.clone(), ready.clone(), asked.clone()); DictationWorker::spawn_finding(move || { asked.fetch_add(1, Ordering::SeqCst); - ready.load(Ordering::SeqCst).then(|| fake.clone()) + if ready.load(Ordering::SeqCst) { + CoreLookup::Ready(fake.clone()) + } else { + CoreLookup::NotFilled + } }) .unwrap() }; @@ -1165,11 +1181,12 @@ mod tests { } } - /// The `CoreCell` contract, on a stand-in engine (no test can build a - /// `Core` yet): the worker keeps no strong reference between jobs, so + /// The `CoreCell` contract, on a stand-in engine behind a weak + /// reference: the worker keeps no strong reference between jobs, so /// the engine can be dropped while the worker exists; jobs after that /// are answered at once, not left polling; and the worker thread ends - /// once its last sender is gone. + /// once its last sender is gone. The same on a real `Core`: + /// `a_core_dropped_before_any_job_answers_every_job_unavailable`. #[test] fn the_engine_can_be_dropped_while_the_worker_exists() { use std::sync::atomic::AtomicBool; @@ -1182,7 +1199,10 @@ mod tests { let guard = SetOnDrop(ended.clone()); DictationWorker::spawn_finding(move || { let _guard = &guard; - cell.upgrade() + match cell.upgrade() { + Some(engine) => CoreLookup::Ready(engine), + None => CoreLookup::Gone, + } }) .unwrap() }; @@ -1296,7 +1316,7 @@ mod tests { // The worker shuts down (its last sender dropped) while the command // still waits for an engine that never came. - let waiting = DictationWorker::spawn_finding(|| None::).unwrap(); + let waiting = DictationWorker::spawn_finding(|| CoreLookup::::NotFilled).unwrap(); let pending = waiting.call_async(start()); drop(waiting); let error = block_on(pending).unwrap_err(); @@ -1321,7 +1341,7 @@ mod tests { let asked = asked.clone(); DictationWorker::spawn_finding(move || { asked.fetch_add(1, Ordering::SeqCst); - Some(Fake::default()) + CoreLookup::Ready(Fake::default()) }) .unwrap() }; @@ -1331,6 +1351,116 @@ mod tests { assert_eq!(asked.load(Ordering::SeqCst), 1); } + /// The regression step 3b fixes: a cell filled and emptied before any + /// job ran used to look unfilled, so the first job polled until the + /// channel closed, and a caller holding a worker handle (which keeps the + /// channel open) never heard back. + #[test] + fn a_core_dropped_before_any_job_answers_every_job_unavailable() { + use crate::core::test_core::TestCore; + + let TestCore { + core, + cell, + ran, + dir: _dir, + .. + } = TestCore::new(); + let worker = core.dictation_worker().clone(); + core.shutdown(); + drop(core); + assert!(matches!(cell.lookup(), CoreLookup::Gone)); + + let error = block_on(worker.call_async(start())).unwrap_err(); + assert_eq!(error.code, "dictation_worker_unavailable"); + let error = call_within_deadline(&worker, DictationCommand::Stop).unwrap_err(); + assert_eq!(error.code, "dictation_worker_unavailable"); + // A fire-and-forget start is dropped too, without leaving a start + // pending (the call behind it returns only after it was handled). + worker.send(start()); + let error = block_on(worker.call_async(DictationCommand::Cancel)).unwrap_err(); + assert_eq!(error.code, "dictation_worker_unavailable"); + assert_eq!(worker.pending_starts.load(Ordering::SeqCst), 0); + assert!(ran.lock().unwrap().is_empty()); + } + + #[test] + fn a_cell_driven_worker_runs_jobs_on_the_real_core_then_answers_unavailable_once_it_is_gone() { + use crate::core::test_core::TestCore; + + let TestCore { + core, + cell, + ran, + dir: _dir, + .. + } = TestCore::new(); + let worker = core.dictation_worker().clone(); + let outcome = block_on(worker.call_async(DictationCommand::Cancel)).unwrap(); + assert!(matches!(outcome, Outcome::Done)); + // Not admitted while the real state machine is idle. + let outcome = block_on(worker.call_async(DictationCommand::Stop)).unwrap(); + assert!(matches!(outcome, Outcome::Skipped)); + assert_eq!(*ran.lock().unwrap(), vec!["Cancel".to_string()]); + + // The worker may still hold the last job's `Core` for a moment after + // replying, but it lets go before it takes the next job, so the next + // job finds the engine gone. + core.shutdown(); + drop(core); + let error = block_on(worker.call_async(DictationCommand::Cancel)).unwrap_err(); + assert_eq!(error.code, "dictation_worker_unavailable"); + assert!(matches!(cell.lookup(), CoreLookup::Gone)); + assert_eq!(*ran.lock().unwrap(), vec!["Cancel".to_string()]); + } + + #[test] + fn jobs_waiting_for_an_engine_that_goes_away_are_all_answered_in_order() { + #[derive(Clone, Copy)] + enum Engine { + NotFilled, + Gone, + } + let engine = Arc::new(Mutex::new(Engine::NotFilled)); + let (asked, was_asked) = channel::<()>(); + let worker = { + let engine = engine.clone(); + DictationWorker::spawn_finding(move || { + let _ = asked.send(()); + match *engine.lock().unwrap() { + Engine::NotFilled => CoreLookup::::NotFilled, + Engine::Gone => CoreLookup::Gone, + } + }) + .unwrap() + }; + + let first = worker.call_async(start()); + worker.send(start()); + let last = worker.call_async(DictationCommand::Stop); + // The worker is waiting for the engine: asked, and asked again. + for _ in 0..2 { + was_asked + .recv_timeout(TEST_DEADLINE) + .expect("the worker looks for the engine"); + } + + *engine.lock().unwrap() = Engine::Gone; + assert_eq!( + block_on(first).unwrap_err().code, + "dictation_worker_unavailable" + ); + assert_eq!( + block_on(last).unwrap_err().code, + "dictation_worker_unavailable" + ); + // Both starts were handled, the fire-and-forget one before `last`. + assert_eq!(worker.pending_starts.load(Ordering::SeqCst), 0); + // And every later job too, at once. + let error = call_within_deadline(&worker, DictationCommand::Cancel).unwrap_err(); + assert_eq!(error.code, "dictation_worker_unavailable"); + } + #[test] fn the_caller_is_never_left_waiting_when_the_worker_is_gone() { let (sender, receiver) = channel::(); diff --git a/crates/scribe-core/src/note_sync.rs b/crates/scribe-core/src/note_sync.rs index cb70209..207eaa5 100644 --- a/crates/scribe-core/src/note_sync.rs +++ b/crates/scribe-core/src/note_sync.rs @@ -9,7 +9,7 @@ use crossbeam_channel::{Receiver, RecvTimeoutError, Sender}; use tauri::{AppHandle, Manager}; use crate::commands::BackendState; -use crate::core::{Core, CoreCell}; +use crate::core::{Core, CoreCell, CoreLookup}; use crate::error::CommandError; use crate::github_backup::{GitHubBackup, SyncReport}; use crate::replacements_file::ReplacementStore; @@ -290,11 +290,10 @@ fn combine_sync_results( } } -/// Owns the channel that note-save events are pushed onto. Held in Tauri's -/// managed state. Clones share the channel (Tauri state and `core::Core` hold -/// the same worker). The thread would end once every clone dropped, but the -/// app never drops them; it ends with the process, so nothing may rely on drop -/// to finish a sync. +/// Owns the channel that note-save events are pushed onto. Clones share the +/// channel; the `Core` holds one. The thread ends once every clone is dropped, +/// or at the next signal after the `Core` is gone, but nothing may rely on +/// drop to finish a sync: the app ends the thread with the process. #[derive(Clone)] pub struct NoteSyncWorker { tx: Sender<()>, @@ -308,7 +307,10 @@ impl NoteSyncWorker { /// engine split switches the shell to [`NoteSyncWorker::spawn_with`]. pub fn spawn(app: AppHandle) -> Self { Self::start( - move || app.try_state::().map(|core| core.inner().clone()), + move || match app.try_state::() { + Some(core) => CoreLookup::Ready(core.inner().clone()), + None => CoreLookup::NotFilled, + }, sync_automatically, DEBOUNCE, ) @@ -319,18 +321,18 @@ impl NoteSyncWorker { /// through `cell` once per sync and drops it when the sync ends. It never /// stores a strong `Core`, so dropping the last `Core` closes the channel /// and ends the thread, when the `Core` holds the last sender. If another - /// sender outlives the `Core`, the thread keeps waking every 50 ms until - /// that sender drops. Until the cell is filled it polls every 50 ms and - /// drops no note-saved signal. + /// sender outlives the `Core`, the thread ends at its next note-saved + /// signal, which finds the `Core` gone. Until the cell is filled it polls + /// every 50 ms and drops no note-saved signal. pub fn spawn_with(cell: CoreCell) -> Self { - Self::start(move || cell.get(), sync_automatically, DEBOUNCE).0 + Self::start(move || cell.lookup(), sync_automatically, DEBOUNCE).0 } /// Starts the thread over any way of finding the engine, so tests can run - /// the whole worker without building a `Core`. Returns the thread's - /// handle too (`None` when the thread could not start). + /// the whole worker on a stand-in engine. Returns the thread's handle too + /// (`None` when the thread could not start). fn start( - find_core: impl Fn() -> Option + Send + 'static, + find_core: impl Fn() -> CoreLookup + Send + 'static, sync: impl Fn(&C) + Send + 'static, debounce: Duration, ) -> (Self, Option>) { @@ -353,12 +355,18 @@ impl NoteSyncWorker { const CORE_POLL: Duration = Duration::from_millis(50); /// Waits for the engine, which the shell builds after it starts this worker. -/// Returns `None` only when the channel disconnects (the app is shutting -/// down), so a note-saved signal is never dropped whatever the startup timing. -fn wait_for_core(find_core: &impl Fn() -> Option, rx: &Receiver<()>) -> Option { +/// Returns `None`, and the thread ends, when the engine is gone for good or +/// the channel disconnects (the app is shutting down); otherwise a +/// note-saved signal is never dropped whatever the startup timing. +fn wait_for_core(find_core: &impl Fn() -> CoreLookup, rx: &Receiver<()>) -> Option { loop { - if let Some(core) = find_core() { - return Some(core); + match find_core() { + CoreLookup::Ready(core) => return Some(core), + CoreLookup::Gone => { + log::info!("The engine is gone; automatic GitHub backup stops"); + return None; + } + CoreLookup::NotFilled => {} } match rx.recv_timeout(CORE_POLL) { // More saves while waiting: the sync that follows covers them. @@ -369,7 +377,7 @@ fn wait_for_core(find_core: &impl Fn() -> Option, rx: &Receiver<()>) -> Op } fn worker_loop( - find_core: impl Fn() -> Option, + find_core: impl Fn() -> CoreLookup, sync: impl Fn(&C), debounce: Duration, rx: Receiver<()>, @@ -514,6 +522,31 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; + /// A stand-in engine that is not built for the first `polls` lookups. + fn ready_after(seen: &AtomicUsize, polls: usize, engine: u32) -> CoreLookup { + if seen.fetch_add(1, Ordering::SeqCst) >= polls { + CoreLookup::Ready(engine) + } else { + CoreLookup::NotFilled + } + } + + /// How long a test waits for the worker before it fails. + const TEST_DEADLINE: Duration = Duration::from_secs(10); + + /// Joins `thread`, failing the test instead of hanging it when the + /// thread does not end within [`TEST_DEADLINE`]. + fn join_within_deadline(thread: thread::JoinHandle<()>) { + let (ended, has_ended) = crossbeam_channel::bounded(1); + thread::spawn(move || { + let _ = ended.send(thread.join()); + }); + has_ended + .recv_timeout(TEST_DEADLINE) + .expect("the worker thread never ended") + .expect("the worker thread panicked"); + } + fn wait_until(what: &str, done: impl Fn() -> bool) { let deadline = std::time::Instant::now() + Duration::from_secs(10); while !done() { @@ -532,7 +565,7 @@ mod tests { worker_loop( move || { seen_polls.fetch_add(1, Ordering::SeqCst); - None:: + CoreLookup::::NotFilled }, move |_| { seen_syncs.fetch_add(1, Ordering::SeqCst); @@ -560,7 +593,7 @@ mod tests { let (seen_polls, seen_synced) = (polls.clone(), synced.clone()); let worker = thread::spawn(move || { worker_loop( - move || (seen_polls.fetch_add(1, Ordering::SeqCst) >= 3).then_some(7u32), + move || ready_after(&seen_polls, 3, 7u32), move |core| seen_synced.lock().unwrap().push(*core), Duration::from_millis(5), rx, @@ -579,7 +612,7 @@ mod tests { let synced = Arc::new(std::sync::Mutex::new(Vec::new())); let (seen_polls, seen_synced) = (polls.clone(), synced.clone()); let (worker, thread) = NoteSyncWorker::start( - move || (seen_polls.fetch_add(1, Ordering::SeqCst) >= 2).then_some(9u32), + move || ready_after(&seen_polls, 2, 9u32), move |core| seen_synced.lock().unwrap().push(*core), Duration::from_millis(20), ); @@ -603,22 +636,86 @@ mod tests { let synced = Arc::new(AtomicUsize::new(0)); let seen_synced = synced.clone(); let find = cell.clone(); + let (asked, was_asked) = crossbeam_channel::unbounded(); let (worker, thread) = NoteSyncWorker::start( - move || find.get(), + move || { + let _ = asked.send(()); + find.lookup() + }, move |_core| { seen_synced.fetch_add(1, Ordering::SeqCst); }, Duration::from_millis(5), ); worker.notify(); - // Let it get past the debounce and into waiting for the engine. - thread::sleep(Duration::from_millis(120)); + // Past the debounce and waiting for the engine: asked, and asked + // again. + for _ in 0..2 { + was_asked + .recv_timeout(TEST_DEADLINE) + .expect("the worker looks for the engine"); + } drop(worker); - thread.expect("the thread started").join().unwrap(); - assert!(cell.get().is_none()); + join_within_deadline(thread.expect("the thread started")); + assert!(matches!(cell.lookup(), CoreLookup::NotFilled)); assert_eq!(synced.load(Ordering::SeqCst), 0); } + /// The regression step 3b fixes: with a sender that outlives the `Core` + /// (here the test's handle), the thread used to wake every 50 ms for as + /// long as that sender lived, since a dropped `Core` looked unfilled. + #[test] + fn a_signal_after_the_core_is_gone_ends_the_thread() { + use crate::core::test_core::TestCore; + + let started = Arc::new(std::sync::Mutex::new(None)); + let synced = Arc::new(AtomicUsize::new(0)); + let (asked, was_asked) = crossbeam_channel::unbounded(); + let TestCore { + core, + cell, + dir: _dir, + .. + } = { + let (started, synced) = (started.clone(), synced.clone()); + TestCore::with_note_sync(move |cell| { + let (worker, thread) = NoteSyncWorker::start( + move || { + let found = cell.lookup(); + let _ = asked.send(matches!(found, CoreLookup::Gone)); + found + }, + move |_core: &Core| { + synced.fetch_add(1, Ordering::SeqCst); + }, + Duration::ZERO, + ); + *started.lock().unwrap() = thread; + worker + }) + }; + let thread = started.lock().unwrap().take().expect("the thread started"); + + // Kept past the `Core`, so the channel stays open. + let worker = core.note_sync().clone(); + core.shutdown(); + drop(core); + assert!(matches!(cell.lookup(), CoreLookup::Gone)); + + worker.notify(); + // The one lookup this signal made found the engine gone ... + let gone = was_asked + .recv_timeout(TEST_DEADLINE) + .expect("the worker looks for the engine"); + assert!(gone); + // ... and the thread ended on it, with the sender still alive. + join_within_deadline(thread); + assert!(was_asked.try_recv().is_err(), "no lookup after Gone"); + assert_eq!(synced.load(Ordering::SeqCst), 0); + worker.notify(); + drop(worker); + } + #[test] fn combines_successful_note_and_transcript_progress() { let attempt = combine_sync_results("alice/notes".into(), report(2, 1), report(3, 2)); From 471fbba0fac11379195add433a6b689b5fd6135d Mon Sep 17 00:00:00 2001 From: Nathan Watkins <8055935+n8watkins@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:07:21 -0800 Subject: [PATCH 2/2] docs(core): mark P1-4 step 3b in review (#170) Release-note: skip --- docs/CORE-SPLIT.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/CORE-SPLIT.md b/docs/CORE-SPLIT.md index 5cdaa9f..82feb9d 100644 --- a/docs/CORE-SPLIT.md +++ b/docs/CORE-SPLIT.md @@ -180,7 +180,8 @@ It is done when `lib.rs` setup calls `app.manage(` exactly once (for the `Core`, |---|---|---| | 1 | `seams`, `e2e-log-check` | merged: #159, #158 | | 2 | `output`, `data`, `audio`, `models`, `sync`, `hotkeys` | merged: #163, #161, #165, #162, #160, #164 (main 550f041) | -| 3a, 3b | `recording-host`, `core-cell` | next; in parallel | +| 3a | `recording-host` | next; in parallel with 3b | +| 3b | `core-cell` | in review: #170 | | 3c | `wiring` | after 3a and 3b | | 4 | `sweep` | after 3c; one lane, alone | | 4b | `test-seams` | after 4; in parallel with 5 |