mold-ai-server 0.17.0

HTTP inference server for mold
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use mold_core::Config;
use mold_inference::InferenceEngine;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::time::Instant;
use tokio::sync::Mutex;

use mold_inference::shared_pool::SharedPool;

use crate::downloads::DownloadQueue;
use crate::events::EventBroadcaster;
use crate::gpu_pool::GpuPool;
use crate::job_registry::{JobRegistry, SharedJobRegistry};
use crate::model_cache::ModelCache;
use crate::resources::ResourceBroadcaster;

#[derive(Debug, Clone, Default)]
pub struct EngineSnapshot {
    /// Currently GPU-loaded model (None if no model on GPU).
    pub model_name: Option<String>,
    pub is_loaded: bool,
    /// All models in the cache (loaded + unloaded), for status display.
    pub cached_models: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct ActiveGenerationSnapshot {
    pub model: String,
    pub prompt_sha256: String,
    pub started_at_unix_ms: u64,
    pub started_at: Instant,
}

// ── Generation queue types ──────────────────────────────────────────────────

/// Internal SSE message type used by both the queue worker and SSE streams.
pub enum SseMessage {
    Progress(mold_core::SseProgressEvent),
    Complete(mold_core::SseCompleteEvent),
    UpscaleComplete(mold_core::SseUpscaleCompleteEvent),
    Error(mold_core::SseErrorEvent),
}

/// A generation job submitted to the queue worker.
pub struct GenerationJob {
    /// Server-assigned UUIDv4. Echoed back to the client in the initial
    /// `SseProgressEvent::Queued` event so the SPA can later reconcile
    /// a persisted "running" card against `GET /api/queue` — anything
    /// the registry doesn't know about is a zombie left over from a
    /// dropped SSE stream and gets dead-lettered client-side. Always
    /// non-empty for jobs created through the public API; tests that
    /// construct `GenerationJob` directly may leave it empty.
    pub id: String,
    pub request: mold_core::GenerateRequest,
    /// Channel to send SSE progress/complete/error events (None for non-streaming).
    pub progress_tx: Option<tokio::sync::mpsc::UnboundedSender<SseMessage>>,
    /// Oneshot to return the final result for non-streaming callers.
    pub result_tx: tokio::sync::oneshot::Sender<Result<GenerationJobResult, String>>,
    /// Pre-resolved output directory for server-side image saving.
    pub output_dir: Option<PathBuf>,
}

pub struct GenerationJobResult {
    pub response: mold_core::GenerateResponse,
    pub image: mold_core::ImageData,
}

/// Handle for submitting jobs to the generation queue.
#[derive(Clone)]
pub struct QueueHandle {
    job_tx: tokio::sync::mpsc::Sender<GenerationJob>,
    pending_count: Arc<AtomicUsize>,
}

/// Reason a `QueueHandle::submit` attempt failed.
#[derive(Debug)]
pub enum SubmitError {
    /// Queue is at capacity — caller should return 503 with `Retry-After`.
    Full { pending: usize, capacity: usize },
    /// Receiving end is gone (server shutting down).
    Shutdown,
}

impl QueueHandle {
    pub fn new(job_tx: tokio::sync::mpsc::Sender<GenerationJob>) -> Self {
        Self {
            job_tx,
            pending_count: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Submit a generation job.
    ///
    /// Atomically reserves a slot against `capacity` using fetch_add, so a
    /// burst of concurrent callers cannot all slip past a separate pending()
    /// pre-check (TOCTOU).  Returns the queue position on success.
    pub async fn submit(&self, job: GenerationJob, capacity: usize) -> Result<usize, SubmitError> {
        let prev = self.pending_count.fetch_add(1, Ordering::SeqCst);
        if prev >= capacity {
            self.pending_count.fetch_sub(1, Ordering::SeqCst);
            return Err(SubmitError::Full {
                pending: prev,
                capacity,
            });
        }
        if self.job_tx.send(job).await.is_err() {
            self.pending_count.fetch_sub(1, Ordering::SeqCst);
            return Err(SubmitError::Shutdown);
        }
        #[cfg(feature = "metrics")]
        {
            crate::metrics::record_queue_submit();
            crate::metrics::record_queue_depth(self.pending_count.load(Ordering::SeqCst));
        }
        Ok(prev)
    }

    pub fn decrement(&self) {
        self.pending_count.fetch_sub(1, Ordering::SeqCst);
    }

    pub fn pending(&self) -> usize {
        self.pending_count.load(Ordering::SeqCst)
    }
}

// ── AppState ────────────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct AppState {
    // ── Multi-GPU fields ────────────────────────────────────────────────────
    /// GPU worker pool for multi-GPU dispatch.
    pub gpu_pool: Arc<GpuPool>,
    /// Maximum queue capacity (for status reporting and 503 responses).
    pub queue_capacity: usize,

    // ── Legacy single-GPU fields (retained during migration) ────────────────
    pub model_cache: Arc<Mutex<ModelCache>>,
    /// Uses std::sync::RwLock (not tokio) because it's only accessed from
    /// synchronous contexts (inside spawn_blocking closures and brief reads).
    /// Must never be held across an .await point.
    pub active_generation: Arc<RwLock<Option<ActiveGenerationSnapshot>>>,
    pub config: Arc<tokio::sync::RwLock<Config>>,
    pub start_time: Instant,
    /// Guards concurrent model loads and hot-swaps.
    pub model_load_lock: Arc<Mutex<()>>,
    /// Guards concurrent pulls — only one download at a time.
    pub pull_lock: Arc<Mutex<()>>,
    /// Generation request queue.
    pub queue: QueueHandle,
    /// Authoritative registry of in-flight jobs (queued + running). Powers
    /// `GET /api/queue` so the SPA can reconcile persisted "running" cards
    /// against server reality and dead-letter zombies whose SSE stream
    /// silently dropped.
    pub job_registry: SharedJobRegistry,
    /// Dispatch pause gate toggled by `POST /api/queue/pause` /
    /// `POST /api/queue/resume`. The dispatch loops park on this at the top of
    /// each iteration; a job already running on a worker finishes untouched.
    pub queue_pause: Arc<crate::queue::QueuePause>,
    /// Shared tokenizer pool for cross-engine caching.
    pub shared_pool: Arc<std::sync::Mutex<SharedPool>>,
    /// Shutdown trigger for graceful shutdown via `/api/shutdown` endpoint.
    pub shutdown_tx: Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>>,
    /// Cached upscaler engine to avoid recreating per request. Small models (2-64MB), single slot.
    pub upscaler_cache: Arc<std::sync::Mutex<Option<Box<dyn mold_inference::UpscaleEngine>>>>,
    /// SQLite-backed gallery metadata store. `None` when MOLD_DB_DISABLE=1 or
    /// when MOLD_HOME could not be resolved — callers must fall back to the
    /// filesystem walk in `routes::scan_gallery_dir`.
    pub metadata_db: Arc<Option<mold_db::MetadataDb>>,
    /// Durable chain-job runner handle. `None` when DB-backed chain jobs are
    /// unavailable; chain-job API handlers return 503 in that state.
    pub chain_jobs: Option<Arc<crate::chain_job_runner::ChainJobRunnerHandle>>,
    // ── Downloads UI (Agent A) ──────────────────────────────────────────────
    /// Bounded-parallel download queue.
    pub downloads: Arc<DownloadQueue>,
    /// Always-on resource telemetry (Agent B).
    pub resources: Arc<ResourceBroadcaster>,
    /// Server-wide lifecycle broadcast backing `GET /api/events` — job
    /// queued/started/ended (mirrored by `job_registry`) plus gallery
    /// added/removed. One SSE connection observes the whole server.
    pub events: Arc<EventBroadcaster>,
    // ── Catalog (live HF + Civitai) ─────────────────────────────────────────
    /// In-process TTL cache backing `/api/catalog/search`.
    pub catalog_live_cache: mold_catalog::live::LiveCache,
    /// Upstream base URL for live Civitai search. Production runs with
    /// the public host; tests override via `with_civitai_base`.
    pub catalog_live_civitai_base: Arc<String>,
    /// Cache of pure synthesis intents for installed catalog (`cv:*`/`hf:*`)
    /// IDs, keyed by ID. Resolution into a `ModelConfig` is deferred to
    /// engine-load time so disk-state races (file present vs not) can't
    /// seal a wrong config; see `model_manager::resolve_intent_to_paths`.
    pub catalog_intents: Arc<
        tokio::sync::RwLock<
            std::collections::HashMap<String, mold_catalog::synthesis::CatalogModelIntent>,
        >,
    >,
}

/// Default TTL for the live-search cache. Five minutes is long enough
/// to absorb SPA re-mounts and quick paging without serving stale
/// rankings.
const CATALOG_LIVE_CACHE_TTL_SECS: u64 = 300;
/// Cap on cached query keys. The working set per user is small —
/// caps too high just retain stale rows past their TTL.
const CATALOG_LIVE_CACHE_MAX_KEYS: usize = 256;
/// Production Civitai endpoint. Tests inject a wiremock URI via
/// [`AppState::with_civitai_base`].
pub const CATALOG_LIVE_CIVITAI_BASE: &str = "https://civitai.com";

fn default_live_cache() -> mold_catalog::live::LiveCache {
    mold_catalog::live::LiveCache::new(
        std::time::Duration::from_secs(CATALOG_LIVE_CACHE_TTL_SECS),
        CATALOG_LIVE_CACHE_MAX_KEYS,
    )
}

/// Default maximum number of cached models (GPU-resident + parked engine structs).
pub const DEFAULT_MAX_CACHED_MODELS: usize = 3;
/// Lower / upper bounds applied to env-overridden cache caps. Below 1 the
/// cache can't hold the active engine; above 16 the OOM risk dwarfs the
/// hit-rate gains for a typical local server.
const MAX_CACHED_MODELS_LOWER: usize = 1;
const MAX_CACHED_MODELS_UPPER: usize = 16;
/// Env var that overrides `DEFAULT_MAX_CACHED_MODELS` at runtime.
pub const MAX_CACHED_MODELS_ENV: &str = "MOLD_MAX_CACHED_MODELS";

/// Default idle-TTL for parked cache entries — 30 minutes. Tuned for a
/// local-first workflow: long enough that a user toggling between two
/// models inside a session never pays a reload, short enough that
/// background memory pressure doesn't accumulate overnight.
pub const DEFAULT_CACHE_IDLE_TTL_SECS: u64 = 1800;
const CACHE_IDLE_TTL_LOWER_SECS: u64 = 60;
const CACHE_IDLE_TTL_UPPER_SECS: u64 = 86_400;
/// Env var that overrides `DEFAULT_CACHE_IDLE_TTL_SECS`.
pub const CACHE_IDLE_TTL_ENV: &str = "MOLD_CACHE_IDLE_TTL_SECS";

/// Resolve the cache idle-TTL from env, falling back to the default.
/// Out-of-range or unparseable values log a warning and use the default.
pub fn resolve_cache_idle_ttl_secs() -> u64 {
    match std::env::var(CACHE_IDLE_TTL_ENV) {
        Ok(raw) => match raw.trim().parse::<u64>() {
            Ok(n) if (CACHE_IDLE_TTL_LOWER_SECS..=CACHE_IDLE_TTL_UPPER_SECS).contains(&n) => n,
            Ok(n) => {
                tracing::warn!(
                    env = CACHE_IDLE_TTL_ENV,
                    value = n,
                    lower = CACHE_IDLE_TTL_LOWER_SECS,
                    upper = CACHE_IDLE_TTL_UPPER_SECS,
                    "ignoring out-of-range cache idle-TTL; using default"
                );
                DEFAULT_CACHE_IDLE_TTL_SECS
            }
            Err(e) => {
                tracing::warn!(
                    env = CACHE_IDLE_TTL_ENV,
                    raw = %raw,
                    error = %e,
                    "ignoring unparseable cache idle-TTL; using default"
                );
                DEFAULT_CACHE_IDLE_TTL_SECS
            }
        },
        Err(_) => DEFAULT_CACHE_IDLE_TTL_SECS,
    }
}

/// Resolve the model-cache capacity from env, falling back to the default.
/// Out-of-range or unparseable values log a warning and use the default so
/// a typo in the env never silently shrinks the cache to an unusable size.
pub fn resolve_max_cached_models() -> usize {
    match std::env::var(MAX_CACHED_MODELS_ENV) {
        Ok(raw) => match raw.trim().parse::<usize>() {
            Ok(n) if (MAX_CACHED_MODELS_LOWER..=MAX_CACHED_MODELS_UPPER).contains(&n) => n,
            Ok(n) => {
                tracing::warn!(
                    env = MAX_CACHED_MODELS_ENV,
                    value = n,
                    lower = MAX_CACHED_MODELS_LOWER,
                    upper = MAX_CACHED_MODELS_UPPER,
                    "ignoring out-of-range cache cap; using default"
                );
                DEFAULT_MAX_CACHED_MODELS
            }
            Err(e) => {
                tracing::warn!(
                    env = MAX_CACHED_MODELS_ENV,
                    raw = %raw,
                    error = %e,
                    "ignoring unparseable cache cap; using default"
                );
                DEFAULT_MAX_CACHED_MODELS
            }
        },
        Err(_) => DEFAULT_MAX_CACHED_MODELS,
    }
}

impl AppState {
    /// Create state with a pre-loaded engine (server starts with a configured model).
    pub fn new(
        engine: Box<dyn InferenceEngine>,
        config: Config,
        queue: QueueHandle,
        gpu_pool: Arc<GpuPool>,
        queue_capacity: usize,
    ) -> Self {
        let mut cache = ModelCache::new(resolve_max_cached_models());
        cache.insert(engine, 0);
        let events = EventBroadcaster::new();
        Self {
            gpu_pool,
            queue_capacity,
            model_cache: Arc::new(Mutex::new(cache)),
            active_generation: Arc::new(RwLock::new(None)),
            config: Arc::new(tokio::sync::RwLock::new(config)),
            start_time: Instant::now(),
            model_load_lock: Arc::new(Mutex::new(())),
            pull_lock: Arc::new(Mutex::new(())),
            queue,
            job_registry: JobRegistry::with_events(events.clone()),
            queue_pause: crate::queue::QueuePause::new(),
            shared_pool: Arc::new(std::sync::Mutex::new(SharedPool::new())),
            shutdown_tx: Arc::new(tokio::sync::Mutex::new(None)),
            upscaler_cache: Arc::new(std::sync::Mutex::new(None)),
            metadata_db: Arc::new(None),
            chain_jobs: None,
            downloads: DownloadQueue::new(),
            resources: ResourceBroadcaster::new(),
            events,
            catalog_live_cache: default_live_cache(),
            catalog_live_civitai_base: Arc::new(CATALOG_LIVE_CIVITAI_BASE.to_string()),
            catalog_intents: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        }
    }

