Skip to main content

modelexpress_server/
services.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::metrics::grpc::RpcOutcome;
5use crate::metrics::registry::{DownloadMetrics, RegistryMetrics, StatusLabel};
6use crate::registry::backend::ClaimOutcome;
7use crate::registry::entry_key::EntryKey;
8use crate::registry::state::RegistryManager;
9use modelexpress_common::{
10    cache::{CacheConfig, resolve_model_path},
11    constants, download,
12    grpc::{
13        api::{ApiRequest, ApiResponse, api_service_server::ApiService},
14        health::{HealthRequest, HealthResponse, health_service_server::HealthService},
15        model::{
16            DeleteModelRequest, DeleteModelResponse, FileChunk, ModelDownloadRequest,
17            ModelFileInfo, ModelFileList, ModelFileSelector, ModelFilesRequest,
18            ModelProvider as GrpcModelProvider, ModelStatusUpdate,
19            model_service_server::ModelService,
20        },
21    },
22    models::{ModelProvider, ModelStatus},
23    providers::is_weight_file,
24};
25use std::{
26    collections::HashMap,
27    path::{Path, PathBuf},
28    sync::{Arc, Mutex},
29    time::SystemTime,
30};
31use tokio::io::AsyncReadExt;
32use tokio_stream::wrappers::ReceiverStream;
33use tonic::{Request, Response, Status};
34use tracing::{debug, error, info, warn};
35
36static START_TIME: std::sync::OnceLock<SystemTime> = std::sync::OnceLock::new();
37
38/// Ceiling on resolving a revision with the provider. This is a metadata lookup, not a
39/// download, so it should complete quickly or not at all.
40const REVISION_RESOLVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
41
42/// Get the configured cache directory for model downloads
43fn get_server_cache_dir() -> Option<std::path::PathBuf> {
44    // Try to get cache configuration
45    if let Ok(config) = CacheConfig::discover() {
46        Some(config.local_path)
47    } else {
48        // Fall back to environment variable
49        modelexpress_common::envs::hf_hub_cache()
50    }
51}
52
53/// Returns true if the model's files are present in the given cache directory. Used to
54/// guard against stale `DOWNLOADED` registry records that point at a cache entry which no
55/// longer exists on disk (e.g. left behind by a client-side `model clear`). When no cache
56/// directory is configured we cannot verify, so we assume the files are present to preserve
57/// existing behavior rather than loop re-downloading forever.
58async fn model_files_present(
59    cache_dir: Option<std::path::PathBuf>,
60    model_name: &str,
61    provider: ModelProvider,
62    revision: Option<&str>,
63) -> bool {
64    let Some(cache_dir) = cache_dir else {
65        return true;
66    };
67    download::get_provider(provider)
68        .get_model_path_revision(model_name, cache_dir, revision)
69        .await
70        .is_ok()
71}
72
73/// A model download request reduced to the identity the registry and the provider need.
74///
75/// `revision` is always the *resolved*, immutable revision (a commit SHA for Hugging
76/// Face), never the branch or tag the caller typed, so cache and lease identity cannot
77/// drift when a tag moves.
78#[derive(Debug, Clone)]
79pub struct DownloadTarget {
80    pub model_name: String,
81    pub provider: ModelProvider,
82    pub revision: Option<String>,
83    pub ignore_weights: bool,
84}
85
86impl DownloadTarget {
87    /// The single string every registry backend keys this download on.
88    fn entry_key(&self) -> String {
89        EntryKey::new(
90            self.model_name.clone(),
91            self.revision.clone(),
92            self.ignore_weights,
93        )
94        .to_string()
95    }
96}
97
98/// Resolve a requested revision to the immutable revision the download will use.
99///
100/// A revision the caller pinned explicitly must resolve or the request fails: silently
101/// serving the default revision instead would hand back a different model than asked
102/// for. For an unpinned request we fall back to whatever snapshot is already cached,
103/// so a Hub outage still serves models the server has downloaded before.
104#[allow(clippy::result_large_err)] // tonic::Status grew past Clippy's Rust 1.98 threshold.
105async fn resolve_target_revision(
106    model_name: &str,
107    provider: ModelProvider,
108    cache_dir: Option<PathBuf>,
109    requested: Option<&str>,
110) -> Result<Option<String>, Status> {
111    let provider_impl = download::get_provider(provider);
112
113    // Pinning a revision on a provider that has none is a malformed request, not a
114    // revision that happens to be missing.
115    if requested.is_some() && !provider_impl.supports_revisions() {
116        return Err(Status::invalid_argument(format!(
117            "Provider '{}' does not support pinned revisions",
118            provider_impl.provider_name()
119        )));
120    }
121
122    // Resolution runs before the download lease is claimed, so an unresponsive provider
123    // would otherwise hold the RPC open indefinitely without any download in progress.
124    let resolve = provider_impl.resolve_revision(model_name, cache_dir.clone(), requested);
125    let error = match tokio::time::timeout(REVISION_RESOLVE_TIMEOUT, resolve).await {
126        Ok(Ok(resolved)) => return Ok(resolved),
127        Ok(Err(e)) => e,
128        Err(_) => anyhow::anyhow!("timed out after {}s", REVISION_RESOLVE_TIMEOUT.as_secs()),
129    };
130
131    if requested.is_some() {
132        return Err(Status::not_found(format!(
133            "Failed to resolve revision for model '{model_name}': {error:#}"
134        )));
135    }
136
137    warn!(
138        "Failed to resolve the default revision for '{model_name}': {error:#}; \
139         falling back to the cached snapshot"
140    );
141
142    match provider_impl
143        .get_model_path_revision(model_name, cache_dir.unwrap_or_default(), None)
144        .await
145        .ok()
146        .and_then(|path| {
147            path.file_name()
148                .and_then(|name| name.to_str())
149                .map(String::from)
150        }) {
151        Some(cached) => Ok(Some(cached)),
152        None => Err(Status::not_found(format!(
153            "Failed to resolve revision for model '{model_name}': {error:#}"
154        ))),
155    }
156}
157
158/// Health service implementation
159#[derive(Debug, Default)]
160pub struct HealthServiceImpl;
161
162#[tonic::async_trait]
163impl HealthService for HealthServiceImpl {
164    async fn get_health(
165        &self,
166        _request: Request<HealthRequest>,
167    ) -> Result<Response<HealthResponse>, Status> {
168        let start_time = START_TIME.get_or_init(SystemTime::now);
169        let uptime = SystemTime::now()
170            .duration_since(*start_time)
171            .unwrap_or_default()
172            .as_secs();
173
174        let response = HealthResponse {
175            version: env!("CARGO_PKG_VERSION").to_string(),
176            status: "ok".to_string(),
177            uptime,
178        };
179
180        Ok(Response::new(response))
181    }
182}
183
184/// API service implementation
185#[derive(Debug, Default)]
186pub struct ApiServiceImpl;
187
188/// Return `body` with the handler's own verdict attached.
189///
190/// See [`crate::metrics::grpc`]. Mirrors the helper in `p2p/service.rs`; kept
191/// local to each module so a handler's outcome is stated next to the handler.
192#[allow(clippy::result_large_err)] // Returns the handlers' own tonic::Status result type.
193fn tagged<T>(body: T, outcome: RpcOutcome) -> Result<Response<T>, Status> {
194    let mut response = Response::new(body);
195    response.extensions_mut().insert(outcome);
196    Ok(response)
197}
198
199#[tonic::async_trait]
200impl ApiService for ApiServiceImpl {
201    async fn send_request(
202        &self,
203        request: Request<ApiRequest>,
204    ) -> Result<Response<ApiResponse>, Status> {
205        let api_request = request.into_inner();
206        info!("Received gRPC request: {:?}", api_request);
207
208        // Process the request based on the action
209        if api_request.action.as_str() == "ping" {
210            info!("Processing ping request");
211            let response_data = serde_json::json!({ "message": "pong" });
212            let data_bytes = serde_json::to_vec(&response_data)
213                .map_err(|e| Status::internal(format!("Serialization error: {e}")))?;
214
215            tagged(
216                ApiResponse {
217                    success: true,
218                    data: Some(data_bytes),
219                    error: None,
220                },
221                RpcOutcome::Ok,
222            )
223        } else {
224            error!("Unknown action: {}", api_request.action);
225            // In band, like the P2P handlers: `Ok` on the wire with
226            // `success: false` in the body, so the outcome has to be stated
227            // rather than inferred from the status code.
228            tagged(
229                ApiResponse {
230                    success: false,
231                    data: None,
232                    error: Some(format!("Unknown action: {}", api_request.action)),
233                },
234                RpcOutcome::InvalidArgument,
235            )
236        }
237    }
238}
239
240/// Model service implementation
241#[derive(Clone)]
242pub struct ModelServiceImpl {
243    tracker: Arc<ModelDownloadTracker>,
244}
245
246impl ModelServiceImpl {
247    /// Each server owns its tracker, so multiple servers can run in one process.
248    pub fn new(tracker: Arc<ModelDownloadTracker>) -> Self {
249        Self { tracker }
250    }
251}
252
253/// Helper function to collect all files in a model directory recursively
254fn collect_model_files(
255    base_path: &Path,
256    current_path: &Path,
257    file_selector: Option<&ModelFileSelector>,
258    ignore_weights: bool,
259) -> Vec<(PathBuf, u64)> {
260    let mut files = Vec::new();
261
262    if let Ok(entries) = std::fs::read_dir(current_path) {
263        for entry in entries.flatten() {
264            let path = entry.path();
265            if path.is_file() {
266                if let Ok(metadata) = std::fs::metadata(&path) {
267                    // Get relative path from base_path
268                    if let Ok(relative) = path.strip_prefix(base_path) {
269                        // Validate that the relative path does not contain any '..' components or is absolute
270                        let mut is_safe = true;
271                        for comp in relative.components() {
272                            use std::path::Component;
273                            match comp {
274                                Component::ParentDir
275                                | Component::RootDir
276                                | Component::Prefix(_) => {
277                                    is_safe = false;
278                                    break;
279                                }
280                                _ => {}
281                            }
282                        }
283                        if !is_safe {
284                            tracing::warn!(
285                                "Skipping potentially unsafe file path: {:?} (relative: {:?})",
286                                path,
287                                relative
288                            );
289                        } else if ignore_weights
290                            && is_weight_file(relative.to_string_lossy().as_ref())
291                        {
292                            // Weight file skipped because ignore_weights is set.
293                        } else if file_selector.is_none_or(|selector| {
294                            selector
295                                .paths
296                                .iter()
297                                .any(|selector_path| Path::new(selector_path) == relative)
298                        }) {
299                            files.push((relative.to_path_buf(), metadata.len()));
300                        }
301                    }
302                }
303            } else if path.is_dir() {
304                files.extend(collect_model_files(
305                    base_path,
306                    &path,
307                    file_selector,
308                    ignore_weights,
309                ));
310            }
311        }
312    }
313
314    files
315}
316
317fn ensure_selected_files_exist(
318    files: &[(PathBuf, u64)],
319    file_selector: Option<&ModelFileSelector>,
320) -> Result<(), String> {
321    let Some(selector) = file_selector else {
322        return Ok(());
323    };
324
325    if let Some(missing_path) = selector.paths.iter().find(|selector_path| {
326        !files
327            .iter()
328            .any(|(path, _)| Path::new(selector_path) == path.as_path())
329    }) {
330        Err(format!(
331            "Selected file not found in model directory: {missing_path}"
332        ))
333    } else {
334        Ok(())
335    }
336}
337
338#[tonic::async_trait]
339impl ModelService for ModelServiceImpl {
340    type EnsureModelDownloadedStream = ReceiverStream<Result<ModelStatusUpdate, Status>>;
341    type StreamModelFilesStream = ReceiverStream<Result<FileChunk, Status>>;
342
343    async fn ensure_model_downloaded(
344        &self,
345        request: Request<ModelDownloadRequest>,
346    ) -> Result<Response<Self::EnsureModelDownloadedStream>, Status> {
347        info!("Starting model download stream");
348        let model_request = request.into_inner();
349        let (tx, rx) = tokio::sync::mpsc::channel(4);
350
351        // Convert gRPC provider to our enum
352        let grpc_provider = GrpcModelProvider::try_from(model_request.provider).map_err(|_| {
353            Status::invalid_argument(format!(
354                "Invalid provider value: {}",
355                model_request.provider
356            ))
357        })?;
358        let provider = ModelProvider::from(grpc_provider);
359        let model_name = download::canonical_model_name(&model_request.model_name, provider)
360            .map_err(|e| Status::invalid_argument(e.to_string()))?;
361        let ignore_weights = model_request.ignore_weights;
362
363        // Resolve before claiming: the registry keys the download lease on the resolved
364        // revision, so two revisions of one model never coalesce onto a single claim.
365        let revision = resolve_target_revision(
366            &model_name,
367            provider,
368            get_server_cache_dir(),
369            model_request.revision.as_deref(),
370        )
371        .await?;
372
373        let target = DownloadTarget {
374            model_name: model_name.clone(),
375            provider,
376            revision: revision.clone(),
377            ignore_weights,
378        };
379
380        // Spawn a task to handle the streaming download updates
381        let tracker = self.tracker.clone();
382        tokio::spawn(async move {
383            // Run the full claim + wait + retry flow. `ensure_model_downloaded` sends
384            // its own initial status update (based on the `ClaimOutcome` returned by the
385            // registry), so we don't do a pre-check here — a pre-check would either
386            // duplicate that update or, worse, emit `status=ERROR` on a model we're
387            // about to retry and trip the client-lib's terminal-error bailout before
388            // the retry completion broadcast arrives.
389            let final_status = tracker.ensure_model_downloaded(&target, &tx).await;
390
391            // Send final status update
392            let final_update = ModelStatusUpdate {
393                model_name: model_name.clone(),
394                status: modelexpress_common::grpc::model::ModelStatus::from(final_status) as i32,
395                message: match final_status {
396                    ModelStatus::DOWNLOADED => {
397                        Some("Model download completed successfully".to_string())
398                    }
399                    ModelStatus::ERROR => Some("Model download failed".to_string()),
400                    ModelStatus::DOWNLOADING => Some("Download still in progress".to_string()),
401                },
402                provider: grpc_provider as i32,
403                resolved_revision: revision,
404            };
405
406            let _ = tx.send(Ok(final_update)).await;
407        });
408
409        Ok(Response::new(ReceiverStream::new(rx)))
410    }
411
412    async fn stream_model_files(
413        &self,
414        request: Request<ModelFilesRequest>,
415    ) -> Result<Response<Self::StreamModelFilesStream>, Status> {
416        let files_request = request.into_inner();
417        let chunk_size = if files_request.chunk_size == 0 {
418            constants::DEFAULT_TRANSFER_CHUNK_SIZE
419        } else {
420            files_request.chunk_size as usize
421        };
422
423        // Convert gRPC provider to our enum
424        let grpc_provider = GrpcModelProvider::try_from(files_request.provider).map_err(|_| {
425            Status::invalid_argument(format!(
426                "Invalid provider value: {}",
427                files_request.provider
428            ))
429        })?;
430        let provider = ModelProvider::from(grpc_provider);
431        let model_name = download::canonical_model_name(&files_request.model_name, provider)
432            .map_err(|e| Status::invalid_argument(e.to_string()))?;
433        let provider_impl = download::get_provider(provider);
434
435        info!(
436            "Starting file stream for model: {} with chunk size: {} bytes",
437            model_name, chunk_size
438        );
439
440        // Get the cache directory
441        let cache_dir = get_server_cache_dir()
442            .ok_or_else(|| Status::internal("Server cache directory not configured"))?;
443
444        // Get the model path using the provider from the request. A requested revision
445        // selects that exact snapshot instead of whichever one is newest on disk.
446        let model_path = provider_impl
447            .get_model_path_revision(
448                &model_name,
449                cache_dir.clone(),
450                files_request.revision.as_deref(),
451            )
452            .await
453            .map_err(|e| Status::not_found(format!("Model not found: {e}")))?;
454
455        debug!("Model path resolved to: {:?}", model_path);
456
457        let commit_hash = if provider == ModelProvider::HuggingFace {
458            model_path
459                .file_name()
460                .and_then(|name| name.to_str())
461                .map(String::from)
462        } else {
463            None
464        };
465
466        if provider == ModelProvider::HuggingFace && commit_hash.is_none() {
467            return Err(Status::internal(
468                "Resolved Hugging Face model path did not contain a revision",
469            ));
470        }
471
472        let expected_model_path =
473            resolve_model_path(&cache_dir, provider, &model_name, commit_hash.as_deref()).map_err(
474                |e| Status::internal(format!("Failed to resolve expected cache layout: {e}")),
475            )?;
476
477        if model_path != expected_model_path {
478            error!(
479                "Resolved model path '{}' does not match expected cache layout '{}' for model '{}'",
480                model_path.display(),
481                expected_model_path.display(),
482                model_name
483            );
484            return Err(Status::internal(
485                "Resolved model path does not match expected cache layout",
486            ));
487        }
488
489        // Collect all files to stream
490        let files = collect_model_files(
491            &model_path,
492            &model_path,
493            files_request.file_selector.as_ref(),
494            files_request.ignore_weights,
495        );
496        ensure_selected_files_exist(&files, files_request.file_selector.as_ref())
497            .map_err(Status::not_found)?;
498
499        if files.is_empty() {
500            return Err(Status::not_found("No files found in model directory"));
501        }
502
503        let total_files = files.len();
504        info!(
505            "Found {} files to stream for model {}",
506            total_files, model_name
507        );
508
509        let (tx, rx) = tokio::sync::mpsc::channel(16);
510
511        // Spawn a task to stream files
512        tokio::spawn(async move {
513            // Allocate buffer once and reuse across all files
514            let mut buffer = vec![0u8; chunk_size];
515            let mut is_first_chunk = true;
516
517            for (file_idx, (relative_path, total_size)) in files.iter().enumerate() {
518                let file_path = model_path.join(relative_path);
519                let is_last_file = file_idx == total_files.saturating_sub(1);
520
521                debug!("Streaming file: {:?} ({} bytes)", relative_path, total_size);
522
523                // Open the file
524                let file = match tokio::fs::File::open(&file_path).await {
525                    Ok(f) => f,
526                    Err(e) => {
527                        error!("Failed to open file {:?}: {}", file_path, e);
528                        let _ = tx
529                            .send(Err(Status::internal(format!("Failed to open file: {e}"))))
530                            .await;
531                        return;
532                    }
533                };
534
535                let mut reader = tokio::io::BufReader::new(file);
536                let mut offset: u64 = 0;
537
538                if *total_size == 0 {
539                    let first_chunk = std::mem::replace(&mut is_first_chunk, false);
540                    let chunk = FileChunk {
541                        relative_path: relative_path.to_string_lossy().to_string(),
542                        data: Vec::new(),
543                        offset: 0,
544                        total_size: 0,
545                        is_last_chunk: true,
546                        is_last_file,
547                        commit_hash: if first_chunk {
548                            commit_hash.clone()
549                        } else {
550                            None
551                        },
552                    };
553
554                    if tx.send(Ok(chunk)).await.is_err() {
555                        debug!("Client disconnected during file stream");
556                        return;
557                    }
558
559                    continue;
560                }
561
562                loop {
563                    let bytes_read = match reader.read(&mut buffer).await {
564                        Ok(0) => break, // EOF
565                        Ok(n) => n,
566                        Err(e) => {
567                            error!("Failed to read file {:?}: {}", file_path, e);
568                            let _ = tx
569                                .send(Err(Status::internal(format!("Failed to read file: {e}"))))
570                                .await;
571                            return;
572                        }
573                    };
574
575                    let is_last_chunk = offset.saturating_add(bytes_read as u64) >= *total_size;
576
577                    let first_chunk = std::mem::replace(&mut is_first_chunk, false);
578
579                    let chunk = FileChunk {
580                        relative_path: relative_path.to_string_lossy().to_string(),
581                        data: buffer[..bytes_read].to_vec(),
582                        offset,
583                        total_size: *total_size,
584                        is_last_chunk,
585                        is_last_file: is_last_file && is_last_chunk,
586                        commit_hash: if first_chunk {
587                            commit_hash.clone()
588                        } else {
589                            None
590                        },
591                    };
592
593                    if tx.send(Ok(chunk)).await.is_err() {
594                        debug!("Client disconnected during file stream");
595                        return;
596                    }
597
598                    offset = offset.saturating_add(bytes_read as u64);
599                }
600            }
601
602            info!("File streaming completed for model");
603        });
604
605        Ok(Response::new(ReceiverStream::new(rx)))
606    }
607
608    async fn list_model_files(
609        &self,
610        request: Request<ModelFilesRequest>,
611    ) -> Result<Response<ModelFileList>, Status> {
612        let files_request = request.into_inner();
613
614        // Convert gRPC provider to our enum
615        let grpc_provider = GrpcModelProvider::try_from(files_request.provider).map_err(|_| {
616            Status::invalid_argument(format!(
617                "Invalid provider value: {}",
618                files_request.provider
619            ))
620        })?;
621        let provider = ModelProvider::from(grpc_provider);
622        let model_name = download::canonical_model_name(&files_request.model_name, provider)
623            .map_err(|e| Status::invalid_argument(e.to_string()))?;
624        let provider_impl = download::get_provider(provider);
625
626        info!("Listing files for model: {}", model_name);
627
628        // Get the cache directory
629        let cache_dir = get_server_cache_dir()
630            .ok_or_else(|| Status::internal("Server cache directory not configured"))?;
631
632        // Get the model path using the provider from the request
633        let model_path = provider_impl
634            .get_model_path_revision(&model_name, cache_dir, files_request.revision.as_deref())
635            .await
636            .map_err(|e| Status::not_found(format!("Model not found: {e}")))?;
637
638        // Collect all files
639        let files = collect_model_files(
640            &model_path,
641            &model_path,
642            files_request.file_selector.as_ref(),
643            files_request.ignore_weights,
644        );
645        ensure_selected_files_exist(&files, files_request.file_selector.as_ref())
646            .map_err(Status::not_found)?;
647
648        let file_infos: Vec<ModelFileInfo> = files
649            .iter()
650            .map(|(path, size)| ModelFileInfo {
651                relative_path: path.to_string_lossy().to_string(),
652                size: *size,
653            })
654            .collect();
655
656        let total_size: u64 = files.iter().map(|(_, size)| size).sum();
657
658        Ok(Response::new(ModelFileList {
659            model_name,
660            files: file_infos,
661            total_size,
662        }))
663    }
664
665    async fn delete_model(
666        &self,
667        request: Request<DeleteModelRequest>,
668    ) -> Result<Response<DeleteModelResponse>, Status> {
669        let delete_request = request.into_inner();
670
671        let grpc_provider = GrpcModelProvider::try_from(delete_request.provider).map_err(|_| {
672            Status::invalid_argument(format!(
673                "Invalid provider value: {}",
674                delete_request.provider
675            ))
676        })?;
677        let provider = ModelProvider::from(grpc_provider);
678        let model_name = download::canonical_model_name(&delete_request.model_name, provider)
679            .map_err(|e| Status::invalid_argument(e.to_string()))?;
680
681        // A model can hold several entries at once (one per revision, and separate ones
682        // for metadata-only downloads). `model clear` means "forget this model", so drop
683        // all of them rather than only the unpinned full-weight entry.
684        let tracker = self.tracker.clone();
685        let outcome = tracker.delete_model_entries(&model_name).await;
686        let removed = outcome.removed;
687        info!("Deleted {removed} registry record(s) for model '{model_name}'");
688
689        // The response stays `success: true` -- the fallback delete was still
690        // attempted and callers depend on that shape. But a registry outage and a
691        // model with no entries both return zero records here, so without the tag
692        // the RPC would be recorded as a plain success during an outage. That is
693        // the exact failure this layer exists to prevent.
694        tagged(
695            DeleteModelResponse {
696                success: true,
697                message: Some(format!(
698                    "Model '{model_name}' removed from registry ({removed} record(s))"
699                )),
700            },
701            if outcome.degraded {
702                RpcOutcome::BackendError
703            } else {
704                RpcOutcome::Ok
705            },
706        )
707    }
708}
709
710/// What clearing a model's registry entries actually achieved.
711///
712/// `removed` alone cannot distinguish "this model had no entries" from "the
713/// registry was unreachable and only the fallback key was tried" -- both are
714/// zero.
715pub struct DeleteEntriesOutcome {
716    /// How many records were removed.
717    pub removed: usize,
718    /// The registry listing failed, so `removed` is a floor rather than a count.
719    pub degraded: bool,
720}
721
722/// Type alias for the complex waiting channels type
723type WaitingChannels =
724    Arc<Mutex<HashMap<String, Vec<tokio::sync::mpsc::Sender<Result<ModelStatusUpdate, Status>>>>>>;
725
726/// What a status update is routed by and what it reports.
727///
728/// Waiters are registered under the registry entry key, which carries the revision and
729/// weight mode, while the update itself reports the plain model name the caller asked
730/// for plus the revision it resolved to.
731struct UpdateIdentity<'a> {
732    entry_key: &'a str,
733    model_name: &'a str,
734    provider: ModelProvider,
735    resolved_revision: Option<&'a str>,
736}
737
738impl UpdateIdentity<'_> {
739    fn status_update(&self, status: ModelStatus, message: Option<String>) -> ModelStatusUpdate {
740        ModelStatusUpdate {
741            model_name: self.model_name.to_string(),
742            status: modelexpress_common::grpc::model::ModelStatus::from(status) as i32,
743            message,
744            provider: GrpcModelProvider::from(self.provider) as i32,
745            resolved_revision: self.resolved_revision.map(String::from),
746        }
747    }
748}
749
750/// Tracks the status of model downloads through the distributed registry backend.
751#[derive(Clone)]
752pub struct ModelDownloadTracker {
753    /// Distributed registry (Redis today, K8s CRDs in a follow-up).
754    registry: Arc<RegistryManager>,
755    /// Maps model names to list of channels waiting for updates on this server replica.
756    waiting_channels: WaitingChannels,
757    download_metrics: DownloadMetrics,
758    registry_metrics: RegistryMetrics,
759}
760
761const DOWNLOAD_LEASE_DURATION: std::time::Duration = std::time::Duration::from_secs(30);
762const DOWNLOAD_HEARTBEAT_INTERVAL: tokio::time::Duration = tokio::time::Duration::from_secs(10);
763
764impl ModelDownloadTracker {
765    pub fn new(
766        registry: Arc<RegistryManager>,
767        download_metrics: DownloadMetrics,
768        registry_metrics: RegistryMetrics,
769    ) -> Self {
770        Self {
771            registry,
772            waiting_channels: Arc::new(Mutex::new(HashMap::new())),
773            download_metrics,
774            registry_metrics,
775        }
776    }
777
778    /// Number of models with callers currently waiting on a download.
779    ///
780    /// This map is never evicted wholesale, so its size is the early warning for
781    /// the leak that would eventually OOM the server. A poisoned lock reports the
782    /// recovered length rather than failing: a metric read must not be able to
783    /// take down the download path.
784    pub fn waiting_count(&self) -> usize {
785        match self.waiting_channels.lock() {
786            Ok(waiting) => waiting.len(),
787            Err(poisoned) => poisoned.into_inner().len(),
788        }
789    }
790
791    async fn touch_and_log(&self, model_name: &str) {
792        if let Err(e) = self.registry.touch_model(model_name).await {
793            error!("Failed to touch model {model_name}: {e}");
794        }
795    }
796
797    /// Gets the status of a model from the registry, bumping `last_used_at` on hit.
798    /// Returns None on lookup failure (error logged) or unknown model.
799    pub async fn get_status(&self, model_name: &str) -> Option<ModelStatus> {
800        match self.registry.get_status(model_name).await {
801            Ok(Some(status)) => {
802                self.touch_and_log(model_name).await;
803                Some(status)
804            }
805            Ok(None) => None,
806            Err(e) => {
807                error!("Failed to get model status from registry: {e}");
808                None
809            }
810        }
811    }
812
813    /// Sets the status of a model and notifies all waiting channels on this replica.
814    pub async fn set_status_and_notify(
815        &self,
816        model_name: String,
817        status: ModelStatus,
818        provider: ModelProvider,
819        message: Option<String>,
820    ) {
821        if let Err(e) = self
822            .registry
823            .set_status(&model_name, provider, status, message.clone())
824            .await
825        {
826            error!("Failed to update model status in registry: {e}");
827            return;
828        }
829        self.notify_waiters(
830            UpdateIdentity {
831                entry_key: &model_name,
832                model_name: &model_name,
833                provider,
834                resolved_revision: None,
835            },
836            status,
837            message,
838        );
839    }
840
841    fn notify_waiters(
842        &self,
843        identity: UpdateIdentity<'_>,
844        status: ModelStatus,
845        message: Option<String>,
846    ) {
847        let mut waiting = match self.waiting_channels.lock() {
848            Ok(guard) => guard,
849            Err(poisoned) => {
850                error!("Waiting channels mutex is poisoned, recovering");
851                poisoned.into_inner()
852            }
853        };
854        if let Some(channels) = waiting.get(identity.entry_key) {
855            let update = identity.status_update(status, message);
856            for channel in channels {
857                let _ = channel.try_send(Ok(update.clone()));
858            }
859            if status == ModelStatus::DOWNLOADED || status == ModelStatus::ERROR {
860                waiting.remove(identity.entry_key);
861            }
862        }
863    }
864
865    /// Adds a channel that wants updates on a specific model (server-replica-local).
866    pub fn add_waiting_channel(
867        &self,
868        model_name: &str,
869        tx: tokio::sync::mpsc::Sender<Result<ModelStatusUpdate, Status>>,
870    ) {
871        let mut waiting = match self.waiting_channels.lock() {
872            Ok(guard) => guard,
873            Err(poisoned) => {
874                error!("Waiting channels mutex is poisoned, recovering");
875                poisoned.into_inner()
876            }
877        };
878        waiting.entry(model_name.to_string()).or_default().push(tx);
879    }
880
881    /// Deletes a model record from the registry and clears local waiters.
882    /// Returns whether the registry record was actually removed.
883    ///
884    /// The error is still swallowed -- callers proceed to notify waiters either
885    /// way -- but the outcome is reported, because a caller that records the
886    /// removal as a lifecycle event must not do so when nothing was removed.
887    pub async fn delete_status(&self, model_name: &str) -> bool {
888        let deleted = match self.registry.delete_model(model_name).await {
889            Ok(()) => true,
890            Err(e) => {
891                error!("Failed to delete model from registry: {e}");
892                false
893            }
894        };
895        let mut waiting = match self.waiting_channels.lock() {
896            Ok(guard) => guard,
897            Err(poisoned) => {
898                error!("Waiting channels mutex is poisoned, recovering");
899                poisoned.into_inner()
900            }
901        };
902        waiting.remove(model_name);
903        deleted
904    }
905
906    /// Deletes every registry entry belonging to `model_name`, whatever revision or
907    /// weight mode each entry covers.
908    ///
909    /// The registry-listing failure is swallowed on purpose: the fallback still
910    /// clears the common case, which is better than refusing outright. It is
911    /// reported in the return value so the caller can say so, because otherwise a
912    /// backend outage and a model with no entries are the same `0`.
913    pub async fn delete_model_entries(&self, model_name: &str) -> DeleteEntriesOutcome {
914        let records = match self.registry.get_models_by_last_used(None).await {
915            Ok(records) => records,
916            Err(e) => {
917                error!("Failed to list registry records for '{model_name}': {e}");
918                // Fall back to the unpinned full-weight key so the common case still
919                // clears rather than failing outright.
920                self.delete_status(model_name).await;
921                return DeleteEntriesOutcome {
922                    removed: 0,
923                    degraded: true,
924                };
925            }
926        };
927
928        let mut removed: usize = 0;
929        for record in records {
930            if EntryKey::parse(&record.model_name).belongs_to(model_name) {
931                // Deleting a record mid-download is a real exit from DOWNLOADING,
932                // and the only one the claim lifecycle cannot see: once the key
933                // is gone, finish_download_claim finds nothing to fence and
934                // returns false, so it records no departure. Without this the
935                // arrival booked by the claim is never matched and the flow
936                // accounting stays permanently ahead. The status is already in
937                // hand here, so this costs no extra read.
938                // Only once the record is really gone. delete_model can fail and
939                // is swallowed, and recording first would book a departure for an
940                // entry still sitting in DOWNLOADING -- turning a backend outage
941                // into a permanently understated flow count.
942                let deleted = self.delete_status(&record.model_name).await;
943                if deleted && record.status == ModelStatus::DOWNLOADING {
944                    self.registry_metrics
945                        .record_transition(StatusLabel::Downloading, StatusLabel::Absent);
946                }
947                removed = removed.saturating_add(1);
948            }
949        }
950        DeleteEntriesOutcome {
951            removed,
952            degraded: false,
953        }
954    }
955
956    /// Spawn a background task that actually downloads the model, updating the tracker on
957    /// success or failure. Extracted here so the claim and retry paths share the code.
958    fn spawn_download_task(&self, target: DownloadTarget, retry: bool, claim_id: String) {
959        let tracker = self.clone();
960        tokio::spawn(async move {
961            let started = std::time::Instant::now();
962            let entry_key = target.entry_key();
963            let DownloadTarget {
964                model_name,
965                provider,
966                revision,
967                ignore_weights,
968            } = target;
969            let cache_dir = get_server_cache_dir();
970            let download = download::download_model_revision(
971                &model_name,
972                provider,
973                cache_dir,
974                ignore_weights,
975                revision.as_deref(),
976            );
977            tokio::pin!(download);
978            let start = tokio::time::Instant::now()
979                .checked_add(DOWNLOAD_HEARTBEAT_INTERVAL)
980                .unwrap_or_else(tokio::time::Instant::now);
981            let mut heartbeat = tokio::time::interval_at(start, DOWNLOAD_HEARTBEAT_INTERVAL);
982            let result = loop {
983                tokio::select! {
984                    result = &mut download => break result,
985                    _ = heartbeat.tick() => {
986                        match tracker
987                            .registry
988                            .refresh_download_claim(
989                                &entry_key,
990                                provider,
991                                &claim_id,
992                                DOWNLOAD_LEASE_DURATION,
993                            )
994                            .await
995                        {
996                            Ok(true) => {}
997                            Ok(false) => {
998                                warn!(
999                                    "Stopping download for {model_name}: lease ownership was lost"
1000                                );
1001                                return;
1002                            }
1003                            Err(e) => {
1004                                warn!("Failed to refresh download lease for {model_name}: {e}");
1005                            }
1006                        }
1007                    }
1008                }
1009            };
1010
1011            let (status, message) = match result {
1012                Ok(_path) => (
1013                    ModelStatus::DOWNLOADED,
1014                    Some("Model download completed successfully".to_string()),
1015                ),
1016                Err(e) => {
1017                    if retry {
1018                        error!("Failed to download model {model_name} on retry: {e}");
1019                    } else {
1020                        error!("Failed to download model {model_name}: {e}");
1021                    }
1022                    let msg = if retry {
1023                        format!("Download failed on retry: {e}")
1024                    } else {
1025                        format!("Download failed: {e}")
1026                    };
1027                    (ModelStatus::ERROR, Some(msg))
1028                }
1029            };
1030
1031            // Timed from the top of the task, so this is the whole download
1032            // rather than the registry write below it. Observed before the fence
1033            // check: the bytes were fetched regardless of whether this replica
1034            // still owns the right to publish the result.
1035            tracker
1036                .download_metrics
1037                .observe(StatusLabel::from(status), started.elapsed().as_secs_f64());
1038
1039            match tracker
1040                .registry
1041                .finish_download_claim(&entry_key, provider, &claim_id, status, message.clone())
1042                .await
1043            {
1044                Ok(true) => {
1045                    tracker.notify_waiters(
1046                        UpdateIdentity {
1047                            entry_key: &entry_key,
1048                            model_name: &model_name,
1049                            provider,
1050                            resolved_revision: revision.as_deref(),
1051                        },
1052                        status,
1053                        message,
1054                    );
1055                }
1056                Ok(false) => {
1057                    warn!("Ignoring completion for {model_name}: lease ownership was lost");
1058                }
1059                Err(e) => {
1060                    error!("Failed to finish download claim for {model_name}: {e}");
1061                }
1062            }
1063        });
1064    }
1065
1066    /// Initiates a download for a model and streams status updates.
1067    ///
1068    /// All registry operations key on the target's entry key rather than its model name,
1069    /// so a second revision (or a full-weight request behind a metadata-only one) claims
1070    /// its own lease instead of coalescing onto an unrelated download.
1071    pub async fn ensure_model_downloaded(
1072        &self,
1073        target: &DownloadTarget,
1074        tx: &tokio::sync::mpsc::Sender<Result<ModelStatusUpdate, Status>>,
1075    ) -> ModelStatus {
1076        let entry_key = target.entry_key();
1077        let entry_key = entry_key.as_str();
1078        let model_name = target.model_name.as_str();
1079        let provider = target.provider;
1080        let identity = UpdateIdentity {
1081            entry_key,
1082            model_name,
1083            provider,
1084            resolved_revision: target.revision.as_deref(),
1085        };
1086
1087        // Atomically try to claim this model for download. The `ClaimOutcome` tells us
1088        // whether THIS replica won the claim or is observing someone else's claim —
1089        // status alone (`DOWNLOADING`) can't distinguish those cases across replicas.
1090        // A claim may report an existing `DOWNLOADED` record whose files no longer exist
1091        // on disk (e.g. after a client-side `model clear` that only removed local files).
1092        // When that happens we drop the stale record and re-claim once, so the download
1093        // path runs instead of returning a false success. Bounded to two attempts to
1094        // avoid looping if the delete or a concurrent re-claim keeps the record around.
1095        const MAX_CLAIM_ATTEMPTS: usize = 2;
1096        let mut claim_id = uuid::Uuid::new_v4().to_string();
1097        let mut attempt: usize = 0;
1098        let (status, is_owner) = loop {
1099            attempt = attempt.saturating_add(1);
1100            match self
1101                .registry
1102                .try_claim_for_download(entry_key, provider, &claim_id, DOWNLOAD_LEASE_DURATION)
1103                .await
1104            {
1105                // Both outcomes mean this replica owns the download; they differ
1106                // only in cost, which the metrics layer records separately.
1107                Ok(ClaimOutcome::Claimed | ClaimOutcome::TookOver) => {
1108                    break (ModelStatus::DOWNLOADING, true);
1109                }
1110                Ok(ClaimOutcome::AlreadyExists(existing)) => {
1111                    if existing == ModelStatus::DOWNLOADED
1112                        && attempt < MAX_CLAIM_ATTEMPTS
1113                        && !model_files_present(
1114                            get_server_cache_dir(),
1115                            model_name,
1116                            provider,
1117                            target.revision.as_deref(),
1118                        )
1119                        .await
1120                    {
1121                        error!(
1122                            "Registry reports model '{model_name}' as DOWNLOADED but its files \
1123                             are missing from the cache; clearing the stale record and \
1124                             re-downloading"
1125                        );
1126                        self.delete_status(entry_key).await;
1127                        continue;
1128                    }
1129                    if existing == ModelStatus::DOWNLOADED {
1130                        // Returning an existing downloaded model is a cache hit for LRU purposes.
1131                        self.touch_and_log(entry_key).await;
1132                    }
1133                    break (existing, false);
1134                }
1135                Err(e) => {
1136                    error!("Failed to claim model for download: {e}");
1137                    let error_update = identity.status_update(
1138                        ModelStatus::ERROR,
1139                        Some("Registry error occurred".to_string()),
1140                    );
1141                    let _ = tx.send(Ok(error_update)).await;
1142                    return ModelStatus::ERROR;
1143                }
1144            }
1145        };
1146
1147        // If we observed a previous ERROR, attempt the ERROR -> DOWNLOADING CAS up front.
1148        // Only the CAS winner spawns the retry download; observers fall through to the
1149        // wait loop. Doing this *before* the initial stream update keeps the reported
1150        // status honest: after this block, the record is DOWNLOADING (the record may
1151        // briefly have been ERROR, but the client should wait, not bail).
1152        let (effective_status, is_retry_owner) = if status == ModelStatus::ERROR {
1153            let won = match self
1154                .registry
1155                .try_reset_error_for_retry(entry_key, provider, &claim_id, DOWNLOAD_LEASE_DURATION)
1156                .await
1157            {
1158                Ok(won) => won,
1159                Err(e) => {
1160                    error!("Failed to CAS status for retry: {e}");
1161                    let _ = tx
1162                        .send(Ok(identity.status_update(
1163                            ModelStatus::ERROR,
1164                            Some("Registry error occurred during retry".to_string()),
1165                        )))
1166                        .await;
1167                    return ModelStatus::ERROR;
1168                }
1169            };
1170            (ModelStatus::DOWNLOADING, won)
1171        } else {
1172            (status, false)
1173        };
1174
1175        let update = identity.status_update(
1176            effective_status,
1177            match (status, effective_status) {
1178                (_, ModelStatus::DOWNLOADED) => Some("Model already downloaded".to_string()),
1179                (ModelStatus::ERROR, _) => Some("Previous download failed, retrying".to_string()),
1180                (_, ModelStatus::DOWNLOADING) => Some("Model download in progress".to_string()),
1181                // effective can never be ERROR: ERROR observations are CAS'd above.
1182                (_, ModelStatus::ERROR) => Some("Download error".to_string()),
1183            },
1184        );
1185        let _ = tx.send(Ok(update)).await;
1186
1187        if effective_status == ModelStatus::DOWNLOADING {
1188            // Every caller is a waiter — whether we own the download or not, we still
1189            // need a channel so the completion broadcast reaches this stream.
1190            self.add_waiting_channel(entry_key, tx.clone());
1191
1192            // Spawn the download only on the replica that won the claim (fresh
1193            // download) or won the ERROR-retry CAS. Everyone else waits.
1194            if is_owner || is_retry_owner {
1195                let retry = status == ModelStatus::ERROR;
1196                self.spawn_download_task(target.clone(), retry, claim_id);
1197                claim_id = uuid::Uuid::new_v4().to_string();
1198            }
1199
1200            loop {
1201                tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
1202                match self
1203                    .registry
1204                    .try_claim_for_download(entry_key, provider, &claim_id, DOWNLOAD_LEASE_DURATION)
1205                    .await
1206                {
1207                    // A taken-over lease must be re-driven exactly like a fresh
1208                    // claim. Letting it fall through instead would leave the entry
1209                    // wedged in DOWNLOADING with no owner running.
1210                    Ok(ClaimOutcome::Claimed | ClaimOutcome::TookOver) => {
1211                        self.spawn_download_task(target.clone(), false, claim_id);
1212                        claim_id = uuid::Uuid::new_v4().to_string();
1213                    }
1214                    Ok(ClaimOutcome::AlreadyExists(current_status))
1215                        if current_status != ModelStatus::DOWNLOADING =>
1216                    {
1217                        return current_status;
1218                    }
1219                    Ok(ClaimOutcome::AlreadyExists(_)) => {}
1220                    Err(e) => warn!("Failed to poll download lease for {model_name}: {e}"),
1221                }
1222            }
1223        }
1224
1225        effective_status
1226    }
1227}
1228
1229#[cfg(test)]
1230#[allow(clippy::expect_used)]
1231mod tests {
1232    use super::*;
1233    use modelexpress_common::grpc::{api::ApiRequest, health::HealthRequest};
1234    use modelexpress_common::test_support::{EnvVarGuard, acquire_env_mutex};
1235    use tempfile::TempDir;
1236    use tokio_stream::StreamExt;
1237    use tonic::Request;
1238
1239    #[tokio::test]
1240    async fn test_health_service() {
1241        let service = HealthServiceImpl;
1242        let request = Request::new(HealthRequest {});
1243
1244        let response = service.get_health(request).await;
1245        assert!(response.is_ok());
1246
1247        let health_response = response.expect("Health response should be ok").into_inner();
1248        assert_eq!(health_response.version, env!("CARGO_PKG_VERSION"));
1249        assert_eq!(health_response.status, "ok");
1250        // uptime is u64, always >= 0, so just verify it exists
1251        let _uptime = health_response.uptime;
1252    }
1253
1254    /// The unknown-action path is an in-band failure and must not read as `ok`.
1255    #[tokio::test]
1256    async fn unknown_action_is_tagged_invalid_argument() {
1257        let service = ApiServiceImpl;
1258        let response = service
1259            .send_request(Request::new(ApiRequest {
1260                id: "test-id".to_string(),
1261                action: "not-a-real-action".to_string(),
1262                payload: None,
1263            }))
1264            .await
1265            .expect("the RPC itself succeeds");
1266
1267        assert_eq!(
1268            response.extensions().get::<RpcOutcome>(),
1269            Some(&RpcOutcome::InvalidArgument)
1270        );
1271        assert!(!response.into_inner().success);
1272    }
1273
1274    #[tokio::test]
1275    async fn test_api_service_ping() {
1276        let service = ApiServiceImpl;
1277        let request = Request::new(ApiRequest {
1278            id: "test-id".to_string(),
1279            action: "ping".to_string(),
1280            payload: None,
1281        });
1282
1283        let response = service.send_request(request).await;
1284        assert!(response.is_ok());
1285
1286        let api_response = response.expect("API response should be ok").into_inner();
1287        assert!(api_response.success);
1288        assert!(api_response.data.is_some());
1289        assert!(api_response.error.is_none());
1290
1291        // Check that the response data contains "pong"
1292        let data_bytes = api_response.data.expect("Data should be present");
1293        let data: serde_json::Value =
1294            serde_json::from_slice(&data_bytes).expect("Data should be valid JSON");
1295        assert_eq!(data["message"], "pong");
1296    }
1297
1298    #[tokio::test]
1299    async fn test_api_service_unknown_action() {
1300        let service = ApiServiceImpl;
1301        let request = Request::new(ApiRequest {
1302            id: "test-id".to_string(),
1303            action: "unknown-action".to_string(),
1304            payload: None,
1305        });
1306
1307        let response = service.send_request(request).await;
1308        assert!(response.is_ok());
1309
1310        let api_response = response.expect("API response should be ok").into_inner();
1311        assert!(!api_response.success);
1312        assert!(api_response.data.is_none());
1313        assert!(api_response.error.is_some());
1314
1315        let error_message = api_response.error.expect("Error should be present");
1316        assert!(error_message.contains("Unknown action"));
1317    }
1318
1319    // Tracker tests exercise the ModelDownloadTracker's interaction with a mocked
1320    // RegistryBackend. The full backend semantics (claim atomicity, LRU ordering, etc.) are
1321    // covered by the per-backend unit tests in modelexpress_server::registry and by the
1322    // testcontainers-based integration tests.
1323    fn tracker_with_mock(
1324        mock: crate::registry::backend::MockRegistryBackend,
1325    ) -> ModelDownloadTracker {
1326        let registry = Arc::new(RegistryManager::with_backend(Arc::new(mock)));
1327        ModelDownloadTracker::new(
1328            registry,
1329            DownloadMetrics::register(&mut crate::metrics::new_registry()),
1330            RegistryMetrics::register(&mut crate::metrics::new_registry()),
1331        )
1332    }
1333
1334    /// As [`tracker_with_mock`], but hands back the Prometheus registry the metric
1335    /// families were registered into.
1336    ///
1337    /// [`tracker_with_mock`] registers into a temporary registry that is dropped on
1338    /// the spot, so nothing recorded through it can ever be encoded. Any metric
1339    /// assertion against a tracker built that way would be vacuous by construction.
1340    fn tracker_with_mock_and_registry(
1341        mock: crate::registry::backend::MockRegistryBackend,
1342    ) -> (ModelDownloadTracker, prometheus_client::registry::Registry) {
1343        let mut metrics_registry = crate::metrics::new_registry();
1344        let download_metrics = DownloadMetrics::register(&mut metrics_registry);
1345        let registry_metrics = RegistryMetrics::register(&mut metrics_registry);
1346        let registry = Arc::new(RegistryManager::with_backend(Arc::new(mock)));
1347        (
1348            ModelDownloadTracker::new(registry, download_metrics, registry_metrics),
1349            metrics_registry,
1350        )
1351    }
1352
1353    fn encoded_metrics(registry: &prometheus_client::registry::Registry) -> String {
1354        crate::metrics::encode_text(registry).unwrap_or_else(|_| String::from("<encode failed>"))
1355    }
1356
1357    /// The `downloading -> absent` series, or 0 when it was never created.
1358    fn departures_from_downloading(encoded: &str) -> i64 {
1359        encoded
1360            .lines()
1361            .find_map(|line| {
1362                line.strip_prefix(
1363                    r#"mx_registry_status_transitions_total{from="downloading",to="absent"} "#,
1364                )
1365            })
1366            .and_then(|value| value.trim().parse().ok())
1367            .unwrap_or_default()
1368    }
1369
1370    fn record_with_status(
1371        model_name: &str,
1372        status: ModelStatus,
1373    ) -> crate::registry::backend::ModelRecord {
1374        let now = chrono::Utc::now();
1375        crate::registry::backend::ModelRecord {
1376            model_name: model_name.to_string(),
1377            provider: ModelProvider::HuggingFace,
1378            status,
1379            created_at: now,
1380            last_used_at: now,
1381            message: None,
1382        }
1383    }
1384
1385    /// Unpinned, full-weight target: its entry key is the bare model name.
1386    fn test_target(model_name: &str) -> DownloadTarget {
1387        DownloadTarget {
1388            model_name: model_name.to_string(),
1389            provider: ModelProvider::HuggingFace,
1390            revision: None,
1391            ignore_weights: false,
1392        }
1393    }
1394
1395    #[tokio::test]
1396    async fn test_tracker_get_status_missing_returns_none() {
1397        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1398        mock.expect_get_status().once().returning(|_| Ok(None));
1399        // touch is NOT called when status is missing
1400        let tracker = tracker_with_mock(mock);
1401        assert!(tracker.get_status("unknown").await.is_none());
1402    }
1403
1404    #[tokio::test]
1405    async fn test_tracker_get_status_hit_bumps_last_used_at() {
1406        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1407        mock.expect_get_status()
1408            .once()
1409            .returning(|_| Ok(Some(ModelStatus::DOWNLOADED)));
1410        mock.expect_touch_model().once().returning(|_| Ok(()));
1411        let tracker = tracker_with_mock(mock);
1412        assert_eq!(tracker.get_status("m").await, Some(ModelStatus::DOWNLOADED));
1413    }
1414
1415    #[tokio::test]
1416    #[allow(clippy::await_holding_lock)]
1417    async fn test_tracker_downloaded_cache_hit_bumps_last_used_at() {
1418        let env_lock = acquire_env_mutex();
1419        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1420        let _cache_dir_guard = EnvVarGuard::set(
1421            &env_lock,
1422            "MODEL_EXPRESS_CACHE_DIRECTORY",
1423            temp_dir.path().to_str().expect("Expected temp dir path"),
1424        );
1425        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
1426        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
1427        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
1428        std::fs::write(model_dir.join("config.json"), b"{}").expect("Failed to write config");
1429
1430        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1431        mock.expect_try_claim_for_download()
1432            .with(
1433                mockall::predicate::eq("test/model"),
1434                mockall::predicate::eq(ModelProvider::HuggingFace),
1435                mockall::predicate::always(),
1436                mockall::predicate::always(),
1437            )
1438            .once()
1439            .returning(|_, _, _, _| Ok(ClaimOutcome::AlreadyExists(ModelStatus::DOWNLOADED)));
1440        mock.expect_touch_model()
1441            .with(mockall::predicate::eq("test/model"))
1442            .once()
1443            .returning(|_| Ok(()));
1444        let tracker = tracker_with_mock(mock);
1445        let (tx, _rx) = tokio::sync::mpsc::channel(1);
1446
1447        assert_eq!(
1448            tracker
1449                .ensure_model_downloaded(&test_target("test/model"), &tx)
1450                .await,
1451            ModelStatus::DOWNLOADED
1452        );
1453    }
1454
1455    /// Claim, touch, and report a cache hit for `target`, asserting the registry was
1456    /// keyed on the target's entry key rather than on the bare model name.
1457    async fn assert_claims_on_entry_key(target: DownloadTarget) {
1458        let expected_key = target.entry_key();
1459        assert_ne!(
1460            expected_key, target.model_name,
1461            "This target must not reduce to the bare model name, or the test proves nothing"
1462        );
1463        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1464        mock.expect_try_claim_for_download()
1465            .with(
1466                mockall::predicate::eq(expected_key.clone()),
1467                mockall::predicate::eq(ModelProvider::HuggingFace),
1468                mockall::predicate::always(),
1469                mockall::predicate::always(),
1470            )
1471            .once()
1472            .returning(|_, _, _, _| Ok(ClaimOutcome::AlreadyExists(ModelStatus::DOWNLOADED)));
1473        mock.expect_touch_model()
1474            .with(mockall::predicate::eq(expected_key))
1475            .once()
1476            .returning(|_| Ok(()));
1477
1478        let tracker = tracker_with_mock(mock);
1479        let (tx, mut rx) = tokio::sync::mpsc::channel(4);
1480
1481        assert_eq!(
1482            tracker.ensure_model_downloaded(&target, &tx).await,
1483            ModelStatus::DOWNLOADED
1484        );
1485
1486        // Clients see the model name they asked for, not the internal registry key.
1487        let update = rx
1488            .recv()
1489            .await
1490            .expect("Expected a status update")
1491            .expect("Expected an ok status update");
1492        assert_eq!(update.model_name, target.model_name);
1493        assert_eq!(update.resolved_revision, target.revision);
1494    }
1495
1496    #[tokio::test]
1497    #[allow(clippy::await_holding_lock)]
1498    async fn test_tracker_scopes_the_lease_to_the_resolved_revision() {
1499        let env_lock = acquire_env_mutex();
1500        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1501        let _cache_dir_guard = EnvVarGuard::set(
1502            &env_lock,
1503            "MODEL_EXPRESS_CACHE_DIRECTORY",
1504            temp_dir.path().to_str().expect("Expected temp dir path"),
1505        );
1506        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
1507        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
1508        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
1509        std::fs::write(model_dir.join("config.json"), b"{}").expect("Failed to write config");
1510
1511        assert_claims_on_entry_key(DownloadTarget {
1512            revision: Some("abc123".to_string()),
1513            ..test_target("test/model")
1514        })
1515        .await;
1516    }
1517
1518    #[tokio::test]
1519    #[allow(clippy::await_holding_lock)]
1520    async fn test_tracker_separates_metadata_only_from_full_weight_downloads() {
1521        let env_lock = acquire_env_mutex();
1522        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1523        let _cache_dir_guard = EnvVarGuard::set(
1524            &env_lock,
1525            "MODEL_EXPRESS_CACHE_DIRECTORY",
1526            temp_dir.path().to_str().expect("Expected temp dir path"),
1527        );
1528        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
1529        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
1530        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
1531        std::fs::write(model_dir.join("config.json"), b"{}").expect("Failed to write config");
1532
1533        // A metadata-only entry must not be the same registry record as a full-weight
1534        // one, or a weightless snapshot would satisfy a request that needs weights.
1535        assert_claims_on_entry_key(DownloadTarget {
1536            ignore_weights: true,
1537            ..test_target("test/model")
1538        })
1539        .await;
1540    }
1541
1542    #[tokio::test]
1543    async fn test_tracker_set_status_notifies_waiting_channel() {
1544        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1545        mock.expect_set_status()
1546            .once()
1547            .returning(|_, _, _, _| Ok(()));
1548        let tracker = tracker_with_mock(mock);
1549
1550        let (tx, mut rx) = tokio::sync::mpsc::channel(4);
1551        tracker.add_waiting_channel("m", tx);
1552
1553        tracker
1554            .set_status_and_notify(
1555                "m".to_string(),
1556                ModelStatus::DOWNLOADED,
1557                ModelProvider::HuggingFace,
1558                Some("done".to_string()),
1559            )
1560            .await;
1561
1562        let update = rx.recv().await.expect("waiter should receive update");
1563        let update = update.expect("notify should send Ok");
1564        assert_eq!(update.model_name, "m");
1565        assert_eq!(
1566            update.status,
1567            modelexpress_common::grpc::model::ModelStatus::Downloaded as i32
1568        );
1569        assert_eq!(update.message.as_deref(), Some("done"));
1570
1571        // Terminal status removes waiters.
1572        let waiters = tracker
1573            .waiting_channels
1574            .lock()
1575            .expect("waiters lock")
1576            .get("m")
1577            .map_or(0, std::vec::Vec::len);
1578        assert_eq!(waiters, 0);
1579    }
1580
1581    #[tokio::test]
1582    async fn test_tracker_delete_status_clears_backend_and_waiters() {
1583        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1584        mock.expect_delete_model().once().returning(|_| Ok(()));
1585        let tracker = tracker_with_mock(mock);
1586
1587        let (tx, _rx) = tokio::sync::mpsc::channel(1);
1588        tracker.add_waiting_channel("m", tx);
1589        tracker.delete_status("m").await;
1590
1591        let waiters = tracker
1592            .waiting_channels
1593            .lock()
1594            .expect("waiters lock")
1595            .contains_key("m");
1596        assert!(!waiters);
1597    }
1598
1599    /// The bool `delete_status` returns is the sole gate on the `downloading ->
1600    /// absent` departure, and no caller is forced to read it -- there is no
1601    /// `#[must_use]` and two of the three call sites discard it. So the contract
1602    /// is pinned here directly rather than only through the delete-path tests
1603    /// below, which would still pass if the two arms were swapped in step.
1604    #[tokio::test]
1605    async fn delete_status_reports_whether_the_backend_removed_the_record() {
1606        let mut removed = crate::registry::backend::MockRegistryBackend::new();
1607        removed.expect_delete_model().once().returning(|_| Ok(()));
1608        assert!(
1609            tracker_with_mock(removed).delete_status("m").await,
1610            "a successful delete must report true"
1611        );
1612
1613        let mut failed = crate::registry::backend::MockRegistryBackend::new();
1614        failed
1615            .expect_delete_model()
1616            .once()
1617            .returning(|_| Err("backend unreachable".into()));
1618        assert!(
1619            !tracker_with_mock(failed).delete_status("m").await,
1620            "the error is still swallowed, but it must not report a removal"
1621        );
1622    }
1623
1624    /// `model clear` on an entry that is still downloading is the third exit from
1625    /// `DOWNLOADING`, and the only one the claim lifecycle cannot observe for
1626    /// itself: once the record is gone `finish_download_claim` finds nothing to
1627    /// fence and records no departure, so the deleting side has to book it.
1628    /// Without this the arrival booked by the claim is never matched and the flow
1629    /// accounting stays permanently ahead by one per deleted download.
1630    #[tokio::test]
1631    async fn deleting_a_downloading_entry_books_a_departure() {
1632        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1633        mock.expect_get_models_by_last_used()
1634            .once()
1635            .returning(|_| Ok(vec![record_with_status("m", ModelStatus::DOWNLOADING)]));
1636        mock.expect_delete_model().once().returning(|_| Ok(()));
1637
1638        let (tracker, metrics_registry) = tracker_with_mock_and_registry(mock);
1639        let outcome = tracker.delete_model_entries("m").await;
1640        assert_eq!(outcome.removed, 1);
1641        assert!(!outcome.degraded);
1642
1643        let encoded = encoded_metrics(&metrics_registry);
1644        assert_eq!(
1645            departures_from_downloading(&encoded),
1646            1,
1647            "a deleted download must not stay counted as in flight: {encoded}"
1648        );
1649    }
1650
1651    /// `delete_model` failing is swallowed so waiters are still notified, which is
1652    /// exactly why the departure has to be gated on the outcome. Booking it anyway
1653    /// would report a departure for an entry still sitting in `DOWNLOADING` and
1654    /// leave the flow count permanently short during a backend outage.
1655    #[tokio::test]
1656    async fn a_failed_delete_books_no_departure() {
1657        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1658        mock.expect_get_models_by_last_used()
1659            .once()
1660            .returning(|_| Ok(vec![record_with_status("m", ModelStatus::DOWNLOADING)]));
1661        mock.expect_delete_model()
1662            .once()
1663            .returning(|_| Err("backend unreachable".into()));
1664
1665        let (tracker, metrics_registry) = tracker_with_mock_and_registry(mock);
1666        tracker.delete_model_entries("m").await;
1667
1668        let encoded = encoded_metrics(&metrics_registry);
1669        assert_eq!(
1670            departures_from_downloading(&encoded),
1671            0,
1672            "a swallowed delete failure must not book a departure: {encoded}"
1673        );
1674    }
1675
1676    /// Ordinary cache eviction clears `DOWNLOADED` entries. Those never occupied
1677    /// the in-flight level, so counting them as departures would drive the
1678    /// derivation negative on the most common delete there is.
1679    #[tokio::test]
1680    async fn deleting_a_downloaded_entry_books_no_departure() {
1681        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1682        mock.expect_get_models_by_last_used()
1683            .once()
1684            .returning(|_| Ok(vec![record_with_status("m", ModelStatus::DOWNLOADED)]));
1685        mock.expect_delete_model().once().returning(|_| Ok(()));
1686
1687        let (tracker, metrics_registry) = tracker_with_mock_and_registry(mock);
1688        let outcome = tracker.delete_model_entries("m").await;
1689        assert_eq!(outcome.removed, 1, "the record is still removed");
1690
1691        let encoded = encoded_metrics(&metrics_registry);
1692        assert_eq!(
1693            departures_from_downloading(&encoded),
1694            0,
1695            "a completed model was never in flight: {encoded}"
1696        );
1697    }
1698
1699    /// `waiting_count` is the sole input to `mx_state_entries{map="download_waiters"}`,
1700    /// the gauge registered as "the OOM early warning". Stuck-at-zero is the failure
1701    /// mode that matters: the map leaks, the server heads for OOM, and the metric
1702    /// built to warn about it reads flat the whole way. The refresh task's own test
1703    /// substitutes a stub closure, so nothing else executes this function.
1704    #[tokio::test]
1705    async fn waiting_count_tracks_the_waiter_map() {
1706        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1707        mock.expect_delete_model().once().returning(|_| Ok(()));
1708        let tracker = tracker_with_mock(mock);
1709        assert_eq!(tracker.waiting_count(), 0);
1710
1711        let (tx_a, _rx_a) = tokio::sync::mpsc::channel(1);
1712        tracker.add_waiting_channel("a", tx_a);
1713        let (tx_b, _rx_b) = tokio::sync::mpsc::channel(1);
1714        tracker.add_waiting_channel("b", tx_b);
1715        // Keyed by model, so a second waiter on "a" does not add an entry.
1716        let (tx_a2, _rx_a2) = tokio::sync::mpsc::channel(1);
1717        tracker.add_waiting_channel("a", tx_a2);
1718        assert_eq!(tracker.waiting_count(), 2);
1719
1720        tracker.delete_status("a").await;
1721        assert_eq!(tracker.waiting_count(), 1);
1722    }
1723
1724    /// The download histogram registers and exports whether or not anything ever
1725    /// observes into it, so an empty series is the deceptive failure mode: the
1726    /// scrape looks healthy and simply reports zero downloads. This drives the
1727    /// real task to its terminal status and checks a sample landed.
1728    ///
1729    /// `finish_download_claim` returns `Ok(false)` on purpose -- this replica was
1730    /// fenced. The bytes were still fetched, so the observation has to happen
1731    /// before the fence check; returning `Ok(true)` here would leave that ordering
1732    /// unpinned.
1733    ///
1734    /// No network: the NGC provider rejects a model name that is not
1735    /// `org/name/version` before it opens a client or touches the filesystem, so
1736    /// the download future resolves to `Err` immediately and the task takes the
1737    /// `ERROR` outcome.
1738    #[tokio::test]
1739    async fn a_finished_download_is_observed_into_the_histogram_even_when_fenced() {
1740        let (done_tx, done_rx) = tokio::sync::oneshot::channel();
1741        let done_tx = Mutex::new(Some(done_tx));
1742
1743        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1744        mock.expect_finish_download_claim()
1745            .once()
1746            .returning(move |_, _, _, status, _| {
1747                assert_eq!(status, ModelStatus::ERROR);
1748                if let Ok(mut slot) = done_tx.lock()
1749                    && let Some(tx) = slot.take()
1750                {
1751                    let _ = tx.send(());
1752                }
1753                // Fenced: someone else owns the claim now.
1754                Ok(false)
1755            });
1756
1757        let (tracker, metrics_registry) = tracker_with_mock_and_registry(mock);
1758        tracker.spawn_download_task(
1759            DownloadTarget {
1760                model_name: "not-a-valid-ngc-artifact".to_string(),
1761                provider: ModelProvider::Ngc,
1762                revision: None,
1763                ignore_weights: false,
1764            },
1765            false,
1766            "claim-1".to_string(),
1767        );
1768        done_rx.await.expect("the download task reaches the finish");
1769
1770        let encoded = encoded_metrics(&metrics_registry);
1771        assert!(
1772            encoded.contains(r#"mx_download_seconds_count{outcome="error"} 1"#),
1773            "a failed download must be observed under its terminal status: {encoded}"
1774        );
1775    }
1776
1777    #[tokio::test]
1778    async fn test_tracker_error_status_clears_waiters() {
1779        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1780        mock.expect_set_status()
1781            .once()
1782            .returning(|_, _, _, _| Ok(()));
1783        let tracker = tracker_with_mock(mock);
1784        let (tx, _rx) = tokio::sync::mpsc::channel(1);
1785        tracker.add_waiting_channel("m", tx);
1786        tracker
1787            .set_status_and_notify(
1788                "m".to_string(),
1789                ModelStatus::ERROR,
1790                ModelProvider::HuggingFace,
1791                Some("fail".to_string()),
1792            )
1793            .await;
1794        let waiters = tracker
1795            .waiting_channels
1796            .lock()
1797            .expect("waiters lock")
1798            .get("m")
1799            .map_or(0, std::vec::Vec::len);
1800        assert_eq!(waiters, 0, "ERROR is terminal, waiters must be cleared");
1801    }
1802
1803    #[tokio::test]
1804    async fn test_tracker_downloading_status_keeps_waiters() {
1805        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1806        mock.expect_set_status()
1807            .once()
1808            .returning(|_, _, _, _| Ok(()));
1809        let tracker = tracker_with_mock(mock);
1810        let (tx, _rx) = tokio::sync::mpsc::channel(1);
1811        tracker.add_waiting_channel("m", tx);
1812        tracker
1813            .set_status_and_notify(
1814                "m".to_string(),
1815                ModelStatus::DOWNLOADING,
1816                ModelProvider::HuggingFace,
1817                None,
1818            )
1819            .await;
1820        let waiters = tracker
1821            .waiting_channels
1822            .lock()
1823            .expect("waiters lock")
1824            .get("m")
1825            .map_or(0, std::vec::Vec::len);
1826        assert_eq!(
1827            waiters, 1,
1828            "DOWNLOADING is non-terminal, waiter must remain"
1829        );
1830    }
1831
1832    #[tokio::test]
1833    async fn test_tracker_set_status_swallows_backend_error() {
1834        let mut mock = crate::registry::backend::MockRegistryBackend::new();
1835        mock.expect_set_status()
1836            .once()
1837            .returning(|_, _, _, _| Err("redis down".into()));
1838        let tracker = tracker_with_mock(mock);
1839        let (tx, mut rx) = tokio::sync::mpsc::channel(1);
1840        tracker.add_waiting_channel("m", tx);
1841        // Error is logged but set_status_and_notify returns ()
1842        tracker
1843            .set_status_and_notify(
1844                "m".to_string(),
1845                ModelStatus::DOWNLOADED,
1846                ModelProvider::HuggingFace,
1847                None,
1848            )
1849            .await;
1850        // Nothing should be notified on the channel because set_status failed early.
1851        assert!(
1852            rx.try_recv().is_err(),
1853            "waiter shouldn't receive on backend error"
1854        );
1855    }
1856
1857    /// Model service for the file-serving tests, which don't touch the tracker. A
1858    /// no-expectation mock backend keeps them off the `memory-backend` feature.
1859    fn test_model_service() -> ModelServiceImpl {
1860        let registry = Arc::new(RegistryManager::with_backend(Arc::new(
1861            crate::registry::backend::MockRegistryBackend::new(),
1862        )));
1863        ModelServiceImpl::new(Arc::new(ModelDownloadTracker::new(
1864            registry,
1865            DownloadMetrics::register(&mut crate::metrics::new_registry()),
1866            RegistryMetrics::register(&mut crate::metrics::new_registry()),
1867        )))
1868    }
1869
1870    #[test]
1871    fn test_collect_model_files_empty_dir() {
1872        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1873        let files = collect_model_files(temp_dir.path(), temp_dir.path(), None, false);
1874        assert!(files.is_empty());
1875    }
1876
1877    #[test]
1878    fn test_collect_model_files_with_files() {
1879        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1880
1881        // Create some test files
1882        let file1_path = temp_dir.path().join("config.json");
1883        std::fs::write(&file1_path, r#"{"test": "data"}"#).expect("Failed to write file1");
1884
1885        let file2_path = temp_dir.path().join("model.bin");
1886        std::fs::write(&file2_path, vec![0u8; 100]).expect("Failed to write file2");
1887
1888        let files = collect_model_files(temp_dir.path(), temp_dir.path(), None, false);
1889
1890        assert_eq!(files.len(), 2);
1891
1892        // Check file sizes
1893        let total_size: u64 = files.iter().map(|(_, size)| size).sum();
1894        assert!(total_size > 0);
1895
1896        // Check that relative paths are correct
1897        let paths: Vec<_> = files
1898            .iter()
1899            .map(|(p, _)| p.to_string_lossy().to_string())
1900            .collect();
1901        assert!(paths.contains(&"config.json".to_string()));
1902        assert!(paths.contains(&"model.bin".to_string()));
1903    }
1904
1905    #[test]
1906    fn test_collect_model_files_ignore_weights() {
1907        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1908
1909        // Mix of non-weight and weight files, including a nested weight shard.
1910        std::fs::write(temp_dir.path().join("config.json"), "{}").expect("write config");
1911        std::fs::write(temp_dir.path().join("tokenizer.json"), "{}").expect("write tokenizer");
1912        std::fs::write(temp_dir.path().join("model.safetensors"), vec![0u8; 10])
1913            .expect("write safetensors");
1914        std::fs::write(temp_dir.path().join("pytorch_model.bin"), vec![0u8; 10])
1915            .expect("write bin");
1916        let subdir = temp_dir.path().join("subdir");
1917        std::fs::create_dir(&subdir).expect("create subdir");
1918        std::fs::write(
1919            subdir.join("model-00001-of-00002.safetensors"),
1920            vec![0u8; 10],
1921        )
1922        .expect("write nested shard");
1923
1924        // ignore_weights = false streams everything.
1925        let all = collect_model_files(temp_dir.path(), temp_dir.path(), None, false);
1926        assert_eq!(all.len(), 5);
1927
1928        // ignore_weights = true keeps only the non-weight files (config + tokenizer),
1929        // dropping weight shards at any depth.
1930        let no_weights = collect_model_files(temp_dir.path(), temp_dir.path(), None, true);
1931        let names: Vec<String> = no_weights
1932            .iter()
1933            .map(|(p, _)| p.to_string_lossy().to_string())
1934            .collect();
1935        assert_eq!(
1936            no_weights.len(),
1937            2,
1938            "expected only non-weight files: {names:?}"
1939        );
1940        assert!(names.contains(&"config.json".to_string()));
1941        assert!(names.contains(&"tokenizer.json".to_string()));
1942        assert!(
1943            names
1944                .iter()
1945                .all(|n| !n.ends_with(".safetensors") && !n.ends_with(".bin")),
1946            "weight files must be excluded: {names:?}"
1947        );
1948    }
1949
1950    #[test]
1951    fn test_collect_model_files_nested() {
1952        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1953
1954        // Create nested directory structure
1955        let subdir = temp_dir.path().join("subdir");
1956        std::fs::create_dir(&subdir).expect("Failed to create subdir");
1957
1958        let file1_path = temp_dir.path().join("root_file.txt");
1959        std::fs::write(&file1_path, "root content").expect("Failed to write file1");
1960
1961        let file2_path = subdir.join("nested_file.txt");
1962        std::fs::write(&file2_path, "nested content").expect("Failed to write file2");
1963
1964        let files = collect_model_files(temp_dir.path(), temp_dir.path(), None, false);
1965
1966        assert_eq!(files.len(), 2);
1967
1968        // Check that nested path is correct
1969        let paths: Vec<_> = files
1970            .iter()
1971            .map(|(p, _)| p.to_string_lossy().to_string())
1972            .collect();
1973        assert!(paths.iter().any(|p| p.contains("nested_file")));
1974    }
1975
1976    #[test]
1977    fn test_collect_model_files_with_selector_filters_exact_paths() {
1978        let temp_dir = TempDir::new().expect("Failed to create temp dir");
1979        let subdir = temp_dir.path().join("subdir");
1980        std::fs::create_dir(&subdir).expect("Failed to create subdir");
1981        std::fs::write(temp_dir.path().join("config.json"), "{}").expect("Failed to write config");
1982        std::fs::write(temp_dir.path().join("model.bin"), vec![0u8; 100])
1983            .expect("Failed to write model");
1984        std::fs::write(temp_dir.path().join("ignored.txt"), "ignore")
1985            .expect("Failed to write ignored");
1986        std::fs::write(subdir.join("nested.txt"), "nested").expect("Failed to write nested");
1987
1988        let selector = ModelFileSelector {
1989            paths: vec!["config.json".to_string(), "subdir/nested.txt".to_string()],
1990        };
1991        let files = collect_model_files(temp_dir.path(), temp_dir.path(), Some(&selector), false);
1992
1993        let mut paths: Vec<_> = files
1994            .iter()
1995            .map(|(p, _)| p.to_string_lossy().to_string())
1996            .collect();
1997        paths.sort();
1998        assert_eq!(
1999            paths,
2000            vec!["config.json".to_string(), "subdir/nested.txt".to_string()]
2001        );
2002    }
2003
2004    #[test]
2005    fn test_collect_model_files_with_selector_empty_and_nonmatching_paths() {
2006        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2007        std::fs::write(temp_dir.path().join("config.json"), "{}").expect("Failed to write config");
2008
2009        let empty_selector = ModelFileSelector { paths: vec![] };
2010        assert!(
2011            collect_model_files(
2012                temp_dir.path(),
2013                temp_dir.path(),
2014                Some(&empty_selector),
2015                false
2016            )
2017            .is_empty()
2018        );
2019
2020        let nonmatching_selector = ModelFileSelector {
2021            paths: vec!["missing.json".to_string(), "../config.json".to_string()],
2022        };
2023        assert!(
2024            collect_model_files(
2025                temp_dir.path(),
2026                temp_dir.path(),
2027                Some(&nonmatching_selector),
2028                false
2029            )
2030            .is_empty()
2031        );
2032    }
2033
2034    #[tokio::test]
2035    #[allow(clippy::await_holding_lock)]
2036    async fn test_list_model_files_hf_honors_file_selector() {
2037        let env_lock = acquire_env_mutex();
2038        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2039        let _cache_dir_guard = EnvVarGuard::set(
2040            &env_lock,
2041            "MODEL_EXPRESS_CACHE_DIRECTORY",
2042            temp_dir.path().to_str().expect("Expected temp dir path"),
2043        );
2044        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2045
2046        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
2047        std::fs::create_dir_all(model_dir.join("subdir")).expect("Failed to create model dir");
2048        std::fs::write(model_dir.join("config.json"), br#"{"model":"test"}"#)
2049            .expect("Failed to write config");
2050        std::fs::write(model_dir.join("model.bin"), vec![0u8; 100]).expect("Failed to write model");
2051        std::fs::write(model_dir.join("subdir/nested.txt"), b"nested")
2052            .expect("Failed to write nested");
2053
2054        let service = test_model_service();
2055        let request = Request::new(ModelFilesRequest {
2056            model_name: "test/model".to_string(),
2057            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2058            chunk_size: 0,
2059            file_selector: Some(ModelFileSelector {
2060                paths: vec!["config.json".to_string(), "subdir/nested.txt".to_string()],
2061            }),
2062            ignore_weights: false,
2063            revision: None,
2064        });
2065
2066        let response = service
2067            .list_model_files(request)
2068            .await
2069            .expect("Expected file list")
2070            .into_inner();
2071        let mut paths: Vec<_> = response
2072            .files
2073            .iter()
2074            .map(|file| file.relative_path.clone())
2075            .collect();
2076        paths.sort();
2077
2078        assert_eq!(
2079            paths,
2080            vec!["config.json".to_string(), "subdir/nested.txt".to_string()]
2081        );
2082        assert_eq!(
2083            response.total_size,
2084            br#"{"model":"test"}"#.len() as u64 + b"nested".len() as u64
2085        );
2086    }
2087
2088    #[tokio::test]
2089    #[allow(clippy::await_holding_lock)]
2090    async fn test_model_files_present_reflects_disk_state() {
2091        let env_lock = acquire_env_mutex();
2092        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2093        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2094        let cache_dir = temp_dir.path().to_path_buf();
2095
2096        // No files on disk: a stale DOWNLOADED record must not be honored.
2097        assert!(
2098            !model_files_present(
2099                Some(cache_dir.clone()),
2100                "test/model",
2101                ModelProvider::HuggingFace,
2102                None
2103            )
2104            .await
2105        );
2106
2107        // Once the snapshot exists, the cache hit is real.
2108        let model_dir = cache_dir.join("models--test--model/snapshots/abc123");
2109        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2110        std::fs::write(model_dir.join("config.json"), b"{}").expect("Failed to write config");
2111        assert!(
2112            model_files_present(
2113                Some(cache_dir),
2114                "test/model",
2115                ModelProvider::HuggingFace,
2116                None
2117            )
2118            .await
2119        );
2120    }
2121
2122    #[tokio::test]
2123    async fn test_model_files_present_assumes_present_without_cache_dir() {
2124        // With no configured cache directory we cannot verify, so we must not force a
2125        // re-download loop: assume the files are present.
2126        assert!(model_files_present(None, "test/model", ModelProvider::HuggingFace, None).await);
2127    }
2128
2129    #[tokio::test]
2130    #[allow(clippy::await_holding_lock)]
2131    async fn test_stream_model_files_hf_honors_file_selector() {
2132        let env_lock = acquire_env_mutex();
2133        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2134        let _cache_dir_guard = EnvVarGuard::set(
2135            &env_lock,
2136            "MODEL_EXPRESS_CACHE_DIRECTORY",
2137            temp_dir.path().to_str().expect("Expected temp dir path"),
2138        );
2139        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2140
2141        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
2142        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2143        std::fs::write(model_dir.join("config.json"), br#"{"model":"test"}"#)
2144            .expect("Failed to write config");
2145        std::fs::write(model_dir.join("model.bin"), vec![0u8; 100]).expect("Failed to write model");
2146
2147        let service = test_model_service();
2148        let request = Request::new(ModelFilesRequest {
2149            model_name: "test/model".to_string(),
2150            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2151            chunk_size: 1024,
2152            file_selector: Some(ModelFileSelector {
2153                paths: vec!["config.json".to_string()],
2154            }),
2155            ignore_weights: false,
2156            revision: None,
2157        });
2158
2159        let response = service
2160            .stream_model_files(request)
2161            .await
2162            .expect("Expected stream response");
2163        let chunks: Vec<_> = response
2164            .into_inner()
2165            .map(|chunk| chunk.expect("Expected chunk"))
2166            .collect()
2167            .await;
2168
2169        assert_eq!(chunks.len(), 1);
2170        assert_eq!(chunks[0].relative_path, "config.json");
2171        assert_eq!(chunks[0].commit_hash.as_deref(), Some("abc123"));
2172        assert!(chunks[0].is_last_file);
2173    }
2174
2175    #[tokio::test]
2176    #[allow(clippy::await_holding_lock)]
2177    async fn test_stream_model_files_serves_the_requested_revision() {
2178        let env_lock = acquire_env_mutex();
2179        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2180        let _cache_dir_guard = EnvVarGuard::set(
2181            &env_lock,
2182            "MODEL_EXPRESS_CACHE_DIRECTORY",
2183            temp_dir.path().to_str().expect("Expected temp dir path"),
2184        );
2185        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2186
2187        // Two revisions cached side by side. Without a requested revision the newest
2188        // snapshot wins, so asking for the older one proves the request is honored.
2189        let write_snapshot = |commit: &str, body: &[u8]| {
2190            let model_dir = temp_dir
2191                .path()
2192                .join("models--test--model/snapshots")
2193                .join(commit);
2194            std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2195            std::fs::write(model_dir.join("config.json"), body).expect("Failed to write config");
2196        };
2197        write_snapshot("older111", b"old");
2198        // Snapshot ordering is by directory timestamp, so the two have to be distinct.
2199        tokio::time::sleep(tokio::time::Duration::from_millis(1100)).await;
2200        write_snapshot("newer222", b"new");
2201
2202        let stream_revision = async |revision: Option<&str>| {
2203            let request = Request::new(ModelFilesRequest {
2204                model_name: "test/model".to_string(),
2205                provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2206                chunk_size: 1024,
2207                file_selector: None,
2208                ignore_weights: false,
2209                revision: revision.map(String::from),
2210            });
2211            let chunks: Vec<_> = test_model_service()
2212                .stream_model_files(request)
2213                .await
2214                .expect("Expected stream response")
2215                .into_inner()
2216                .map(|chunk| chunk.expect("Expected chunk"))
2217                .collect()
2218                .await;
2219            assert_eq!(chunks.len(), 1);
2220            (chunks[0].commit_hash.clone(), chunks[0].data.clone())
2221        };
2222
2223        assert_eq!(
2224            stream_revision(Some("older111")).await,
2225            (Some("older111".to_string()), b"old".to_vec())
2226        );
2227        assert_eq!(
2228            stream_revision(None).await,
2229            (Some("newer222".to_string()), b"new".to_vec()),
2230            "Without a revision the newest snapshot is served, so the pinned request above \
2231             really did select a different one"
2232        );
2233    }
2234
2235    #[tokio::test]
2236    async fn test_ensure_model_downloaded_rejects_a_revision_on_a_provider_without_revisions() {
2237        let service = test_model_service();
2238        let request = Request::new(ModelDownloadRequest {
2239            model_name: "gs://test-bucket/org/model/rev-1".to_string(),
2240            provider: modelexpress_common::grpc::model::ModelProvider::Gcs as i32,
2241            ignore_weights: false,
2242            revision: Some("v1.0".to_string()),
2243        });
2244
2245        let status = service
2246            .ensure_model_downloaded(request)
2247            .await
2248            .map(|_| ())
2249            .expect_err("A provider without revisions must reject a pinned revision");
2250        assert_eq!(status.code(), tonic::Code::InvalidArgument);
2251        assert!(
2252            status
2253                .message()
2254                .contains("does not support pinned revisions"),
2255            "Unexpected message: {}",
2256            status.message()
2257        );
2258    }
2259
2260    #[tokio::test]
2261    #[allow(clippy::await_holding_lock)]
2262    async fn test_stream_model_files_rejects_an_uncached_revision() {
2263        let env_lock = acquire_env_mutex();
2264        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2265        let _cache_dir_guard = EnvVarGuard::set(
2266            &env_lock,
2267            "MODEL_EXPRESS_CACHE_DIRECTORY",
2268            temp_dir.path().to_str().expect("Expected temp dir path"),
2269        );
2270        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2271
2272        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
2273        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2274        std::fs::write(model_dir.join("config.json"), b"{}").expect("Failed to write config");
2275
2276        let service = test_model_service();
2277        let request = Request::new(ModelFilesRequest {
2278            model_name: "test/model".to_string(),
2279            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2280            chunk_size: 1024,
2281            file_selector: None,
2282            ignore_weights: false,
2283            revision: Some("not-cached".to_string()),
2284        });
2285
2286        let status = service
2287            .stream_model_files(request)
2288            .await
2289            .map(|_| ())
2290            .expect_err("An uncached revision must not fall back to another snapshot");
2291        assert_eq!(status.code(), tonic::Code::NotFound);
2292    }
2293
2294    #[tokio::test]
2295    #[allow(clippy::await_holding_lock)]
2296    async fn test_stream_model_files_hf_returns_not_found_for_missing_selector_path() {
2297        let env_lock = acquire_env_mutex();
2298        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2299        let _cache_dir_guard = EnvVarGuard::set(
2300            &env_lock,
2301            "MODEL_EXPRESS_CACHE_DIRECTORY",
2302            temp_dir.path().to_str().expect("Expected temp dir path"),
2303        );
2304        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2305
2306        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
2307        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2308        std::fs::write(model_dir.join("config.json"), br#"{"model":"test"}"#)
2309            .expect("Failed to write config");
2310
2311        let service = test_model_service();
2312        let request = Request::new(ModelFilesRequest {
2313            model_name: "test/model".to_string(),
2314            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2315            chunk_size: 1024,
2316            file_selector: Some(ModelFileSelector {
2317                paths: vec!["config.json".to_string(), "missing.json".to_string()],
2318            }),
2319            ignore_weights: false,
2320            revision: None,
2321        });
2322
2323        let result = service.stream_model_files(request).await;
2324        let status = result.expect_err("Expected not found");
2325        assert_eq!(status.code(), tonic::Code::NotFound);
2326        assert_eq!(
2327            status.message(),
2328            "Selected file not found in model directory: missing.json"
2329        );
2330    }
2331
2332    #[tokio::test]
2333    async fn test_list_model_files_not_found() {
2334        let service = test_model_service();
2335
2336        let request = Request::new(ModelFilesRequest {
2337            model_name: "non-existent-model-12345".to_string(),
2338            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2339            chunk_size: 0,
2340            file_selector: None,
2341            ignore_weights: false,
2342            revision: None,
2343        });
2344
2345        let result = service.list_model_files(request).await;
2346        assert!(result.is_err());
2347        let status = result.expect_err("Should return error");
2348        assert_eq!(status.code(), tonic::Code::NotFound);
2349    }
2350
2351    #[tokio::test]
2352    async fn test_stream_model_files_not_found() {
2353        let service = test_model_service();
2354
2355        let request = Request::new(ModelFilesRequest {
2356            model_name: "non-existent-model-12345".to_string(),
2357            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2358            chunk_size: 1024,
2359            file_selector: None,
2360            ignore_weights: false,
2361            revision: None,
2362        });
2363
2364        let result = service.stream_model_files(request).await;
2365        assert!(result.is_err());
2366        let status = result.expect_err("Should return error");
2367        assert_eq!(status.code(), tonic::Code::NotFound);
2368    }
2369
2370    #[tokio::test]
2371    async fn test_ensure_model_downloaded_rejects_invalid_provider() {
2372        let service = test_model_service();
2373
2374        let request = Request::new(ModelDownloadRequest {
2375            model_name: "test/model".to_string(),
2376            provider: 99,
2377            ignore_weights: false,
2378            revision: None,
2379        });
2380
2381        let result = service.ensure_model_downloaded(request).await;
2382        assert!(result.is_err());
2383        let status = result.expect_err("Should return error");
2384        assert_eq!(status.code(), tonic::Code::InvalidArgument);
2385        assert!(status.message().contains("Invalid provider value"));
2386    }
2387
2388    #[tokio::test]
2389    async fn test_list_model_files_rejects_invalid_provider() {
2390        let service = test_model_service();
2391
2392        let request = Request::new(ModelFilesRequest {
2393            model_name: "test/model".to_string(),
2394            provider: 99,
2395            chunk_size: 0,
2396            file_selector: None,
2397            ignore_weights: false,
2398            revision: None,
2399        });
2400
2401        let result = service.list_model_files(request).await;
2402        assert!(result.is_err());
2403        let status = result.expect_err("Should return error");
2404        assert_eq!(status.code(), tonic::Code::InvalidArgument);
2405        assert!(status.message().contains("Invalid provider value"));
2406    }
2407
2408    #[tokio::test]
2409    async fn test_stream_model_files_rejects_invalid_provider() {
2410        let service = test_model_service();
2411
2412        let request = Request::new(ModelFilesRequest {
2413            model_name: "test/model".to_string(),
2414            provider: 99,
2415            chunk_size: 1024,
2416            file_selector: None,
2417            ignore_weights: false,
2418            revision: None,
2419        });
2420
2421        let result = service.stream_model_files(request).await;
2422        assert!(result.is_err());
2423        let status = result.expect_err("Should return error");
2424        assert_eq!(status.code(), tonic::Code::InvalidArgument);
2425        assert!(status.message().contains("Invalid provider value"));
2426    }
2427
2428    #[tokio::test]
2429    #[allow(clippy::await_holding_lock)]
2430    async fn test_stream_model_files_hf_first_chunk_includes_commit_hash() {
2431        let env_lock = acquire_env_mutex();
2432        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2433        let _cache_dir_guard = EnvVarGuard::set(
2434            &env_lock,
2435            "MODEL_EXPRESS_CACHE_DIRECTORY",
2436            temp_dir.path().to_str().expect("Expected temp dir path"),
2437        );
2438        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2439
2440        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
2441        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2442        std::fs::write(model_dir.join("config.json"), br#"{"model":"test"}"#)
2443            .expect("Failed to write model file");
2444
2445        let service = test_model_service();
2446        let request = Request::new(ModelFilesRequest {
2447            model_name: "test/model".to_string(),
2448            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2449            chunk_size: 1024,
2450            file_selector: None,
2451            ignore_weights: false,
2452            revision: None,
2453        });
2454
2455        let response = service
2456            .stream_model_files(request)
2457            .await
2458            .expect("Expected stream response");
2459        let mut stream = response.into_inner();
2460        let first_chunk = stream
2461            .next()
2462            .await
2463            .expect("Expected stream item")
2464            .expect("Expected first chunk");
2465
2466        assert_eq!(first_chunk.relative_path, "config.json");
2467        assert_eq!(first_chunk.commit_hash.as_deref(), Some("abc123"));
2468        assert!(first_chunk.is_last_chunk);
2469        assert!(first_chunk.is_last_file);
2470    }
2471
2472    #[tokio::test]
2473    #[allow(clippy::await_holding_lock)]
2474    async fn test_stream_model_files_hf_emits_chunk_for_zero_byte_file() {
2475        let env_lock = acquire_env_mutex();
2476        let temp_dir = TempDir::new().expect("Failed to create temp dir");
2477        let _cache_dir_guard = EnvVarGuard::set(
2478            &env_lock,
2479            "MODEL_EXPRESS_CACHE_DIRECTORY",
2480            temp_dir.path().to_str().expect("Expected temp dir path"),
2481        );
2482        let _offline_guard = EnvVarGuard::set(&env_lock, "HF_HUB_OFFLINE", "1");
2483
2484        let model_dir = temp_dir.path().join("models--test--model/snapshots/abc123");
2485        std::fs::create_dir_all(&model_dir).expect("Failed to create model dir");
2486        std::fs::write(model_dir.join("empty.bin"), []).expect("Failed to write empty file");
2487
2488        let service = test_model_service();
2489        let request = Request::new(ModelFilesRequest {
2490            model_name: "test/model".to_string(),
2491            provider: modelexpress_common::grpc::model::ModelProvider::HuggingFace as i32,
2492            chunk_size: 1024,
2493            file_selector: None,
2494            ignore_weights: false,
2495            revision: None,
2496        });
2497
2498        let response = service
2499            .stream_model_files(request)
2500            .await
2501            .expect("Expected stream response");
2502        let mut stream = response.into_inner();
2503        let first_chunk = stream
2504            .next()
2505            .await
2506            .expect("Expected stream item")
2507            .expect("Expected first chunk");
2508
2509        assert_eq!(first_chunk.relative_path, "empty.bin");
2510        assert_eq!(first_chunk.total_size, 0);
2511        assert_eq!(first_chunk.data.len(), 0);
2512        assert_eq!(first_chunk.offset, 0);
2513        assert_eq!(first_chunk.commit_hash.as_deref(), Some("abc123"));
2514        assert!(first_chunk.is_last_chunk);
2515        assert!(first_chunk.is_last_file);
2516    }
2517}