A high-performance inference engine for AI models
update downloader tests
eugeneb58f5199ac74
diff --git a/Cargo.lock b/Cargo.lockindex 715c5a8ff..fa2a89033 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -240,6 +240,16 @@ dependencies = ["winnow 0.7.15",]+[[package]]+name = "assert-json-diff"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -1975,6 +1985,24 @@ dependencies = ["zeroize",]+[[package]]+name = "deadpool"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b"+dependencies = [+ "deadpool-runtime",+ "lazy_static",+ "num_cpus",+ "tokio",+]++[[package]]+name = "deadpool-runtime"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"+[[package]]name = "deltae"version = "0.3.2"@@ -2204,10 +2232,12 @@ dependencies = ["futures-util","indicatif","libc",+ "mock-registry","objc-sys","objc2","objc2-foundation","reqwest 0.13.2",+ "rstest","serde","serde_json","tempfile",@@ -2219,6 +2249,7 @@ dependencies = ["tracing-appender","tracing-subscriber","uuid",+ "wiremock",][[package]]@@ -3188,6 +3219,7 @@ dependencies = ["http 1.4.0","http-body 1.0.1","httparse",+ "httpdate","itoa","pin-project-lite","smallvec",@@ -4271,6 +4303,25 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "mock-registry"+version = "0.4.4"+dependencies = [+ "base64 0.22.1",+ "bitflags 2.11.1",+ "bytesize",+ "crc32c",+ "http 1.4.0",+ "httparse",+ "serde_json",+ "shoji",+ "stream_throttle",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "wiremock",+]+[[package]]name = "monostate"version = "0.1.18"@@ -5132,6 +5183,12 @@ version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+[[package]]+name = "pin-utils"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"+[[package]]name = "piper"version = "0.2.5"@@ -6002,6 +6059,12 @@ dependencies = ["syn 1.0.109",]+[[package]]+name = "relative-path"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"+[[package]]name = "reqwest"version = "0.12.28"@@ -6243,6 +6306,35 @@ dependencies = ["uncased",]+[[package]]+name = "rstest"+version = "0.26.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49"+dependencies = [+ "futures-timer",+ "futures-util",+ "rstest_macros",+]++[[package]]+name = "rstest_macros"+version = "0.26.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0"+dependencies = [+ "cfg-if 1.0.4",+ "glob",+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "regex",+ "relative-path",+ "rustc_version",+ "syn 2.0.117",+ "unicode-ident",+]+[[package]]name = "rustc-hash"version = "1.1.0"@@ -6983,6 +7075,18 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "stream_throttle"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5c28c494ad34b726248a73abd7184468b351ff6218c8524f0f8a426664dcbd7"+dependencies = [+ "futures",+ "log",+ "pin-utils",+ "tokio",+]+[[package]]name = "strsim"version = "0.11.1"@@ -8202,6 +8306,7 @@ dependencies = ["indicatif","inventory","keyring",+ "mock-registry","nagare","napi","napi-build",@@ -9045,6 +9150,29 @@ dependencies = ["memchr",]+[[package]]+name = "wiremock"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031"+dependencies = [+ "assert-json-diff",+ "base64 0.22.1",+ "deadpool",+ "futures",+ "http 1.4.0",+ "http-body-util",+ "hyper 1.9.0",+ "hyper-util",+ "log",+ "once_cell",+ "regex",+ "serde",+ "serde_json",+ "tokio",+ "url",+]+[[package]]name = "wit-bindgen"version = "0.51.0"diff --git a/Cargo.toml b/Cargo.tomlindex 1eef7e458..3437c9ed8 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,6 +11,7 @@ members = ["crates/hanashi","crates/nagare","crates/download-manager",+ "crates/mock-registry","crates/uzu","crates/benchmarks","crates/cli",@@ -52,6 +53,7 @@ token-stream-parser = { path = "crates/token-stream-parser", default-features =hanashi = { path = "crates/hanashi", default-features = false }nagare = { path = "crates/nagare", default-features = false }download-manager = { path = "crates/download-manager", default-features = false }+mock-registry = { path = "crates/mock-registry", default-features = false }benchmarks = { path = "crates/benchmarks", default-features = false }uzu = { path = "crates/uzu", default-features = false }xgrammar = { package = "xgrammar-rs", version = "0.1", features = ["hf"] }@@ -117,6 +119,8 @@ cxx = "1.0"cmake = "0.1"autocxx-build = "0.30"test-tag = "0.1"+rstest = "0.26"+wiremock = "0.6"proptest = { version = "1.10", default-features = false, features = ["std"] }criterion = { version = "0.8.2", default-features = false }criterion-macro = "0.4.0"@@ -129,6 +133,9 @@ tracing-appender = "0.2.4"llm_json = "1.0.2"tokio-stream = { version = "0.1.18", features = ["sync"] }futures-util = "0.3.31"+http = "1.4.0"+httparse = "1.10.1"+stream_throttle = "0.5.1"async-fetcher = "0.12"reqwest = { version = "0.13.2", features = ["json",@@ -141,6 +148,7 @@ async-shutdown = "0.2.2"objc-sys = "0.3.5"crc32c = "0.6.8"base64 = "0.22.1"+bitflags = "2.11.1"chrono = { version = "0.4.42", features = ["serde"] }jsonschema = "0.46.0"# Please make sure to use compatible versions of the cargo-swift / uniffi pair.diff --git a/crates/download-manager/Cargo.toml b/crates/download-manager/Cargo.tomlindex 7b149a0b2..06b4a4552 100644--- a/crates/download-manager/Cargo.toml+++ b/crates/download-manager/Cargo.toml@@ -39,3 +39,11 @@ libc.workspace = trueindicatif.workspace = truetracing-subscriber.workspace = truetracing-appender.workspace = true+rstest.workspace = true+mock-registry.workspace = true+wiremock.workspace = true+chrono.workspace = true++[[test]]+name = "unit"+path = "tests/unit/test_entry.rs"diff --git a/crates/download-manager/examples/cross_platform_download.rs b/crates/download-manager/examples/cross_platform_download.rsindex 0f15bf768..982746e98 100644--- a/crates/download-manager/examples/cross_platform_download.rs+++ b/crates/download-manager/examples/cross_platform_download.rs@@ -10,7 +10,7 @@ use tokio::runtime::Handle;async fn main() -> Result<(), Box<dyn std::error::Error>> {let tokio_handle = Handle::current();- let manager = create_download_manager(FileDownloadManagerType::default(), None, tokio_handle).await?;+ let manager = create_download_manager(FileDownloadManagerType::default(), tokio_handle).await?;let url = "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/tokenizer.json".to_string();diff --git a/crates/download-manager/src/download_manager_state.rs b/crates/download-manager/src/download_manager_state.rsnew file mode 100644index 000000000..954f9c2fa--- /dev/null+++ b/crates/download-manager/src/download_manager_state.rs@@ -0,0 +1,71 @@+use std::{collections::HashMap, sync::Arc};++use tokio::sync::broadcast::channel as tokio_broadcast_channel;+use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;++use crate::{+ DownloadError, DownloadEvent, DownloadId, FileDownloadTask, SharedDownloadEventSender, TokioHandle, TokioMutex,+};++pub(crate) type TaskCache = Arc<TokioMutex<HashMap<DownloadId, Arc<dyn FileDownloadTask>>>>;++#[derive(Clone)]+pub(crate) struct DownloadManagerState {+ pub(crate) manager_id: String,+ pub(crate) global_broadcast_sender: SharedDownloadEventSender,+ pub(crate) tokio_handle: TokioHandle,+ pub(crate) task_cache: TaskCache,+}++impl std::fmt::Debug for DownloadManagerState {+ fn fmt(+ &self,+ formatter: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ formatter.debug_struct("DownloadManagerState").field("manager_id", &self.manager_id).finish()+ }+}++impl DownloadManagerState {+ pub(crate) fn new(+ suffix: &str,+ tokio_handle: TokioHandle,+ ) -> Self {+ let manager_id = generate_manager_id(suffix);+ let (global_broadcast_sender, _global_broadcast_receiver) = tokio_broadcast_channel::<DownloadEvent>(256);+ Self {+ manager_id,+ global_broadcast_sender: Arc::new(global_broadcast_sender),+ tokio_handle,+ task_cache: Arc::new(TokioMutex::new(HashMap::new())),+ }+ }++ pub(crate) fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent> {+ TokioBroadcastStream::new(self.global_broadcast_sender.subscribe())+ }++ pub(crate) async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTask>>, DownloadError> {+ let task_cache_guard = self.task_cache.lock().await;+ Ok(task_cache_guard.values().cloned().collect())+ }+}++fn generate_manager_id(suffix: &str) -> String {+ #[cfg(target_vendor = "apple")]+ {+ use crate::NSBundle;+ let bundle_id = NSBundle::mainBundle().bundleIdentifier().unwrap_or_default().to_string();++ if bundle_id.is_empty() {+ format!("mirai.{suffix}")+ } else {+ format!("{bundle_id}.mirai.{suffix}")+ }+ }++ #[cfg(not(target_vendor = "apple"))]+ {+ format!("mirai.{suffix}")+ }+}diff --git a/crates/download-manager/src/file_download_manager.rs b/crates/download-manager/src/file_download_manager.rsindex ed73b129d..a5a1bd495 100644--- a/crates/download-manager/src/file_download_manager.rs+++ b/crates/download-manager/src/file_download_manager.rs@@ -1,17 +1,21 @@use std::{path::Path, sync::Arc};-use tokio::sync::broadcast::Sender as TokioBroadcastSender;+use tokio::{runtime::Handle as TokioHandle, sync::broadcast::Sender as TokioBroadcastSender};use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;use crate::{DownloadError, DownloadId, FileCheck, FileDownloadEvent, FileDownloadTask};+pub type DownloadEvent = (DownloadId, FileDownloadEvent);+pub type DownloadEventSender = TokioBroadcastSender<DownloadEvent>;+pub type SharedDownloadEventSender = Arc<DownloadEventSender>;+#[async_trait::async_trait]pub trait FileDownloadManager: Send + Sync + 'static {fn manager_id(&self) -> &str;- fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<(DownloadId, FileDownloadEvent)>;+ fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent>;- fn global_broadcast_sender(&self) -> Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>>;+ fn global_broadcast_sender(&self) -> SharedDownloadEventSender;async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTask>>, DownloadError>;@@ -43,8 +47,7 @@ impl Default for FileDownloadManagerType {#[allow(unreachable_code)]pub async fn create_download_manager(r#type: FileDownloadManagerType,- identifier: Option<String>,- tokio_handle: tokio::runtime::Handle,+ tokio_handle: TokioHandle,) -> Result<Box<dyn FileDownloadManager>, DownloadError> {match r#type {FileDownloadManagerType::Universal => {@@ -53,18 +56,17 @@ pub async fn create_download_manager(.with_connections_per_file(4).with_retries(3).with_progress_interval_ms(500);- let manager = AsyncFetcherDownloadManager::new_with_manager_id(config, tokio_handle, identifier).await?;+ let manager = AsyncFetcherDownloadManager::new(config, tokio_handle).await?;return Ok(Box::new(manager) as Box<dyn FileDownloadManager>);},FileDownloadManagerType::Apple => {#[cfg(target_vendor = "apple")]{use crate::managers::apple::{SessionConfig, URLSessionDownloadManager, URLSessionDropPolicy};- let manager = URLSessionDownloadManager::new_with_manager_id(+ let manager = URLSessionDownloadManager::new(SessionConfig::default(),URLSessionDropPolicy::FinishTasksAndInvalidate,tokio_handle,- identifier,).await?;return Ok(Box::new(manager) as Box<dyn FileDownloadManager>);diff --git a/crates/download-manager/src/file_download_task.rs b/crates/download-manager/src/file_download_task.rsindex 423bd2867..71af57270 100644--- a/crates/download-manager/src/file_download_task.rs+++ b/crates/download-manager/src/file_download_task.rs@@ -1,7 +1,7 @@use std::path::Path;use crate::{- DownloadError, DownloadId, FileCheck, FileDownloadEvent, FileDownloadState,+ DownloadError, DownloadEventSender, DownloadId, FileCheck, FileDownloadState,prelude::{TokioBroadcastSender, TokioBroadcastStream},};@@ -20,7 +20,7 @@ pub trait FileDownloadTask: Send + Sync + std::fmt::Debug {async fn start_listening(&self,- global_broadcast: TokioBroadcastSender<(DownloadId, FileDownloadEvent)>,+ global_broadcast: DownloadEventSender,);async fn stop_listening(&self);diff --git a/crates/download-manager/src/lib.rs b/crates/download-manager/src/lib.rsindex 244df88e6..9d8af0e2b 100644--- a/crates/download-manager/src/lib.rs+++ b/crates/download-manager/src/lib.rs@@ -2,6 +2,7 @@ mod checked_file_state;mod crc_utils;mod download_error;mod download_info;+mod download_manager_state;mod download_state;mod file_check;mod file_download_event;@@ -24,7 +25,10 @@ pub use download_info::DownloadInfo;pub use download_state::DownloadState;pub use file_check::FileCheck;pub use file_download_event::FileDownloadEvent;-pub use file_download_manager::{FileDownloadManager, FileDownloadManagerType, create_download_manager};+pub use file_download_manager::{+ DownloadEvent, DownloadEventSender, FileDownloadManager, FileDownloadManagerType, SharedDownloadEventSender,+ create_download_manager,+};pub use file_download_phase::FileDownloadPhase;pub use file_download_state::FileDownloadState;pub use file_download_task::FileDownloadTask;diff --git a/crates/download-manager/src/managers/apple/file_download_task.rs b/crates/download-manager/src/managers/apple/file_download_task.rsindex fb92a5c66..d39c7976e 100644--- a/crates/download-manager/src/managers/apple/file_download_task.rs+++ b/crates/download-manager/src/managers/apple/file_download_task.rs@@ -1,14 +1,27 @@use std::path::PathBuf;-use tokio::sync::{Mutex as TokioMutex, broadcast::Sender as TokioBroadcastSender};+use tokio::{+ sync::{+ Mutex as TokioMutex,+ broadcast::Sender as TokioBroadcastSender,+ watch::{Receiver as TokioWatchReceiver, Sender as TokioWatchSender, channel as tokio_watch_channel},+ },+ time::{Duration as TokioDuration, sleep as tokio_sleep},+};use uuid::Uuid;use crate::{- DownloadError, DownloadId, DownloadInfo, FileCheck, FileDownloadEvent, FileDownloadPhase, FileDownloadState,- FileDownloadTask as FileDownloadTaskTrait, InternalDownloadState, LockFileState, StateTransitionAction,- check_lock_file,+ DownloadError, DownloadEventSender, DownloadId, DownloadInfo, FileCheck, FileDownloadEvent, FileDownloadPhase,+ FileDownloadState, FileDownloadTask as FileDownloadTaskTrait, InternalDownloadState, LockFileState,+ StateTransitionAction, check_lock_file,lock_manager::{acquire_lock, release_lock},- managers::apple::{URLSessionDownloadTaskResumeData, URLSessionExt, UrlSessionDownloadTaskExt},+ managers::apple::{+ URLSessionDownloadTaskResumeData, URLSessionExt, UrlSessionDownloadTaskExt,+ url_session_state_reducer::{+ check_crc_file_exists, check_file_exists, check_resume_file_exists, reconcile_to_internal_state,+ reduce_to_checked_file_state, reduce_to_file_download_state,+ },+ },prelude::*,};@@ -25,8 +38,8 @@ pub struct FileDownloadTask {session: Option<Retained<NSURLSession>>,listener_task: Arc<TokioMutex<Option<TokioJoinHandle<()>>>>,tokio_handle: TokioHandle,- completed_tx: tokio::sync::watch::Sender<bool>,- _completed_rx: tokio::sync::watch::Receiver<bool>,+ completed_tx: TokioWatchSender<bool>,+ _completed_rx: TokioWatchReceiver<bool>,}impl std::fmt::Debug for FileDownloadTask {@@ -57,7 +70,7 @@ impl FileDownloadTask {tokio_handle: TokioHandle,) -> Self {let (broadcast_sender, _receiver) = tokio_broadcast_channel::<FileDownloadState>(64);- let (completed_tx, completed_rx) = tokio::sync::watch::channel(false);+ let (completed_tx, completed_rx) = tokio_watch_channel(false);Self {download_id,source_url,@@ -532,11 +545,6 @@ impl FileDownloadTask {/// Handle URLSession download completion event/// This encapsulates the reduction and reconciliation logicpub async fn handle_download_completion(&self) {- use crate::managers::apple::url_session_state_reducer::{- check_crc_file_exists, check_file_exists, check_resume_file_exists, reconcile_to_internal_state,- reduce_to_checked_file_state, reduce_to_file_download_state,- };-tracing::debug!("[FILE_TASK] handle_download_completion: id={}, dest={}",self.download_id,@@ -547,7 +555,7 @@ impl FileDownloadTask {// macOS file system might have slight latencyself.tokio_handle.spawn(async {- tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;+ tokio_sleep(TokioDuration::from_millis(10)).await;}).await.ok();@@ -664,7 +672,7 @@ impl FileDownloadTask {/// Start listening to global download eventspub async fn start_listening(&self,- global_broadcast: TokioBroadcastSender<(crate::DownloadId, crate::FileDownloadEvent)>,+ global_broadcast: DownloadEventSender,) {// Check if already listeninglet mut listener_guard = self.listener_task.lock().await;@@ -692,7 +700,7 @@ impl FileDownloadTask {tracing::debug!("[FILE_TASK] Received event for download_id={}: {:?}", download_id, event);match event {- crate::FileDownloadEvent::DownloadCompleted {+ FileDownloadEvent::DownloadCompleted {final_destination,..} => {@@ -711,14 +719,14 @@ impl FileDownloadTask {let _ = task.tokio_handle.spawn(async {- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;+ tokio_sleep(TokioDuration::from_millis(100)).await;}).await;task.handle_download_completion().await;let _ = completed.send(true);},- crate::FileDownloadEvent::ProgressUpdate {+ FileDownloadEvent::ProgressUpdate {bytes_written,total_bytes_written,total_bytes_expected,@@ -726,7 +734,7 @@ impl FileDownloadTask {task.handle_progress_update(bytes_written, total_bytes_written, total_bytes_expected).await;},- crate::FileDownloadEvent::Error {+ FileDownloadEvent::Error {message,} => {task.handle_error(message).await;@@ -815,7 +823,7 @@ impl FileDownloadTaskTrait for FileDownloadTask {async fn start_listening(&self,- global_broadcast: TokioBroadcastSender<(DownloadId, FileDownloadEvent)>,+ global_broadcast: DownloadEventSender,) {self.start_listening(global_broadcast).await}diff --git a/crates/download-manager/src/managers/apple/url_session_delegate.rs b/crates/download-manager/src/managers/apple/url_session_delegate.rsindex e7bf92a00..2b1e12244 100644--- a/crates/download-manager/src/managers/apple/url_session_delegate.rs+++ b/crates/download-manager/src/managers/apple/url_session_delegate.rs@@ -1,14 +1,14 @@use std::path::PathBuf;use crate::{- DownloadId, FileDownloadEvent,+ FileDownloadEvent, SharedDownloadEventSender,managers::apple::{URLSessionError, UrlSessionDownloadTaskExt},prelude::*,};#[derive(Debug, Clone)]pub struct URLSessionDelegateIvars {- pub global_broadcast_sender: Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>>,+ pub global_broadcast_sender: SharedDownloadEventSender,}define_class!(@@ -184,7 +184,7 @@ define_class!();impl URLSessionDelegate {- pub fn new(global_broadcast_sender: Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>>) -> Retained<Self> {+ pub fn new(global_broadcast_sender: SharedDownloadEventSender) -> Retained<Self> {unsafe {let class = Self::class();let allocated: Allocated<Self> = msg_send![class, alloc];diff --git a/crates/download-manager/src/managers/apple/url_session_download_manager.rs b/crates/download-manager/src/managers/apple/url_session_download_manager.rsindex c846bc424..62e257dea 100644--- a/crates/download-manager/src/managers/apple/url_session_download_manager.rs+++ b/crates/download-manager/src/managers/apple/url_session_download_manager.rs@@ -1,11 +1,9 @@-use std::{- collections::HashMap,- path::{Path, PathBuf},-};+use std::path::{Path, PathBuf};use crate::{- DownloadError, DownloadId, FileCheck, FileDownloadEvent, FileDownloadManager,- FileDownloadTask as FileDownloadTaskTrait, compute_download_id,+ DownloadError, DownloadEvent, FileCheck, FileDownloadManager, FileDownloadTask as FileDownloadTaskTrait,+ SharedDownloadEventSender, compute_download_id,+ download_manager_state::DownloadManagerState,managers::apple::{FileDownloadTask, SessionConfig, URLSessionDelegate, URLSessionExt, UrlSessionDownloadTaskExt,url_session_state_reducer::{@@ -16,8 +14,6 @@ use crate::{prelude::*,};-type TaskCache = Arc<TokioMutex<HashMap<DownloadId, Arc<dyn FileDownloadTaskTrait>>>>;-#[allow(unused)]#[derive(Debug, Clone)]pub enum URLSessionDropPolicy {@@ -28,34 +24,20 @@ pub enum URLSessionDropPolicy {#[derive(Debug, Clone)]#[allow(dead_code)]pub struct URLSessionDownloadManager {- manager_id: String,+ state: DownloadManagerState,session: Retained<NSURLSession>,delegate: Retained<URLSessionDelegate>,delegate_protocol_object: Retained<ProtocolObject<dyn NSURLSessionDelegate>>,drop_policy: URLSessionDropPolicy,- pub global_broadcast_sender: Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>>,- tokio_handle: TokioHandle,- task_cache: TaskCache,}unsafe impl Send for URLSessionDownloadManager {}unsafe impl Sync for URLSessionDownloadManager {}impl URLSessionDownloadManager {- fn generate_manager_id() -> String {- use crate::NSBundle;- let bundle_id = NSBundle::mainBundle().bundleIdentifier().unwrap_or_default().to_string();-- if bundle_id.is_empty() {- "mirai.apple".to_string()- } else {- format!("{}.mirai.apple", bundle_id)- }- }-#[allow(unused)]pub fn manager_id(&self) -> &str {- &self.manager_id+ &self.state.manager_id}#[allow(unused)]@@ -64,25 +46,10 @@ impl URLSessionDownloadManager {drop_policy: URLSessionDropPolicy,tokio_handle: TokioHandle,) -> Result<Self, DownloadError> {- Self::new_with_manager_id(session_config, drop_policy, tokio_handle, None).await- }-- pub async fn new_with_manager_id(- session_config: SessionConfig,- drop_policy: URLSessionDropPolicy,- tokio_handle: TokioHandle,- custom_manager_id: Option<String>,- ) -> Result<Self, DownloadError> {- let manager_id = custom_manager_id.unwrap_or_else(|| Self::generate_manager_id());-- let (global_broadcast_sender, _global_broadcast_receiver) =- tokio_broadcast_channel::<(DownloadId, FileDownloadEvent)>(256);- let global_broadcast_sender = Arc::new(global_broadcast_sender);-- let task_cache: TaskCache = Arc::new(TokioMutex::new(HashMap::new()));+ let state = DownloadManagerState::new("apple", tokio_handle);let backend = autoreleasepool(|_| unsafe {- let delegate = URLSessionDelegate::new(global_broadcast_sender.clone());+ let delegate = URLSessionDelegate::new(state.global_broadcast_sender.clone());let delegate_protocol_object = ProtocolObject::<dyn NSURLSessionDelegate>::from_retained(delegate.clone());@@ -93,14 +60,11 @@ impl URLSessionDownloadManager {);Self {- manager_id,+ state,session,delegate: delegate.clone(),delegate_protocol_object,drop_policy,- global_broadcast_sender,- tokio_handle,- task_cache,}});@@ -179,7 +143,7 @@ impl URLSessionDownloadManager {Some(&download_task),&destination,expected_bytes,- &self.manager_id,+ &self.state.manager_id,);let file_check = download_info.crc32c.map_or(FileCheck::None, |crc_hash| FileCheck::CRC(crc_hash));@@ -189,15 +153,15 @@ impl URLSessionDownloadManager {download_info.source_url.clone(),destination.clone(),file_check,- self.manager_id.clone(),+ self.state.manager_id.clone(),expected_bytes,internal_state,file_download_state,Some(self.session.clone()),- self.tokio_handle.clone(),+ self.state.tokio_handle.clone(),));- file_task.start_listening((*self.global_broadcast_sender).clone()).await;+ file_task.start_listening((*self.state.global_broadcast_sender).clone()).await;// Special case: If task is Completed and file exists with valid CRC,// the delegate callback was missed (app was closed during completion).@@ -212,7 +176,7 @@ impl URLSessionDownloadManager {file_task.handle_download_completion().await;}- self.task_cache.lock().await.insert(download_id, file_task);+ self.state.task_cache.lock().await.insert(download_id, file_task);} else {download_task.cancel();}@@ -238,20 +202,19 @@ impl Drop for URLSessionDownloadManager {#[async_trait::async_trait]impl FileDownloadManager for URLSessionDownloadManager {fn manager_id(&self) -> &str {- &self.manager_id+ &self.state.manager_id}- fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<(DownloadId, FileDownloadEvent)> {- TokioBroadcastStream::new(self.global_broadcast_sender.subscribe())+ fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent> {+ self.state.subscribe_to_all_downloads()}- fn global_broadcast_sender(&self) -> Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>> {- self.global_broadcast_sender.clone()+ fn global_broadcast_sender(&self) -> SharedDownloadEventSender {+ self.state.global_broadcast_sender.clone()}async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTaskTrait>>, DownloadError> {- let task_cache_guard = self.task_cache.lock().await;- Ok(task_cache_guard.values().cloned().collect())+ self.state.get_all_file_tasks().await}async fn file_download_task(@@ -266,7 +229,7 @@ impl FileDownloadManager for URLSessionDownloadManager {let download_id = compute_download_id(source_url, destination_path);{- let task_cache_guard = self.task_cache.lock().await;+ let task_cache_guard = self.state.task_cache.lock().await;if let Some(cached_task) = task_cache_guard.get(&download_id) {return Ok(cached_task.clone());}@@ -274,7 +237,7 @@ impl FileDownloadManager for URLSessionDownloadManager {// Check lock file before proceeding (result will be used by reduction only)let lock_path = PathBuf::from(format!("{}.lock", destination_path.display()));- let _ = check_lock_file(&lock_path, &self.manager_id, std::process::id());+ let _ = check_lock_file(&lock_path, &self.state.manager_id, std::process::id());// If file is locked by another manager, do not error here.// Reduction will expose LockedByOther in the FileDownloadState.@@ -311,7 +274,7 @@ impl FileDownloadManager for URLSessionDownloadManager {None,destination_path,expected_bytes,- &self.manager_id,+ &self.state.manager_id,);// Do not acquire lock here. Lock acquisition/release is handled during@@ -322,19 +285,19 @@ impl FileDownloadManager for URLSessionDownloadManager {source_url.clone(),destination_path.to_path_buf(),file_check,- self.manager_id.clone(),+ self.state.manager_id.clone(),expected_bytes,internal_state,file_download_state,Some(self.session.clone()),- self.tokio_handle.clone(),+ self.state.tokio_handle.clone(),));// Start listening to global broadcast eventstracing::debug!("[MANAGER] Starting listener for download_id={}", download_id);- file_task.start_listening((*self.global_broadcast_sender).clone()).await;+ file_task.start_listening((*self.state.global_broadcast_sender).clone()).await;- self.task_cache.lock().await.insert(download_id, file_task.clone());+ self.state.task_cache.lock().await.insert(download_id, file_task.clone());Ok(file_task)}}diff --git a/crates/download-manager/src/managers/universal/async_fetcher_download_manager.rs b/crates/download-manager/src/managers/universal/async_fetcher_download_manager.rsindex b319beaca..e54190266 100644--- a/crates/download-manager/src/managers/universal/async_fetcher_download_manager.rs+++ b/crates/download-manager/src/managers/universal/async_fetcher_download_manager.rs@@ -1,48 +1,22 @@-use std::collections::HashMap;-use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;use crate::{- Arc, DownloadError, DownloadId, FileCheck, FileDownloadEvent, FileDownloadManager,- FileDownloadTask as FileDownloadTaskTrait, Path, PathBuf, TokioBroadcastSender, TokioHandle, TokioMutex,- compute_download_id,+ Arc, DownloadError, DownloadEvent, FileCheck, FileDownloadManager, FileDownloadTask as FileDownloadTaskTrait, Path,+ PathBuf, SharedDownloadEventSender, TokioHandle, compute_download_id,+ download_manager_state::DownloadManagerState,managers::universal::{AsyncFetcherConfig, FileDownloadTask},- tokio_broadcast_channel,};-type TaskCache = Arc<TokioMutex<HashMap<DownloadId, Arc<dyn FileDownloadTaskTrait>>>>;-#[derive(Debug, Clone)]pub struct AsyncFetcherDownloadManager {- manager_id: String,+ state: DownloadManagerState,pub config: AsyncFetcherConfig,- pub global_broadcast_sender: Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>>,- tokio_handle: TokioHandle,- task_cache: TaskCache,}impl AsyncFetcherDownloadManager {- fn generate_manager_id() -> String {- #[cfg(target_vendor = "apple")]- {- use crate::NSBundle;- let bundle_id = NSBundle::mainBundle().bundleIdentifier().unwrap_or_default().to_string();-- if bundle_id.is_empty() {- "mirai.universal".to_string()- } else {- format!("{}.mirai.universal", bundle_id)- }- }- #[cfg(not(target_vendor = "apple"))]- {- "mirai.universal".to_string()- }- }-#[allow(unused)]pub fn manager_id(&self) -> &str {- &self.manager_id+ &self.state.manager_id}#[allow(unused)]@@ -50,33 +24,16 @@ impl AsyncFetcherDownloadManager {config: AsyncFetcherConfig,tokio_handle: TokioHandle,) -> Result<Self, DownloadError> {- Self::new_with_manager_id(config, tokio_handle, None).await- }-- pub async fn new_with_manager_id(- config: AsyncFetcherConfig,- tokio_handle: TokioHandle,- custom_manager_id: Option<String>,- ) -> Result<Self, DownloadError> {- let manager_id = custom_manager_id.unwrap_or_else(|| Self::generate_manager_id());-- let (global_broadcast_sender, _global_broadcast_receiver) =- tokio_broadcast_channel::<(DownloadId, FileDownloadEvent)>(256);- let global_broadcast_sender = Arc::new(global_broadcast_sender);-- let task_cache: TaskCache = Arc::new(TokioMutex::new(HashMap::new()));+ let state = DownloadManagerState::new("universal", tokio_handle);let manager = Self {- manager_id: manager_id.clone(),+ state,config,- global_broadcast_sender,- tokio_handle,- task_cache,};tracing::debug!("[DOWNLOAD_MANAGER] AsyncFetcherDownloadManager created with tokio handle, manager_id={}",- manager_id+ manager.manager_id());Ok(manager)@@ -87,20 +44,19 @@ impl AsyncFetcherDownloadManager {impl FileDownloadManager for AsyncFetcherDownloadManager {#[allow(unused)]fn manager_id(&self) -> &str {- &self.manager_id+ &self.state.manager_id}- fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<(DownloadId, FileDownloadEvent)> {- TokioBroadcastStream::new(self.global_broadcast_sender.subscribe())+ fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent> {+ self.state.subscribe_to_all_downloads()}- fn global_broadcast_sender(&self) -> Arc<TokioBroadcastSender<(DownloadId, FileDownloadEvent)>> {- self.global_broadcast_sender.clone()+ fn global_broadcast_sender(&self) -> SharedDownloadEventSender {+ self.state.global_broadcast_sender.clone()}async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTaskTrait>>, DownloadError> {- let task_cache_guard = self.task_cache.lock().await;- Ok(task_cache_guard.values().cloned().collect())+ self.state.get_all_file_tasks().await}async fn file_download_task(@@ -118,7 +74,7 @@ impl FileDownloadManager for AsyncFetcherDownloadManager {let download_id = compute_download_id(source_url, destination_path);{- let task_cache_guard = self.task_cache.lock().await;+ let task_cache_guard = self.state.task_cache.lock().await;if let Some(cached_task) = task_cache_guard.get(&download_id) {return Ok(cached_task.clone());}@@ -174,7 +130,7 @@ impl FileDownloadManager for AsyncFetcherDownloadManager {destination_path.display(),part_file_path.display(),expected_bytes,- self.manager_id+ self.state.manager_id);let file_download_state = reduce_to_file_download_state(checked_file_state,@@ -182,7 +138,7 @@ impl FileDownloadManager for AsyncFetcherDownloadManager {destination_path,&part_file_path,expected_bytes,- &self.manager_id,+ &self.state.manager_id,);tracing::info!("[MANAGER:AF] initial states: internal={:?}, display={:?}", internal_state, file_download_state);@@ -192,18 +148,18 @@ impl FileDownloadManager for AsyncFetcherDownloadManager {source_url.clone(),destination_path.to_path_buf(),file_check,- self.manager_id.clone(),+ self.state.manager_id.clone(),expected_bytes,internal_state,file_download_state,self.config.clone(),- self.tokio_handle.clone(),+ self.state.tokio_handle.clone(),));tracing::debug!("[MANAGER] Starting listener for download_id={}", download_id);- file_task.start_listening((*self.global_broadcast_sender).clone()).await;+ file_task.start_listening((*self.state.global_broadcast_sender).clone()).await;- self.task_cache.lock().await.insert(download_id, file_task.clone());+ self.state.task_cache.lock().await.insert(download_id, file_task.clone());Ok(file_task)}}diff --git a/crates/download-manager/src/managers/universal/async_fetcher_file_download_task.rs b/crates/download-manager/src/managers/universal/async_fetcher_file_download_task.rsindex 85bd2c860..ffedbbcf1 100644--- a/crates/download-manager/src/managers/universal/async_fetcher_file_download_task.rs+++ b/crates/download-manager/src/managers/universal/async_fetcher_file_download_task.rs@@ -1,16 +1,23 @@use async_fetcher::{FetchEvent, Fetcher, Source};use async_shutdown::ShutdownManager;-use tokio::sync::mpsc;+use tokio::{+ sync::{+ mpsc,+ watch::{Receiver as TokioWatchReceiver, Sender as TokioWatchSender, channel as tokio_watch_channel},+ },+ time::{Duration as TokioDuration, sleep as tokio_sleep},+};use tokio_stream::{StreamExt as TokioStreamExt,wrappers::{BroadcastStream as TokioBroadcastStream, UnboundedReceiverStream},};use crate::{- Arc, DownloadError, DownloadId, FileCheck, FileDownloadEvent, FileDownloadPhase, FileDownloadState,- FileDownloadTask as FileDownloadTaskTrait, InternalDownloadState, LockFileState, PathBuf, StateTransitionAction,- TokioBroadcastSender, TokioHandle, TokioJoinHandle, TokioMutex, Uuid, acquire_lock, calculate_and_verify_crc,- check_lock_file, crc_utils, fs, managers::universal::AsyncFetcherConfig, release_lock, tokio_broadcast_channel,+ Arc, DownloadError, DownloadEventSender, DownloadId, FileCheck, FileDownloadEvent, FileDownloadPhase,+ FileDownloadState, FileDownloadTask as FileDownloadTaskTrait, InternalDownloadState, LockFileState, PathBuf,+ StateTransitionAction, TokioBroadcastSender, TokioHandle, TokioJoinHandle, TokioMutex, Uuid, acquire_lock,+ calculate_and_verify_crc, check_lock_file, crc_utils, fs, managers::universal::AsyncFetcherConfig, release_lock,+ tokio_broadcast_channel,};pub struct FileDownloadTask {@@ -28,8 +35,8 @@ pub struct FileDownloadTask {fetcher_task: Arc<TokioMutex<Option<TokioJoinHandle<()>>>>,listener_task: Arc<TokioMutex<Option<TokioJoinHandle<()>>>>,tokio_handle: TokioHandle,- completed_tx: tokio::sync::watch::Sender<bool>,- _completed_rx: tokio::sync::watch::Receiver<bool>,+ completed_tx: TokioWatchSender<bool>,+ _completed_rx: TokioWatchReceiver<bool>,}impl std::fmt::Debug for FileDownloadTask {@@ -60,7 +67,7 @@ impl FileDownloadTask {tokio_handle: TokioHandle,) -> Self {let (broadcast_sender, _receiver) = tokio_broadcast_channel::<FileDownloadState>(64);- let (completed_tx, completed_rx) = tokio::sync::watch::channel(false);+ let (completed_tx, completed_rx) = tokio_watch_channel(false);Self {download_id,source_url,@@ -295,7 +302,7 @@ impl FileDownloadTask {destination.display());// Give a brief moment for filesystem operations to complete- tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;+ tokio_sleep(TokioDuration::from_millis(100)).await;if !destination.exists() {tracing::error!(@@ -560,7 +567,7 @@ impl FileDownloadTask {pub async fn start_listening(&self,- global_broadcast: TokioBroadcastSender<(DownloadId, FileDownloadEvent)>,+ global_broadcast: DownloadEventSender,) {let mut listener_guard = self.listener_task.lock().await;if listener_guard.is_some() {@@ -716,7 +723,7 @@ impl FileDownloadTaskTrait for FileDownloadTask {async fn start_listening(&self,- global_broadcast: TokioBroadcastSender<(DownloadId, FileDownloadEvent)>,+ global_broadcast: DownloadEventSender,) {self.start_listening(global_broadcast).await}diff --git a/crates/download-manager/src/prelude/universal.rs b/crates/download-manager/src/prelude/universal.rsindex 463284b9b..26b576ea3 100644--- a/crates/download-manager/src/prelude/universal.rs+++ b/crates/download-manager/src/prelude/universal.rs@@ -8,7 +8,6 @@ pub use tokio::{fs,runtime::Handle as TokioHandle,sync::{- Mutex as TokioMutex,broadcast::{Sender as TokioBroadcastSender, channel as tokio_broadcast_channel},oneshot::{Sender as TokioOneshotSender, channel as tokio_oneshot_channel},},diff --git a/crates/download-manager/tests/common/mod.rs b/crates/download-manager/tests/common/mod.rsindex 3b11e91b6..835a12efe 100644--- a/crates/download-manager/tests/common/mod.rs+++ b/crates/download-manager/tests/common/mod.rs@@ -1,4 +1,32 @@-mod test_helpers;-pub mod tracing_setup;+use std::sync::Arc;-pub use test_helpers::TestDownloadManager;+use download_manager::{FileDownloadPhase, FileDownloadState, FileDownloadTask};+pub use mock_registry::{Behavior, MockRegistry};+use tokio_stream::{StreamExt, wrappers::BroadcastStream};++pub async fn wait_for_phase(+ task: &Arc<dyn FileDownloadTask>,+ progress_stream: &mut BroadcastStream<FileDownloadState>,+ mut is_expected_phase: impl FnMut(&FileDownloadPhase) -> bool,+) -> FileDownloadState {+ let state = task.state().await;+ if is_expected_phase(&state.phase) {+ return state;+ }++ while let Some(result) = progress_stream.next().await {+ let state = result.expect("download progress stream must not lag");+ if is_expected_phase(&state.phase) {+ return state;+ }+ }++ panic!("download progress stream ended before expected phase");+}++pub fn error_message(state: FileDownloadState) -> String {+ let FileDownloadPhase::Error(message) = state.phase else {+ unreachable!("state must be an error")+ };+ message+}diff --git a/crates/download-manager/tests/common/test_helpers.rs b/crates/download-manager/tests/common/test_helpers.rsdeleted file mode 100644index aa3e2b895..000000000--- a/crates/download-manager/tests/common/test_helpers.rs+++ /dev/null@@ -1,98 +0,0 @@-#![allow(dead_code)]--use std::path::PathBuf;--use download_manager::{FileDownloadManager, FileDownloadManagerType, create_download_manager};--pub struct TestFile {- pub url: String,- pub size: u64,- pub crc: String,-}--impl Default for TestFile {- fn default() -> Self {- Self {- url: "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/tokenizer.json".to_string(),- size: 12807982,- crc: "C/tYqQ==".to_string(),- }- }-}--pub struct TestDownloadManager {- pub manager: Box<dyn FileDownloadManager>,- pub temp_dir: PathBuf,- pub _temp_dir_guard: tempfile::TempDir,- pub test_file: TestFile,-}--impl TestDownloadManager {- /// Create a test manager (platform-specific implementation)- pub async fn new(- test_name: &str,- r#type: FileDownloadManagerType,- ) -> Result<Self, Box<dyn std::error::Error>> {- let temp_dir_guard = tempfile::tempdir()?;- let temp_dir = temp_dir_guard.path().to_path_buf();-- tracing::info!("Test download manager directory: {}", temp_dir.display());-- tracing::info!("Using {:?} manager for test: {}", r#type, test_name);- let tokio_handle = tokio::runtime::Handle::current();- let manager = create_download_manager(r#type, Some(test_name.to_string()), tokio_handle).await?;-- Ok(Self {- manager,- temp_dir,- _temp_dir_guard: temp_dir_guard,- test_file: TestFile::default(),- })- }-- pub fn dest_path(- &self,- filename: &str,- ) -> PathBuf {- self.temp_dir.join(filename)- }-- #[allow(dead_code)]- pub fn cleanup_artifacts(- &self,- filename: &str,- ) {- let file_path = self.dest_path(filename);- let _ = std::fs::remove_file(&file_path);- let _ = std::fs::remove_file(format!("{}.crc", file_path.display()));- let _ = std::fs::remove_file(format!("{}.resume_data", file_path.display()));- }-- #[allow(dead_code)]- pub fn create_test_file(- &self,- filename: &str,- content: &[u8],- ) -> PathBuf {- let file_path = self.dest_path(filename);- std::fs::write(&file_path, content).unwrap();- file_path- }-- #[allow(dead_code)]- pub fn create_crc_file(- &self,- filename: &str,- crc_value: &str,- ) {- let file_path = self.dest_path(filename);- let crc_path = format!("{}.crc", file_path.display());- std::fs::write(crc_path, crc_value).unwrap();- }-- #[allow(dead_code)]- pub async fn cleanup(self) {- drop(self.manager);- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- }-}diff --git a/crates/download-manager/tests/common/tracing_setup.rs b/crates/download-manager/tests/common/tracing_setup.rsdeleted file mode 100644index 3debca931..000000000--- a/crates/download-manager/tests/common/tracing_setup.rs+++ /dev/null@@ -1,33 +0,0 @@-use std::sync::Once;--use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};--#[allow(dead_code)]-static INIT: Once = Once::new();--#[allow(dead_code)]-pub fn init_test_tracing() {- INIT.call_once(|| {- let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");-- // Use workspace root for test_logs- let log_dir = std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")).join("test_logs");- std::fs::create_dir_all(&log_dir).ok();-- let file_appender =- tracing_appender::rolling::never(&log_dir, format!("file_download_manager_{}.log", timestamp));-- let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);-- // Keep guard alive for entire test run- std::mem::forget(guard);-- tracing_subscriber::registry()- .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))- .with(fmt::layer().with_writer(non_blocking).with_ansi(false))- .with(fmt::layer().with_writer(std::io::stdout))- .init();-- tracing::info!("Test logging initialized, writing to test_logs/");- });-}diff --git a/crates/download-manager/tests/test_apple_manager_comprehensive.rs b/crates/download-manager/tests/test_apple_manager_comprehensive.rsdeleted file mode 100644index 37de2fae8..000000000--- a/crates/download-manager/tests/test_apple_manager_comprehensive.rs+++ /dev/null@@ -1,413 +0,0 @@-mod common;--use std::time::Duration;--use common::TestDownloadManager;-use download_manager::{FileCheck, FileDownloadManagerType, FileDownloadPhase};-use indicatif::{ProgressBar, ProgressStyle};-use tokio::time::timeout;-use tokio_stream::StreamExt;--#[tokio::test(flavor = "multi_thread")]-#[ignore = "flaky"]-async fn test_apple_manager_comprehensive() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!(- "[TEST][{}] ========== COMPREHENSIVE DOWNLOAD TEST STARTING ==========",- format!("{:?}", std::thread::current().id())- );-- let test_manager =- TestDownloadManager::new("test_apple_manager_comprehensive", FileDownloadManagerType::Apple).await?;- let mgr = &test_manager.manager;- let dest_path = test_manager.dest_path("test_file");- tracing::info!("[TEST] Destination: {}", dest_path.display());-- // Clean up any existing artifacts from previous runs- tracing::info!("[TEST] Cleaning up any existing artifacts...");- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(format!("{}.crc", dest_path.display()));- let _ = std::fs::remove_file(format!("{}.resume_data", dest_path.display()));- let _ = std::fs::remove_file(format!("{}.lock", dest_path.display()));- tracing::info!("[TEST] Starting fresh download...");-- // Create progress bar- let pb = ProgressBar::new(0);- pb.set_style(- ProgressStyle::default_bar()- .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%, {bytes_per_sec}, eta {eta}) - {msg}")- .unwrap()- .progress_chars("█▓▒░ "),- );-- // ========== PHASE 1: Download to 25% ==========- tracing::info!("\n[TEST] ========== PHASE 1: Download to 25% ==========");- pb.set_message("Phase 1: Downloading to 25%");-- let task = mgr- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;-- let initial_state = task.state().await;- tracing::info!("[TEST] Initial task state: {:?}", initial_state.phase);- tracing::info!("[TEST] Initial bytes: {} / {}", initial_state.downloaded_bytes, initial_state.total_bytes);-- let mut stream = task.progress().await?;- tracing::info!("[TEST] Subscribed to progress stream");-- task.download().await?;- tracing::info!("[TEST] Started download (task_id={}), waiting for 25% progress...", task.download_id());-- // Verify lock file was created- let lock_path = format!("{}.lock", dest_path.display());- tokio::time::sleep(Duration::from_millis(500)).await; // Give it a moment- if std::path::Path::new(&lock_path).exists() {- tracing::info!("[TEST] ✓ Lock file created: {}", lock_path);- } else {- tracing::warn!("[TEST] ⚠ Lock file not found (may not be implemented yet)");- }-- let mut total_bytes: u64 = 0;- let mut update_count = 0;- let phase1_result = timeout(Duration::from_secs(120), async {- tracing::info!("[TEST] Waiting for progress updates...");- while let Some(next) = stream.next().await {- update_count += 1;- tracing::info!("[TEST] Received update #{}", update_count);- if let Ok(state) = next {- tracing::info!(- "[TEST] Update #{}: phase={:?}, bytes={}/{}",- update_count,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- match state.phase {- FileDownloadPhase::Downloading => {- if state.total_bytes > 0 {- total_bytes = state.total_bytes;- if pb.length().unwrap_or(0) == 0 {- pb.set_length(state.total_bytes);- }- pb.set_position(state.downloaded_bytes);-- let progress_pct = (state.downloaded_bytes as f64 / state.total_bytes as f64) * 100.0;- tracing::info!(- "[TEST] Progress: {:.1}% ({} / {} bytes)",- progress_pct,- state.downloaded_bytes,- state.total_bytes- );- if progress_pct >= 25.0 {- tracing::info!(- "[TEST] ✓ Reached 25% target ({} / {} bytes)",- state.downloaded_bytes,- state.total_bytes- );- return Ok::<(u64, u64), String>((state.downloaded_bytes, state.total_bytes));- }- }- },- FileDownloadPhase::Downloaded => {- tracing::info!("[TEST] ⚠️ Download completed before 25%!");- return Ok((state.downloaded_bytes, state.total_bytes));- },- FileDownloadPhase::Error(err) => {- tracing::info!("[TEST] ❌ Error in phase 1: {}", err);- return Err(format!("Error in phase 1: {}", err));- },- _ => {- tracing::info!("[TEST] Other phase: {:?}", state.phase);- },- }- }- }- Err("Stream ended before reaching 25%".to_string())- })- .await;-- let (_, _, download_completed_early) = match phase1_result {- Ok(Ok((downloaded, total))) => {- tracing::info!("[TEST] Phase 1 complete: {} / {} bytes", downloaded, total);- let completed = downloaded >= total && total > 0;- if completed {- tracing::info!("[TEST] ⚠️ Download completed during phase 1 - network too fast!");- }- (downloaded, total, completed)- },- Ok(Err(e)) => panic!("Phase 1 failed: {}", e),- Err(_) => panic!("Phase 1 timed out"),- };-- // ========== PHASE 2: Pause ==========- tracing::info!("\n[TEST] ========== PHASE 2: Pause ==========");- pb.set_message("Phase 2: Pausing...");-- if download_completed_early {- tracing::info!("[TEST] Skipping pause phase - download already completed");- let state = task.state().await;- assert!(- matches!(state.phase, FileDownloadPhase::Downloaded),- "Expected Downloaded state for completed download, got {:?}",- state.phase- );- tracing::info!("[TEST] Confirmed downloaded state: {} bytes", state.downloaded_bytes);- } else {- task.pause().await?;- tracing::info!("[TEST] Paused download");- tokio::time::sleep(Duration::from_millis(500)).await;-- let state = task.state().await;- assert!(matches!(state.phase, FileDownloadPhase::Paused), "Expected Paused state, got {:?}", state.phase);- tracing::info!("[TEST] Confirmed paused state: {} / {} bytes", state.downloaded_bytes, state.total_bytes);- }-- // ========== PHASE 3: Resume to 50% ==========- if download_completed_early {- tracing::info!("\n[TEST] ========== PHASE 3: Skipped (already downloaded) ==========");- } else {- tracing::info!("\n[TEST] ========== PHASE 3: Resume to 50% ==========");- pb.set_message("Phase 3: Resuming to 50%");-- // Get fresh task handle after pause- let task = mgr- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;- task.download().await?;- tracing::info!("[TEST] Resumed download, waiting for 50% progress...");-- // Get fresh stream from new handle- let mut stream = task.progress().await?;-- let phase3_result = timeout(Duration::from_secs(120), async {- while let Some(next) = stream.next().await {- if let Ok(state) = next {- match state.phase {- FileDownloadPhase::Downloading => {- if state.total_bytes > 0 {- if pb.length().unwrap_or(0) == 0 {- pb.set_length(state.total_bytes);- }- pb.set_position(state.downloaded_bytes);-- let progress_pct = (state.downloaded_bytes as f64 / state.total_bytes as f64) * 100.0;- if progress_pct >= 50.0 {- tracing::info!(- "[TEST] Reached 50% ({} / {} bytes)",- state.downloaded_bytes,- state.total_bytes- );- return Ok::<(u64, u64), String>((state.downloaded_bytes, state.total_bytes));- }- }- },- FileDownloadPhase::Downloaded => {- tracing::info!("[TEST] Download completed before 50%!");- return Ok((state.downloaded_bytes, state.total_bytes));- },- FileDownloadPhase::Error(err) => {- return Err(format!("Error in phase 3: {}", err));- },- _ => {},- }- }- }- Err("Stream ended before reaching 50%".to_string())- })- .await;-- match phase3_result {- Ok(Ok((downloaded, total))) => {- tracing::info!("[TEST] Phase 3 complete: {} / {} bytes", downloaded, total);- },- Ok(Err(e)) => panic!("Phase 3 failed: {}", e),- Err(_) => panic!("Phase 3 timed out"),- }-- // ========== PHASE 4: Cancel ==========- tracing::info!("\n[TEST] ========== PHASE 4: Cancel ==========");- pb.set_message("Phase 4: Cancelling...");-- task.cancel().await?;- tracing::info!("[TEST] Cancelled download");- tokio::time::sleep(Duration::from_millis(500)).await;-- let state = task.state().await;- assert!(- matches!(state.phase, FileDownloadPhase::NotDownloaded),- "Expected NotDownloaded state after cancel, got {:?}",- state.phase- );- tracing::info!("[TEST] Confirmed cancelled state");-- // Drop the old stream- drop(stream);-- // ========== PHASE 5: Download again to 50% ==========- tracing::info!("\n[TEST] ========== PHASE 5: Download again to 50% ==========");- pb.set_message("Phase 5: Downloading again to 50%");- pb.set_position(0); // Reset progress bar-- // Create new task for fresh download- let task2 = mgr- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;- let mut stream2 = task2.progress().await?;-- task2.download().await?;- tracing::info!("[TEST] Started fresh download, waiting for 50% progress...");-- let phase5_result = timeout(Duration::from_secs(120), async {- while let Some(next) = stream2.next().await {- if let Ok(state) = next {- match state.phase {- FileDownloadPhase::Downloading => {- if state.total_bytes > 0 {- if pb.length().unwrap_or(0) == 0 {- pb.set_length(state.total_bytes);- }- pb.set_position(state.downloaded_bytes);-- let progress_pct = (state.downloaded_bytes as f64 / state.total_bytes as f64) * 100.0;- if progress_pct >= 50.0 {- tracing::info!(- "[TEST] Reached 50% again ({} / {} bytes)",- state.downloaded_bytes,- state.total_bytes- );- return Ok::<(u64, u64), String>((state.downloaded_bytes, state.total_bytes));- }- }- },- FileDownloadPhase::Downloaded => {- tracing::info!("[TEST] Download completed before 50%!");- return Ok((state.downloaded_bytes, state.total_bytes));- },- FileDownloadPhase::Error(err) => {- return Err(format!("Error in phase 5: {}", err));- },- _ => {},- }- }- }- Err("Stream ended before reaching 50%".to_string())- })- .await;-- match phase5_result {- Ok(Ok((downloaded, total))) => {- tracing::info!("[TEST] Phase 5 complete: {} / {} bytes", downloaded, total);- },- Ok(Err(e)) => panic!("Phase 5 failed: {}", e),- Err(_) => panic!("Phase 5 timed out"),- }-- // ========== PHASE 6: Pause at 50% ==========- tracing::info!("\n[TEST] ========== PHASE 6: Pause at 50% ==========");- pb.set_message("Phase 6: Pausing at 50%");-- task2.pause().await?;- tracing::info!("[TEST] Paused download at ~50%");- tokio::time::sleep(Duration::from_millis(500)).await;-- let state = task2.state().await;- assert!(matches!(state.phase, FileDownloadPhase::Paused), "Expected Paused state, got {:?}", state.phase);- tracing::info!(- "[TEST] Confirmed paused state at 50%: {} / {} bytes",- state.downloaded_bytes,- state.total_bytes- );-- // ========== PHASE 7: Resume to completion ==========- tracing::info!("\n[TEST] ========== PHASE 7: Resume to completion ==========");- pb.set_message("Phase 7: Resuming to completion");-- // Get fresh task handle after pause- let task2 = mgr- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;- task2.download().await?;- tracing::info!("[TEST] Resumed download, waiting for completion...");-- // Get fresh stream from new handle- let mut stream2 = task2.progress().await?;-- let phase7_result = timeout(Duration::from_secs(240), async {- while let Some(next) = stream2.next().await {- match next {- Ok(state) => match state.phase {- FileDownloadPhase::Downloading => {- if state.total_bytes > 0 {- if pb.length().unwrap_or(0) == 0 {- pb.set_length(state.total_bytes);- }- pb.set_position(state.downloaded_bytes);- }- },- FileDownloadPhase::Downloaded => {- pb.finish_with_message("✓ Download complete!");- tracing::info!("[TEST] Download completed successfully!");- return Ok::<(), String>(());- },- FileDownloadPhase::Error(err) => {- pb.abandon_with_message(format!("✗ Error: {}", err));- return Err(format!("Error in phase 7: {}", err));- },- _ => {},- },- Err(_) => {- // Ignore lag errors- },- }- }- Err("Stream ended before completion".to_string())- })- .await;-- match phase7_result {- Ok(Ok(())) => {- tracing::info!("[TEST] Phase 7 complete: Download finished!");- },- Ok(Err(e)) => panic!("Phase 7 failed: {}", e),- Err(_) => panic!("Phase 7 timed out"),- }- }-- // Verify file exists and has content- tracing::info!("\n[TEST] ========== FINAL VERIFICATION ==========");- assert!(dest_path.is_file(), "Destination file does not exist");- let metadata = std::fs::metadata(&dest_path)?;- assert!(metadata.len() > 0, "Downloaded file is empty");- tracing::info!("[TEST] Verified file exists with size: {} bytes", metadata.len());-- // Verify lock file was cleaned up after completion- let lock_path = format!("{}.lock", dest_path.display());- if std::path::Path::new(&lock_path).exists() {- tracing::warn!("[TEST] ⚠ Lock file still exists after completion (should be cleaned up)");- } else {- tracing::info!("[TEST] ✓ Lock file properly cleaned up");- }-- test_manager.cleanup().await;- tracing::info!("[TEST] ========== COMPREHENSIVE DOWNLOAD TEST COMPLETE ==========\n");- Ok(())-}diff --git a/crates/download-manager/tests/test_apple_manager_global_broadcast.rs b/crates/download-manager/tests/test_apple_manager_global_broadcast.rsdeleted file mode 100644index 2c2603498..000000000--- a/crates/download-manager/tests/test_apple_manager_global_broadcast.rs+++ /dev/null@@ -1,149 +0,0 @@-mod common;--use std::{sync::Arc, time::Duration};--use common::TestDownloadManager;-use download_manager::{FileCheck, FileDownloadEvent, FileDownloadManagerType};-use futures_util::StreamExt;-use indicatif::{ProgressBar, ProgressStyle};--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_global_broadcast() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("=== Global Broadcast Progress Test ===");-- let test_manager =- TestDownloadManager::new("test_apple_manager_global_broadcast", FileDownloadManagerType::Apple).await?;- let dest_path = test_manager.dest_path("test_file");- let manager = Arc::new(test_manager.manager);-- tracing::info!("Creating file download task...");- let task = manager- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc),- Some(test_manager.test_file.size),- )- .await?;-- tracing::info!("Subscribing to GLOBAL downloads...");- let mut global_updates = manager.subscribe_to_all_downloads();- tracing::info!("[GLOBAL_TEST] Subscribed to global broadcast channel");-- let pb = ProgressBar::new(0);- pb.set_style(- ProgressStyle::default_bar()- .template(- "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, eta {eta})"- )- .unwrap()- .progress_chars("█▓▒░ "),- );- pb.set_message("Downloading");-- let task_download_id = task.download_id();- let pb_clone = pb.clone();- let (completion_tx, mut completion_rx) = tokio::sync::mpsc::channel::<()>(1);-- let monitor_task = tokio::spawn(async move {- const IDLE_TIMEOUT: Duration = Duration::from_secs(30);- let mut update_count = 0;-- loop {- match tokio::time::timeout(IDLE_TIMEOUT, global_updates.next()).await {- Ok(Some(Ok((download_id, event)))) => {- update_count += 1;-- if download_id == task_download_id {- match event {- FileDownloadEvent::ProgressUpdate {- bytes_written: _,- total_bytes_written,- total_bytes_expected,- } => {- let progress = if total_bytes_expected > 0 {- total_bytes_written as f64 / total_bytes_expected as f64 * 100.0- } else {- 0.0- };-- tracing::info!(- "[GLOBAL_TEST] Update #{}: Progress - {}/{} bytes ({:.1}%)",- update_count,- total_bytes_written,- total_bytes_expected,- progress- );-- if pb_clone.length().unwrap_or(0) == 0 && total_bytes_expected > 0 {- pb_clone.set_length(total_bytes_expected);- }-- pb_clone.set_position(total_bytes_written);- },- FileDownloadEvent::DownloadCompleted {- tmp_path: _,- final_destination: _,- } => {- tracing::info!("[GLOBAL_TEST] Update #{}: Downloaded", update_count);- pb_clone.finish_with_message("✓ Downloaded");- let _ = completion_tx.send(()).await;- break;- },- FileDownloadEvent::Error {- message,- } => {- pb_clone.abandon_with_message(format!("Error: {}", message));- break;- },- }- } else {- tracing::info!("Update #{}: Different file ({})", update_count, download_id);- }- },- Ok(Some(Err(e))) => {- tracing::info!("Broadcast error: {}", e);- },- Ok(None) => {- tracing::info!("Stream ended after {} updates", update_count);- pb_clone.abandon_with_message("Stream ended");- break;- },- Err(_) => {- tracing::info!("No progress for 30s after {} updates", update_count);- pb_clone.abandon_with_message("Timeout");- break;- },- }- }-- update_count- });-- tracing::info!("Starting download...");- task.download().await?;- tracing::info!("[GLOBAL_TEST] Download started, task_id={}", task.download_id());-- tracing::info!("Waiting for completion or timeout...");- let completed = tokio::time::timeout(Duration::from_secs(60), completion_rx.recv()).await.is_ok();-- let update_count = monitor_task.await?;-- tracing::info!("\nResults:");- tracing::info!(" Updates received: {}", update_count);- tracing::info!(" Completed: {}", completed);-- if update_count > 0 {- tracing::info!(" ✓ Global broadcast is working!");- } else {- tracing::info!(" ❌ No updates received - URLSession delegates not firing in test");- tracing::info!(" This is expected in cargo test environment");- tracing::info!(" Actual downloads work in CLI/app context");- }-- // Cleanup (manager is Arc wrapped, just drop it and wait)- drop(manager);- tokio::time::sleep(Duration::from_millis(100)).await;-- Ok(())-}diff --git a/crates/download-manager/tests/test_apple_manager_lock_file.rs b/crates/download-manager/tests/test_apple_manager_lock_file.rsdeleted file mode 100644index 4eff4a5a0..000000000--- a/crates/download-manager/tests/test_apple_manager_lock_file.rs+++ /dev/null@@ -1,323 +0,0 @@-mod common;--use std::time::Duration;--use common::TestDownloadManager;-use download_manager::{- FileCheck, FileDownloadManagerType, LockFileInfo, LockFileState, acquire_lock, check_lock_file, release_lock,-};-use tokio::time::sleep;--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_lock_file_prevents_concurrent_downloads() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("[TEST] ========== LOCK FILE CONCURRENT DOWNLOAD TEST ==========");-- // Create two managers (simulating two app instances)- let test_manager1 = TestDownloadManager::new(- "test_apple_manager_lock_file_prevents_concurrent_downloads_1",- FileDownloadManagerType::Apple,- )- .await?;- let test_manager2 = TestDownloadManager::new(- "test_apple_manager_lock_file_prevents_concurrent_downloads_2",- FileDownloadManagerType::Apple,- )- .await?;-- let dest_path = test_manager1.dest_path("locked_file.safetensors");- tracing::info!("[TEST] Destination: {}", dest_path.display());-- // Clean up any existing artifacts- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(format!("{}.crc", dest_path.display()));- let _ = std::fs::remove_file(format!("{}.resume_data", dest_path.display()));- let _ = std::fs::remove_file(format!("{}.lock", dest_path.display()));-- // Manager 1 starts download (should acquire lock)- tracing::info!("[TEST] Manager 1: Creating task and starting download...");- let task1 = test_manager1- .manager- .file_download_task(&test_manager1.test_file.url, &dest_path, FileCheck::None, None)- .await?;-- task1.download().await?;- tracing::info!("[TEST] Manager 1: Download started");-- // Give it a moment to acquire the lock- sleep(Duration::from_millis(500)).await;-- // Verify lock file exists- let lock_path = format!("{}.lock", dest_path.display());- assert!(std::path::Path::new(&lock_path).exists(), "Lock file should exist after download started");-- // Manager 2 creates the same task; reduction should mark it as LockedByOther- tracing::info!("[TEST] Manager 2: Creating task for same file...");- let task2 = test_manager2- .manager- .file_download_task(&test_manager2.test_file.url, &dest_path, FileCheck::None, None)- .await?;-- // Wait a moment for state to be computed- sleep(Duration::from_millis(200)).await;-- let state2 = task2.state().await;- match state2.phase {- download_manager::FileDownloadPhase::LockedByOther(owner) => {- tracing::info!("[TEST] ✓ Task 2 marked as locked by {}", owner);- assert!(owner.contains("downloads_1"));- },- other => panic!("Task 2 should be LockedByOther, got: {:?}", other),- }-- // Cancel manager 1's download- tracing::info!("[TEST] Manager 1: Cancelling download...");- task1.cancel().await?;-- tracing::info!("[TEST] ========== LOCK FILE TEST PASSED ==========");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_lock_file_stale_detection() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("[TEST] ========== LOCK FILE STALE DETECTION TEST ==========");-- let test_manager =- TestDownloadManager::new("test_apple_manager_lock_file_stale_detection", FileDownloadManagerType::Apple)- .await?;- let dest_path = test_manager.dest_path("stale_lock_file.txt");- let lock_path = std::path::PathBuf::from(format!("{}.lock", dest_path.display()));-- // Clean up- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(&lock_path);-- // Create a stale lock file (with a fake PID that doesn't exist)- let fake_lock = LockFileInfo {- manager_id: "com.otherapp.trymirai.url-session-download-manager".to_string(),- acquired_at: chrono::Utc::now() - chrono::Duration::hours(2), // 2 hours ago (stale)- process_id: 99999, // Non-existent PID- };-- let lock_json = serde_json::to_string_pretty(&fake_lock)?;- std::fs::write(&lock_path, lock_json)?;- tracing::info!("[TEST] Created fake stale lock file");-- // Check lock state - should be detected as stale- let our_manager_id = test_manager.manager.manager_id();- let lock_state = check_lock_file(&lock_path, our_manager_id, std::process::id());-- tracing::info!("[TEST] Lock state: {:?}", lock_state);-- match lock_state {- LockFileState::Stale(info) => {- tracing::info!("[TEST] ✓ Lock correctly detected as stale");- assert_eq!(info.process_id, 99999);- },- _ => {- panic!("Lock should have been detected as stale, got: {:?}", lock_state);- },- }-- // Now acquire the lock (should succeed)- tracing::info!("[TEST] Attempting to acquire stale lock...");- let handle = tokio::runtime::Handle::current();- acquire_lock(&handle, &lock_path, our_manager_id).await?;- tracing::info!("[TEST] ✓ Successfully acquired stale lock");-- // Verify we own it now- let lock_state = check_lock_file(&lock_path, our_manager_id, std::process::id());- match lock_state {- LockFileState::OwnedByUs(_) => {- tracing::info!("[TEST] ✓ Lock now owned by us");- },- _ => {- panic!("Lock should be owned by us, got: {:?}", lock_state);- },- }-- // Release the lock- let handle = tokio::runtime::Handle::current();- release_lock(&handle, &lock_path).await?;- assert!(!lock_path.exists(), "Lock file should be deleted after release");-- tracing::info!("[TEST] ========== STALE DETECTION TEST PASSED ==========");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_lock_file_same_app_crash_recovery() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("[TEST] ========== LOCK FILE CRASH RECOVERY TEST ==========");-- let test_manager = TestDownloadManager::new(- "test_apple_manager_lock_file_same_app_crash_recovery",- FileDownloadManagerType::Apple,- )- .await?;- let dest_path = test_manager.dest_path("crash_recovery_file.txt");- let lock_path = std::path::PathBuf::from(format!("{}.lock", dest_path.display()));-- // Clean up- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(&lock_path);-- let our_manager_id = test_manager.manager.manager_id();-- // Simulate a crash: create a lock with our manager_id but different PID- let old_lock = LockFileInfo {- manager_id: our_manager_id.to_string(),- acquired_at: chrono::Utc::now() - chrono::Duration::minutes(5),- process_id: std::process::id() + 10000, // Different PID from same app- };-- let lock_json = serde_json::to_string_pretty(&old_lock)?;- std::fs::write(&lock_path, lock_json)?;- tracing::info!("[TEST] Created fake lock from crashed process (same app)");-- // Check lock state - should be detected as OwnedBySameAppOldProcess (if PID dead)- // or OwnedByUs if we can detect it's safe to reacquire- let lock_state = check_lock_file(&lock_path, our_manager_id, std::process::id());-- tracing::info!("[TEST] Lock state after crash: {:?}", lock_state);-- // The lock should either be Stale or OwnedBySameAppOldProcess- // Both mean we can reacquire it- assert!(lock_state.can_proceed(), "Lock from crashed same-app process should be reacquirable");-- // Acquire the lock (simulating app restart after crash)- let handle = tokio::runtime::Handle::current();- acquire_lock(&handle, &lock_path, our_manager_id).await?;- tracing::info!("[TEST] ✓ Successfully reacquired lock after simulated crash");-- // Verify we own it now with current PID- let lock_state = check_lock_file(&lock_path, our_manager_id, std::process::id());- match lock_state {- LockFileState::OwnedByUs(info) => {- tracing::info!("[TEST] ✓ Lock owned by current process");- assert_eq!(info.process_id, std::process::id());- assert_eq!(info.manager_id, our_manager_id);- },- _ => {- panic!("Lock should be owned by us, got: {:?}", lock_state);- },- }-- let handle = tokio::runtime::Handle::current();- release_lock(&handle, &lock_path).await?;-- tracing::info!("[TEST] ========== CRASH RECOVERY TEST PASSED ==========");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_lock_file_atomic_operations() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("[TEST] ========== LOCK FILE ATOMIC OPERATIONS TEST ==========");-- let test_manager =- TestDownloadManager::new("test_apple_manager_lock_file_atomic_operations", FileDownloadManagerType::Apple)- .await?;- let dest_path = test_manager.dest_path("atomic_lock_file.txt");- let lock_path = std::path::PathBuf::from(format!("{}.lock", dest_path.display()));-- // Clean up- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(&lock_path);-- let manager_id = test_manager.manager.manager_id();-- // Test acquire- tracing::info!("[TEST] Acquiring lock...");- let handle = tokio::runtime::Handle::current();- acquire_lock(&handle, &lock_path, manager_id).await?;- assert!(lock_path.exists(), "Lock file should exist after acquire");-- // Read and verify lock contents- let lock_contents = std::fs::read_to_string(&lock_path)?;- let lock_info: LockFileInfo = serde_json::from_str(&lock_contents)?;-- assert_eq!(lock_info.manager_id, manager_id);- assert_eq!(lock_info.process_id, std::process::id());- tracing::info!("[TEST] ✓ Lock file contains correct information");-- // Test release- tracing::info!("[TEST] Releasing lock...");- let handle = tokio::runtime::Handle::current();- release_lock(&handle, &lock_path).await?;- assert!(!lock_path.exists(), "Lock file should be deleted after release");-- tracing::info!("[TEST] ========== ATOMIC OPERATIONS TEST PASSED ==========");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_lock_file_removed_after_download_completion() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("[TEST] ========== LOCK FILE CLEANUP TEST ==========");-- // Create a test manager- let test_manager = TestDownloadManager::new(- "test_apple_manager_lock_file_removed_after_download_completion",- FileDownloadManagerType::Apple,- )- .await?;- let dest_path = test_manager.dest_path("test_file");- let lock_path = std::path::PathBuf::from(format!("{}.lock", dest_path.display()));-- tracing::info!("[TEST] Destination: {}", dest_path.display());- tracing::info!("[TEST] Lock path: {}", lock_path.display());-- // Clean up any existing artifacts- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(format!("{}.crc", dest_path.display()));- let _ = std::fs::remove_file(format!("{}.resume_data", dest_path.display()));- let _ = std::fs::remove_file(&lock_path);-- // Start download (should acquire lock)- tracing::info!("[TEST] Starting download...");- let task =- test_manager.manager.file_download_task(&test_manager.test_file.url, &dest_path, FileCheck::None, None).await?;-- task.download().await?;- tracing::info!("[TEST] Download started");-- // Wait a moment for lock acquisition- sleep(Duration::from_millis(200)).await;-- // Verify lock file exists during download- assert!(lock_path.exists(), "Lock file should exist during download");- tracing::info!("[TEST] ✓ Lock file exists during download");-- // Wait for download to complete (with timeout)- let mut attempts = 0;- let max_attempts = 600; // 60 seconds max- let mut download_completed = false;-- while attempts < max_attempts {- let state = task.state().await;- tracing::debug!("[TEST] Download state: {:?}", state.phase);-- if matches!(state.phase, download_manager::FileDownloadPhase::Downloaded) {- download_completed = true;- break;- }-- if matches!(state.phase, download_manager::FileDownloadPhase::Error(_)) {- panic!("Download failed: {:?}", state.phase);- }-- sleep(Duration::from_millis(100)).await;- attempts += 1;- }-- assert!(download_completed, "Download should complete within timeout");- tracing::info!("[TEST] ✓ Download completed successfully");-- // Give a small delay for lock cleanup to complete- sleep(Duration::from_millis(200)).await;-- // Verify lock file is removed after completion- assert!(!lock_path.exists(), "Lock file should be removed after successful download completion");- tracing::info!("[TEST] ✓ Lock file removed after download completion");-- tracing::info!("[TEST] ========== LOCK FILE CLEANUP TEST PASSED ==========");- Ok(())-}diff --git a/crates/download-manager/tests/test_apple_manager_resume_data_cleanup.rs b/crates/download-manager/tests/test_apple_manager_resume_data_cleanup.rsdeleted file mode 100644index 2968d93f6..000000000--- a/crates/download-manager/tests/test_apple_manager_resume_data_cleanup.rs+++ /dev/null@@ -1,105 +0,0 @@-#![cfg(target_vendor = "apple")]--mod common;--use std::time::Duration;--use common::TestDownloadManager;-use download_manager::{FileCheck, FileDownloadManagerType, FileDownloadPhase};-use tokio::time::sleep;--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_resume_data_deleted_on_resume() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("[TEST] ========== RESUME DATA CLEANUP TEST ==========");-- let test_manager =- TestDownloadManager::new("test_apple_manager_resume_data_deleted_on_resume", FileDownloadManagerType::Apple)- .await?;- let dest_path = test_manager.dest_path("test_file");- let resume_path = std::path::PathBuf::from(format!("{}.resume_data", dest_path.display()));- let lock_path = std::path::PathBuf::from(format!("{}.lock", dest_path.display()));-- // Clean up any existing artifacts- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(format!("{}.crc", dest_path.display()));- let _ = std::fs::remove_file(&resume_path);- let _ = std::fs::remove_file(&lock_path);-- // Create task and start download- let task = test_manager- .manager- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;-- task.download().await?;-- // Wait until we are Downloading and have some bytes- let mut attempts = 0;- let max_attempts = 200;- loop {- let state = task.state().await;- if matches!(state.phase, FileDownloadPhase::Downloading) && state.total_bytes > 0 {- break;- }- attempts += 1;- if attempts >= max_attempts {- panic!("Timeout waiting for Downloading state");- }- sleep(Duration::from_millis(50)).await;- }-- // Pause to create resume_data- task.pause().await?;-- // Wait for Paused and resume_data to appear- let mut attempts = 0;- loop {- let state = task.state().await;- let has_resume = resume_path.exists();- if matches!(state.phase, FileDownloadPhase::Paused) && has_resume {- break;- }- attempts += 1;- if attempts >= max_attempts {- panic!(- "Timeout waiting for Paused state with resume_data present (state={:?}, resume_exists={})",- state.phase, has_resume- );- }- sleep(Duration::from_millis(50)).await;- }-- // Resume download- task.download().await?;-- // After resume begins, resume_data must be deleted promptly- let mut attempts = 0;- loop {- let state = task.state().await;- let resume_exists = resume_path.exists();- // Accept either Downloading without resume_data, or very fast completion with no resume_data- if (!resume_exists)- && (matches!(state.phase, FileDownloadPhase::Downloading)- || matches!(state.phase, FileDownloadPhase::Downloaded))- {- break;- }- attempts += 1;- if attempts >= max_attempts {- panic!(- "Timeout waiting for resume_data deletion on resume (state={:?}, resume_exists={})",- state.phase, resume_exists- );- }- sleep(Duration::from_millis(50)).await;- }-- tracing::info!("[TEST] ✓ resume_data removed upon resuming download");-- Ok(())-}diff --git a/crates/download-manager/tests/test_apple_manager_resume_data_modify.rs b/crates/download-manager/tests/test_apple_manager_resume_data_modify.rsdeleted file mode 100644index 4b8b7463f..000000000--- a/crates/download-manager/tests/test_apple_manager_resume_data_modify.rs+++ /dev/null@@ -1,150 +0,0 @@-#![cfg(target_vendor = "apple")]--mod common;--use std::time::Duration;--use common::TestDownloadManager;-use download_manager::{- FileCheck, FileDownloadManagerType, FileDownloadPhase, managers::apple::URLSessionDownloadTaskResumeData,-};-use tokio::time::timeout;-use tokio_stream::StreamExt;--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_resume_data_can_be_modified_and_saved() -> Result<(), Box<dyn std::error::Error>> {- let test_manager = TestDownloadManager::new(- "test_apple_manager_resume_data_can_be_modified_and_saved",- FileDownloadManagerType::Apple,- )- .await?;- let mgr = &test_manager.manager;- let dest_path = test_manager.dest_path("test_file");-- tracing::info!("Cleaning up any existing artifacts...");- let _ = std::fs::remove_file(&dest_path);- let _ = std::fs::remove_file(format!("{}.crc", dest_path.display()));- let _ = std::fs::remove_file(format!("{}.resume_data", dest_path.display()));-- let task = mgr- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;-- let initial_state = task.state().await;- tracing::info!("Initial state: {:?}", initial_state.phase);-- // Start download BEFORE subscribing to stream- task.download().await?;- tracing::info!("Download started...");-- tokio::time::sleep(Duration::from_millis(100)).await;-- let mut stream = task.progress().await?;- tracing::info!("Subscribed to progress stream, waiting for updates...");-- let mut observed_downloaded: Option<u64> = None;- let mut observed_total: Option<u64> = None;-- let _ = timeout(Duration::from_secs(60), async {- let mut update_count = 0;- while let Some(next) = stream.next().await {- if let Ok(state) = next {- update_count += 1;- if update_count % 10 == 1 {- tracing::info!(- "Update #{}: {:?} - {}/{} bytes",- update_count,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- }-- match state.phase {- FileDownloadPhase::Downloading => {- if state.total_bytes > 0 {- observed_total = Some(state.total_bytes);- let target = state.total_bytes / 50; // 2%- if state.downloaded_bytes >= target && target > 0 {- observed_downloaded = Some(state.downloaded_bytes);- tracing::info!("Reached target at {} bytes", state.downloaded_bytes);- break;- }- }- },- FileDownloadPhase::Downloaded => {- tracing::info!("Download completed: {} bytes", state.downloaded_bytes);- observed_downloaded = Some(state.downloaded_bytes);- observed_total = Some(state.total_bytes);- break;- },- _ => {},- }- }- }- tracing::info!("Stream ended after {} updates", update_count);- })- .await;-- assert!(observed_downloaded.is_some(), "should have observed progress");- assert!(observed_total.is_some(), "should have observed total bytes");-- // Pause to generate resume data- task.pause().await?;-- // Check if download completed- let final_state = task.state().await;- if matches!(final_state.phase, FileDownloadPhase::Downloaded) {- tracing::info!("Download completed before pause - test passed (no resume data to modify)");- test_manager.cleanup().await;- return Ok(());- }-- // Read the resume data file- let resume_path = format!("{}.resume_data", dest_path.display());- let original_bytes = std::fs::read(&resume_path)?;-- // Parse resume data- let mut resume_data = URLSessionDownloadTaskResumeData::from_bytes(&original_bytes)?;-- tracing::info!(- "Original resume data: bytes_received={:?}, bytes_expected={:?}",- resume_data.bytes_received,- resume_data.bytes_expected_to_receive- );-- // Verify bytes_received is present- assert!(resume_data.bytes_received.is_some(), "bytes_received should be present");-- // Modify: add expected bytes if not present- if resume_data.bytes_expected_to_receive.is_none() {- resume_data.bytes_expected_to_receive = observed_total;- tracing::info!("Injected expected bytes: {:?}", resume_data.bytes_expected_to_receive);-- // Save modified resume data- resume_data.save_to_file(&resume_path)?;-- // Re-read and verify the modification was saved- let saved_bytes = std::fs::read(&resume_path)?;- let reloaded = URLSessionDownloadTaskResumeData::from_bytes(&saved_bytes)?;-- tracing::info!(- "Reloaded resume data: bytes_received={:?}, bytes_expected={:?}",- reloaded.bytes_received,- reloaded.bytes_expected_to_receive- );-- assert_eq!(reloaded.bytes_received, resume_data.bytes_received, "bytes_received should be preserved");- assert_eq!(reloaded.bytes_expected_to_receive, observed_total, "bytes_expected_to_receive should be saved");-- tracing::info!("✓ Successfully modified and saved resume data");- }-- test_manager.cleanup().await;- Ok(())-}diff --git a/crates/download-manager/tests/test_apple_manager_resume_data_parse.rs b/crates/download-manager/tests/test_apple_manager_resume_data_parse.rsdeleted file mode 100644index f2ef1ffe6..000000000--- a/crates/download-manager/tests/test_apple_manager_resume_data_parse.rs+++ /dev/null@@ -1,121 +0,0 @@-#![cfg(target_vendor = "apple")]--mod common;--use std::time::Duration;--use common::TestDownloadManager;-use download_manager::{- FileCheck, FileDownloadManagerType, FileDownloadPhase, managers::apple::URLSessionDownloadTaskResumeData,-};-use tokio::time::{sleep, timeout};-use tokio_stream::StreamExt;--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_resume_data_contains_reasonable_progress_bytes() -> Result<(), Box<dyn std::error::Error>> {- let test_manager = TestDownloadManager::new(- "test_apple_manager_resume_data_contains_reasonable_progress_bytes",- FileDownloadManagerType::Apple,- )- .await?;- let mgr = &test_manager.manager;- let dest_path = test_manager.dest_path("test_file");-- let task = mgr- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;- let mut stream = task.progress().await?;-- // Start the download and wait until we have some meaningful progress- task.download().await?;-- let mut observed_downloaded: Option<u64> = None;- let mut observed_total: Option<u64> = None;-- let _ = timeout(Duration::from_secs(60), async {- while let Some(next) = stream.next().await {- if let Ok(state) = next {- match state.phase {- FileDownloadPhase::Downloading => {- observed_total = Some(state.total_bytes);- // Choose a modest threshold to ensure resumeData has content- let target = if state.total_bytes > 0 {- // 2% or at least 5 MiB, whichever is lower- let two_percent = state.total_bytes / 50;- two_percent.min(5 * 1024 * 1024)- } else {- 5 * 1024 * 1024- };- if state.downloaded_bytes >= target && target > 0 {- observed_downloaded = Some(state.downloaded_bytes);- break;- }- },- FileDownloadPhase::Downloaded => {- // Completed too fast; take the final number- observed_downloaded = Some(state.downloaded_bytes);- observed_total = Some(state.total_bytes);- break;- },- _ => {},- }- }- }- })- .await;-- // Ensure we recorded some progress- let observed_downloaded = observed_downloaded.unwrap_or(0);- assert!(observed_downloaded > 0, "no progress observed before cancellation");-- // Pause to generate resume data- task.pause().await?;-- // Check if download completed- let final_state = task.state().await;- if matches!(final_state.phase, FileDownloadPhase::Downloaded) {- tracing::info!("Download completed before pause - test passed (no resume data to parse)");- test_manager.cleanup().await;- return Ok(());- }-- // Read the written resume data file- let resume_path = format!("{}.resume_data", dest_path.display());- let resume_bytes = std::fs::read(&resume_path)?;- assert!(!resume_bytes.is_empty(), "resume_data file is empty: {}", resume_path);-- // Parse and verify- let resume_data = URLSessionDownloadTaskResumeData::from_bytes(&resume_bytes).expect("failed to parse resume_data");-- // Expect positive received bytes- let bytes_received = resume_data.bytes_received.expect("bytes_received should be present");- assert!(bytes_received > 0, "parsed bytes_received is zero");-- // Tolerance: allow up to 10% or 10 MiB difference, whichever is larger- let diff = if bytes_received > observed_downloaded {- bytes_received - observed_downloaded- } else {- observed_downloaded - bytes_received- };- let ten_percent = observed_downloaded / 10;- let max_allowed = ten_percent.max(10 * 1024 * 1024);- assert!(- diff <= max_allowed,- "parsed bytes_received ({}) diverges too much from observed ({})",- bytes_received,- observed_downloaded- );-- // Note: total_bytes is not reliably available in resume data, so we skip that check-- // Small wait to allow any background cleanup- sleep(Duration::from_millis(200)).await;-- test_manager.cleanup().await;- Ok(())-}diff --git a/crates/download-manager/tests/test_apple_manager_specific_broadcast.rs b/crates/download-manager/tests/test_apple_manager_specific_broadcast.rsdeleted file mode 100644index da87637f7..000000000--- a/crates/download-manager/tests/test_apple_manager_specific_broadcast.rs+++ /dev/null@@ -1,128 +0,0 @@-mod common;--use std::time::Duration;--use common::TestDownloadManager;-use download_manager::{FileCheck, FileDownloadManagerType, FileDownloadPhase};-use futures_util::StreamExt;-use indicatif::{ProgressBar, ProgressStyle};--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_manager_specific_broadcast() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("=== Task-Specific Broadcast Test ===");-- let test_manager =- TestDownloadManager::new("test_apple_manager_specific_broadcast", FileDownloadManagerType::Apple).await?;- let dest_path = test_manager.dest_path("test_file");- let manager = &test_manager.manager;-- tracing::info!("Creating task...");- let task = manager- .file_download_task(- &test_manager.test_file.url,- &dest_path,- FileCheck::CRC(test_manager.test_file.crc.clone()),- Some(test_manager.test_file.size),- )- .await?;-- tracing::info!("Subscribing to TASK-SPECIFIC progress...");- let mut task_progress = task.progress().await?;- tracing::info!("[TASK_TEST] Subscribed to task-specific progress channel");-- let pb = ProgressBar::new(0);- pb.set_style(- ProgressStyle::default_bar()- .template(- "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec})",- )- .unwrap()- .progress_chars("█▓▒░ "),- );-- let pb_clone = pb.clone();- let (completion_tx, mut completion_rx) = tokio::sync::mpsc::channel::<()>(1);-- let monitor_task = tokio::spawn(async move {- const IDLE_TIMEOUT: Duration = Duration::from_secs(30);- let mut update_count = 0;-- loop {- match tokio::time::timeout(IDLE_TIMEOUT, task_progress.next()).await {- Ok(Some(Ok(state))) => {- update_count += 1;-- let progress = if state.total_bytes > 0 {- state.downloaded_bytes as f64 / state.total_bytes as f64 * 100.0- } else {- 0.0- };-- tracing::info!(- "[TASK_TEST] Update #{}: {:?} - {}/{} bytes ({:.1}%)",- update_count,- state.phase,- state.downloaded_bytes,- state.total_bytes,- progress- );-- if pb_clone.length().unwrap_or(0) == 0 && state.total_bytes > 0 {- pb_clone.set_length(state.total_bytes);- }- pb_clone.set_position(state.downloaded_bytes);-- match state.phase {- FileDownloadPhase::Downloaded => {- pb_clone.finish_with_message("✓ Downloaded");- let _ = completion_tx.send(()).await;- break;- },- FileDownloadPhase::Error(msg) => {- pb_clone.abandon_with_message(format!("Error: {}", msg));- break;- },- _ => {},- }- },- Ok(Some(Err(e))) => {- tracing::info!("Stream error: {}", e);- },- Ok(None) => {- tracing::info!("Stream ended after {} updates", update_count);- break;- },- Err(_) => {- tracing::info!("No updates for 30s after {} updates", update_count);- pb_clone.abandon_with_message("Timeout");- break;- },- }- }-- update_count- });-- tracing::info!("Starting download...");- task.download().await?;- tracing::info!("[TASK_TEST] Download started, task_id={}", task.download_id());-- let completed = tokio::time::timeout(Duration::from_secs(60), completion_rx.recv()).await.is_ok();-- let update_count = monitor_task.await?;-- tracing::info!("\nResults:");- tracing::info!(" Task-specific updates received: {}", update_count);- tracing::info!(" Download completed: {}", completed);-- if update_count > 0 {- tracing::info!(" ✓ TASK-SPECIFIC broadcast works!");- tracing::info!(" This proves URLSession delegates ARE firing");- } else {- tracing::info!(" ❌ No task-specific updates");- tracing::info!(" URLSession delegates not firing in test environment");- }-- test_manager.cleanup().await;- Ok(())-}diff --git a/crates/download-manager/tests/test_universal_manager.rs b/crates/download-manager/tests/test_universal_manager.rsdeleted file mode 100644index 294c4e5f7..000000000--- a/crates/download-manager/tests/test_universal_manager.rs+++ /dev/null@@ -1,94 +0,0 @@-mod common;--use common::TestDownloadManager;-use download_manager::{FileCheck, FileDownloadManagerType};--#[tokio::test]-async fn test_universal_manager_create() {- let test_manager = TestDownloadManager::new("test_universal_manager_create", FileDownloadManagerType::Universal)- .await- .expect("Failed to create manager");-- let tasks = test_manager.manager.get_all_file_tasks().await.expect("Failed to get tasks");- assert_eq!(tasks.len(), 0, "New manager should have no tasks");-}--#[tokio::test]-async fn test_universal_manager_create_download_task() {- let test_manager =- TestDownloadManager::new("test_universal_manager_create_download_task", FileDownloadManagerType::Universal)- .await- .expect("Failed to create manager");-- let destination = test_manager.dest_path("test_file");-- let task = test_manager- .manager- .file_download_task(&test_manager.test_file.url, &destination, FileCheck::None, None)- .await- .expect("Failed to create task");-- assert_eq!(task.source_url(), &test_manager.test_file.url);- assert_eq!(task.destination(), &destination);-}--#[tokio::test]-async fn test_universal_manager_task_state_transitions() {- let test_manager =- TestDownloadManager::new("test_universal_manager_task_state_transitions", FileDownloadManagerType::Universal)- .await- .expect("Failed to create manager");-- let destination = test_manager.dest_path("test_file");-- let task = test_manager- .manager- .file_download_task(- &test_manager.test_file.url,- &destination,- FileCheck::None,- Some(test_manager.test_file.size),- )- .await- .expect("Failed to create task");-- let initial_state = task.state().await;- assert!(- matches!(initial_state.phase, download_manager::FileDownloadPhase::NotDownloaded),- "Initial state should be NotDownloaded"- );-}--#[tokio::test]-async fn test_universal_manager_part_file_state_reconciliation() {- let test_manager = TestDownloadManager::new(- "test_universal_manager_part_file_state_reconciliation",- FileDownloadManagerType::Universal,- )- .await- .expect("Failed to create manager");-- let destination = test_manager.dest_path("test_file");-- let part_path = destination.with_extension("part");- std::fs::write(&part_path, b"partial content").expect("Failed to write part file");-- let task = test_manager- .manager- .file_download_task(- &test_manager.test_file.url,- &destination,- FileCheck::None,- Some(test_manager.test_file.size),- )- .await- .expect("Failed to create task");-- let state = task.state().await;- assert!(- matches!(state.phase, download_manager::FileDownloadPhase::Paused),- "State should be Paused when part file exists, got {:?}",- state.phase- );- assert!(state.downloaded_bytes > 0, "Should have downloaded bytes");-}diff --git a/crates/download-manager/tests/unit/lifecycle_test.rs b/crates/download-manager/tests/unit/lifecycle_test.rsnew file mode 100644index 000000000..3e8c6ff7b--- /dev/null+++ b/crates/download-manager/tests/unit/lifecycle_test.rs@@ -0,0 +1,39 @@+use download_manager::{FileCheck, FileDownloadManagerType, FileDownloadPhase, create_download_manager};+use rstest::rstest;+use tokio::runtime::Handle as TokioHandle;++use crate::common::{MockRegistry, wait_for_phase};++#[rstest]+#[case::universal(FileDownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]+#[tokio::test(flavor = "multi_thread")]+async fn test_download_fresh_completes(+ #[case] download_manager_type: FileDownloadManagerType,+) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start().await?;+ let tokenizer = registry.file("tokenizer.json")?;+ let temp_dir = tempfile::tempdir().unwrap();+ let destination = temp_dir.path().join(&tokenizer.file.name);++ let manager = create_download_manager(download_manager_type, TokioHandle::current()).await.unwrap();+ let task = manager+ .file_download_task(+ &tokenizer.file.url,+ &destination,+ FileCheck::CRC(tokenizer.crc32c()?),+ Some(tokenizer.file.size as u64),+ )+ .await+ .unwrap();+ let mut progress = task.progress().await.unwrap();++ task.download().await.unwrap();+ let state = wait_for_phase(&task, &mut progress, |phase| matches!(phase, FileDownloadPhase::Downloaded)).await;++ assert_eq!(state.downloaded_bytes, tokenizer.file.size as u64);+ assert_eq!(state.total_bytes, tokenizer.file.size as u64);+ assert_eq!(tokio::fs::read(&destination).await.unwrap(), tokenizer.bytes.to_vec());+ assert!(std::path::PathBuf::from(format!("{}.crc", destination.display())).is_file());+ Ok(())+}diff --git a/crates/download-manager/tests/unit/mod.rs b/crates/download-manager/tests/unit/mod.rsnew file mode 100644index 000000000..1170c23f9--- /dev/null+++ b/crates/download-manager/tests/unit/mod.rs@@ -0,0 +1,2 @@+mod lifecycle_test;+mod universal;diff --git a/crates/download-manager/tests/unit/test_entry.rs b/crates/download-manager/tests/unit/test_entry.rsnew file mode 100644index 000000000..c0d36c57c--- /dev/null+++ b/crates/download-manager/tests/unit/test_entry.rs@@ -0,0 +1,4 @@+#[path = "../common/mod.rs"]+mod common;++include!("mod.rs");diff --git a/crates/download-manager/tests/unit/universal/corrupt_body_test.rs b/crates/download-manager/tests/unit/universal/corrupt_body_test.rsnew file mode 100644index 000000000..ae480c730--- /dev/null+++ b/crates/download-manager/tests/unit/universal/corrupt_body_test.rs@@ -0,0 +1,32 @@+use download_manager::{FileCheck, FileDownloadManagerType, FileDownloadPhase, create_download_manager};+use tokio::runtime::Handle as TokioHandle;++use crate::common::{Behavior, MockRegistry, error_message, wait_for_phase};++#[tokio::test(flavor = "multi_thread")]+async fn test_universal_corrupt_body_fails_crc() -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start_with(Behavior::CORRUPT_BODY).await?;+ let tokenizer = registry.file("tokenizer.json")?;+ let temp_dir = tempfile::tempdir().unwrap();+ let destination = temp_dir.path().join(&tokenizer.file.name);+ let manager = create_download_manager(FileDownloadManagerType::Universal, TokioHandle::current()).await.unwrap();+ let task = manager+ .file_download_task(+ &tokenizer.file.url,+ &destination,+ FileCheck::CRC(tokenizer.crc32c()?),+ Some(tokenizer.file.size as u64),+ )+ .await+ .unwrap();+ let mut progress = task.progress().await.unwrap();++ task.download().await.unwrap();+ let state = wait_for_phase(&task, &mut progress, |phase| matches!(phase, FileDownloadPhase::Error(_))).await;+ let message = error_message(state);+ assert!(+ message.contains("CRC") || message.contains("checksum"),+ "unexpected error: {message}"+ );+ Ok(())+}diff --git a/crates/download-manager/tests/unit/universal/mod.rs b/crates/download-manager/tests/unit/universal/mod.rsnew file mode 100644index 000000000..0b67dbb8c--- /dev/null+++ b/crates/download-manager/tests/unit/universal/mod.rs@@ -0,0 +1,2 @@+mod corrupt_body_test;+mod state_and_lock_regression_test;diff --git a/crates/download-manager/tests/unit/universal/state_and_lock_regression_test.rs b/crates/download-manager/tests/unit/universal/state_and_lock_regression_test.rsnew file mode 100644index 000000000..790245e10--- /dev/null+++ b/crates/download-manager/tests/unit/universal/state_and_lock_regression_test.rs@@ -0,0 +1,71 @@+use std::{path::PathBuf, sync::Arc};++use chrono::Utc;+use download_manager::{FileCheck, FileDownloadManagerType, FileDownloadPhase, create_download_manager};+use tokio::{fs::write as tokio_write, runtime::Handle as TokioHandle};++use crate::common::MockRegistry;++#[tokio::test(flavor = "multi_thread")]+async fn test_universal_foreign_lock_surfaces_locked_state() -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start().await?;+ let model_weights = registry.file("model.safetensors")?;+ let temp_dir = tempfile::tempdir().unwrap();+ let destination = temp_dir.path().join(&model_weights.file.name);+ let lock_path = PathBuf::from(format!("{}.lock", destination.display()));+ let foreign_lock = serde_json::json!({+ "manager_id": "other-manager",+ "acquired_at": Utc::now(),+ "process_id": std::process::id(),+ });+ tokio_write(&lock_path, serde_json::to_vec(&foreign_lock).unwrap())+ .await+ .unwrap();++ let manager = create_download_manager(FileDownloadManagerType::Universal, TokioHandle::current()).await.unwrap();+ let task = manager+ .file_download_task(+ &model_weights.file.url,+ &destination,+ FileCheck::CRC(model_weights.crc32c()?),+ Some(model_weights.file.size as u64),+ )+ .await+ .unwrap();++ let state = task.state().await;+ assert!(matches!(state.phase, FileDownloadPhase::LockedByOther(_)));+ Ok(())+}++#[tokio::test(flavor = "multi_thread")]+async fn test_universal_concurrent_task_creation_returns_same_task() -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start().await?;+ let tokenizer = registry.file("tokenizer.json")?;+ let temp_dir = tempfile::tempdir().unwrap();+ let destination = temp_dir.path().join(&tokenizer.file.name);+ let manager = create_download_manager(FileDownloadManagerType::Universal, TokioHandle::current()).await.unwrap();++ let (first, second) = tokio::join!(+ manager.file_download_task(+ &tokenizer.file.url,+ &destination,+ FileCheck::CRC(tokenizer.crc32c()?),+ Some(tokenizer.file.size as u64),+ ),+ manager.file_download_task(+ &tokenizer.file.url,+ &destination,+ FileCheck::CRC(tokenizer.crc32c()?),+ Some(tokenizer.file.size as u64),+ ),+ );+ let first = first.unwrap();+ let second = second.unwrap();++ assert!(+ Arc::ptr_eq(&first, &second),+ "same URL and destination should return the same task object"+ );+ Ok(())+}diff --git a/crates/mock-registry/Cargo.toml b/crates/mock-registry/Cargo.tomlnew file mode 100644index 000000000..d49067fd9--- /dev/null+++ b/crates/mock-registry/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "mock-registry"+edition.workspace = true+rust-version.workspace = true+version.workspace = true+authors.workspace = true+homepage.workspace = true+repository.workspace = true+license.workspace = true++[dependencies]+base64.workspace = true+bitflags.workspace = true+bytesize.workspace = true+crc32c.workspace = true+http.workspace = true+httparse.workspace = true+serde_json.workspace = true+shoji.workspace = true+stream_throttle.workspace = true+thiserror.workspace = true+tokio.workspace = true+tracing.workspace = true+wiremock.workspace = truediff --git a/crates/mock-registry/README.md b/crates/mock-registry/README.mdnew file mode 100644index 000000000..650e9ccf5--- /dev/null+++ b/crates/mock-registry/README.md@@ -0,0 +1,14 @@+# mock-registry++`mock-registry` provides a local model registry for tests that should not depend on the internet. It returns realistic `shoji::Model` data from a registry endpoint and serves deterministic model files from local HTTP URLs.++## Internals++- `MockRegistry` starts two local servers: a `wiremock` server for `POST /fetch/models` and a lightweight TCP file server for model file downloads.+- The registry response is built from `models`, so tests can model a remote registry with more than one model.+- Files are generated in memory with deterministic bytes, real sizes, and CRC32C hashes. No fixture files are checked into the repository.+- `FileServer` supports `GET`, `HEAD`, range requests, and close-delimited HTTP responses used by the download managers.+- `Behavior` is a bitflag set for test scenarios such as corrupted bodies and throttled streaming.+- Public APIs return the crate-local `Result<T>` and `Error` types from `error.rs`.++The crate is intended for integration-style tests in `download-manager` and `uzu`, especially tests that need real HTTP URLs without calling external services.diff --git a/crates/mock-registry/src/behavior.rs b/crates/mock-registry/src/behavior.rsnew file mode 100644index 000000000..f540438bc--- /dev/null+++ b/crates/mock-registry/src/behavior.rs@@ -0,0 +1,7 @@+bitflags::bitflags! {+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+ pub struct Behavior: u8 {+ const CORRUPT_BODY = 1 << 0;+ const THROTTLED = 1 << 1;+ }+}diff --git a/crates/mock-registry/src/bytes.rs b/crates/mock-registry/src/bytes.rsnew file mode 100644index 000000000..00a6d9720--- /dev/null+++ b/crates/mock-registry/src/bytes.rs@@ -0,0 +1,15 @@+use std::sync::Arc;++pub fn generate(+ name: &str,+ size: usize,+) -> Arc<[u8]> {+ let seed = name.bytes().fold(0u8, |accumulator, byte| accumulator.wrapping_add(byte));+ (0..size)+ .map(|byte_index| {+ let low_bits = byte_index as u8;+ low_bits.wrapping_mul(31).wrapping_add(seed).wrapping_add((byte_index / 7) as u8)+ })+ .collect::<Vec<_>>()+ .into()+}diff --git a/crates/mock-registry/src/error.rs b/crates/mock-registry/src/error.rsnew file mode 100644index 000000000..117883cb8--- /dev/null+++ b/crates/mock-registry/src/error.rs@@ -0,0 +1,52 @@+use bytesize::ByteSize;++#[derive(Debug, thiserror::Error)]+pub enum Error {+ #[error("mock registry IO error: {0}")]+ Io(#[from] std::io::Error),++ #[error("mock registry HTTP build error: {0}")]+ Http(#[from] http::Error),++ #[error("mock registry HTTP parse error: {0}")]+ HttpParse(#[from] httparse::Error),++ #[error("mock registry invalid header value: {0}")]+ InvalidHeaderValue(#[from] http::header::ToStrError),++ #[error("mock registry request is missing method")]+ MissingRequestMethod,++ #[error("mock registry request is missing path")]+ MissingRequestPath,++ #[error("mock registry request ended before headers")]+ RequestEndedBeforeHeaders,++ #[error("mock registry request headers exceed {limit} bytes")]+ RequestHeadersTooLarge {+ limit: usize,+ },++ #[error("mock registry file not found: {name}")]+ FileNotFound {+ name: String,+ },++ #[error("mock registry file {name} size {size} does not fit {target_type}")]+ FileSizeOutOfRange {+ name: String,+ size: ByteSize,+ target_type: &'static str,+ },++ #[error("mock registry model must have at least one backend")]+ MissingBackend,++ #[error("mock registry file {name} must have a CRC32C hash")]+ MissingCrc32c {+ name: String,+ },+}++pub type Result<T> = std::result::Result<T, Error>;diff --git a/crates/mock-registry/src/file_request.rs b/crates/mock-registry/src/file_request.rsnew file mode 100644index 000000000..60fcb3925--- /dev/null+++ b/crates/mock-registry/src/file_request.rs@@ -0,0 +1,37 @@+use http::Request;+use tokio::{io::AsyncReadExt, net::TcpStream};++use crate::{Error, Result};++const REQUEST_HEADER_LIMIT: usize = 16 * 1024;++pub(crate) async fn read_request(stream: &mut TcpStream) -> Result<Request<()>> {+ let mut request_bytes = Vec::new();+ let mut buffer = [0_u8; 1024];+ while !request_bytes.windows(4).any(|window| window == b"\r\n\r\n") {+ let bytes_read = stream.read(&mut buffer).await?;+ if bytes_read == 0 {+ return Err(Error::RequestEndedBeforeHeaders);+ }+ request_bytes.extend_from_slice(&buffer[..bytes_read]);+ if request_bytes.len() > REQUEST_HEADER_LIMIT {+ return Err(Error::RequestHeadersTooLarge {+ limit: REQUEST_HEADER_LIMIT,+ });+ }+ }++ let mut headers = [httparse::EMPTY_HEADER; 32];+ let mut parsed_request = httparse::Request::new(&mut headers);+ parsed_request.parse(&request_bytes)?;++ let method = parsed_request.method.ok_or(Error::MissingRequestMethod)?;+ let path = parsed_request.path.ok_or(Error::MissingRequestPath)?;++ let mut request_builder = Request::builder().method(method).uri(path);+ for header in parsed_request.headers {+ request_builder = request_builder.header(header.name, header.value);+ }++ Ok(request_builder.body(())?)+}diff --git a/crates/mock-registry/src/file_response.rs b/crates/mock-registry/src/file_response.rsnew file mode 100644index 000000000..ff82114e8--- /dev/null+++ b/crates/mock-registry/src/file_response.rs@@ -0,0 +1,64 @@+use http::{+ Response, StatusCode,+ header::{+ ACCEPT_RANGES, CONNECTION, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, HeaderValue,+ LAST_MODIFIED as LAST_MODIFIED_HEADER,+ },+};+use tokio::{io::AsyncWriteExt, net::TcpStream};++use crate::Result;++const LAST_MODIFIED: &str = "Sun, 26 Apr 2026 12:00:00 GMT";++pub(crate) fn file_response(+ status: StatusCode,+ body_start: u64,+ body_end_exclusive: u64,+ file_size: u64,+) -> Result<Response<()>> {+ let content_length = body_end_exclusive.saturating_sub(body_start);+ let mut response = Response::builder()+ .status(status)+ .header(ACCEPT_RANGES, "bytes")+ .header(LAST_MODIFIED_HEADER, LAST_MODIFIED)+ .header(CONTENT_LENGTH, content_length.to_string())+ .header(CONTENT_TYPE, "application/octet-stream")+ .header(CONNECTION, "close");++ if status == StatusCode::PARTIAL_CONTENT {+ response = response.header(+ CONTENT_RANGE,+ format!("bytes {}-{}/{}", body_start, body_end_exclusive.saturating_sub(1), file_size),+ );+ } else if status == StatusCode::RANGE_NOT_SATISFIABLE {+ response = response.header(CONTENT_RANGE, format!("bytes */{file_size}"));+ }++ Ok(response.body(())?)+}++pub(crate) fn empty_response(status: StatusCode) -> Result<Response<()>> {+ Ok(Response::builder().status(status).header(CONTENT_LENGTH, "0").header(CONNECTION, "close").body(())?)+}++pub(crate) async fn write_response_headers(+ stream: &mut TcpStream,+ response: &Response<()>,+) -> Result<()> {+ let reason = response.status().canonical_reason().unwrap_or("Unknown");+ let mut response_head = format!("HTTP/1.1 {} {reason}\r\n", response.status().as_u16());+ for (name, value) in response.headers() {+ response_head.push_str(name.as_str());+ response_head.push_str(": ");+ response_head.push_str(header_value(value)?);+ response_head.push_str("\r\n");+ }+ response_head.push_str("\r\n");+ stream.write_all(response_head.as_bytes()).await?;+ Ok(())+}++fn header_value(value: &HeaderValue) -> Result<&str> {+ Ok(value.to_str()?)+}diff --git a/crates/mock-registry/src/file_server.rs b/crates/mock-registry/src/file_server.rsnew file mode 100644index 000000000..8af6c287a--- /dev/null+++ b/crates/mock-registry/src/file_server.rs@@ -0,0 +1,161 @@+use std::{net::SocketAddr, sync::Arc, time::Duration};++use http::{Method, StatusCode, header::RANGE};+use stream_throttle::{ThrottlePool, ThrottleRate};+use tokio::{+ io::AsyncWriteExt,+ net::{TcpListener, TcpStream},+ task::JoinHandle as TokioJoinHandle,+};++use crate::{+ Behavior, Result, ServedFile,+ file_request::read_request,+ file_response::{empty_response, file_response, write_response_headers},+};++const THROTTLED_CHUNK_SIZE: usize = 64 * 1024;+const THROTTLED_CHUNK_INTERVAL: Duration = Duration::from_millis(5);++pub(crate) struct FileServer {+ listener: TcpListener,+ pub(crate) base_url: String,+}++impl FileServer {+ pub(crate) async fn bind() -> Result<Self> {+ let listener = TcpListener::bind(("127.0.0.1", 0)).await?;+ let base_url = file_server_base_url(&listener)?;+ Ok(Self {+ listener,+ base_url,+ })+ }++ pub(crate) fn serve(+ self,+ files: Box<[ServedFile]>,+ behavior: Behavior,+ ) -> FileServerTask {+ FileServerTask {+ task: tokio::spawn(serve_files(self.listener, files, behavior)),+ }+ }+}++pub(crate) struct FileServerTask {+ task: TokioJoinHandle<()>,+}++impl Drop for FileServerTask {+ fn drop(&mut self) {+ self.task.abort();+ }+}++async fn serve_files(+ listener: TcpListener,+ files: Box<[ServedFile]>,+ behavior: Behavior,+) {+ let files: Arc<[ServedFile]> = files.into();+ loop {+ let Ok((stream, _address)) = listener.accept().await else {+ break;+ };+ let files = files.clone();+ tokio::spawn(async move {+ if let Err(error) = handle_file_request(stream, files, behavior).await {+ tracing::debug!("mock registry file request failed: {}", error);+ }+ });+ }+}++async fn handle_file_request(+ mut stream: TcpStream,+ files: Arc<[ServedFile]>,+ behavior: Behavior,+) -> Result<()> {+ let request = read_request(&mut stream).await?;+ let Some(served_file) = files.iter().find(|served_file| request.uri().path() == file_path(served_file)) else {+ let response = empty_response(StatusCode::NOT_FOUND)?;+ write_response_headers(&mut stream, &response).await?;+ return Ok(());+ };+ if request.method() != Method::GET && request.method() != Method::HEAD {+ let response = empty_response(StatusCode::METHOD_NOT_ALLOWED)?;+ write_response_headers(&mut stream, &response).await?;+ return Ok(());+ }++ let bytes = if behavior.contains(Behavior::CORRUPT_BODY) {+ corrupt_bytes(&served_file.bytes)+ } else {+ served_file.bytes.clone()+ };+ let file_size = bytes.len() as u64;+ let range_header = request.headers().get(RANGE).and_then(|header| header.to_str().ok());+ let (status, body_start, body_end_exclusive) =+ parse_range(range_header, file_size).unwrap_or((StatusCode::OK, 0, file_size));+ let response = file_response(status, body_start, body_end_exclusive, file_size)?;++ write_response_headers(&mut stream, &response).await?;+ if request.method() == Method::GET && response.status() != StatusCode::RANGE_NOT_SATISFIABLE {+ write_file_body(&mut stream, &bytes[body_start as usize..body_end_exclusive as usize], behavior).await?;+ }+ Ok(())+}++async fn write_file_body(+ stream: &mut TcpStream,+ body: &[u8],+ behavior: Behavior,+) -> Result<()> {+ if !behavior.contains(Behavior::THROTTLED) {+ stream.write_all(body).await?;+ return Ok(());+ }++ let throttle = ThrottlePool::new(ThrottleRate::new(1, THROTTLED_CHUNK_INTERVAL));+ for chunk in body.chunks(THROTTLED_CHUNK_SIZE) {+ throttle.queue().await;+ stream.write_all(chunk).await?;+ stream.flush().await?;+ }+ Ok(())+}++fn corrupt_bytes(bytes: &Arc<[u8]>) -> Arc<[u8]> {+ let mut corrupted_bytes = bytes.to_vec();+ if let Some(first_byte) = corrupted_bytes.first_mut() {+ *first_byte = first_byte.wrapping_add(1);+ }+ corrupted_bytes.into()+}++fn file_server_base_url(listener: &TcpListener) -> Result<String> {+ let address = listener.local_addr()?;+ Ok(match address {+ SocketAddr::V4(address) => format!("http://{}", address),+ SocketAddr::V6(address) => format!("http://[{}]:{}", address.ip(), address.port()),+ })+}++fn file_path(served_file: &ServedFile) -> String {+ format!("/{}", served_file.file.name)+}++fn parse_range(+ header: Option<&str>,+ file_size: u64,+) -> Option<(StatusCode, u64, u64)> {+ let range = header?.strip_prefix("bytes=")?;+ let (start, end) = range.split_once('-')?;+ let start = start.parse::<u64>().ok()?;+ if start >= file_size {+ return Some((StatusCode::RANGE_NOT_SATISFIABLE, 0, 0));+ }+ let end_exclusive = end.parse::<u64>().ok().map_or(file_size, |end| (end + 1).min(file_size));+ Some((StatusCode::PARTIAL_CONTENT, start, end_exclusive))+}diff --git a/crates/mock-registry/src/lib.rs b/crates/mock-registry/src/lib.rsnew file mode 100644index 000000000..c787707fa--- /dev/null+++ b/crates/mock-registry/src/lib.rs@@ -0,0 +1,14 @@+mod behavior;+mod bytes;+mod error;+mod file_request;+mod file_response;+mod file_server;+mod mock_registry;+mod model;+mod served_file;++pub use behavior::Behavior;+pub use error::{Error, Result};+pub use mock_registry::MockRegistry;+pub use served_file::ServedFile;diff --git a/crates/mock-registry/src/mock_registry.rs b/crates/mock-registry/src/mock_registry.rsnew file mode 100644index 000000000..80970f109--- /dev/null+++ b/crates/mock-registry/src/mock_registry.rs@@ -0,0 +1,147 @@+use base64::{Engine, engine::general_purpose::STANDARD as BASE64_STANDARD};+use bytesize::ByteSize;+use serde_json::json;+use shoji::types::{+ basic::{File, Hash, HashMethod},+ model::Model,+};+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{method, path},+};++use crate::{+ Behavior, Error, Result, ServedFile, bytes,+ file_server::{FileServer, FileServerTask},+ model,+};++const FILES: &[(&str, ByteSize)] = &[+ ("config.json", ByteSize::b(55_559)),+ ("tokenizer.json", ByteSize::b(17_209_920)),+ ("model.safetensors", ByteSize::mib(32)),+ ("traces.safetensors", ByteSize::b(31_050_840)),+];+const DEFAULT_MODEL_IDENTIFIER: &str = "mock/MockModel-1B";++pub struct MockRegistry {+ server: MockServer,+ _file_server_task: FileServerTask,+ pub models: Box<[Model]>,+ pub files: Box<[ServedFile]>,+}++impl MockRegistry {+ pub async fn start() -> Result<Self> {+ Self::start_with(Behavior::empty()).await+ }++ pub async fn start_with(behavior: Behavior) -> Result<Self> {+ let server = MockServer::start().await;+ let file_server = FileServer::bind().await?;+ let files = build_files(&file_server.base_url)?;+ let models = [model::mock_model(DEFAULT_MODEL_IDENTIFIER, &files)].into();+ let file_server_task = file_server.serve(files.clone(), behavior);+ let registry = Self {+ server,+ _file_server_task: file_server_task,+ models,+ files,+ };+ registry.mount_listing_route().await?;+ Ok(registry)+ }++ pub fn file(+ &self,+ name: &str,+ ) -> Result<&ServedFile> {+ self.files.iter().find(|served_file| served_file.file.name == name).ok_or_else(|| Error::FileNotFound {+ name: name.to_string(),+ })+ }++ async fn mount_listing_route(&self) -> Result<()> {+ Mock::given(method("POST"))+ .and(path("/fetch/models"))+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_response(&self.models)?))+ .mount(&self.server)+ .await;+ Ok(())+ }+}++fn build_files(base_url: &str) -> Result<Box<[ServedFile]>> {+ FILES+ .iter()+ .map(|(name, size)| {+ let file_size = size.as_u64();+ let byte_count = usize::try_from(file_size).map_err(|_| Error::FileSizeOutOfRange {+ name: (*name).to_string(),+ size: *size,+ target_type: "usize",+ })?;+ let shoji_file_size = i64::try_from(file_size).map_err(|_| Error::FileSizeOutOfRange {+ name: (*name).to_string(),+ size: *size,+ target_type: "i64",+ })?;+ let bytes = bytes::generate(name, byte_count);+ let crc32c = BASE64_STANDARD.encode(crc32c::crc32c(&bytes).to_be_bytes());+ Ok(ServedFile {+ file: File {+ url: format!("{}/{}", base_url.trim_end_matches('/'), name),+ name: (*name).to_string(),+ size: shoji_file_size,+ hashes: vec![Hash {+ method: HashMethod::CRC32C,+ value: crc32c,+ }],+ },+ bytes,+ })+ })+ .collect()+}++fn listing_response(models: &[Model]) -> Result<serde_json::Value> {+ let models_json = models+ .iter()+ .map(|model| {+ let registry = &model.registry;+ let backend = model.backends.first().ok_or(Error::MissingBackend)?;+ Ok(json!({+ "id": model.identifier,+ "registry": {+ "id": registry.identifier,+ "metadata_id": registry.metadata.identifier,+ },+ "backends": [{+ "id": backend.identifier,+ "version": backend.version,+ "metadata_id": backend.metadata.identifier,+ }],+ "family": null,+ "properties": null,+ "quantization": null,+ "specializations": [],+ "accessibility": model.accessibility,+ }))+ })+ .collect::<Result<Vec<_>>>()?;+ let metadatas = models+ .iter()+ .map(|model| {+ let backend = model.backends.first().ok_or(Error::MissingBackend)?;+ Ok([json!(model.registry.metadata), json!(backend.metadata)])+ })+ .collect::<Result<Vec<_>>>()?+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();++ Ok(json!({+ "models": models_json,+ "metadatas": metadatas,+ }))+}diff --git a/crates/mock-registry/src/model.rs b/crates/mock-registry/src/model.rsnew file mode 100644index 000000000..c91f72260--- /dev/null+++ b/crates/mock-registry/src/model.rs@@ -0,0 +1,48 @@+use shoji::types::{+ basic::Metadata,+ model::{Model, ModelAccessibility, ModelBackend, ModelReference, ModelRegistry},+};++use crate::ServedFile;++pub fn mock_model(+ identifier: &str,+ files: &[ServedFile],+) -> Model {+ let registry = ModelRegistry {+ identifier: "mock-registry".to_string(),+ metadata: Metadata {+ identifier: "mock-registry-metadata".to_string(),+ name: "Mock Registry".to_string(),+ description: None,+ icons: vec![],+ },+ };+ let backend = ModelBackend {+ identifier: "mock-backend".to_string(),+ version: "1.0".to_string(),+ metadata: Metadata {+ identifier: "mock-backend-metadata".to_string(),+ name: "Mock Backend".to_string(),+ description: None,+ icons: vec![],+ },+ };+ Model {+ identifier: identifier.to_string(),+ registry,+ backends: vec![backend],+ family: None,+ properties: None,+ quantization: None,+ specializations: vec![],+ accessibility: ModelAccessibility::Local {+ reference: ModelReference::Mirai {+ toolchain_version: "1.0".to_string(),+ repository: None,+ source_repository: None,+ files: files.iter().map(|served_file| served_file.file.clone()).collect(),+ },+ },+ }+}diff --git a/crates/mock-registry/src/served_file.rs b/crates/mock-registry/src/served_file.rsnew file mode 100644index 000000000..1c427f2c5--- /dev/null+++ b/crates/mock-registry/src/served_file.rs@@ -0,0 +1,24 @@+use std::sync::Arc;++use shoji::types::basic::{File, HashMethod};++use crate::{Error, Result};++#[derive(Clone, Debug)]+pub struct ServedFile {+ pub file: File,+ pub bytes: Arc<[u8]>,+}++impl ServedFile {+ pub fn crc32c(&self) -> Result<String> {+ self.file+ .hashes+ .iter()+ .find(|hash| hash.method == HashMethod::CRC32C)+ .map(|hash| hash.value.clone())+ .ok_or_else(|| Error::MissingCrc32c {+ name: self.file.name.clone(),+ })+ }+}diff --git a/crates/uzu/Cargo.toml b/crates/uzu/Cargo.tomlindex e2d7c52f6..67b214fed 100644--- a/crates/uzu/Cargo.toml+++ b/crates/uzu/Cargo.toml@@ -111,6 +111,11 @@ indicatif.workspace = truedotenvy.workspace = trueschemars.workspace = trueserde_json.workspace = true+mock-registry.workspace = true++[[test]]+name = "unit"+path = "tests/unit/test_entry.rs"[build-dependencies]napi-build = { workspace = true, optional = true }diff --git a/crates/uzu/src/storage/mod.rs b/crates/uzu/src/storage/mod.rsindex 07c62e8f3..5a5feb8c7 100644--- a/crates/uzu/src/storage/mod.rs+++ b/crates/uzu/src/storage/mod.rs@@ -18,15 +18,11 @@ use shoji::types::{basic::File,model::{Model, ModelAccessibility, ModelReference},};-use tokio::{- runtime::Handle,- sync::broadcast::{Sender, channel},-};-use tokio_stream::wrappers::BroadcastStream;+use tokio::{runtime::Handle as TokioHandle, sync::broadcast::channel as tokio_broadcast_channel};use crate::{helpers::SharedAccess,- storage::types::{DownloadPhase, DownloadState, Item},+ storage::types::{DownloadPhase, DownloadState, Item, StorageDownloadEventSender, StorageDownloadEventStream},};pub struct Storage {@@ -34,13 +30,13 @@ pub struct Storage {download_manager: SharedAccess<Arc<dyn FileDownloadManager>>,items: SharedAccess<HashMap<String, Item>>,- items_broadcast_sender: Sender<(String, DownloadState)>,- handle: Handle,+ items_broadcast_sender: StorageDownloadEventSender,+ handle: TokioHandle,}impl Storage {pub async fn new(- tokio_handle: Handle,+ tokio_handle: TokioHandle,config: Config,) -> Result<Self, StorageError> {create_dir_all(config.cache_path()).map_err(|_| StorageError::UnableToCreateDirectory {@@ -48,20 +44,16 @@ impl Storage {})?;let download_manager = SharedAccess::new(Arc::from(- create_download_manager(- FileDownloadManagerType::default(),- Some(config.name.clone()),- tokio_handle.clone(),- )- .await- .map_err(|error| StorageError::DownloadManager {- message: error.to_string(),- })?,+ create_download_manager(FileDownloadManagerType::default(), tokio_handle.clone()).await.map_err(+ |error| StorageError::DownloadManager {+ message: error.to_string(),+ },+ )?,));let items = SharedAccess::new(HashMap::new());- let (items_broadcast_sender, _) = channel(256);+ let (items_broadcast_sender, _) = tokio_broadcast_channel(256);let storage = Self {config,@@ -198,8 +190,8 @@ impl Storage {Ok(())}- pub fn subscribe(&self) -> BroadcastStream<(String, DownloadState)> {- BroadcastStream::new(self.items_broadcast_sender.subscribe())+ pub fn subscribe(&self) -> StorageDownloadEventStream {+ StorageDownloadEventStream::new(self.items_broadcast_sender.subscribe())}pub async fn get(diff --git a/crates/uzu/src/storage/types/item.rs b/crates/uzu/src/storage/types/item.rsindex 637244baa..6b5597352 100644--- a/crates/uzu/src/storage/types/item.rs+++ b/crates/uzu/src/storage/types/item.rs@@ -8,9 +8,12 @@ use download_manager::{FileDownloadManager, FileDownloadState, FileDownloadTask}use futures_util::future::join_all;use shoji::types::basic::File;use tokio::{- runtime::Handle,- sync::broadcast::{Sender, channel},- task::JoinHandle,+ runtime::Handle as TokioHandle,+ sync::{+ broadcast::{Sender as TokioBroadcastSender, channel as tokio_broadcast_channel},+ mpsc::channel as tokio_mpsc_channel,+ },+ task::JoinHandle as TokioJoinHandle,};use tokio_stream::wrappers::BroadcastStream;@@ -18,7 +21,7 @@ use crate::{helpers::SharedAccess,storage::{StorageError,- types::{CrcSnapshot, DownloadPhase, DownloadState, reduce_file_download_states},+ types::{CrcSnapshot, DownloadPhase, DownloadState, StorageDownloadEventSender, reduce_file_download_states},},};@@ -32,10 +35,10 @@ pub struct Item {file_download_tasks: SharedAccess<Vec<Arc<dyn FileDownloadTask>>>,file_download_states: SharedAccess<Vec<FileDownloadState>>,- handle: Handle,- broadcast_sender: Sender<DownloadState>,- storage_broadcast_sender: Sender<(String, DownloadState)>,- listener_task: SharedAccess<Option<JoinHandle<()>>>,+ handle: TokioHandle,+ broadcast_sender: TokioBroadcastSender<DownloadState>,+ storage_broadcast_sender: StorageDownloadEventSender,+ listener_task: SharedAccess<Option<TokioJoinHandle<()>>>,}impl std::fmt::Debug for Item {@@ -73,10 +76,10 @@ impl Item {download_state: DownloadState,file_download_manager: Arc<dyn FileDownloadManager>,file_download_tasks: Vec<Arc<dyn FileDownloadTask>>,- handle: Handle,- storage_broadcast_sender: Sender<(String, DownloadState)>,+ handle: TokioHandle,+ storage_broadcast_sender: StorageDownloadEventSender,) -> Self {- let (broadcast_sender, _) = channel(64);+ let (broadcast_sender, _) = tokio_broadcast_channel(64);let file_download_states = SharedAccess::new(Vec::new());Self {identifier,@@ -351,6 +354,21 @@ impl Item {tracing::debug!("[MODEL] Calling ensure_paused");let result = self.ensure_paused().await;+ if result.is_ok() {+ let file_tasks_guard = self.file_download_tasks.lock().await;+ let mut file_download_states = Vec::with_capacity(file_tasks_guard.len());+ for file_task in file_tasks_guard.iter() {+ file_download_states.push(file_task.state().await);+ }+ drop(file_tasks_guard);++ let mut cache_guard = self.file_download_states.lock().await;+ *cache_guard = file_download_states;+ drop(cache_guard);++ let paused_state = self.reduce_state().await;+ self.update_state_and_broadcast(paused_state).await;+ }tracing::debug!("[MODEL] pause() completed for model: {}", self.identifier);@@ -557,7 +575,7 @@ impl Item {// Fan-in: per-stream forwarders into a single bounded channellet num_streams = streams.len();- let (tx, mut rx) = tokio::sync::mpsc::channel::<(usize, FileDownloadState)>(1024);+ let (tx, mut rx) = tokio_mpsc_channel::<(usize, FileDownloadState)>(1024);for (idx, mut stream) in streams {let tx = tx.clone();diff --git a/crates/uzu/src/storage/types/mod.rs b/crates/uzu/src/storage/types/mod.rsindex a97a84efc..75ff9ea90 100644--- a/crates/uzu/src/storage/types/mod.rs+++ b/crates/uzu/src/storage/types/mod.rs@@ -7,3 +7,9 @@ pub use crc_snapshot::CrcSnapshot;pub use download_phase::DownloadPhase;pub use download_state::{DownloadState, reduce_file_download_states};pub use item::Item;+use tokio::sync::broadcast::Sender as TokioBroadcastSender;+use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;++pub type StorageDownloadEvent = (String, DownloadState);+pub type StorageDownloadEventSender = TokioBroadcastSender<StorageDownloadEvent>;+pub type StorageDownloadEventStream = TokioBroadcastStream<StorageDownloadEvent>;diff --git a/crates/uzu/tests/common/mod.rs b/crates/uzu/tests/common/mod.rsindex 8e4c29202..62e95933c 100644--- a/crates/uzu/tests/common/mod.rs+++ b/crates/uzu/tests/common/mod.rs@@ -1,2 +1,2 @@-pub mod test_helpers;+pub mod test_storage;pub mod tracing_setup;diff --git a/crates/uzu/tests/common/test_helpers.rs b/crates/uzu/tests/common/test_helpers.rsdeleted file mode 100644index 0c6db2182..000000000--- a/crates/uzu/tests/common/test_helpers.rs+++ /dev/null@@ -1,147 +0,0 @@-#![allow(dead_code)]--use std::path::PathBuf;--use shoji::types::{- basic::{File, Hash, HashMethod, Metadata},- model::{Model, ModelAccessibility, ModelBackend, ModelReference, ModelRegistry},-};-use tokio::runtime::Handle;-use uzu::{- device::Device,- registry::FixedRegistry,- storage::{Config, Storage},-};--pub struct TestStorage {- pub models: Vec<Model>,- pub config: Config,- pub registry: FixedRegistry,- pub storage: Storage,- pub base_path: PathBuf,-}--impl TestStorage {- pub async fn new_with_base_path(base_path: PathBuf) -> Result<Self, Box<dyn std::error::Error>> {- let model1 = test_model(0);- let model2 = test_model(1);-- let registry = FixedRegistry::new("test_registry".to_string(), vec![model1.clone(), model2.clone()]);-- let device = Device::new().unwrap();- let config = Config::new(device, Some(base_path.clone()), "test_storage".to_string());-- let handle = Handle::current();- let storage = Storage::new(handle, config.clone()).await.unwrap();- storage.refresh(vec![model1.clone(), model2.clone()]).await.unwrap();- Ok(Self {- models: vec![model1, model2],- config,- registry,- storage,- base_path,- })- }-- pub fn model(- &self,- index: usize,- ) -> Model {- self.models[index].clone()- }-}--fn test_model(index: usize) -> Model {- let registry = ModelRegistry {- identifier: "test-registry".to_string(),- metadata: Metadata::external("test-registry-metadata".to_string()),- };-- let backend = ModelBackend {- identifier: "test-backend".to_string(),- version: "1.0".to_string(),- metadata: Metadata::external("test-backend-metadata".to_string()),- };-- let files_1 = vec![- File {- url: "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/config.json".to_string(),- name: "config.json".to_string(),- size: 2907,- hashes: vec![Hash {- method: HashMethod::CRC32C,- value: "nx43ZQ==".to_string(),- }],- },- File {- url: "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/tokenizer.json".to_string(),- name: "tokenizer.json".to_string(),- size: 12807982,- hashes: vec![Hash {- method: HashMethod::CRC32C,- value: "C/tYqQ==".to_string(),- }],- },- File {- url: "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/tokenizer_config.json".to_string(),- name: "tokenizer_config.json".to_string(),- size: 16709,- hashes: vec![Hash {- method: HashMethod::CRC32C,- value: "MtGCnw==".to_string(),- }],- },- ];-- let files_2 = vec![- File {- url: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/main/config.json".to_string(),- name: "config.json".to_string(),- size: 726,- hashes: vec![Hash {- method: HashMethod::CRC32C,- value: "BLHgXg==".to_string(),- }],- },- File {- url: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/main/tokenizer.json".to_string(),- name: "tokenizer.json".to_string(),- size: 11422654,- hashes: vec![Hash {- method: HashMethod::CRC32C,- value: "t3YzMQ==".to_string(),- }],- },- File {- url: "https://huggingface.co/Qwen/Qwen3-0.6B/resolve/main/tokenizer_config.json".to_string(),- name: "tokenizer_config.json".to_string(),- size: 9732,- hashes: vec![Hash {- method: HashMethod::CRC32C,- value: "PUp7Mg==".to_string(),- }],- },- ];-- Model {- identifier: format!("test-model-{}", index),- registry: registry,- backends: vec![backend],- family: None,- properties: None,- quantization: None,- specializations: vec![],- accessibility: ModelAccessibility::Local {- reference: ModelReference::Mirai {- toolchain_version: "1.0".to_string(),- repository: None,- source_repository: None,- files: if index % 2 == 0 {- files_1- } else {- files_2- },- },- },- }-}diff --git a/crates/uzu/tests/common/test_storage.rs b/crates/uzu/tests/common/test_storage.rsnew file mode 100644index 000000000..2eb40d2a7--- /dev/null+++ b/crates/uzu/tests/common/test_storage.rs@@ -0,0 +1,41 @@+#![allow(dead_code)]++use std::path::PathBuf;++use shoji::types::model::Model;+use tokio::runtime::Handle as TokioHandle;+use uzu::{+ device::Device,+ registry::FixedRegistry,+ storage::{Config, Storage},+};++pub struct TestStorage {+ pub config: Config,+ pub registry: FixedRegistry,+ pub storage: Storage,+ pub base_path: PathBuf,+ _temp_dir_guard: tempfile::TempDir,+}++impl TestStorage {+ pub async fn with_models(+ tokio_handle: TokioHandle,+ models: Vec<Model>,+ ) -> Result<Self, Box<dyn std::error::Error>> {+ let temp_dir_guard = tempfile::tempdir()?;+ let base_path = temp_dir_guard.path().to_path_buf();+ let registry = FixedRegistry::new("test_registry".to_string(), models.clone());+ let device = Device::new()?;+ let config = Config::new(device, Some(base_path.clone()), "test_storage".to_string());+ let storage = Storage::new(tokio_handle, config.clone()).await?;+ storage.refresh(models).await?;+ Ok(Self {+ config,+ registry,+ storage,+ base_path,+ _temp_dir_guard: temp_dir_guard,+ })+ }+}diff --git a/crates/uzu/tests/test_storage_comprehensive_download.rs b/crates/uzu/tests/test_storage_comprehensive_download.rsdeleted file mode 100644index 3c44cd390..000000000--- a/crates/uzu/tests/test_storage_comprehensive_download.rs+++ /dev/null@@ -1,263 +0,0 @@-#![cfg(not(target_family = "wasm"))]--mod common;--use std::time::Duration;--use common::test_helpers::TestStorage;-use futures_util::StreamExt;-use indicatif::{ProgressBar, ProgressStyle};-use uzu::storage::types::{DownloadPhase, Item};--#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_download() -> Result<(), Box<dyn std::error::Error>> {- common::tracing_setup::init_test_tracing();- tracing::info!("\n[TEST] ========== MODEL DOWNLOAD TEST STARTING ==========");-- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- tracing::info!("[TEST] Initializing storage...");- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model_identifier = test_storage.model(0).identifier.clone();- let storage = &test_storage.storage;- tokio::time::sleep(Duration::from_millis(200)).await;-- tracing::info!("[TEST] Getting model {}...", model_identifier.clone());- let model: Item =- storage.get(&model_identifier).await.ok_or_else(|| format!("Model {} not found", model_identifier.clone()))?;-- let initial_state = model.state().await;- tracing::info!(- "[TEST] Model found, total_bytes: {}, initial phase: {:?}",- initial_state.total_bytes,- initial_state.phase- );- let pb = ProgressBar::new(initial_state.total_bytes as u64);- pb.set_style(- ProgressStyle::default_bar()- .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%, {bytes_per_sec}, eta {eta}) - {msg}")- .unwrap()- .progress_chars("█▓▒░ "),- );- tracing::info!("\n[TEST] ========== PHASE 1: Download to 25% ==========");- pb.set_message("Phase 1: Downloading to 25%");- let mut updates = storage.subscribe();- let pb_clone = pb.clone();- let quarter_threshold = initial_state.total_bytes / 4;- let (phase1_tx, mut phase1_rx) = tokio::sync::mpsc::channel::<u64>(1);- let model_identifier_clone = model_identifier.clone();- let monitor_task = tokio::spawn(async move {- const TIMEOUT: Duration = Duration::from_secs(120);- tracing::info!("[PHASE1] Monitor task started, waiting for updates...");- while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(TIMEOUT, updates.next()).await {- tracing::info!(- "[PHASE1] Received update: id={}, phase={:?}, bytes={}/{}",- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes as u64);- if state.downloaded_bytes >= quarter_threshold {- tracing::info!("[PHASE1] ✓ Reached 25% threshold");- let _ = phase1_tx.send(state.downloaded_bytes as u64).await;- break;- }- if matches!(state.phase, DownloadPhase::Downloaded {}) {- tracing::info!("[PHASE1] ✓ Downloaded state reached (completed before 25%)");- let _ = phase1_tx.send(state.downloaded_bytes as u64).await;- break;- }- }- }- tracing::info!("[PHASE1] Monitor task exiting");- });-- tracing::info!("[PHASE1] Starting download...");- model.download().await?;-- tracing::info!("[PHASE1] Waiting for progress update...");- if phase1_rx.recv().await.is_none() {- monitor_task.abort();- panic!("Phase 1 failed: no progress update received");- }- tracing::info!("[PHASE1] ✓ Phase 1 complete");- monitor_task.abort();-- let current_state = model.state().await;- if matches!(current_state.phase, DownloadPhase::Downloaded {}) {- tracing::info!("\n[TEST] ========== Download completed early, skipping pause/resume tests ==========");- pb.finish_with_message("Download completed");- return Ok(());- }-- tracing::info!("\n[TEST] ========== PHASE 2: Pause at 25% ==========");- pb.set_message("Phase 2: Pausing...");- model.pause().await?;- tokio::time::sleep(Duration::from_secs(2)).await;-- let paused_state = model.state().await;- tracing::info!(- "[PHASE2] ✓ Paused state confirmed: phase={:?}, bytes={}/{}",- paused_state.phase,- paused_state.downloaded_bytes,- paused_state.total_bytes- );-- tracing::info!("\n[TEST] ========== PHASE 3: Resume to 50% ==========");- pb.set_message("Phase 3: Resuming to 50%");- let mut updates = storage.subscribe();- let pb_clone = pb.clone();- let half_threshold = initial_state.total_bytes / 2;- let (phase3_tx, mut phase3_rx) = tokio::sync::mpsc::channel::<u64>(1);- let model_identifier_clone = model_identifier.clone();- let monitor_task = tokio::spawn(async move {- const TIMEOUT: Duration = Duration::from_secs(120);- while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(TIMEOUT, updates.next()).await {- if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes as u64);- if state.downloaded_bytes >= half_threshold {- let _ = phase3_tx.send(state.downloaded_bytes as u64).await;- break;- }- if matches!(state.phase, DownloadPhase::Downloaded {}) {- let _ = phase3_tx.send(state.downloaded_bytes as u64).await;- break;- }- }- }- });- model.download().await?;- if phase3_rx.recv().await.is_none() {- monitor_task.abort();- panic!("Phase 3 failed: no progress update received");- }- tracing::info!("[PHASE3] ✓ Phase 3 complete");- monitor_task.abort();-- tracing::info!("\n[TEST] ========== PHASE 4: Cancel at 50% ==========");- pb.set_message("Phase 4: Cancelling...");- model.cancel().await?;- tokio::time::sleep(Duration::from_millis(500)).await;-- let cancelled_state = model.state().await;- tracing::info!("[PHASE4] ✓ Cancelled state confirmed: phase={:?}", cancelled_state.phase);- assert!(- matches!(cancelled_state.phase, DownloadPhase::NotDownloaded {}),- "Expected model to be in NotDownloaded state after cancellation, got {:?}",- cancelled_state.phase- );-- tracing::info!("\n[TEST] ========== PHASE 5: Download again to 50% ==========");- pb.set_message("Phase 5: Downloading again to 50%");- pb.set_position(0); // Reset progress bar- let mut updates = storage.subscribe();- let pb_clone = pb.clone();- let (phase5_tx, mut phase5_rx) = tokio::sync::mpsc::channel::<u64>(1);- let model_identifier_clone = model_identifier.clone();- let monitor_task = tokio::spawn(async move {- const TIMEOUT: Duration = Duration::from_secs(120);- while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(TIMEOUT, updates.next()).await {- if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes as u64);- if state.downloaded_bytes >= half_threshold {- let _ = phase5_tx.send(state.downloaded_bytes as u64).await;- break;- }- if matches!(state.phase, DownloadPhase::Downloaded {}) {- let _ = phase5_tx.send(state.downloaded_bytes as u64).await;- break;- }- }- }- });- model.download().await?;- if phase5_rx.recv().await.is_none() {- monitor_task.abort();- panic!("Phase 5 failed: no progress update received");- }- tracing::info!("[PHASE5] ✓ Phase 5 complete");- monitor_task.abort();-- tracing::info!("\n[TEST] ========== PHASE 6: Pause at 50% ==========");- pb.set_message("Phase 6: Pausing at 50%");- model.pause().await?;- tokio::time::sleep(Duration::from_secs(2)).await;-- let paused_state2 = model.state().await;- tracing::info!(- "[PHASE6] ✓ Paused state confirmed: phase={:?}, bytes={}/{}",- paused_state2.phase,- paused_state2.downloaded_bytes,- paused_state2.total_bytes- );-- tracing::info!("\n[TEST] ========== PHASE 7: Resume to completion ==========");- pb.set_message("Phase 7: Resuming to completion");- let mut updates = storage.subscribe();- let pb_clone = pb.clone();- let (phase7_tx, mut phase7_rx) = tokio::sync::mpsc::channel::<()>(1);- let model_identifier_clone = model_identifier.clone();- let monitor_task = tokio::spawn(async move {- const TIMEOUT: Duration = Duration::from_secs(240);- tracing::info!("[PHASE7] Monitor task started, waiting for completion...");- while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(TIMEOUT, updates.next()).await {- tracing::info!(- "[PHASE7] Received update: id={}, phase={:?}, bytes={}/{}",- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- if id == model_identifier_clone {- pb_clone.set_position(state.downloaded_bytes as u64);- match state.phase {- DownloadPhase::Downloaded {} => {- tracing::info!("[PHASE7] ✓ Downloaded state reached!");- pb_clone.finish_with_message("✓ Download complete!");- let send_result = phase7_tx.send(()).await;- tracing::info!("[PHASE7] Channel send result: {:?}", send_result);- break;- },- DownloadPhase::Error {- message: ref err,- } => {- tracing::info!("[PHASE7] ✗ Error state reached: {}", err);- pb_clone.abandon_with_message(format!("✗ Error: {}", err));- break;- },- _ => {},- }- }- }- tracing::info!("[PHASE7] Monitor task exiting");- });-- tracing::info!("[PHASE7] Starting download...");- model.download().await?;-- tracing::info!("[PHASE7] Waiting for download completion...");- if phase7_rx.recv().await.is_none() {- tracing::info!("[PHASE7] ✗ Channel recv returned None!");- monitor_task.abort();- panic!("Phase 7 failed: download did not complete");- }- tracing::info!("[PHASE7] ✓ Phase 7 complete");- monitor_task.abort();-- tracing::info!("\n[TEST] ========== FINAL VERIFICATION ==========");- let final_state = model.state().await;- tracing::info!("[TEST] Final model state: {:?}, bytes: {}", final_state.phase, final_state.downloaded_bytes);-- assert!(- matches!(final_state.phase, DownloadPhase::Downloaded {}),- "Expected Downloaded state, got {:?}",- final_state.phase- );-- tracing::info!("[TEST] ✓ Test verification passed");- tracing::info!("[TEST] ========== MODEL DOWNLOAD TEST COMPLETE ==========\n");- Ok(())-}diff --git a/crates/uzu/tests/test_storage_comprehensive_state.rs b/crates/uzu/tests/test_storage_comprehensive_state.rsdeleted file mode 100644index 66ff6005b..000000000--- a/crates/uzu/tests/test_storage_comprehensive_state.rs+++ /dev/null@@ -1,479 +0,0 @@-#![cfg(target_vendor = "apple")]--mod common;--use std::time::Duration;--use common::test_helpers::TestStorage;-use futures_util::StreamExt;-use indicatif::{ProgressBar, ProgressStyle};-use uzu::storage::types::DownloadPhase;--#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_fresh_download_to_completion() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- tracing::info!("\n[SCENARIO_1] Fresh download to completion");- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::NotDownloaded {}), "Fresh model should be NotDownloaded");-- // Set up progress bar- let pb = ProgressBar::new(state.total_bytes as u64);- pb.set_style(- ProgressStyle::default_bar()- .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({percent}%, {bytes_per_sec}) - {msg}")- .unwrap()- .progress_chars("█▓▒░ "),- );- pb.set_message("Downloading to completion");-- // Subscribe to updates- let mut updates = test_storage.storage.subscribe();- let pb_clone = pb.clone();- let (done_tx, mut done_rx) = tokio::sync::mpsc::channel::<()>(1);-- let monitor = tokio::spawn(async move {- while let Ok(Some(Ok((id, state)))) = tokio::time::timeout(Duration::from_secs(120), updates.next()).await {- if id == test_storage.model(0).identifier.clone() {- pb_clone.set_position(state.downloaded_bytes as u64);- if matches!(state.phase, DownloadPhase::Downloaded {}) {- pb_clone.finish_with_message("✓ Downloaded");- let _ = done_tx.send(()).await;- break;- }- }- }- });-- model.download().await?;- tokio::time::sleep(Duration::from_millis(300)).await;-- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloading {}), "Should be Downloading after start");-- // Wait for completion with timeout- let completed = tokio::time::timeout(Duration::from_secs(600), done_rx.recv()).await;- monitor.abort();-- assert!(completed.is_ok(), "Download did not complete within timeout");-- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloaded {}), "Should be Downloaded after completion");-- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_pause_and_resume() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused {}), "Should be Paused after pause command");- let paused_progress = state.progress();- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloading {}), "Should be Downloading after resume");- assert!(state.progress() >= paused_progress, "Progress should not decrease after resume");- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_pause_quit_relaunch_resume() -> Result<(), Box<dyn std::error::Error>> {- {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path.clone()).await?;- let storage = &test_storage.storage;- let model = storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- let paused_progress = state.progress();- let model_dir = test_storage.config.clone().cache_model_path(&test_storage.model(0)).unwrap();- let mut file_list = Vec::new();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let file_name = entry.file_name();- let name_str = file_name.to_string_lossy().to_string();- if !name_str.starts_with('.') {- let metadata = entry.metadata().await?;- file_list.push((name_str.clone(), metadata.len()));- }- }- }- drop(test_storage);-- tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let complete_files: Vec<_> =- file_list.iter().filter(|(name, _)| !name.ends_with(".resume_data")).cloned().collect();-- let test_storage_2 = TestStorage::new_with_base_path(base_path).await?;- let storage_2 = &test_storage_2.storage;- let model =- storage_2.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found after relaunch")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused {}), "Model should remain Paused after relaunch");- assert!(state.progress() >= paused_progress, "Progress should not decrease after relaunch");- let model_dir = test_storage_2.config.cache_model_path(&test_storage_2.model(0)).unwrap();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- let mut files_after = Vec::new();- while let Some(entry) = entries.next_entry().await? {- let file_name = entry.file_name();- let name_str = file_name.to_string_lossy().to_string();- if !name_str.starts_with('.') && !name_str.ends_with(".resume_data") {- let metadata = entry.metadata().await?;- files_after.push((name_str.clone(), metadata.len()));- }- }- for (name, size) in &complete_files {- assert!(- files_after.iter().any(|(n, s)| n == name && s == size),- "Complete file {} should remain after relaunch",- name- );- }- }- let model = storage_2.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = storage_2.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Downloading {}), "Should be Downloading after resume");- }- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_delete_from_various_states() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused {}), "Should be Paused");- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.cancel().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- assert!(- !model_dir.exists() || {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- let mut has_files = false;- while let Some(entry) = entries.next_entry().await? {- let name = entry.file_name();- let name_str = name.to_string_lossy();- if !name_str.starts_with('.') {- has_files = true;- break;- }- }- !has_files- },- "Model directory should be empty or removed after delete"- );- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_multiple_pause_resume_cycles() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- for cycle in 1..=3 {- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- let paused_progress = state.progress();- assert!(- matches!(- state.phase,- DownloadPhase::Paused {} | DownloadPhase::Downloaded {} | DownloadPhase::Downloading {}- ),- "Should be Paused/Downloaded/Downloading in cycle {} (got {:?})",- cycle,- state.phase- );- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(state.progress() >= paused_progress, "Progress should not decrease in cycle {}", cycle);- }- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_completed_files_preserved_on_relaunch()--> Result<(), Box<dyn std::error::Error>> {- {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path.clone()).await?;- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.download().await?;- for _ in 0..30 {- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- let mut complete_count = 0;- let mut incomplete_count = 0;- while let Some(entry) = entries.next_entry().await? {- let file_name = entry.file_name();- let name_str = file_name.to_string_lossy();- if name_str.ends_with(".resume_data") || name_str.starts_with('.') {- continue;- }- let metadata = entry.metadata().await?;- let size = metadata.len();- if name_str == "config.json" && size == 2907 {- complete_count += 1;- } else if name_str == "tokenizer.json" && size == 12807982 {- complete_count += 1;- } else if name_str == "tokenizer_config.json" && size == 16709 {- complete_count += 1;- } else if size > 0 {- incomplete_count += 1;- }- }- if complete_count > 0 && incomplete_count > 0 {- break;- }- }- }- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- let mut files_before = Vec::new();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let file_name = entry.file_name();- let name_str = file_name.to_string_lossy().to_string();- if !name_str.starts_with('.') && !name_str.ends_with(".resume_data") {- let metadata = entry.metadata().await?;- files_before.push((name_str.clone(), metadata.len()));- }- }- }- drop(test_storage.storage);- tokio::time::sleep(std::time::Duration::from_millis(200)).await;-- let test_storage_2 = TestStorage::new_with_base_path(base_path).await?;- let model_dir = test_storage_2.config.cache_model_path(&test_storage_2.model(0)).unwrap();- let mut files_after = Vec::new();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let file_name = entry.file_name();- let name_str = file_name.to_string_lossy().to_string();- if !name_str.starts_with('.') && !name_str.ends_with(".resume_data") {- let metadata = entry.metadata().await?;- files_after.push((name_str.clone(), metadata.len()));- }- }- }- for (name, size) in &files_before {- assert!(- files_after.iter().any(|(n, s)| n == name && s == size),- "Complete file {} should be preserved after relaunch",- name- );- }- let model =- test_storage_2.storage.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused {}), "Model should be Paused after relaunch");- }- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_idempotent_pause() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- let progress_after_first_pause = state.progress();- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;-- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(matches!(state.phase, DownloadPhase::Paused {}), "Should remain Paused after second pause");- assert_eq!(state.progress(), progress_after_first_pause, "Progress should not change on idempotent pause");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_crc_validation_on_init() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path.clone()).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.download().await?;- for _ in 0..60 {- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- if model_dir.exists() {- let config_path = model_dir.join("config.json");- let tokenizer_path = model_dir.join("tokenizer.json");- if config_path.exists() && tokenizer_path.exists() {- if let Ok(config_meta) = tokio::fs::metadata(&config_path).await {- if let Ok(tok_meta) = tokio::fs::metadata(&tokenizer_path).await {- if config_meta.len() == 2907 && tok_meta.len() == 12807982 {- break;- }- }- }- }- }- }- // Check if download completed before we can pause- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await;- if let Some(m) = model {- let state = m.state().await;- if !matches!(state.phase, DownloadPhase::Downloaded {}) {- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.pause().await?;- }- }- drop(test_storage.storage);-- {- let test_storage_2 = TestStorage::new_with_base_path(base_path).await?;- let model_dir = test_storage_2.config.cache_model_path(&test_storage_2.model(0)).unwrap();- let config_path = model_dir.join("config.json");- let tokenizer_path = model_dir.join("tokenizer.json");- let config_resume = model_dir.join("config.json.resume_data");- let tokenizer_resume = model_dir.join("tokenizer.json.resume_data");- assert!(config_path.exists(), "config.json should exist after relaunch");- assert!(tokenizer_path.exists(), "tokenizer.json should exist after relaunch");- assert!(!config_resume.exists(), "config.json.resume_data should be deleted for complete file");- assert!(!tokenizer_resume.exists(), "tokenizer.json.resume_data should be deleted for complete file");- let model =- test_storage_2.storage.get(&test_storage_2.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- assert!(- matches!(- state.phase,- DownloadPhase::Paused {} | DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}- ),- "Model should be in a valid state after relaunch (Paused, Downloading, or Downloaded)"- );- }- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_comprehensive_state_progress_calculation_with_mixed_files()--> Result<(), Box<dyn std::error::Error>> {- {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();-- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let expected_config_bytes = 2907;- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.download().await?;- let mut config_completed = false;- for _ in 0..30 {- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- let config_path = model_dir.join("config.json");- if let Ok(meta) = tokio::fs::metadata(&config_path).await {- if meta.len() == expected_config_bytes {- config_completed = true;- break;- }- }- }- if config_completed {- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model =- test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- let state = model.state().await;- let downloaded_bytes = state.downloaded_bytes;- assert!(- downloaded_bytes >= expected_config_bytes as i64,- "Downloaded bytes should include completed config.json"- );- }- }- Ok(())-}diff --git a/crates/uzu/tests/test_storage_concurrent_multi_model.rs b/crates/uzu/tests/test_storage_concurrent_multi_model.rsdeleted file mode 100644index baeeeb3fb..000000000--- a/crates/uzu/tests/test_storage_concurrent_multi_model.rs+++ /dev/null@@ -1,326 +0,0 @@-#![cfg(not(target_family = "wasm"))]--mod common;--use std::time::Duration;--use common::test_helpers::TestStorage;-use futures_util::StreamExt;-use uzu::storage::types::DownloadPhase;--const TEST_COUNT: usize = 2;--#[tokio::test(flavor = "multi_thread")]-#[ignore]-async fn test_storage_concurrent_multi_model_download() -> Result<(), Box<dyn std::error::Error>> {- common::tracing_setup::init_test_tracing();-- tracing::info!("========== STARTING CONCURRENT DOWNLOAD TEST ==========");-- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();- let test_storage = TestStorage::new_with_base_path(base_path).await?;-- tracing::info!("[CONCURRENT_TEST] Initializing storage...");- tokio::time::sleep(Duration::from_millis(200)).await;-- // Create test instances - we'll use the same model reference multiple times- let mut models = Vec::new();- for i in 0..TEST_COUNT {- // Get the test model and create instances- tracing::info!("[CONCURRENT_TEST] Fetching test model {}...", i);- let model = test_storage.model(i).clone();- let item = test_storage.storage.get(&model.identifier.clone()).await.ok_or("Model not found")?;-- // Cancel first to ensure it's not already downloaded- tracing::info!("[CONCURRENT_TEST] Canceling model {} to ensure fresh download...", i);- item.cancel().await?;- tokio::time::sleep(Duration::from_millis(500)).await;- models.push((model.identifier.clone(), item.clone()));- }-- tracing::info!("[CONCURRENT_TEST] ✓ Created {} model instances", models.len());-- // Start downloading all models concurrently- tracing::info!("\n[CONCURRENT_TEST] ========== PHASE 1: Start all downloads ==========");- let download_futures: Vec<_> = models- .iter()- .map(|(id, model)| {- let id = id.clone();- let model = model.clone();- async move {- tracing::info!("[CONCURRENT_TEST] Starting download for {}", id);- match model.download().await {- Ok(_) => tracing::info!("[CONCURRENT_TEST] ✓ Download started for {}", id),- Err(e) => tracing::info!("[CONCURRENT_TEST] ✗ Download failed for {}: {:?}", id, e),- }- }- })- .collect();-- futures_util::future::join_all(download_futures).await;-- // Wait for some progress with timeout protection- // Note: Since we're using clones of the same model, they share state and have the same ID- tracing::info!("\n[CONCURRENT_TEST] Waiting for downloads to progress...");- let mut progress_stream = test_storage.storage.subscribe();- let mut progress_count = 0;- let expected_progress = 10; // Wait for at least 10 progress updates-- let progress_check = tokio::time::timeout(Duration::from_secs(10), async {- while let Some(Ok((id, state))) = progress_stream.next().await {- if matches!(state.phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}) {- progress_count += 1;- if progress_count <= 5 || progress_count % 10 == 0 {- tracing::info!(- "[CONCURRENT_TEST] Progress #{}: {} - bytes={}/{}",- progress_count,- id,- state.downloaded_bytes,- state.total_bytes- );- }- if progress_count >= expected_progress {- break;- }- }- }- progress_count- })- .await;-- let count = progress_check.unwrap_or(0);- assert!(count >= expected_progress, "TIMEOUT: Expected {} progress updates, got {}", expected_progress, count);-- // Check all are downloading- for (id, model) in &models {- let state = model.state().await;- tracing::info!(- "[CONCURRENT_TEST] Model {} state: phase={:?}, bytes={}/{}",- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- assert!(- matches!(state.phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}),- "Model {} should be downloading or downloaded, got {:?}",- id,- state.phase- );- }-- // Pause all models concurrently- tracing::info!("\n[CONCURRENT_TEST] ========== PHASE 2: Pause all downloads ==========");- let pause_futures: Vec<_> = models- .iter()- .map(|(id, model)| {- let id = id.clone();- let model = model.clone();- async move {- tracing::info!("[CONCURRENT_TEST] Pausing {}", id);- match model.pause().await {- Ok(_) => {- tracing::info!("[CONCURRENT_TEST] ✓ Paused {}", id)- },- Err(e) => tracing::info!("[CONCURRENT_TEST] ⚠ Pause for {} returned: {:?}", id, e),- }- }- })- .collect();-- futures_util::future::join_all(pause_futures).await;-- // Wait for pause confirmations with timeout- let pause_check = tokio::time::timeout(Duration::from_secs(5), async {- let mut all_paused = false;- for _ in 0..10 {- tokio::time::sleep(Duration::from_millis(200)).await;- let mut paused_count = 0;- for (_, model) in &models {- let state = model.state().await;- if matches!(state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}) {- paused_count += 1;- }- }- if paused_count == models.len() {- all_paused = true;- break;- }- }- all_paused- })- .await;-- assert!(pause_check.unwrap_or(false), "TIMEOUT: Not all models paused within 5 seconds");-- // Verify all are paused (or completed)- for (id, model) in &models {- let state = model.state().await;- tracing::info!(- "[CONCURRENT_TEST] Model {} after pause: phase={:?}, bytes={}/{}",- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- assert!(- matches!(state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}),- "Model {} should be paused or downloaded after pause, got {:?}",- id,- state.phase- );- }-- // Resume all models concurrently- tracing::info!("\n[CONCURRENT_TEST] ========== PHASE 3: Resume all downloads ==========");- let resume_futures: Vec<_> = models- .iter()- .map(|(id, model)| {- let id = id.clone();- let model = model.clone();- async move {- tracing::info!("[CONCURRENT_TEST] Resuming {}", id);- match model.download().await {- Ok(_) => {- tracing::info!("[CONCURRENT_TEST] ✓ Resumed {}", id)- },- Err(e) => tracing::info!("[CONCURRENT_TEST] ⚠ Resume for {} returned: {:?}", id, e),- }- }- })- .collect();-- futures_util::future::join_all(resume_futures).await;-- tokio::time::sleep(Duration::from_secs(2)).await;-- // Check resumed- for (id, model) in &models {- let state = model.state().await;- tracing::info!(- "[CONCURRENT_TEST] Model {} after resume: phase={:?}, bytes={}/{}",- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- }-- // Cancel half the models while others continue- tracing::info!("\n[CONCURRENT_TEST] ========== PHASE 4: Cancel half while others continue ==========");- let cancel_count = models.len() / 2;- let cancel_futures: Vec<_> = models- .iter()- .take(cancel_count)- .map(|(id, model)| {- let id = id.clone();- let model = model.clone();- async move {- tracing::info!("[CONCURRENT_TEST] Canceling {}", id);- match model.cancel().await {- Ok(_) => {- tracing::info!("[CONCURRENT_TEST] ✓ Canceled {}", id)- },- Err(e) => tracing::info!("[CONCURRENT_TEST] ✗ Cancel for {} failed: {:?}", id, e),- }- }- })- .collect();-- futures_util::future::join_all(cancel_futures).await;-- // Wait for cancel confirmations with timeout- let cancel_check = tokio::time::timeout(Duration::from_secs(5), async {- let mut all_cancelled = false;- for _ in 0..10 {- tokio::time::sleep(Duration::from_millis(200)).await;- let mut cancelled_count = 0;- for (idx, (_, model)) in models.iter().enumerate() {- if idx < cancel_count {- let state = model.state().await;- if matches!(state.phase, DownloadPhase::NotDownloaded {}) {- cancelled_count += 1;- }- }- }- if cancelled_count == cancel_count {- all_cancelled = true;- break;- }- }- all_cancelled- })- .await;-- assert!(cancel_check.unwrap_or(false), "TIMEOUT: Not all models cancelled within 5 seconds");-- // Verify cancelled models are not downloaded, others still progressing- for (idx, (id, model)) in models.iter().enumerate() {- let state = model.state().await;- if idx < cancel_count {- tracing::info!("[CONCURRENT_TEST] Cancelled model {} state: phase={:?}", id, state.phase);- assert!(- matches!(state.phase, DownloadPhase::NotDownloaded {}),- "Cancelled model {} should be NotDownloaded, got {:?}",- id,- state.phase- );- } else {- tracing::info!(- "[CONCURRENT_TEST] Continuing model {} state: phase={:?}, bytes={}/{}",- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- }- }-- // Monitor progress updates for continuing models- tracing::info!("\n[CONCURRENT_TEST] ========== PHASE 5: Monitor progress updates ==========");- // Use a model that wasn't cancelled (second half of the list)- if let Some((id, model)) = models.iter().skip(cancel_count).next() {- tracing::info!("[CONCURRENT_TEST] Starting download for monitoring {}", id);- model.download().await?;-- tracing::info!("[CONCURRENT_TEST] Monitoring progress for {}", id);- let mut progress_stream = test_storage.storage.subscribe();- let model_id = id.clone();-- let monitor_task = tokio::spawn(async move {- let mut update_count = 0;- while let Some(Ok((id, state))) = progress_stream.next().await {- if id == model_id {- update_count += 1;- tracing::info!(- "[CONCURRENT_TEST] Progress update #{} for {}: phase={:?}, bytes={}/{}",- update_count,- id,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- if update_count >= 5 || matches!(state.phase, DownloadPhase::Downloaded {}) {- break;- }- }- }- update_count- });-- let update_count =- tokio::time::timeout(Duration::from_secs(30), monitor_task).await.unwrap_or(Ok(0)).unwrap_or(0);-- tracing::info!("[CONCURRENT_TEST] Received {} progress updates", update_count);- tracing::info!("[CONCURRENT_TEST] ✓ Progress monitoring successful");- }-- tracing::info!("\n[CONCURRENT_TEST] ========== CLEANUP ==========");- drop(test_storage.storage);-- tracing::info!("[CONCURRENT_TEST] ========== TEST COMPLETE ✓ ==========\n");- Ok(())-}--// concurrent_pause_resume_stress_test removeddiff --git a/crates/uzu/tests/test_storage_debug_file_preservation.rs b/crates/uzu/tests/test_storage_debug_file_preservation.rsdeleted file mode 100644index 9e05c67df..000000000--- a/crates/uzu/tests/test_storage_debug_file_preservation.rs+++ /dev/null@@ -1,457 +0,0 @@-#![cfg(target_vendor = "apple")]--mod common;--use common::test_helpers::TestStorage;-use uzu::storage::types::DownloadPhase;--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_debug_file_preservation_complete_app_relaunch_resume() -> Result<(), Box<dyn std::error::Error>> {- // Enable test tracing to file for deeper diagnostics- common::tracing_setup::init_test_tracing();- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();- let base_path_clone = base_path.clone();-- let (progress_session1, _bytes_session1, _total_bytes);- {- let (p1, b1, tb) = std::thread::spawn(move || {- let runtime = tokio::runtime::Runtime::new().unwrap();- runtime.block_on(async {- let test_storage = TestStorage::new_with_base_path(base_path_clone).await.unwrap();- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- tracing::info!("[S1] Starting download for {}", test_storage.model(0).identifier.clone());- model.download().await.unwrap();- let mut reached_target = false;- for i in 0..180 {- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- tracing::info!("[S1] Iteration {}: pausing model", i);- model.pause().await.unwrap();- let state = model.state().await;- let progress = state.progress();- tracing::info!(- "[S1] Iteration {}: phase={:?}, progress={:.2}%, bytes={}/{}",- i,- state.phase,- progress * 100.0,- state.downloaded_bytes,- state.total_bytes- );-- if progress >= 0.08 && progress <= 0.25 {- reached_target = true;- break;- }- model.download().await.unwrap();- }- assert!(reached_target, "Failed to reach target progress");- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- tracing::info!("[S1] Pausing before shutdown");- model.pause().await.unwrap();- tokio::time::sleep(std::time::Duration::from_millis(1000)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- let progress = state.progress();- let bytes = state.downloaded_bytes;- let total = state.total_bytes;- tracing::info!(- "[S1] Pre-shutdown state: phase={:?}, progress={:.2}%, bytes={}/{}",- state.phase,- progress * 100.0,- bytes,- total- );- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- let mut entries = tokio::fs::read_dir(&model_dir).await.unwrap();- while let Some(entry) = entries.next_entry().await.unwrap() {- let name = entry.file_name();- let meta = entry.metadata().await.unwrap();- let marker = if name.to_string_lossy().ends_with(".resume_data") {- "📄"- } else {- "📦"- };- tracing::info!("[S1] Model dir entry {} {} ({} bytes)", marker, name.to_string_lossy(), meta.len());- }- drop(test_storage.storage);- (progress, bytes, total)- })- })- .join()- .expect("Session 1 thread panicked");- progress_session1 = p1;- _bytes_session1 = b1;- _total_bytes = tb;- std::thread::sleep(std::time::Duration::from_millis(500));- }- {- std::thread::spawn(move || {- let runtime = tokio::runtime::Runtime::new().unwrap();- runtime.block_on(async {- common::tracing_setup::init_test_tracing();- let test_storage = TestStorage::new_with_base_path(base_path).await.unwrap();- tokio::time::sleep(std::time::Duration::from_millis(200)).await;-- let mut entries =- tokio::fs::read_dir(&test_storage.config.cache_model_path(&test_storage.model(0)).unwrap())- .await- .unwrap();- while let Some(entry) = entries.next_entry().await.unwrap() {- let name = entry.file_name();- let meta = entry.metadata().await.unwrap();- tracing::info!(- "[S2] Existing entry before init: {} ({} bytes)",- name.to_string_lossy(),- meta.len()- );- }-- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- let progress_session2 = state.progress();- let bytes_session2 = state.downloaded_bytes;- tracing::info!(- "[S2] Post-init state: phase={:?}, progress={:.2}%, bytes={}/{}",- state.phase,- progress_session2 * 100.0,- state.downloaded_bytes,- state.total_bytes- );- let progress_diff = (progress_session1 - progress_session2).abs();- assert!(- progress_diff < 0.02,- "Progress NOT preserved across sessions! Session1: {:.1}%, Session2: {:.1}%",- progress_session1 * 100.0,- progress_session2 * 100.0- );- tracing::info!("[S2] Resuming download after relaunch");- model.download().await.unwrap();- tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- let progress_after_resume = state.progress();- let bytes_after_resume = state.downloaded_bytes;- tracing::info!(- "[S2] After resume: phase={:?}, progress={:.2}%, bytes={}/{} (delta bytes: {})",- state.phase,- progress_after_resume * 100.0,- bytes_after_resume,- state.total_bytes,- bytes_after_resume.saturating_sub(bytes_session2)- );- if bytes_after_resume >= bytes_session2 * 90 / 100 {- } else {- }- drop(test_storage);- })- })- .join()- .expect("Session 2 thread panicked");- }- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_debug_file_preservation_resume_from_20_percent() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();- let base_path_clone = base_path.clone();-- let (progress_at_pause, bytes_at_pause, _total_bytes);- {- let test_storage = TestStorage::new_with_base_path(base_path_clone).await.unwrap();- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.download().await.unwrap();- let mut reached_target = false;- for i in 0..180 {- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- let progress = state.progress();- let _downloaded = state.downloaded_bytes;- let _total = state.total_bytes;- if i % 4 == 0 {}- if progress >= 0.08 && progress <= 0.25 {- reached_target = true;- break;- }- }- if !reached_target {- return Err("Failed to reach target progress range in time".into());- }- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.pause().await?;- for i in 0..20 {- tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- if matches!(state.phase, DownloadPhase::Paused {}) {- break;- }- if i == 19 {}- }- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- progress_at_pause = state.progress();- bytes_at_pause = state.downloaded_bytes;- _total_bytes = state.total_bytes;- if !matches!(state.phase, DownloadPhase::Paused {}) {}- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- let mut resume_files = Vec::new();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let name = entry.file_name();- let name_str = name.to_string_lossy().to_string();- if name_str.ends_with(".resume_data") {- let meta = entry.metadata().await?;- resume_files.push((name_str.clone(), meta.len()));- let resume_path = model_dir.join(&name_str);- if let Ok(data) = tokio::fs::read(&resume_path).await {- if let Ok(_resume) =- download_manager::managers::apple::URLSessionDownloadTaskResumeData::from_bytes(&data)- {- }- }- }- }- }- assert!(!resume_files.is_empty(), "Should have at least one .resume_data file");- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let _name = entry.file_name();- let _meta = entry.metadata().await?;- }- }- drop(test_storage);- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- }- {- let test_storage = TestStorage::new_with_base_path(base_path).await.unwrap();- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let _name = entry.file_name();- let _meta = entry.metadata().await?;- }- }- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- let progress_after_relaunch = state.progress();- let bytes_after_relaunch = state.downloaded_bytes;- assert!(matches!(state.phase, DownloadPhase::Paused {}), "Model should be Paused after relaunch");- let progress_diff = (progress_at_pause - progress_after_relaunch).abs();- let _bytes_diff = (bytes_at_pause as i64 - bytes_after_relaunch as i64).abs();- assert!(- progress_diff < 0.10,- "Progress should be preserved after relaunch (pause: {:.1}%, relaunch: {:.1}%, diff: {:.1}%)",- progress_at_pause * 100.0,- progress_after_relaunch * 100.0,- progress_diff * 100.0- );- let mut resume_files_after = Vec::new();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let name = entry.file_name();- let name_str = name.to_string_lossy().to_string();- if name_str.ends_with(".resume_data") {- let meta = entry.metadata().await?;- resume_files_after.push((name_str.clone(), meta.len()));- let resume_path = model_dir.join(&name_str);- if let Ok(data) = tokio::fs::read(&resume_path).await {- if let Ok(_resume) =- download_manager::managers::apple::URLSessionDownloadTaskResumeData::from_bytes(&data)- {- }- }- }- }- }- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- let model_immediate = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model_immediate.state().await;- let progress_immediate = state.progress();- let bytes_immediate = state.downloaded_bytes;- if bytes_immediate < bytes_after_relaunch * 90 / 100 {- panic!(- "\n ❌ CRITICAL: Download restarted from scratch on resume!\n\- Before resume: {} bytes ({:.1}%)\n\- After resume: {} bytes ({:.1}%)\n\- Loss: {} bytes",- bytes_after_relaunch,- progress_after_relaunch * 100.0,- bytes_immediate,- progress_immediate * 100.0,- bytes_after_relaunch - bytes_immediate- );- }- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model.state().await;- let progress_after_resume = state.progress();- let bytes_after_resume = state.downloaded_bytes;- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let _name = entry.file_name();- let _meta = entry.metadata().await?;- }- }- assert!(- bytes_after_resume >= bytes_after_relaunch,- "Progress should not decrease after resuming and downloading (relaunch: {:.1}%, after 1s: {:.1}%)",- progress_after_relaunch * 100.0,- progress_after_resume * 100.0- );- drop(test_storage);- }- Ok(())-}--#[ignore]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_debug_file_preservation_completed_file_detection() -> Result<(), Box<dyn std::error::Error>> {- let temp_dir = tempfile::tempdir()?;- let base_dir = temp_dir.path().to_path_buf();- let base_dir_clone = base_dir.clone();- let (_progress_after_pause, downloaded_bytes_after_pause);- {- let test_storage = TestStorage::new_with_base_path(base_dir_clone).await.unwrap();- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.download().await?;- let mut config_done = false;- let mut tokenizer_done = false;- for _ in 0..60 {- tokio::time::sleep(std::time::Duration::from_secs(1)).await;- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- let config_path = model_dir.join("config.json");- let tokenizer_path = model_dir.join("tokenizer.json");- if !config_done {- if let Ok(meta) = tokio::fs::metadata(&config_path).await {- if meta.len() == 2907 {- config_done = true;- }- }- }- if !tokenizer_done {- if let Ok(meta) = tokio::fs::metadata(&tokenizer_path).await {- if meta.len() == 12807982 {- tokenizer_done = true;- }- }- }- if config_done && tokenizer_done {- break;- }- }-- // Check if download is already complete before trying to pause- let model_before_pause = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();-- let state = model_before_pause.state().await;- if !matches!(state.phase, DownloadPhase::Downloaded {}) {- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.pause().await?;- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- }-- let model_paused = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model_paused.state().await;- _progress_after_pause = state.progress();- downloaded_bytes_after_pause = state.downloaded_bytes;- drop(test_storage);- tokio::time::sleep(std::time::Duration::from_millis(500)).await;- }- {- let test_storage = TestStorage::new_with_base_path(base_dir).await.unwrap();- let model_dir = test_storage.config.cache_model_path(&test_storage.model(0)).unwrap();- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let _name = entry.file_name();- let _meta = entry.metadata().await?;- }- }- let model_relaunched = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model_relaunched.state().await;- let _progress_after_relaunch = state.progress();- let downloaded_bytes_after_relaunch = state.downloaded_bytes;- assert!(- matches!(state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}),- "Model should be Paused or Downloaded after relaunch, got: {:?}",- state.phase- );- let bytes_diff = (downloaded_bytes_after_pause as i64 - downloaded_bytes_after_relaunch as i64).abs();- assert!(- bytes_diff < 1000,- "Downloaded bytes should match after relaunch (pause: {}, relaunch: {}, diff: {})",- downloaded_bytes_after_pause,- downloaded_bytes_after_relaunch,- bytes_diff- );- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let name = entry.file_name();- let _name_str = name.to_string_lossy();- let _meta = entry.metadata().await?;- }- }-- // Only try to resume if not already downloaded- let state = model_relaunched.state().await;- if !matches!(state.phase, DownloadPhase::Downloaded {}) {- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- model.download().await?;- tokio::time::sleep(std::time::Duration::from_millis(2000)).await;- }-- let model_resumed = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.unwrap();- let state = model_resumed.state().await;- let _progress_after_resume = state.progress();- let downloaded_bytes_after_resume = state.downloaded_bytes;- assert!(- matches!(- state.phase,- DownloadPhase::Downloading {} | DownloadPhase::Paused {} | DownloadPhase::Downloaded {}- ),- "Model should be Downloading, Paused, or Downloaded after resume, got: {:?}",- state.phase- );- assert!(- downloaded_bytes_after_resume >= downloaded_bytes_after_relaunch,- "Downloaded bytes should not decrease after resume (relaunch: {}, resume: {})",- downloaded_bytes_after_relaunch,- downloaded_bytes_after_resume- );- if model_dir.exists() {- let mut entries = tokio::fs::read_dir(&model_dir).await?;- while let Some(entry) = entries.next_entry().await? {- let name = entry.file_name();- let _name_str = name.to_string_lossy();- let _meta = entry.metadata().await?;- }- }- if downloaded_bytes_after_resume < downloaded_bytes_after_relaunch * 95 / 100 {- panic!(- "\n ❌ FAIL: Download restarted from scratch!\n Expected: >= {} bytes\n Got: {} bytes\n Loss: {} bytes",- downloaded_bytes_after_relaunch * 95 / 100,- downloaded_bytes_after_resume,- downloaded_bytes_after_relaunch - downloaded_bytes_after_resume- );- }- drop(test_storage);- }- Ok(())-}diff --git a/crates/uzu/tests/test_storage_stall_detection.rs b/crates/uzu/tests/test_storage_stall_detection.rsdeleted file mode 100644index 1ef5db87e..000000000--- a/crates/uzu/tests/test_storage_stall_detection.rs+++ /dev/null@@ -1,187 +0,0 @@-#![cfg(not(target_family = "wasm"))]--mod common;--use std::time::Duration;--use common::test_helpers::TestStorage;-use futures_util::StreamExt;-use uzu::storage::types::DownloadPhase;--#[tokio::test(flavor = "multi_thread")]-async fn test_stall_detection_no_progress() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("\n[STALL_TEST] ========== NO PROGRESS STALL DETECTION TEST ==========");-- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- tracing::info!("[STALL_TEST] Starting download...");- model.download().await?;-- // Monitor for progress with stall detection- let mut progress_stream = test_storage.storage.subscribe();- let mut last_progress_time = std::time::Instant::now();- let mut last_bytes = 0u64;- let max_stall_duration = Duration::from_secs(10);- let check_interval = Duration::from_millis(500);-- tracing::info!("[STALL_TEST] Monitoring for stalls (max stall: {:?})...", max_stall_duration);-- let stall_check = tokio::time::timeout(Duration::from_secs(60), async {- let mut check_count = 0;- loop {- tokio::select! {- Some(Ok((id, state))) = progress_stream.next() => {- if id == test_storage.model(0).identifier.clone() {- let current_bytes = state.downloaded_bytes;- if current_bytes > last_bytes as i64 {- let elapsed = last_progress_time.elapsed();- tracing::info!(- "[STALL_TEST] Progress: {} bytes (delta: {}, time_since_last: {:?})",- current_bytes,- current_bytes - last_bytes as i64,- elapsed- );- last_bytes = current_bytes as u64;- last_progress_time = std::time::Instant::now();- }-- if matches!(state.phase, DownloadPhase::Downloaded {}) {- tracing::info!("[STALL_TEST] ✓ Download completed");- return Ok::<_, String>(());- }- }- }- _ = tokio::time::sleep(check_interval) => {- check_count += 1;- let elapsed = last_progress_time.elapsed();-- if elapsed > max_stall_duration {- return Err(format!(- "STALL DETECTED: No progress for {:?} (last bytes: {})",- elapsed, last_bytes- ));- }-- if check_count % 10 == 0 {- tracing::info!(- "[STALL_TEST] Check #{}: No stall detected (last progress: {:?} ago)",- check_count, elapsed- );- }-- // Stop after reaching 10% for this test- let state = model.state().await;- if state.total_bytes > 0 && state.downloaded_bytes > state.total_bytes / 10 {- tracing::info!("[STALL_TEST] ✓ Reached 10%, stopping test");- return Ok(());- }- }- }- }- })- .await;-- match stall_check {- Ok(Ok(())) => {- tracing::info!("[STALL_TEST] ✓ No stalls detected");- },- Ok(Err(stall_msg)) => {- panic!("{}", stall_msg);- },- Err(_) => {- panic!("TIMEOUT: Test took longer than 60 seconds");- },- }-- // Cancel the download- tracing::info!("[STALL_TEST] Canceling download...");- model.cancel().await?;-- tracing::info!("\n[STALL_TEST] ========== CLEANUP ==========");- drop(test_storage.storage);-- tracing::info!("[STALL_TEST] ========== TEST COMPLETE ✓ ==========\n");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_stall_detection_broadcast_liveness() -> Result<(), Box<dyn std::error::Error>> {- tracing::info!("\n[BROADCAST_TEST] ========== BROADCAST LIVENESS TEST ==========");-- let temp_dir = tempfile::tempdir()?;- let base_path = temp_dir.path().to_path_buf();- let test_storage = TestStorage::new_with_base_path(base_path).await?;- let model = test_storage.storage.get(&test_storage.model(0).identifier.clone()).await.ok_or("Model not found")?;- tracing::info!("[BROADCAST_TEST] Starting download...");- model.download().await?;-- // Verify we receive regular broadcast updates- let mut progress_stream = test_storage.storage.subscribe();- let mut update_count = 0;- let mut last_update_time = std::time::Instant::now();- let max_gap = Duration::from_secs(5);-- tracing::info!("[BROADCAST_TEST] Monitoring broadcast updates (max gap: {:?})...", max_gap);-- let broadcast_check = tokio::time::timeout(Duration::from_secs(30), async {- while let Some(Ok((id, state))) = progress_stream.next().await {- if id == test_storage.model(0).identifier.clone() {- let gap = last_update_time.elapsed();- update_count += 1;-- if gap > max_gap {- return Err(format!(- "BROADCAST GAP TOO LARGE: {:?} between updates #{} and #{}",- gap,- update_count - 1,- update_count- ));- }-- if update_count <= 10 || update_count % 50 == 0 {- tracing::info!(- "[BROADCAST_TEST] Update #{}: bytes={}/{}, gap={:?}",- update_count,- state.downloaded_bytes,- state.total_bytes,- gap- );- }-- last_update_time = std::time::Instant::now();-- // Stop after 100 updates or completion- if update_count >= 100 || matches!(state.phase, DownloadPhase::Downloaded {}) {- return Ok::<_, String>(update_count);- }- }- }- Err("Stream ended unexpectedly".to_string())- })- .await;-- match broadcast_check {- Ok(Ok(count)) => {- tracing::info!("[BROADCAST_TEST] ✓ Received {} updates, all gaps < {:?}", count, max_gap);- assert!(count >= 10, "Should receive at least 10 updates");- },- Ok(Err(gap_msg)) => {- panic!("{}", gap_msg);- },- Err(_) => {- panic!("TIMEOUT: Did not receive enough updates within 30 seconds");- },- }-- // Cancel the download- tracing::info!("[BROADCAST_TEST] Canceling download...");- model.cancel().await?;-- tracing::info!("\n[BROADCAST_TEST] ========== CLEANUP ==========");- drop(test_storage.storage);-- tracing::info!("[BROADCAST_TEST] ========== TEST COMPLETE ✓ ==========\n");- Ok(())-}diff --git a/crates/uzu/tests/unit/mod.rs b/crates/uzu/tests/unit/mod.rsnew file mode 100644index 000000000..80aaac2ba--- /dev/null+++ b/crates/uzu/tests/unit/mod.rs@@ -0,0 +1 @@+mod storage;diff --git a/crates/uzu/tests/unit/storage/lifecycle_mock_registry_model_test.rs b/crates/uzu/tests/unit/storage/lifecycle_mock_registry_model_test.rsnew file mode 100644index 000000000..d61498195--- /dev/null+++ b/crates/uzu/tests/unit/storage/lifecycle_mock_registry_model_test.rs@@ -0,0 +1,89 @@+use std::sync::Arc;++use mock_registry::{Behavior, MockRegistry};+use tokio::runtime::Handle as TokioHandle;+use tokio_stream::{StreamExt, wrappers::BroadcastStream};+use uzu::storage::types::{DownloadPhase, DownloadState, Item};++use crate::common::test_storage::TestStorage;++#[tokio::test(flavor = "multi_thread")]+async fn test_storage_mock_registry_model_download_lifecycle() -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;+ let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;+ let test_storage = TestStorage::with_models(TokioHandle::current(), vec![model.clone()]).await?;+ let model_identifier = model.identifier.clone();+ let item = Arc::new(+ test_storage+ .storage+ .get(&model_identifier)+ .await+ .ok_or_else(|| format!("model not found: {model_identifier}"))?,+ );+ let mut progress = item.progress().await?;+ let total_bytes = item.state().await.total_bytes;++ item.download().await?;+ wait_for_item_state(&item, &mut progress, |state| {+ has_reached_fraction(state, 1, 4) || matches!(state.phase, DownloadPhase::Downloaded {})+ })+ .await;++ item.pause().await?;+ item.reconcile().await?;+ let paused_state = item.state().await;+ assert!(matches!(paused_state.phase, DownloadPhase::Paused {} | DownloadPhase::Downloaded {}));++ item.download().await?;+ wait_for_item_state(&item, &mut progress, |state| {+ has_reached_fraction(state, 1, 2) || matches!(state.phase, DownloadPhase::Downloaded {})+ })+ .await;++ item.cancel().await?;+ let cancelled_state = item.state().await;+ assert!(matches!(cancelled_state.phase, DownloadPhase::NotDownloaded {}));+ assert_eq!(cancelled_state.downloaded_bytes, 0);++ item.download().await?;+ let final_state =+ wait_for_item_state(&item, &mut progress, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;++ assert_eq!(final_state.downloaded_bytes, total_bytes);+ assert_eq!(final_state.total_bytes, total_bytes);+ for served_file in registry.files {+ let destination = item.cache_path.join(&served_file.file.name);+ assert_eq!(tokio::fs::read(&destination).await?, served_file.bytes.to_vec());+ assert!(std::path::PathBuf::from(format!("{}.crc", destination.display())).is_file());+ }++ Ok(())+}++async fn wait_for_item_state(+ item: &Arc<Item>,+ progress: &mut BroadcastStream<DownloadState>,+ mut is_expected_state: impl FnMut(&DownloadState) -> bool,+) -> DownloadState {+ let current_state = item.state().await;+ if is_expected_state(¤t_state) {+ return current_state;+ }++ while let Some(result) = progress.next().await {+ let state = result.expect("storage progress stream must not lag");+ if is_expected_state(&state) {+ return state;+ }+ }++ panic!("storage progress stream ended before expected state");+}++fn has_reached_fraction(+ state: &DownloadState,+ numerator: i64,+ denominator: i64,+) -> bool {+ state.total_bytes > 0 && state.downloaded_bytes >= state.total_bytes * numerator / denominator+}diff --git a/crates/uzu/tests/unit/storage/mod.rs b/crates/uzu/tests/unit/storage/mod.rsnew file mode 100644index 000000000..3ae7e42c9--- /dev/null+++ b/crates/uzu/tests/unit/storage/mod.rs@@ -0,0 +1 @@+mod lifecycle_mock_registry_model_test;diff --git a/crates/uzu/tests/unit/test_entry.rs b/crates/uzu/tests/unit/test_entry.rsnew file mode 100644index 000000000..c0d36c57c--- /dev/null+++ b/crates/uzu/tests/unit/test_entry.rs@@ -0,0 +1,4 @@+#[path = "../common/mod.rs"]+mod common;++include!("mod.rs");