    /// Create state with no engine (zero-config startup, models pulled on demand).
    pub fn empty(
        config: Config,
        queue: QueueHandle,
        gpu_pool: Arc<GpuPool>,
        queue_capacity: usize,
    ) -> Self {
        let events = EventBroadcaster::new();
        Self {
            gpu_pool,
            queue_capacity,
            model_cache: Arc::new(Mutex::new(ModelCache::new(resolve_max_cached_models()))),
            active_generation: Arc::new(RwLock::new(None)),
            config: Arc::new(tokio::sync::RwLock::new(config)),
            start_time: Instant::now(),
            model_load_lock: Arc::new(Mutex::new(())),
            pull_lock: Arc::new(Mutex::new(())),
            queue,
            job_registry: JobRegistry::with_events(events.clone()),
            queue_pause: crate::queue::QueuePause::new(),
            shared_pool: Arc::new(std::sync::Mutex::new(SharedPool::new())),
            shutdown_tx: Arc::new(tokio::sync::Mutex::new(None)),
            upscaler_cache: Arc::new(std::sync::Mutex::new(None)),
            metadata_db: Arc::new(None),
            chain_jobs: None,
            downloads: DownloadQueue::new(),
            resources: ResourceBroadcaster::new(),
            events,
            catalog_live_cache: default_live_cache(),
            catalog_live_civitai_base: Arc::new(CATALOG_LIVE_CIVITAI_BASE.to_string()),
            catalog_intents: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        }
    }

