返回 CodeWhale
models_dev_live.rs
根目录 / crates / engine / src / models_dev_live.rs
1 //! Live Models.dev catalog fetch + secret-free disk cache (#4187).
2 //!
3 //! OpenCode-style producer that:
4 //! - reads a stale/fresh disk cache on startup (never blocks model selection),
5 //! - fetches `https://models.dev/catalog.json` in the background with a bounded
6 //! timeout and explicit user-agent (no credentials),
7 //! - writes the cache atomically via temp file + rename,
8 //! - compiles parsed rows into `CatalogOffering`s and publishes them into
9 //! [`crate::provider_lake`],
10 //! - falls back to the prior cache or the bundled snapshot on any failure.
11 //!
12 //! Override knobs (tests / dogfood):
13 //! - `CODEWHALE_MODELS_DEV_URL` — base URL (appends `/catalog.json`) or a full
14 //! `*.json` URL.
15 //! - `CODEWHALE_MODELS_DEV_PATH` — local file path; skips the network.
16 //! - `CODEWHALE_DISABLE_MODELS_DEV_FETCH` — when truthy, never hits the network.
17
18 #[cfg(test)]
19 use codewhale_runtime::catalog_cache::CACHE_FILE;
20 use codewhale_runtime::catalog_cache::cache_path;
21 use std::path::Path;
22 use std::sync::RwLock;
23 use std::time::{Duration, Instant};
24
25 use codewhale_config::catalog::{
26 CatalogSnapshot, base_url_fingerprint, live_offerings_from_models_dev, now_unix,
27 };
28 use codewhale_config::models_dev::{MODELS_DEV_CATALOG_URL, ModelsDevCatalog};
29 use codewhale_config::persistence::atomic_write;
30 use serde::{Deserialize, Serialize};
31
32 /// Default TTL for a live Models.dev snapshot (24h, #4187 / #4114).
33 pub const DEFAULT_MODELS_DEV_TTL_SECS: u64 = 24 * 60 * 60;
34
35 /// Bounded HTTP timeout for the Models.dev fetch.
36 pub const FETCH_TIMEOUT: Duration = Duration::from_secs(15);
37
38 /// Explicit user-agent; no credentials, no session cookies.
39 pub const USER_AGENT: &str = concat!("CodeWhale/", env!("CARGO_PKG_VERSION"), " (+models-dev)");
40
41 /// Env: override Models.dev base URL or full catalog URL.
42 pub const ENV_MODELS_DEV_URL: &str = "CODEWHALE_MODELS_DEV_URL";
43 /// Env: load catalog JSON from a local path (skips network).
44 pub const ENV_MODELS_DEV_PATH: &str = "CODEWHALE_MODELS_DEV_PATH";
45 /// Env: disable network fetch entirely (`1`/`true`/`yes`/`on`).
46 pub const ENV_DISABLE_FETCH: &str = "CODEWHALE_DISABLE_MODELS_DEV_FETCH";
47
48 struct RefreshAttempt {
49 source: String,
50 completed_at: Instant,
51 result: Result<usize, ModelsDevRefreshError>,
52 }
53
54 static REFRESH_ATTEMPT: tokio::sync::Mutex<Option<RefreshAttempt>> =
55 tokio::sync::Mutex::const_new(None);
56
57 const CACHE_SCHEMA_VERSION: u32 = 1;
58 /// Largest catalog body accepted from the network, an override file, or the
59 /// disk cache. The public catalog is a few MiB; anything past this is refused
60 /// instead of being read whole into memory.
61 const MAX_CATALOG_BYTES: usize = 32 * 1024 * 1024;
62 /// Clock skew tolerated on a cache timestamp. A `fetched_at` further in the
63 /// future than this is not "age zero": it is untrustworthy, so the cache is
64 /// published as stale and the next refresh fetches.
65 const MAX_CACHE_CLOCK_SKEW_SECS: u64 = 5 * 60;
66
67 /// Provenance / freshness of the Models.dev live layer for UI chips (#4187).
68 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
69 #[serde(rename_all = "snake_case")]
70 pub enum ModelsDevFreshness {
71 /// No live/cache layer; pickers see bundled rows only.
72 #[default]
73 Bundled,
74 /// Live (or disk-cache) rows within TTL.
75 Live,
76 /// Disk-cache / prior live rows past TTL; still visible.
77 Stale,
78 /// Last refresh failed; prior/bundled rows remain available.
79 Failed,
80 }
81
82 /// Where the rows a caller can currently see were produced.
83 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
84 #[serde(rename_all = "snake_case")]
85 pub enum ModelsDevProvenance {
86 #[default]
87 Bundled,
88 Live,
89 Cache,
90 File,
91 }
92
93 impl ModelsDevProvenance {
94 #[must_use]
95 pub const fn label(self) -> &'static str {
96 match self {
97 Self::Bundled => "bundled_snapshot",
98 Self::Live => "models_dev_live",
99 Self::Cache => "models_dev_cache",
100 Self::File => "models_dev_file",
101 }
102 }
103 }
104
105 /// Quiet status snapshot for UI / `/model refresh` feedback.
106 #[derive(Debug, Clone, PartialEq, Eq, Default)]
107 pub struct ModelsDevStatus {
108 pub freshness: ModelsDevFreshness,
109 pub provenance: ModelsDevProvenance,
110 pub offering_count: usize,
111 pub fetched_at: Option<u64>,
112 pub source_label: String,
113 pub last_error: Option<String>,
114 }
115
116 static STATUS: RwLock<ModelsDevStatus> = RwLock::new(ModelsDevStatus {
117 freshness: ModelsDevFreshness::Bundled,
118 provenance: ModelsDevProvenance::Bundled,
119 offering_count: 0,
120 fetched_at: None,
121 source_label: String::new(),
122 last_error: None,
123 });
124
125 #[derive(Debug, Clone, Serialize, Deserialize)]
126 struct PersistedModelsDevCache {
127 schema_version: u32,
128 /// Unix seconds the payload was fetched (or loaded from an override path).
129 fetched_at: u64,
130 /// Fingerprint of the source URL/path this body was fetched from. It scopes
131 /// the on-disk cache; it is deliberately not carried on the published rows,
132 /// which describe a model rather than an endpoint (`ModelsDevLive`).
133 source_fingerprint: String,
134 /// Human-readable source label (URL or `file:…`); never a secret.
135 source_label: String,
136 /// Raw Models.dev catalog JSON body (secret-free by construction).
137 body: String,
138 }
139
140 /// Metadata header for the v2 cache format.
141 ///
142 /// v1 serialized the whole cache as one JSON envelope with the catalog body
143 /// escaped inside it, so loading parsed ~5MB twice (envelope, then body) plus
144 /// a full-body copy on every interactive boot. v2 stores the metadata as a
145 /// single JSON header line followed by the raw catalog body bytes, so boot
146 /// performs exactly one catalog parse and zero body copies.
147 const CACHE_SCHEMA_VERSION_V2: u32 = 2;
148
149 #[derive(Debug, Clone, Serialize, Deserialize)]
150 struct PersistedModelsDevCacheV2 {
151 schema_version: u32,
152 fetched_at: u64,
153 source_fingerprint: String,
154 source_label: String,
155 }
156
157 /// Why a Models.dev refresh did not publish new rows.
158 #[derive(Debug, Clone, PartialEq, Eq)]
159 pub enum ModelsDevRefreshError {
160 Disabled,
161 Network(String),
162 HttpStatus(u16),
163 InvalidResponse(String),
164 EmptyCatalog,
165 Io(String),
166 }
167
168 impl std::fmt::Display for ModelsDevRefreshError {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 match self {
171 Self::Disabled => write!(f, "Models.dev fetch disabled"),
172 Self::Network(msg) => write!(f, "network: {msg}"),
173 Self::HttpStatus(code) => write!(f, "HTTP {code}"),
174 Self::InvalidResponse(msg) => write!(f, "invalid response: {msg}"),
175 Self::EmptyCatalog => write!(f, "empty catalog"),
176 Self::Io(msg) => write!(f, "io: {msg}"),
177 }
178 }
179 }
180
181 /// Current quiet status (for UI / slash-command feedback).
182 #[must_use]
183 pub fn status() -> ModelsDevStatus {
184 let mut current = STATUS.read().map(|guard| guard.clone()).unwrap_or_default();
185 if current.freshness == ModelsDevFreshness::Live
186 && current
187 .fetched_at
188 .is_none_or(|timestamp| !within_ttl(timestamp, now_unix()))
189 {
190 current.freshness = ModelsDevFreshness::Stale;
191 }
192 honor_bundled_staleness(
193 current,
194 codewhale_config::catalog::reviewed::bundled_source_fetched_at()
195 .is_none_or(|fetched_at| !within_ttl(fetched_at, now_unix())),
196 )
197 }
198
199 /// A Bundled-only report whose snapshot is itself past TTL reports `Stale`:
200 /// rows stay visible for offline use, but never as a current catalog (#A2).
201 fn honor_bundled_staleness(mut status: ModelsDevStatus, bundled_stale: bool) -> ModelsDevStatus {
202 if status.freshness == ModelsDevFreshness::Bundled && bundled_stale {
203 status.freshness = ModelsDevFreshness::Stale;
204 }
205 status
206 }
207
208 fn set_status(next: ModelsDevStatus) {
209 if let Ok(mut guard) = STATUS.write() {
210 *guard = next;
211 }
212 }
213
214 fn env_truthy(name: &str) -> bool {
215 std::env::var(name)
216 .map(|v| {
217 matches!(
218 v.trim().to_ascii_lowercase().as_str(),
219 "1" | "true" | "yes" | "on"
220 )
221 })
222 .unwrap_or(false)
223 }
224
225 /// Resolve the catalog URL from env override or the Models.dev default.
226 #[must_use]
227 pub fn resolve_catalog_url() -> String {
228 match std::env::var(ENV_MODELS_DEV_URL) {
229 Ok(raw) => {
230 let trimmed = raw.trim();
231 if trimmed.is_empty() {
232 MODELS_DEV_CATALOG_URL.to_string()
233 } else if trimmed.ends_with(".json") {
234 trimmed.to_string()
235 } else {
236 format!("{}/catalog.json", trimmed.trim_end_matches('/'))
237 }
238 }
239 Err(_) => MODELS_DEV_CATALOG_URL.to_string(),
240 }
241 }
242
243 /// Seed ProviderLake from the on-disk Models.dev cache before any picker read.
244 ///
245 /// Missing / corrupt / empty caches are a no-op — bundled rows remain available.
246 /// Stale caches still publish (freshness = Stale) so offline startups keep the
247 /// last-known live rows.
248 pub fn maybe_load_persisted_cache() {
249 let Some(path) = cache_path() else {
250 return;
251 };
252 let Some(cache) = load_cache_file(&path) else {
253 return;
254 };
255 // The cache belongs to the selected source. Another mirror or override
256 // cannot supply fallback facts for this selection.
257 if cache.source_fingerprint != current_source_fingerprint() {
258 mark_failed(ModelsDevRefreshError::InvalidResponse(
259 "cached catalog belongs to a different source".into(),
260 ));
261 return;
262 }
263 let freshness = if within_ttl(cache.fetched_at, now_unix()) {
264 ModelsDevFreshness::Live
265 } else {
266 ModelsDevFreshness::Stale
267 };
268 if let Err(err) = publish_from_body(
269 &cache.body,
270 cache.fetched_at,
271 cache.source_label.as_str(),
272 freshness,
273 ModelsDevProvenance::Cache,
274 ) {
275 tracing::debug!(
276 target: "models_dev_live",
277 error = %err,
278 "persisted Models.dev cache failed to publish; keeping bundled"
279 );
280 }
281 }
282
283 /// Force a refresh: prefer `CODEWHALE_MODELS_DEV_PATH`, else network fetch.
284 ///
285 /// On success, publishes to ProviderLake and updates the disk cache. On
286 /// failure, keeps any prior live/bundled rows and records a quiet Failed
287 /// status. A cache write that fails after a successful publish keeps the fresh
288 /// rows and reports only the persistence error.
289 pub async fn refresh(force_network: bool) -> Result<usize, ModelsDevRefreshError> {
290 let mut previous = REFRESH_ATTEMPT.lock().await;
291 let source = current_source_fingerprint();
292 if !force_network
293 && std::env::var(ENV_MODELS_DEV_PATH)
294 .ok()
295 .is_none_or(|path| path.trim().is_empty())
296 && let Some(attempt) = previous.as_ref()
297 && attempt.source == source
298 && attempt.completed_at.elapsed() < Duration::from_secs(60)
299 && attempt.result.is_err()
300 && !matches!(attempt.result, Err(ModelsDevRefreshError::Disabled))
301 {
302 return attempt.result.clone();
303 }
304 let result = refresh_inner(force_network).await;
305 *previous = Some(RefreshAttempt {
306 source,
307 completed_at: Instant::now(),
308 result: result.clone(),
309 });
310 result
311 }
312
313 async fn refresh_inner(force_network: bool) -> Result<usize, ModelsDevRefreshError> {
314 if let Ok(path) = std::env::var(ENV_MODELS_DEV_PATH) {
315 let trimmed = path.trim();
316 if !trimmed.is_empty() {
317 return refresh_from_path(Path::new(trimmed)).await;
318 }
319 }
320
321 if env_truthy(ENV_DISABLE_FETCH) {
322 mark_failed(ModelsDevRefreshError::Disabled);
323 return Err(ModelsDevRefreshError::Disabled);
324 }
325
326 if !force_network {
327 let current = status();
328 if current.freshness == ModelsDevFreshness::Live
329 && current.source_label == resolve_catalog_url()
330 && current
331 .fetched_at
332 .is_some_and(|ts| within_ttl(ts, now_unix()))
333 {
334 return Ok(current.offering_count);
335 }
336 }
337
338 let url = resolve_catalog_url();
339 let body = match fetch_catalog_body(&url).await {
340 Ok(body) => body,
341 Err(err) => {
342 mark_failed(err.clone());
343 return Err(err);
344 }
345 };
346 let fetched_at = now_unix();
347 let fingerprint = base_url_fingerprint(&url);
348 let count = publish_from_body(
349 &body,
350 fetched_at,
351 &url,
352 ModelsDevFreshness::Live,
353 ModelsDevProvenance::Live,
354 )?;
355 if let Some(path) = cache_path() {
356 save_cache_file(
357 &path,
358 &PersistedModelsDevCache {
359 schema_version: CACHE_SCHEMA_VERSION,
360 fetched_at,
361 source_fingerprint: fingerprint,
362 source_label: url,
363 body,
364 },
365 )
366 .inspect_err(note_persistence_error)?;
367 }
368 Ok(count)
369 }
370
371 /// Whether a payload fetched at `fetched_at` is still inside the TTL at
372 /// `now`. A timestamp beyond the tolerated clock skew is never fresh: a
373 /// saturating age would read it as zero and suppress refresh until the clock
374 /// caught up.
375 fn within_ttl(fetched_at: u64, now: u64) -> bool {
376 if fetched_at > now.saturating_add(MAX_CACHE_CLOCK_SKEW_SECS) {
377 return false;
378 }
379 now.saturating_sub(fetched_at) <= DEFAULT_MODELS_DEV_TTL_SECS
380 }
381
382 /// Fingerprint of the source a refresh would read right now: the override
383 /// file when `CODEWHALE_MODELS_DEV_PATH` is set, else the catalog URL. Same
384 /// derivation `refresh` stores in the cache.
385 fn current_source_fingerprint() -> String {
386 match std::env::var(ENV_MODELS_DEV_PATH) {
387 Ok(path) if !path.trim().is_empty() => {
388 base_url_fingerprint(&format!("file:{}", Path::new(path.trim()).display()))
389 }
390 _ => base_url_fingerprint(&resolve_catalog_url()),
391 }
392 }
393
394 const CI_ENV_VARS: &[&str] = &[
395 "CI",
396 "CONTINUOUS_INTEGRATION",
397 "GITHUB_ACTIONS",
398 "GITLAB_CI",
399 "BUILDKITE",
400 "CIRCLECI",
401 "JENKINS_URL",
402 "TRAVIS",
403 "TF_BUILD",
404 "TEAMCITY_VERSION",
405 "CODEBUILD_BUILD_ID",
406 ];
407
408 fn is_ci_env() -> bool {
409 CI_ENV_VARS.iter().any(|name| {
410 std::env::var(name).is_ok_and(|raw| {
411 let trimmed = raw.trim();
412 !trimmed.is_empty()
413 && !matches!(
414 trimmed.to_ascii_lowercase().as_str(),
415 "0" | "false" | "no" | "off"
416 )
417 })
418 })
419 }
420
421 pub fn background_fetch_disabled(auto_refresh: bool) -> bool {
422 if std::env::var(ENV_MODELS_DEV_PATH).is_ok_and(|p| !p.trim().is_empty()) {
423 return false;
424 }
425 !auto_refresh
426 || env_truthy(ENV_DISABLE_FETCH)
427 || is_ci_env()
428 || codewhale_config::do_not_track()
429 }
430
431 pub fn spawn_background_refresh() {
432 spawn_background_refresh_if_enabled(true);
433 }
434
435 pub fn spawn_background_refresh_if_enabled(auto_refresh: bool) {
436 if background_fetch_disabled(auto_refresh) {
437 return;
438 }
439 let Ok(handle) = tokio::runtime::Handle::try_current() else {
440 return;
441 };
442 handle.spawn(async {
443 loop {
444 match refresh(false).await {
445 Ok(count) => {
446 tracing::debug!(
447 target: "models_dev_live",
448 offering_count = count,
449 "Models.dev live catalog refreshed"
450 );
451 }
452 Err(err) => {
453 tracing::debug!(
454 target: "models_dev_live",
455 error = %err,
456 "Models.dev live catalog refresh skipped"
457 );
458 }
459 }
460 tokio::time::sleep(Duration::from_secs(15 * 60)).await;
461 }
462 });
463 }
464
465 async fn refresh_from_path(path: &Path) -> Result<usize, ModelsDevRefreshError> {
466 let body = match read_catalog_file(path).await {
467 Ok(body) => body,
468 Err(mapped) => {
469 mark_failed(mapped.clone());
470 return Err(mapped);
471 }
472 };
473 let fetched_at = now_unix();
474 let label = format!("file:{}", path.display());
475 let fingerprint = base_url_fingerprint(&label);
476 let count = publish_from_body(
477 &body,
478 fetched_at,
479 &label,
480 ModelsDevFreshness::Live,
481 ModelsDevProvenance::File,
482 )?;
483 if let Some(cache) = cache_path() {
484 save_cache_file(
485 &cache,
486 &PersistedModelsDevCache {
487 schema_version: CACHE_SCHEMA_VERSION,
488 fetched_at,
489 source_fingerprint: fingerprint,
490 source_label: label,
491 body,
492 },
493 )
494 .inspect_err(note_persistence_error)?;
495 }
496 Ok(count)
497 }
498
499 async fn fetch_catalog_body(url: &str) -> Result<String, ModelsDevRefreshError> {
500 let client = crate::platform_client_builder()
501 .timeout(FETCH_TIMEOUT)
502 .connect_timeout(Duration::from_secs(10))
503 .user_agent(USER_AGENT)
504 .build()
505 .map_err(|err| ModelsDevRefreshError::Network(err.to_string()))?;
506
507 let response = client
508 .get(url)
509 .send()
510 .await
511 .map_err(|err| ModelsDevRefreshError::Network(err.to_string()))?;
512
513 let status = response.status();
514 if !status.is_success() {
515 return Err(ModelsDevRefreshError::HttpStatus(status.as_u16()));
516 }
517
518 read_catalog_response(response, MAX_CATALOG_BYTES).await
519 }
520
521 fn oversized_catalog(limit: usize) -> ModelsDevRefreshError {
522 ModelsDevRefreshError::InvalidResponse(format!("catalog exceeds {limit} bytes"))
523 }
524
525 /// Read a catalog response body without ever holding more than `limit` bytes.
526 async fn read_catalog_response(
527 mut response: reqwest::Response,
528 limit: usize,
529 ) -> Result<String, ModelsDevRefreshError> {
530 if response
531 .content_length()
532 .is_some_and(|length| length > limit as u64)
533 {
534 return Err(oversized_catalog(limit));
535 }
536 let mut bytes = Vec::new();
537 while let Some(chunk) = response
538 .chunk()
539 .await
540 .map_err(|err| ModelsDevRefreshError::Network(err.to_string()))?
541 {
542 if bytes.len().saturating_add(chunk.len()) > limit {
543 return Err(oversized_catalog(limit));
544 }
545 bytes.extend_from_slice(&chunk);
546 }
547 String::from_utf8(bytes)
548 .map_err(|_| ModelsDevRefreshError::InvalidResponse("catalog is not UTF-8".into()))
549 }
550
551 /// Read an override catalog file, refusing one larger than the catalog limit.
552 async fn read_catalog_file(path: &Path) -> Result<String, ModelsDevRefreshError> {
553 use tokio::io::AsyncReadExt as _;
554
555 let file = tokio::fs::File::open(path)
556 .await
557 .map_err(|err| ModelsDevRefreshError::Io(err.to_string()))?;
558 let mut bytes = Vec::new();
559 file.take(MAX_CATALOG_BYTES as u64 + 1)
560 .read_to_end(&mut bytes)
561 .await
562 .map_err(|err| ModelsDevRefreshError::Io(err.to_string()))?;
563 if bytes.len() > MAX_CATALOG_BYTES {
564 return Err(oversized_catalog(MAX_CATALOG_BYTES));
565 }
566 String::from_utf8(bytes)
567 .map_err(|_| ModelsDevRefreshError::InvalidResponse("catalog is not UTF-8".into()))
568 }
569
570 fn publish_from_body(
571 body: &str,
572 fetched_at: u64,
573 source_label: &str,
574 freshness: ModelsDevFreshness,
575 provenance: ModelsDevProvenance,
576 ) -> Result<usize, ModelsDevRefreshError> {
577 let catalog = ModelsDevCatalog::parse_json(body).map_err(|err| {
578 let mapped = ModelsDevRefreshError::InvalidResponse(err.to_string());
579 mark_failed(mapped.clone());
580 mapped
581 })?;
582 // The source fingerprint scopes the *disk cache*, not the rows: a
583 // models.dev row describes a model, not an endpoint (`ModelsDevLive`).
584 let offerings = live_offerings_from_models_dev(&catalog, fetched_at);
585 if offerings.is_empty() {
586 let err = ModelsDevRefreshError::EmptyCatalog;
587 mark_failed(err.clone());
588 return Err(err);
589 }
590 let count = offerings.len();
591 crate::provider_lake::set_live_snapshot(
592 CatalogSnapshot { offerings },
593 crate::provider_lake::LiveSource::ModelsDev,
594 );
595 set_status(ModelsDevStatus {
596 freshness,
597 provenance,
598 offering_count: count,
599 fetched_at: Some(fetched_at),
600 source_label: source_label.to_string(),
601 last_error: None,
602 });
603 Ok(count)
604 }
605
606 fn note_persistence_error(err: &ModelsDevRefreshError) {
607 let mut next = status();
608 next.last_error = Some(err.to_string());
609 set_status(next);
610 }
611
612 fn mark_failed(err: ModelsDevRefreshError) {
613 let mut next = status();
614 // Keep prior offering_count / fetched_at so UI can still show the last
615 // rows, but mark the last refresh outcome distinctly from TTL staleness.
616 next.freshness = ModelsDevFreshness::Failed;
617 next.last_error = Some(err.to_string());
618 set_status(next);
619 }
620
621 /// Load the on-disk Models.dev cache.
622 ///
623 /// Reads v2 (single-parse: one header line + raw body) and v1 (JSON envelope
624 /// with an escaped body) formats. Returns metadata and the *unescaped* body
625 /// without copying it in the v2 path.
626 fn load_cache_file(path: &Path) -> Option<PersistedModelsDevCache> {
627 use std::io::Read as _;
628
629 // Header line plus body; a larger file is not ours to trust or to read
630 // whole, so the bundled rows stand instead.
631 const MAX_CACHE_FILE_BYTES: u64 = MAX_CATALOG_BYTES as u64 + 64 * 1024;
632 let mut bytes = Vec::new();
633 std::fs::File::open(path)
634 .ok()?
635 .take(MAX_CACHE_FILE_BYTES + 1)
636 .read_to_end(&mut bytes)
637 .ok()?;
638 if bytes.len() as u64 > MAX_CACHE_FILE_BYTES {
639 return None;
640 }
641 // v2: single-line JSON header terminated by a newline, then the verbatim
642 // catalog body. One small parse, zero body copies.
643 if bytes.first() == Some(&b'{') && bytes.contains(&b'\n') {
644 let split = bytes.iter().position(|b| *b == b'\n')?;
645 if let Ok(header) = serde_json::from_slice::<PersistedModelsDevCacheV2>(&bytes[..split])
646 && header.schema_version == CACHE_SCHEMA_VERSION_V2
647 && !bytes[split + 1..].is_empty()
648 {
649 let body = String::from_utf8(bytes[split + 1..].to_vec()).ok()?;
650 return Some(PersistedModelsDevCache {
651 schema_version: CACHE_SCHEMA_VERSION,
652 fetched_at: header.fetched_at,
653 source_fingerprint: header.source_fingerprint,
654 source_label: header.source_label,
655 body,
656 });
657 }
658 }
659 // v1 fallback: whole-file JSON envelope with the body escaped inside.
660 let cache: PersistedModelsDevCache = serde_json::from_slice(&bytes).ok()?;
661 if cache.schema_version != CACHE_SCHEMA_VERSION {
662 return None;
663 }
664 if cache.body.trim().is_empty() {
665 return None;
666 }
667 Some(cache)
668 }
669
670 fn save_cache_file(
671 path: &Path,
672 cache: &PersistedModelsDevCache,
673 ) -> Result<(), ModelsDevRefreshError> {
674 // Write the single-parse format so the next boot parses the catalog once.
675 let header = PersistedModelsDevCacheV2 {
676 schema_version: CACHE_SCHEMA_VERSION_V2,
677 fetched_at: cache.fetched_at,
678 source_fingerprint: cache.source_fingerprint.clone(),
679 source_label: cache.source_label.clone(),
680 };
681 let mut header_line =
682 serde_json::to_vec(&header).map_err(|err| ModelsDevRefreshError::Io(err.to_string()))?;
683 header_line.push(b'\n');
684 let mut payload = header_line;
685 payload.extend_from_slice(cache.body.as_bytes());
686 atomic_write(path, &payload).map_err(|err| ModelsDevRefreshError::Io(err.to_string()))
687 }
688
689 /// Compile helper exposed for unit tests: body → live offerings with normalized
690 /// provider ids.
691 #[cfg(any(test, feature = "test-support"))]
692 pub fn offerings_from_json_for_test(
693 body: &str,
694 ) -> Result<Vec<codewhale_config::catalog::CatalogOffering>, String> {
695 let catalog = ModelsDevCatalog::parse_json(body).map_err(|e| e.to_string())?;
696 Ok(live_offerings_from_models_dev(&catalog, 1_700_000_000))
697 }
698
699 #[cfg(test)]
700 mod tests {
701 use super::*;
702 use crate::provider_lake::{
703 all_catalog_models_for_provider, clear_live_snapshot, lock_live_snapshot,
704 };
705 use crate::test_support::{EnvVarGuard, lock_test_env};
706 use codewhale_config::ProviderKind;
707 use codewhale_config::catalog::CatalogSource;
708
709 const FIXTURE: &str = r#"{
710 "models": {},
711 "providers": {
712 "togetherai": {
713 "id": "togetherai",
714 "models": {
715 "deepseek-ai/DeepSeek-V4-Pro": {
716 "id": "deepseek-ai/DeepSeek-V4-Pro",
717 "name": "DeepSeek V4 Pro",
718 "modalities": { "input": ["text"], "output": ["text"] },
719 "limit": { "context": 128000, "output": 8192 }
720 }
721 }
722 },
723 "moonshotai": {
724 "id": "moonshotai",
725 "models": {
726 "kimi-k2.5": {
727 "id": "kimi-k2.5",
728 "name": "Kimi K2.5",
729 "modalities": { "input": ["text"], "output": ["text"] },
730 "limit": { "context": 256000, "output": 8192 }
731 }
732 }
733 },
734 "unknown-gateway": {
735 "id": "unknown-gateway",
736 "models": {
737 "mystery-1": {
738 "id": "mystery-1",
739 "modalities": { "input": ["text"], "output": ["text"] }
740 }
741 }
742 }
743 }
744 }"#;
745
746 /// An unguarded test must not resolve the developer's catalog cache.
747 ///
748 /// `resolve_state_dir` lives in `codewhale-config`, which is a plain
749 /// dependency here and cannot see this crate's isolated test root, so this
750 /// path had no equivalent of the settings confinement (#5359). A picker
751 /// test then rendered against whatever models the developer last fetched.
752 #[test]
753 fn unguarded_cache_path_stays_inside_the_isolated_test_root() {
754 let path = cache_path().expect("cache path");
755 let isolated = crate::test_support::isolated_test_state_root();
756 assert!(
757 path.starts_with(isolated),
758 "catalog cache escaped the isolated test root: {}",
759 path.display()
760 );
761 assert_eq!(path.file_name().and_then(|n| n.to_str()), Some(CACHE_FILE));
762 }
763
764 /// A test that does seal the environment still resolves it, so the
765 /// confinement above cannot silently break the guarded callers.
766 #[test]
767 fn guarded_cache_path_follows_the_sealed_home() {
768 let _lock = lock_test_env();
769 let home = tempfile::tempdir().expect("tempdir");
770 let _guard = EnvVarGuard::set("CODEWHALE_HOME", home.path());
771
772 let path = cache_path().expect("cache path");
773
774 assert!(
775 path.starts_with(home.path()),
776 "sealed CODEWHALE_HOME was ignored: {}",
777 path.display()
778 );
779 }
780
781 #[test]
782 fn resolve_catalog_url_defaults_and_overrides() {
783 let _lock = lock_test_env();
784 let _url = EnvVarGuard::remove(ENV_MODELS_DEV_URL);
785 assert_eq!(resolve_catalog_url(), MODELS_DEV_CATALOG_URL);
786
787 let _url = EnvVarGuard::set(ENV_MODELS_DEV_URL, "https://example.test");
788 assert_eq!(resolve_catalog_url(), "https://example.test/catalog.json");
789
790 let _url = EnvVarGuard::set(ENV_MODELS_DEV_URL, "https://example.test/api.json");
791 assert_eq!(resolve_catalog_url(), "https://example.test/api.json");
792 }
793
794 #[test]
795 fn live_offerings_normalize_models_dev_provider_ids() {
796 let rows = offerings_from_json_for_test(FIXTURE).expect("fixture");
797 let providers: Vec<_> = rows.iter().map(|r| r.provider.as_str()).collect();
798 assert!(providers.contains(&"together"));
799 assert!(providers.contains(&"moonshot"));
800 assert!(providers.contains(&"unknown-gateway"));
801 assert!(!providers.contains(&"togetherai"));
802 assert!(!providers.contains(&"moonshotai"));
803 // Layer 10, not layer 20: a refresh of a public catalog is external
804 // enrichment about a model, not a provider's answer about an endpoint,
805 // so it stays correctable by the signed layer above it.
806 assert!(
807 rows.iter()
808 .all(|r| matches!(r.source, CatalogSource::ModelsDevLive { .. }))
809 );
810 }
811
812 #[test]
813 fn publish_from_path_updates_provider_lake() {
814 let _lock = lock_test_env();
815 let _live = lock_live_snapshot();
816 clear_live_snapshot();
817 let dir = tempfile::tempdir().expect("tempdir");
818 let path = dir.path().join("catalog.json");
819 std::fs::write(&path, FIXTURE).expect("write fixture");
820
821 let _home = EnvVarGuard::set("CODEWHALE_HOME", dir.path().join("home"));
822 let _disable = EnvVarGuard::set(ENV_DISABLE_FETCH, "1");
823 let _path = EnvVarGuard::set(ENV_MODELS_DEV_PATH, &path);
824
825 let rt = tokio::runtime::Builder::new_current_thread()
826 .enable_all()
827 .build()
828 .expect("runtime");
829 let count = rt.block_on(refresh(true)).expect("refresh from path");
830 assert!(count >= 2);
831
832 let together = all_catalog_models_for_provider(ProviderKind::Together);
833 assert!(
834 together.iter().any(|m| m == "deepseek-ai/DeepSeek-V4-Pro"),
835 "Together lake missing live Models.dev row: {together:?}"
836 );
837 let moonshot = all_catalog_models_for_provider(ProviderKind::Moonshot);
838 assert!(
839 moonshot.iter().any(|m| m == "kimi-k2.5"),
840 "Moonshot lake missing live Models.dev row: {moonshot:?}"
841 );
842
843 let st = status();
844 assert_eq!(st.freshness, ModelsDevFreshness::Live);
845 assert!(st.last_error.is_none());
846 assert!(st.offering_count >= 2);
847
848 // Cache file should exist and be secret-free.
849 let cache = cache_path().expect("cache path");
850 assert!(cache.exists());
851 let on_disk = std::fs::read_to_string(&cache).expect("read cache");
852 let lowered = on_disk.to_lowercase();
853 for needle in ["api_key", "authorization", "bearer", "password"] {
854 assert!(
855 !lowered.contains(&format!("\"{needle}\"")),
856 "cache must not persist `{needle}`"
857 );
858 }
859
860 clear_live_snapshot();
861 }
862
863 #[test]
864 fn bundled_staleness_flips_only_bundled_reports() {
865 let bundled = ModelsDevStatus::default();
866 assert_eq!(bundled.freshness, ModelsDevFreshness::Bundled);
867 assert_eq!(
868 honor_bundled_staleness(bundled.clone(), true).freshness,
869 ModelsDevFreshness::Stale
870 );
871 assert_eq!(
872 honor_bundled_staleness(bundled, false).freshness,
873 ModelsDevFreshness::Bundled
874 );
875 let live = ModelsDevStatus {
876 freshness: ModelsDevFreshness::Live,
877 ..ModelsDevStatus::default()
878 };
879 assert_eq!(
880 honor_bundled_staleness(live, true).freshness,
881 ModelsDevFreshness::Live
882 );
883 }
884
885 #[test]
886 fn invalid_json_keeps_bundled_and_marks_failed() {
887 let _lock = lock_test_env();
888 let _live = lock_live_snapshot();
889 clear_live_snapshot();
890 let dir = tempfile::tempdir().expect("tempdir");
891 let path = dir.path().join("bad.json");
892 std::fs::write(&path, "{not-json").expect("write");
893
894 let _home = EnvVarGuard::set("CODEWHALE_HOME", dir.path().join("home"));
895 let _path = EnvVarGuard::set(ENV_MODELS_DEV_PATH, &path);
896
897 let before = all_catalog_models_for_provider(ProviderKind::Together);
898 assert!(!before.is_empty(), "bundled Together rows required");
899
900 let rt = tokio::runtime::Builder::new_current_thread()
901 .enable_all()
902 .build()
903 .expect("runtime");
904 let err = rt.block_on(refresh(true)).expect_err("bad json");
905 assert!(matches!(err, ModelsDevRefreshError::InvalidResponse(_)));
906
907 let after = all_catalog_models_for_provider(ProviderKind::Together);
908 assert_eq!(after, before, "bundled rows must survive parse failure");
909 let st = status();
910 assert_eq!(st.freshness, ModelsDevFreshness::Failed);
911 assert!(st.last_error.is_some());
912 clear_live_snapshot();
913 }
914
915 #[test]
916 fn stale_disk_cache_still_publishes() {
917 let _lock = lock_test_env();
918 let _live = lock_live_snapshot();
919 clear_live_snapshot();
920 let dir = tempfile::tempdir().expect("tempdir");
921 let home = dir.path().join("home");
922 let _home = EnvVarGuard::set("CODEWHALE_HOME", &home);
923
924 let cache_dir = home.join("catalog");
925 std::fs::create_dir_all(&cache_dir).expect("mkdir");
926 let cache = cache_dir.join(CACHE_FILE);
927 let stale = PersistedModelsDevCache {
928 schema_version: CACHE_SCHEMA_VERSION,
929 fetched_at: 1, // far in the past → stale
930 source_fingerprint: current_source_fingerprint(),
931 source_label: "https://models.dev/catalog.json".into(),
932 body: FIXTURE.into(),
933 };
934 save_cache_file(&cache, &stale).expect("save");
935
936 maybe_load_persisted_cache();
937 let st = status();
938 assert_eq!(st.freshness, ModelsDevFreshness::Stale);
939 assert!(st.offering_count >= 2);
940 let together = all_catalog_models_for_provider(ProviderKind::Together);
941 assert!(together.iter().any(|m| m == "deepseek-ai/DeepSeek-V4-Pro"));
942 clear_live_snapshot();
943 }
944
945 #[test]
946 fn a_future_or_foreign_cache_is_never_live() {
947 let now = 2_000_000_000;
948 assert!(within_ttl(now - 60, now));
949 assert!(within_ttl(now + 30, now), "small skew is tolerated");
950 assert!(
951 !within_ttl(now + 3 * 24 * 60 * 60, now),
952 "a future timestamp is not age zero"
953 );
954 assert!(!within_ttl(now - DEFAULT_MODELS_DEV_TTL_SECS - 1, now));
955
956 let _lock = lock_test_env();
957 let _live = lock_live_snapshot();
958 clear_live_snapshot();
959 let dir = tempfile::tempdir().expect("tempdir");
960 let home = dir.path().join("home");
961 let _home = EnvVarGuard::set("CODEWHALE_HOME", &home);
962 let _path = EnvVarGuard::remove(ENV_MODELS_DEV_PATH);
963 let _url = EnvVarGuard::remove(ENV_MODELS_DEV_URL);
964 let cache_dir = home.join("catalog");
965 std::fs::create_dir_all(&cache_dir).expect("mkdir");
966 let cache = cache_dir.join(CACHE_FILE);
967
968 // Fresh by the clock, but fetched from another source.
969 let foreign = PersistedModelsDevCache {
970 schema_version: CACHE_SCHEMA_VERSION,
971 fetched_at: now_unix(),
972 source_fingerprint: base_url_fingerprint("https://mirror.example/catalog.json"),
973 source_label: "https://mirror.example/catalog.json".into(),
974 body: FIXTURE.into(),
975 };
976 save_cache_file(&cache, &foreign).expect("save");
977 maybe_load_persisted_cache();
978 assert_eq!(status().freshness, ModelsDevFreshness::Failed);
979
980 // From the current source, but stamped far in the future.
981 let future = PersistedModelsDevCache {
982 fetched_at: now_unix() + 30 * 24 * 60 * 60,
983 source_fingerprint: base_url_fingerprint(MODELS_DEV_CATALOG_URL),
984 source_label: MODELS_DEV_CATALOG_URL.into(),
985 ..foreign.clone()
986 };
987 save_cache_file(&cache, &future).expect("save");
988 maybe_load_persisted_cache();
989 assert_eq!(status().freshness, ModelsDevFreshness::Stale);
990
991 // The same cache stamped now is live.
992 let current = PersistedModelsDevCache {
993 fetched_at: now_unix(),
994 ..future
995 };
996 save_cache_file(&cache, &current).expect("save");
997 maybe_load_persisted_cache();
998 assert_eq!(status().freshness, ModelsDevFreshness::Live);
999 clear_live_snapshot();
1000 }
1001
1002 #[test]
1003 fn an_oversized_override_catalog_is_refused() {
1004 let dir = tempfile::tempdir().expect("tempdir");
1005 let path = dir.path().join("huge.json");
1006 let file = std::fs::File::create(&path).expect("create");
1007 file.set_len(MAX_CATALOG_BYTES as u64 + 1)
1008 .expect("sparse size");
1009 let rt = tokio::runtime::Builder::new_current_thread()
1010 .enable_all()
1011 .build()
1012 .expect("runtime");
1013 let error = rt
1014 .block_on(read_catalog_file(&path))
1015 .expect_err("oversized catalog must be refused");
1016 assert!(error.to_string().contains("exceeds"), "{error}");
1017 }
1018
1019 #[test]
1020 fn network_failure_keeps_prior_rows_and_marks_failed() {
1021 let _lock = lock_test_env();
1022 let _live = lock_live_snapshot();
1023 clear_live_snapshot();
1024 let dir = tempfile::tempdir().expect("tempdir");
1025 let path = dir.path().join("catalog.json");
1026 std::fs::write(&path, FIXTURE).expect("write");
1027
1028 let _home = EnvVarGuard::set("CODEWHALE_HOME", dir.path().join("home"));
1029 let _path = EnvVarGuard::set(ENV_MODELS_DEV_PATH, &path);
1030
1031 let rt = tokio::runtime::Builder::new_current_thread()
1032 .enable_all()
1033 .build()
1034 .expect("runtime");
1035 let count = rt.block_on(refresh(true)).expect("seed from path");
1036 assert!(count >= 2);
1037
1038 // Point at a dead URL and force network (clear path override).
1039 let _path = EnvVarGuard::remove(ENV_MODELS_DEV_PATH);
1040 let _disable = EnvVarGuard::remove(ENV_DISABLE_FETCH);
1041 let _url = EnvVarGuard::set(ENV_MODELS_DEV_URL, "http://127.0.0.1:1");
1042
1043 let err = rt.block_on(refresh(true)).expect_err("dead URL");
1044 assert!(matches!(err, ModelsDevRefreshError::Network(_)));
1045
1046 let together = all_catalog_models_for_provider(ProviderKind::Together);
1047 assert!(
1048 together.iter().any(|m| m == "deepseek-ai/DeepSeek-V4-Pro"),
1049 "prior live rows must survive network failure"
1050 );
1051 let st = status();
1052 assert_eq!(st.freshness, ModelsDevFreshness::Failed);
1053 assert!(st.last_error.is_some());
1054 assert!(
1055 st.offering_count >= 2,
1056 "status should retain prior live row count after failure"
1057 );
1058 clear_live_snapshot();
1059 }
1060
1061 #[test]
1062 fn background_fetch_respects_config_ci_and_do_not_track() {
1063 let _lock = lock_test_env();
1064 let _disable = EnvVarGuard::remove(ENV_DISABLE_FETCH);
1065 let _ci = EnvVarGuard::remove("CI");
1066 let _gha = EnvVarGuard::remove("GITHUB_ACTIONS");
1067 let _gl = EnvVarGuard::remove("GITLAB_CI");
1068 let _dnt = EnvVarGuard::remove("DO_NOT_TRACK");
1069
1070 assert!(!background_fetch_disabled(true));
1071 assert!(background_fetch_disabled(false));
1072
1073 {
1074 let _ci_on = EnvVarGuard::set("CI", "true");
1075 assert!(background_fetch_disabled(true));
1076 }
1077 {
1078 let _dnt_on = EnvVarGuard::set("DO_NOT_TRACK", "1");
1079 assert!(background_fetch_disabled(true));
1080 }
1081 {
1082 let _dnt_off = EnvVarGuard::set("DO_NOT_TRACK", "0");
1083 assert!(!background_fetch_disabled(true));
1084 }
1085 }
1086 }
1087
1087 lines RUST