use crate::util::UnwrapPoison;
use crate::util::model_state::{AtomicModelState, ModelLoadGuard, ModelState};
use anyhow::{Context as _, Result};
use futures_util::FutureExt as _;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tracing::{debug, info, warn};
use crate::speech::models::{self, Purpose};
const RETRY_BASE_SECS: u64 = 5;
const MAX_LOAD_RETRIES: u32 = 12;
const LOAD_WAIT_POLL: Duration = Duration::from_millis(100);
const LOAD_WAIT_LIMIT: Duration = Duration::from_mins(2);
pub(crate) const IDLE_RELEASE: Duration = Duration::from_mins(5);
fn now_millis() -> u64 {
static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
u64::try_from(START.get_or_init(Instant::now).elapsed().as_millis()).unwrap_or(u64::MAX)
}
pub(crate) struct Lazy<E: Send + 'static> {
purpose: Purpose,
open: fn() -> Result<E>,
engine: Mutex<Option<Arc<Mutex<E>>>>,
state: AtomicModelState,
fetching: AtomicBool,
last_use: AtomicU64,
busy: AtomicUsize,
}
impl<E: Send + 'static> Lazy<E> {
pub(crate) const fn new(purpose: Purpose, open: fn() -> Result<E>) -> Self {
Self {
purpose,
open,
engine: Mutex::new(None),
state: AtomicModelState::new(ModelState::Uninit),
fetching: AtomicBool::new(false),
last_use: AtomicU64::new(0),
busy: AtomicUsize::new(0),
}
}
fn title(&self) -> &'static str {
self.purpose.title()
}
pub(crate) fn state(&self) -> ModelState {
self.state.load(Ordering::Acquire)
}
pub(crate) fn is_loaded(&self) -> bool {
self.state.is_ready()
}
pub(crate) fn is_loading(&self) -> bool {
self.state() == ModelState::Loading
}
pub(crate) fn is_failed(&self) -> bool {
self.state() == ModelState::Failed
}
pub(crate) fn engine(&self) -> Option<Arc<Mutex<E>>> {
self.touch();
self.engine.lock().unwrap_poison().clone()
}
pub(crate) async fn acquire(&'static self, dir: &Path) -> Option<Arc<Mutex<E>>> {
let _busy = Busy::new(&self.busy);
if !self.ensure_loaded(dir).await {
return None;
}
self.engine()
}
fn touch(&self) {
self.last_use.store(now_millis(), Ordering::Release);
}
fn idle_for_release(&self) -> bool {
let idle = u64::try_from(IDLE_RELEASE.as_millis()).unwrap_or(u64::MAX);
now_millis().saturating_sub(self.last_use.load(Ordering::Acquire)) >= idle
}
pub(crate) fn release_if_idle(&self) -> bool {
if !self.state.is_ready() {
return false;
}
if self.in_use() {
self.touch();
return false;
}
self.idle_for_release() && self.try_release("after an idle period")
}
fn in_use(&self) -> bool {
self.engine
.lock()
.unwrap_poison()
.as_ref()
.is_some_and(|engine| Arc::strong_count(engine) > 1)
}
pub(crate) fn release(&self) -> bool {
if self.state.is_ready() && !self.try_release("for the process-wide memory clear") {
return false;
}
self.is_cold()
}
pub(crate) fn is_cold(&self) -> bool {
!matches!(self.state(), ModelState::Ready | ModelState::Loading)
}
fn try_release(&self, why: &'static str) -> bool {
if self.busy.load(Ordering::Acquire) > 0 {
return false;
}
let mut guard = self.engine.lock().unwrap_poison();
let Some(engine) = guard.as_ref() else {
return false;
};
if Arc::strong_count(engine) > 1 {
return false;
}
if !self
.state
.transition(ModelState::Ready, ModelState::Released)
{
return false;
}
let taken = guard.take();
drop(guard);
drop(taken);
info!("{}: released {why}", self.title());
true
}
#[cfg(test)]
pub(crate) fn test_set_state(&self, state: ModelState) {
self.state.store(state, Ordering::Release);
}
pub(crate) fn retry_init(&'static self) -> bool {
if !self
.state
.transition(ModelState::Failed, ModelState::Uninit)
{
return false;
}
self.spawn_background_init();
true
}
fn begin_load(&self) -> bool {
let started = self
.state
.transition(ModelState::Uninit, ModelState::Loading)
|| self
.state
.transition(ModelState::Released, ModelState::Loading);
if started {
self.fetching.store(false, Ordering::Release);
}
started
}
pub(crate) fn retry(&'static self) {
if !self.retry_init() {
self.spawn_background_init();
}
}
pub(crate) fn spawn_background_init(&'static self) {
if !self.begin_load() {
debug!("{}: background init skipped", self.title());
return;
}
tokio::spawn(async move {
if std::panic::AssertUnwindSafe(self.load_retry_loop())
.catch_unwind()
.await
.is_err()
{
warn!(
"{}: background init panicked — marking failed",
self.title()
);
self.state.store(ModelState::Failed, Ordering::Release);
}
});
}
pub(crate) async fn ensure_loaded(&'static self, dir: &Path) -> bool {
loop {
match self.state() {
ModelState::Ready => {
self.touch();
return true;
}
ModelState::Loading => {
return models::usable(dir, self.purpose) && self.wait_until_settled().await;
}
ModelState::Failed => {
if !models::usable(dir, self.purpose) {
self.retry_init();
return false;
}
let _ = self
.state
.transition(ModelState::Failed, ModelState::Uninit);
}
ModelState::Released | ModelState::Uninit => {
if !models::usable(dir, self.purpose) {
self.spawn_background_init();
return false;
}
if !self.begin_load() {
continue;
}
let loaded = {
let _guard = ModelLoadGuard::new(&self.state);
self.open_and_publish().await
};
match loaded {
Ok(()) => return true,
Err(e) => {
warn!("{}: {e:#}", self.title());
return false;
}
}
}
}
}
}
pub(crate) async fn ensure_ready_once(&self, announce: impl FnOnce(&Path)) -> Result<()> {
let mut said = Some(announce);
let mut fetch_starting = |dir: &Path| {
if let Some(say) = said.take() {
say(dir);
}
};
self.load_or_fetch(&mut fetch_starting).await
}
async fn wait_until_settled(&self) -> bool {
let deadline = tokio::time::Instant::now() + LOAD_WAIT_LIMIT;
loop {
match self.state() {
ModelState::Ready => return true,
ModelState::Failed | ModelState::Uninit | ModelState::Released => return false,
ModelState::Loading if self.fetching.load(Ordering::Acquire) => return false,
ModelState::Loading => {}
}
if tokio::time::Instant::now() >= deadline {
warn!("{}: the model load did not settle in time", self.title());
return false;
}
tokio::time::sleep(LOAD_WAIT_POLL).await;
}
}
async fn load_retry_loop(&'static self) {
let _guard = ModelLoadGuard::new(&self.state);
let mut delay = Duration::from_secs(RETRY_BASE_SECS);
for attempt in 1..=MAX_LOAD_RETRIES {
info!(
"{}: model load attempt {attempt}/{MAX_LOAD_RETRIES}",
self.title()
);
match self
.load_or_fetch(&mut |_dir| {
self.fetching.store(true, Ordering::Release);
})
.await
{
Ok(()) => return,
Err(e) => warn!("{}: {e:#}", self.title()),
}
self.fetching.store(false, Ordering::Release);
if !crate::shutdown::sleep_or_shutdown_or_drain(delay).await {
return;
}
delay = (delay * 2).min(Duration::from_mins(2));
}
warn!(
"{}: the model set could not be loaded; giving up",
self.title()
);
self.state.store(ModelState::Failed, Ordering::Release);
}
async fn load_or_fetch(&self, fetch_starting: &mut impl FnMut(&Path)) -> Result<()> {
self.fetching.store(false, Ordering::Release);
let dir = models::root()?;
let client = models::download_client()?;
models::ensure_in(&dir, self.purpose, &client, fetch_starting).await?;
self.open_and_publish().await
}
async fn open_and_publish(&self) -> Result<()> {
let open = self.open;
let engine = tokio::task::spawn_blocking(open)
.await
.context("the engine's load task panicked")??;
*self.engine.lock().unwrap_poison() = Some(Arc::new(Mutex::new(engine)));
self.touch();
self.state.store(ModelState::Ready, Ordering::Release);
info!("{}: the engine is ready", self.title());
Ok(())
}
}
struct Busy<'a>(&'a AtomicUsize);
impl<'a> Busy<'a> {
fn new(counter: &'a AtomicUsize) -> Self {
counter.fetch_add(1, Ordering::AcqRel);
Self(counter)
}
}
impl Drop for Busy<'_> {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
#[cfg(test)]
#[expect(
clippy::unnecessary_wraps,
reason = "the fake engine's constructor must match Lazy::new's fallible signature"
)]
mod tests {
use super::*;
use crate::speech::models::write_sparse_set;
struct Fake;
fn set_on_disk() -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("a temp dir");
write_sparse_set(dir.path(), Purpose::Synthesis);
dir
}
#[tokio::test]
async fn a_held_engine_is_not_released_and_a_released_one_is_loaded_again() {
static ENGINE: Lazy<Fake> = Lazy::new(Purpose::Synthesis, open);
static OPENS: AtomicUsize = AtomicUsize::new(0);
fn open() -> Result<Fake> {
OPENS.fetch_add(1, Ordering::AcqRel);
Ok(Fake)
}
let dir = set_on_disk();
assert!(ENGINE.acquire(dir.path()).await.is_some());
assert!(ENGINE.is_loaded());
assert!(!ENGINE.release_if_idle(), "an engine just used is not idle");
let held = ENGINE.engine().expect("the handle");
assert!(
!ENGINE.try_release("the test"),
"a pass holding a handle keeps the engine"
);
drop(held);
assert!(ENGINE.try_release("the test"));
assert_eq!(ENGINE.state(), ModelState::Released);
assert!(ENGINE.engine().is_none(), "the released engine is gone");
assert!(ENGINE.acquire(dir.path()).await.is_some());
assert!(ENGINE.is_loaded());
assert_eq!(OPENS.load(Ordering::Acquire), 2, "the next use reloaded it");
}
#[tokio::test]
async fn a_failed_load_over_files_on_disk_is_retried_by_the_next_use() {
static ENGINE: Lazy<Fake> = Lazy::new(Purpose::Synthesis, open);
static OPENS: AtomicUsize = AtomicUsize::new(0);
fn open() -> Result<Fake> {
OPENS.fetch_add(1, Ordering::AcqRel);
Ok(Fake)
}
let dir = set_on_disk();
ENGINE.test_set_state(ModelState::Failed);
assert!(ENGINE.ensure_loaded(dir.path()).await);
assert!(ENGINE.is_loaded());
assert_eq!(OPENS.load(Ordering::Acquire), 1);
}
#[test]
fn a_new_load_does_not_inherit_the_previous_fetch() {
static ENGINE: Lazy<Fake> = Lazy::new(Purpose::Synthesis, open);
fn open() -> Result<Fake> {
Ok(Fake)
}
ENGINE.fetching.store(true, Ordering::Release);
ENGINE.test_set_state(ModelState::Released);
assert!(ENGINE.begin_load());
assert!(!ENGINE.fetching.load(Ordering::Acquire));
}
}