    /// Create an empty GpuPool for testing (no GPU workers).
    #[cfg(test)]
    pub(crate) fn empty_gpu_pool() -> Arc<GpuPool> {
        Arc::new(GpuPool {
            workers: Vec::new(),
        })
    }

    /// Alias for `empty_gpu_pool` — exposed for tests in sibling modules
    /// (routes_test.rs, downloads_test.rs) that live in the crate but not
    /// in the same file.
    #[cfg(test)]
    pub(crate) fn empty_gpu_pool_for_test() -> Arc<GpuPool> {
        Self::empty_gpu_pool()
    }

    #[cfg(test)]
    pub fn with_engine(engine: impl InferenceEngine + 'static) -> Self {
        let (tx, _rx) = tokio::sync::mpsc::channel(16);
        let queue = QueueHandle::new(tx);
        let mut cache = ModelCache::new(resolve_max_cached_models());
        cache.insert(Box::new(engine), 0);
        let events = EventBroadcaster::new();
        Self {
            gpu_pool: Self::empty_gpu_pool(),
            queue_capacity: 200,
            model_cache: Arc::new(Mutex::new(cache)),
            active_generation: Arc::new(RwLock::new(None)),
            config: Arc::new(tokio::sync::RwLock::new(Config::default())),
            start_time: Instant::now(),
            model_load_lock: Arc::new(Mutex::new(())),
            pull_lock: Arc::new(Mutex::new(())),
            queue,
            job_registry: JobRegistry::with_events(events.clone()),
            queue_pause: crate::queue::QueuePause::new(),
            shared_pool: Arc::new(std::sync::Mutex::new(SharedPool::new())),
            shutdown_tx: Arc::new(tokio::sync::Mutex::new(None)),
            upscaler_cache: Arc::new(std::sync::Mutex::new(None)),
            metadata_db: Arc::new(None),
            chain_jobs: None,
            downloads: DownloadQueue::new(),
            resources: ResourceBroadcaster::new(),
            events,
            catalog_live_cache: default_live_cache(),
            catalog_live_civitai_base: Arc::new(CATALOG_LIVE_CIVITAI_BASE.to_string()),
            catalog_intents: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        }
    }

    /// Create state with a queue whose receiver is returned for testing.
    #[cfg(test)]
    pub fn with_engine_and_queue(
        engine: impl InferenceEngine + 'static,
    ) -> (Self, tokio::sync::mpsc::Receiver<GenerationJob>) {
        let (tx, rx) = tokio::sync::mpsc::channel(16);
        let queue = QueueHandle::new(tx);
        let mut cache = ModelCache::new(resolve_max_cached_models());
        cache.insert(Box::new(engine), 0);
        let events = EventBroadcaster::new();
        let state = Self {
            gpu_pool: Self::empty_gpu_pool(),
            queue_capacity: 200,
            model_cache: Arc::new(Mutex::new(cache)),
            active_generation: Arc::new(RwLock::new(None)),
            config: Arc::new(tokio::sync::RwLock::new(Config::default())),
            start_time: Instant::now(),
            model_load_lock: Arc::new(Mutex::new(())),
            pull_lock: Arc::new(Mutex::new(())),
            queue,
            job_registry: JobRegistry::with_events(events.clone()),
            queue_pause: crate::queue::QueuePause::new(),
            shared_pool: Arc::new(std::sync::Mutex::new(SharedPool::new())),
            shutdown_tx: Arc::new(tokio::sync::Mutex::new(None)),
            upscaler_cache: Arc::new(std::sync::Mutex::new(None)),
            metadata_db: Arc::new(None),
            chain_jobs: None,
            downloads: DownloadQueue::new(),
            resources: ResourceBroadcaster::new(),
            events,
            catalog_live_cache: default_live_cache(),
            catalog_live_civitai_base: Arc::new(CATALOG_LIVE_CIVITAI_BASE.to_string()),
            catalog_intents: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        };
        (state, rx)
    }

    /// Construct an empty AppState for integration tests. Catalog
    /// surfaces hit live HF/Civitai (test callers point those at a
    /// wiremock instance via `with_civitai_base`).
    pub fn for_tests() -> Self {
        let (tx, _rx) = tokio::sync::mpsc::channel(16);
        let queue = QueueHandle::new(tx);
        let events = EventBroadcaster::new();
        Self {
            gpu_pool: Arc::new(GpuPool {
                workers: Vec::new(),
            }),
            queue_capacity: 200,
            model_cache: Arc::new(Mutex::new(ModelCache::new(resolve_max_cached_models()))),
            active_generation: Arc::new(RwLock::new(None)),
            config: Arc::new(tokio::sync::RwLock::new(Config::default())),
            start_time: Instant::now(),
            model_load_lock: Arc::new(Mutex::new(())),
            pull_lock: Arc::new(Mutex::new(())),
            queue,
            job_registry: JobRegistry::with_events(events.clone()),
            queue_pause: crate::queue::QueuePause::new(),
            shared_pool: Arc::new(std::sync::Mutex::new(SharedPool::new())),
            shutdown_tx: Arc::new(tokio::sync::Mutex::new(None)),
            upscaler_cache: Arc::new(std::sync::Mutex::new(None)),
            metadata_db: Arc::new(None),
            chain_jobs: None,
            downloads: DownloadQueue::new(),
            resources: ResourceBroadcaster::new(),
            events,
            catalog_live_cache: default_live_cache(),
            catalog_live_civitai_base: Arc::new(CATALOG_LIVE_CIVITAI_BASE.to_string()),
            catalog_intents: Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        }
    }

    /// Override the live-search Civitai base URL on an existing state.
    /// Tests point this at a wiremock instance; production never calls
    /// it (the `new` / `empty` constructors set the public host).
    pub fn with_civitai_base(mut self, base: impl Into<String>) -> Self {
        self.catalog_live_civitai_base = Arc::new(base.into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn engine_snapshot_default_is_unloaded() {
        let snap = EngineSnapshot::default();
        assert!(snap.model_name.is_none());
        assert!(!snap.is_loaded);
    }

    #[test]
    fn active_generation_snapshot_stores_fields() {
        let snap = ActiveGenerationSnapshot {
            model: "flux-dev:q8".to_string(),
            prompt_sha256: "abc123".to_string(),
            started_at_unix_ms: 1700000000000,
            started_at: std::time::Instant::now(),
        };
        assert_eq!(snap.model, "flux-dev:q8");
        assert_eq!(snap.prompt_sha256, "abc123");
        assert_eq!(snap.started_at_unix_ms, 1700000000000);
    }

    #[test]
    fn queue_handle_pending_starts_at_zero() {
        let (tx, _rx) = tokio::sync::mpsc::channel::<GenerationJob>(16);
        let handle = QueueHandle::new(tx);
        assert_eq!(handle.pending(), 0);
    }

    #[test]
    fn upscaler_cache_starts_empty() {
        let config = mold_core::Config::default();
        let state = AppState::empty(
            config,
            QueueHandle::new(tokio::sync::mpsc::channel(1).0),
            AppState::empty_gpu_pool(),
            200,
        );
        let cache = state.upscaler_cache.lock().unwrap();
        assert!(cache.is_none());
    }

    #[test]
    fn upscaler_cache_cleared_by_setting_none() {
        let config = mold_core::Config::default();
        let state = AppState::empty(
            config,
            QueueHandle::new(tokio::sync::mpsc::channel(1).0),
            AppState::empty_gpu_pool(),
            200,
        );
        {
            let mut cache = state.upscaler_cache.lock().unwrap();
            *cache = None;
        }
        let cache = state.upscaler_cache.lock().unwrap();
        assert!(cache.is_none());
    }

    #[test]
    fn app_state_exposes_resources_broadcaster() {
        let config = mold_core::Config::default();
        let state = AppState::empty(
            config,
            QueueHandle::new(tokio::sync::mpsc::channel(1).0),
            AppState::empty_gpu_pool(),
            200,
        );
        // The broadcaster must exist and return None before any aggregator tick.
        assert!(state.resources.latest().is_none());
        // Subscribing must succeed (no panics).
        let _rx = state.resources.subscribe();
    }

    /// Serializes every test that touches a process-wide env var via
    /// `std::env::set_var` — mutating env is global state, so without this
    /// guard parallel tests would race on the env table.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Set `name` to `value` (or remove it when `value` is `None`), invoke
    /// `f`, then restore the original value. Lock-serialized so concurrent
    /// tests don't race on the env table.
    fn with_env<R>(name: &str, value: Option<&str>, f: impl FnOnce() -> R) -> R {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let prev = std::env::var(name).ok();
        match value {
            Some(v) => std::env::set_var(name, v),
            None => std::env::remove_var(name),
        }
        let out = f();
        match prev {
            Some(v) => std::env::set_var(name, v),
            None => std::env::remove_var(name),
        }
        out
    }

    #[test]
    fn resolve_max_cached_uses_default_when_env_missing() {
        let n = with_env(MAX_CACHED_MODELS_ENV, None, resolve_max_cached_models);
        assert_eq!(n, DEFAULT_MAX_CACHED_MODELS);
    }

    #[test]
    fn resolve_max_cached_honors_env_within_range() {
        let n = with_env(MAX_CACHED_MODELS_ENV, Some("8"), resolve_max_cached_models);
        assert_eq!(n, 8);
    }

    #[test]
    fn resolve_max_cached_clamps_zero_back_to_default() {
        let n = with_env(MAX_CACHED_MODELS_ENV, Some("0"), resolve_max_cached_models);
        assert_eq!(n, DEFAULT_MAX_CACHED_MODELS);
    }

    #[test]
    fn resolve_max_cached_clamps_overflow_back_to_default() {
        let n = with_env(
            MAX_CACHED_MODELS_ENV,
            Some("999"),
            resolve_max_cached_models,
        );
        assert_eq!(n, DEFAULT_MAX_CACHED_MODELS);
    }

    #[test]
    fn resolve_max_cached_falls_back_when_env_unparseable() {
        let n = with_env(
            MAX_CACHED_MODELS_ENV,
            Some("not-a-number"),
            resolve_max_cached_models,
        );
        assert_eq!(n, DEFAULT_MAX_CACHED_MODELS);
    }

    #[test]
    fn resolve_cache_idle_ttl_uses_default_when_env_missing() {
        let n = with_env(CACHE_IDLE_TTL_ENV, None, resolve_cache_idle_ttl_secs);
        assert_eq!(n, DEFAULT_CACHE_IDLE_TTL_SECS);
    }

    #[test]
    fn resolve_cache_idle_ttl_honors_env_within_range() {
        // 600s is comfortably inside [60, 86_400] — the resolver must echo it.
        let n = with_env(CACHE_IDLE_TTL_ENV, Some("600"), resolve_cache_idle_ttl_secs);
        assert_eq!(n, 600);
    }

    #[test]
    fn resolve_cache_idle_ttl_clamps_zero_back_to_default() {
        // 0 is below the 60s lower bound; falls back to the default with a warn log.
        let n = with_env(CACHE_IDLE_TTL_ENV, Some("0"), resolve_cache_idle_ttl_secs);
        assert_eq!(n, DEFAULT_CACHE_IDLE_TTL_SECS);
    }

    #[test]
    fn resolve_cache_idle_ttl_clamps_overflow_back_to_default() {
        // 100_000 is above the 86_400s upper bound; falls back to the default.
        let n = with_env(
            CACHE_IDLE_TTL_ENV,
            Some("100000"),
            resolve_cache_idle_ttl_secs,
        );
        assert_eq!(n, DEFAULT_CACHE_IDLE_TTL_SECS);
    }

    #[test]
    fn resolve_cache_idle_ttl_falls_back_when_env_unparseable() {
        let n = with_env(
            CACHE_IDLE_TTL_ENV,
            Some("not-a-number"),
            resolve_cache_idle_ttl_secs,
        );
        assert_eq!(n, DEFAULT_CACHE_IDLE_TTL_SECS);
    }
}