1use crate::sizing::{
2 Architecture, KvCacheType, Model, Quantization, ValidationError, typed_kv_bytes_per_token,
3};
4use regex::Regex;
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, HashSet};
7use time::{Date, OffsetDateTime, format_description::well_known::Rfc3339};
8
9pub const BACKENDS: [&str; 5] = ["ollama", "llamacpp", "mlx", "lmstudio", "bitnet"];
10pub const CAPABILITIES: [&str; 6] = ["chat", "code", "vision", "reasoning", "tools", "embedding"];
11pub const VENDORS: [&str; 5] = ["apple", "nvidia", "amd", "intel", "none"];
12pub(crate) const LICENSES: [&str; 18] = [
13 "apache-2.0",
14 "mit",
15 "modified-mit",
16 "bsd-3-clause",
17 "llama-2-community",
18 "llama-3-community",
19 "llama-3.1-community",
20 "llama-3.2-community",
21 "llama-3.3-community",
22 "gemma",
23 "qwen",
24 "qwen-research",
25 "tongyi-qianwen",
26 "deepseek",
27 "yi-license",
28 "cc-by-4.0",
29 "cc-by-sa-4.0",
30 "openrail",
31];
32
33pub fn require(ok: bool, message: &str) -> Result<(), ValidationError> {
34 if ok {
35 Ok(())
36 } else {
37 Err(ValidationError(message.into()))
38 }
39}
40fn matches(value: &str, pattern: &'static str) -> bool {
42 static COMPILED: std::sync::LazyLock<
43 std::sync::Mutex<std::collections::HashMap<&'static str, Option<Regex>>>,
44 > = std::sync::LazyLock::new(Default::default);
45 let Ok(mut compiled) = COMPILED.lock() else {
46 return Regex::new(pattern).is_ok_and(|regex| regex.is_match(value));
47 };
48 compiled
49 .entry(pattern)
50 .or_insert_with(|| Regex::new(pattern).ok())
51 .as_ref()
52 .is_some_and(|regex| regex.is_match(value))
53}
54pub(crate) fn parameter_label(value: &str) -> bool {
55 matches(value, r"^\d+(\.\d+)?[BMT]$")
56}
57fn integer(value: f64, minimum: f64) -> bool {
58 value.is_finite()
59 && value.fract() == 0.0
60 && value >= minimum
61 && value <= 9_007_199_254_740_991.0
62}
63fn nonempty(value: &str) -> Result<(), ValidationError> {
64 require(!value.is_empty(), "empty text field")
65}
66pub(crate) fn timestamp(value: &str) -> Result<(), ValidationError> {
67 require(
68 value.ends_with('Z') && OffsetDateTime::parse(value, &Rfc3339).is_ok(),
69 "invalid generatedAt timestamp",
70 )
71}
72pub fn date(value: &str) -> Result<Date, ValidationError> {
73 Date::parse(
74 value,
75 time::macros::format_description!("[year]-[month]-[day]"),
76 )
77 .map_err(|_| ValidationError("invalid calendar date".into()))
78}
79fn no_nulls(value: &serde_json::Value) -> bool {
80 match value {
81 serde_json::Value::Null => false,
82 serde_json::Value::Array(values) => values.iter().all(no_nulls),
83 serde_json::Value::Object(values) => values.values().all(no_nulls),
84 _ => true,
85 }
86}
87pub fn parse_document<T: serde::de::DeserializeOwned>(raw: &str) -> Result<T, ValidationError> {
88 require(raw.len() <= 16 * 1024 * 1024, "dataset exceeds 16 MiB")?;
89 let value: serde_json::Value =
90 serde_json::from_str(raw).map_err(|error| ValidationError(error.to_string()))?;
91 require(no_nulls(&value), "null fields are not allowed")?;
92 serde_json::from_value(value).map_err(|error| ValidationError(error.to_string()))
93}
94
95#[derive(Debug, Clone, Deserialize, Serialize)]
96#[serde(rename_all = "camelCase", deny_unknown_fields)]
97pub struct GgufSource {
98 pub repo: String,
99 pub revision: String,
100 pub file: String,
101 pub sha256: String,
102}
103#[derive(Debug, Clone, Deserialize, Serialize)]
104#[serde(deny_unknown_fields)]
105pub struct MlxFile {
106 pub file: String,
107 pub sha256: String,
108 pub bytes: f64,
109}
110#[derive(Debug, Clone, Deserialize, Serialize)]
111#[serde(deny_unknown_fields)]
112pub struct MlxSource {
113 pub repo: String,
114 pub revision: String,
115 pub files: Vec<MlxFile>,
116}
117#[derive(Debug, Clone, Default, Deserialize, Serialize)]
118#[serde(deny_unknown_fields)]
119pub struct Source {
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub ollama: Option<String>,
122 #[serde(skip_serializing_if = "Option::is_none")]
123 pub hf: Option<String>,
124 #[serde(skip_serializing_if = "Option::is_none")]
125 pub gguf: Option<GgufSource>,
126 #[serde(skip_serializing_if = "Option::is_none")]
127 pub mlx: Option<MlxSource>,
128}
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
130#[serde(rename_all = "lowercase")]
131pub enum EntryProvenance {
132 #[default]
133 Curated,
134 Auto,
135 Local,
137}
138impl EntryProvenance {
139 pub(crate) fn is_curated(&self) -> bool {
140 matches!(self, Self::Curated)
141 }
142}
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
144#[serde(rename_all = "lowercase")]
145pub enum RecencyBasis {
146 Released,
147 Added,
148}
149pub const SCHEMA_VERSION: u8 = 4;
150pub fn required_schema_version(models: &[CatalogModel]) -> u8 {
153 if models.iter().any(|model| model.drafter.is_some()) {
154 4
155 } else {
156 3
157 }
158}
159#[derive(Debug, Clone, Deserialize, Serialize)]
160#[serde(rename_all = "camelCase", deny_unknown_fields)]
161pub struct CatalogModel {
162 pub id: String,
163 pub family: String,
164 pub params: String,
165 pub architecture: Architecture,
166 #[serde(skip_serializing_if = "Option::is_none")]
167 pub active_params: Option<String>,
168 pub license: String,
169 pub open_weight: bool,
170 pub context_length: f64,
171 pub capabilities: Vec<String>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub release_date: Option<String>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub added_at: Option<String>,
176 #[serde(default, skip_serializing_if = "EntryProvenance::is_curated")]
177 pub provenance: EntryProvenance,
178 pub source: Source,
179 pub quantizations: Vec<Quantization>,
180 #[serde(skip_serializing_if = "Option::is_none")]
181 pub kv_bytes_per_token: Option<f64>,
182 #[serde(skip_serializing_if = "Option::is_none")]
183 pub benchmark_proxy: Option<f64>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub drafter: Option<String>,
187}
188#[derive(Debug, Clone, Deserialize, Serialize)]
189#[serde(rename_all = "camelCase", deny_unknown_fields)]
190pub struct Catalog {
191 pub schema_version: u8,
192 pub generated_at: String,
193 pub models: Vec<CatalogModel>,
194}
195
196impl CatalogModel {
197 pub fn supports_backend(&self, backend: &str) -> bool {
198 if self.quantizations.iter().any(Quantization::is_bitnet) {
199 return backend == "bitnet"
200 && self.source.gguf.is_some()
201 && self.quantizations.len() == 1;
202 }
203 match backend {
204 "ollama" => self.source.ollama.is_some(),
205 "llamacpp" => self.source.gguf.is_some(),
206 "mlx" => self.source.mlx.is_some(),
207 "lmstudio" => self.source.gguf.is_some() || self.source.mlx.is_some(),
208 _ => false,
209 }
210 }
211}
212
213pub(crate) fn coordinates(repo: &str, revision: &str) -> Result<(), ValidationError> {
214 require(
215 repo.len() <= 200
216 && matches(
217 repo,
218 r"^[a-zA-Z0-9][a-zA-Z0-9._-]*/[a-zA-Z0-9][a-zA-Z0-9._-]*$",
219 ),
220 "invalid source repository",
221 )?;
222 require(
223 matches(revision, r"^[0-9a-fA-F]{40}$"),
224 "invalid pinned source revision",
225 )
226}
227pub(crate) fn model_file(file: &str, max: usize) -> Result<(), ValidationError> {
228 require(
229 !file.is_empty()
230 && file.len() <= max
231 && !file
232 .chars()
233 .any(|ch| ch.is_control() || "*?[]{}\\%".contains(ch))
234 && file
235 .split('/')
236 .all(|segment| !segment.is_empty() && segment != "." && segment != ".."),
237 "unsafe model file path",
238 )
239}
240pub(crate) fn digest(value: &str) -> Result<(), ValidationError> {
241 require(
242 matches(value, r"^[0-9a-fA-F]{64}$"),
243 "invalid SHA-256 digest",
244 )
245}
246
247pub fn recency<'a>(
249 release_date: Option<&'a str>,
250 added_at: Option<&'a str>,
251) -> Option<(&'a str, RecencyBasis)> {
252 release_date
253 .map(|day| (day, RecencyBasis::Released))
254 .or_else(|| added_at.map(|day| (day, RecencyBasis::Added)))
255}
256pub fn recency_label(recency: Option<(&str, RecencyBasis)>) -> String {
258 match recency {
259 Some((day, RecencyBasis::Released)) => day.to_string(),
260 Some((day, RecencyBasis::Added)) => format!("added {day}"),
261 None => "unknown".into(),
262 }
263}
264
265impl CatalogModel {
266 pub fn recency(&self) -> Option<(&str, RecencyBasis)> {
267 recency(self.release_date.as_deref(), self.added_at.as_deref())
268 }
269 pub fn recency_label(&self) -> String {
270 recency_label(self.recency())
271 }
272 pub fn sizing(&self) -> Model {
273 Model {
274 id: self.id.clone(),
275 params: self.params.clone(),
276 architecture: self.architecture.clone(),
277 context_length: self.context_length,
278 kv_bytes_per_token: self.kv_bytes_per_token,
279 quantizations: self.quantizations.clone(),
280 }
281 }
282 pub fn with_kv_cache(&self, kind: KvCacheType) -> Result<Self, ValidationError> {
284 let mut model = self.clone();
285 if let Some(rate) = self.kv_bytes_per_token {
286 model.kv_bytes_per_token =
287 Some(typed_kv_bytes_per_token(rate as u64, kind, kind)? as f64);
288 }
289 Ok(model)
290 }
291 pub(crate) fn validate(&self) -> Result<(), ValidationError> {
292 nonempty(&self.id)?;
293 nonempty(&self.family)?;
294 require(parameter_label(&self.params), "invalid parameter label")?;
295 require(
296 self.open_weight
297 && !self.license.is_empty()
298 && LICENSES.contains(&self.license.as_str()),
299 "catalog requires open-weight license",
300 )?;
301 require(
302 integer(self.context_length, 1.0)
303 && !self.capabilities.is_empty()
304 && self
305 .capabilities
306 .iter()
307 .all(|cap| CAPABILITIES.contains(&cap.as_str())),
308 "invalid context or capabilities",
309 )?;
310 if let Some(released) = &self.release_date {
311 date(released)?;
312 }
313 if let Some(added) = &self.added_at {
314 date(added)?;
315 }
316 match self.provenance {
317 EntryProvenance::Curated => require(
318 self.release_date.is_some(),
319 "curated entry needs releaseDate",
320 )?,
321 EntryProvenance::Local => require(
322 self.added_at.is_some()
323 && self.benchmark_proxy.is_none()
324 && self.source.gguf.is_some()
325 && self
326 .quantizations
327 .iter()
328 .all(|quant| quant.sha256.is_some()),
329 "local entry needs addedAt, a pinned GGUF artifact and no benchmarkProxy",
330 )?,
331 EntryProvenance::Auto => require(
333 self.added_at.is_some()
334 && self.benchmark_proxy.is_none()
335 && (self.source.ollama.is_some()
336 || self.source.gguf.is_some()
337 || self.source.mlx.is_some())
338 && self
339 .quantizations
340 .iter()
341 .all(|quant| quant.sha256.is_some()),
342 "auto entry needs addedAt, a pinned runtime artifact and no benchmarkProxy",
343 )?,
344 }
345 require(
346 matches!(self.architecture, Architecture::Moe) == self.active_params.is_some(),
347 "activeParams must exist only for MoE",
348 )?;
349 if let Some(active) = &self.active_params {
350 require(parameter_label(active), "invalid activeParams")?;
351 }
352 if let Some(rate) = self.kv_bytes_per_token {
353 require(integer(rate, 1.0), "invalid KV geometry")?;
354 }
355 if let Some(proxy) = self.benchmark_proxy {
356 require((0.0..=1.0).contains(&proxy), "invalid benchmark proxy")?;
357 }
358 require(
359 !self.quantizations.is_empty(),
360 "model must have quantizations",
361 )?;
362 for quant in &self.quantizations {
363 nonempty(&quant.name)?;
364 require(
365 integer(quant.disk_bytes, 1.0)
366 && integer(quant.min_ram_bytes, 1.0)
367 && integer(quant.min_vram_bytes, 0.0),
368 "invalid quantization sizes",
369 )?;
370 if let Some(sha) = &quant.sha256 {
371 digest(sha)?;
372 }
373 require(quant.projectors.len() <= 16, "too many projector artifacts")?;
374 let mut projector_digests = std::collections::HashSet::new();
375 let mut projector_bytes = 0_u64;
376 for projector in &quant.projectors {
377 digest(&projector.sha256)?;
378 require(
379 projector.bytes > 0
380 && projector.bytes <= 9_007_199_254_740_991
381 && projector_digests.insert(&projector.sha256),
382 "invalid projector artifact",
383 )?;
384 projector_bytes = projector_bytes
385 .checked_add(projector.bytes)
386 .ok_or_else(|| ValidationError("projector size overflow".into()))?;
387 }
388 require(
389 quant.projectors.is_empty()
390 || (self.source.ollama.is_some()
391 && quant.sha256.is_some()
392 && (projector_bytes as f64) < quant.disk_bytes),
393 "projector artifacts require pinned Ollama weights and aggregate size",
394 )?;
395 }
396 let source = &self.source;
397 require(
398 source.ollama.is_some()
399 || source.hf.is_some()
400 || source.gguf.is_some()
401 || source.mlx.is_some(),
402 "missing model source",
403 )?;
404 for text in [&source.ollama, &source.hf].into_iter().flatten() {
405 nonempty(text)?;
406 }
407 if let Some(gguf) = &source.gguf {
408 coordinates(&gguf.repo, &gguf.revision)?;
409 model_file(&gguf.file, 255)?;
410 digest(&gguf.sha256)?;
411 }
412 if let Some(mlx) = &source.mlx {
413 coordinates(&mlx.repo, &mlx.revision)?;
414 require(
415 (3..=256).contains(&mlx.files.len()) && self.quantizations.len() == 1,
416 "invalid MLX manifest cardinality",
417 )?;
418 let mut paths = HashSet::new();
419 let mut total = 0.0;
420 for file in &mlx.files {
421 model_file(&file.file, 512)?;
422 digest(&file.sha256)?;
423 require(
424 !matches(&file.file, r"(?i)\.(py|pyc|pyo|so|dylib|dll|bundle)$"),
425 "executable MLX file forbidden",
426 )?;
427 require(
428 integer(file.bytes, 1.0) && paths.insert(file.file.as_str()),
429 "invalid or duplicate MLX file",
430 )?;
431 total += file.bytes;
432 require(integer(total, 1.0), "MLX total overflows")?;
433 }
434 require(
435 paths.contains("config.json")
436 && paths.contains("tokenizer_config.json")
437 && paths.iter().any(|path| path.ends_with(".safetensors")),
438 "incomplete MLX manifest",
439 )?;
440 require(
441 total == self.quantizations[0].disk_bytes,
442 "MLX manifest size mismatch",
443 )?;
444 }
445 Ok(())
446 }
447}
448pub fn months_before(today: &str, months: u8) -> Result<Date, ValidationError> {
450 require(
451 (1..=3).contains(&months),
452 "recency window must be 1, 2 or 3 months",
453 )?;
454 let today = date(today)?;
455 let mut year = today.year();
456 let mut month = u8::from(today.month()) as i32 - i32::from(months);
457 if month < 1 {
458 month += 12;
459 year -= 1;
460 }
461 let month =
462 time::Month::try_from(month as u8).map_err(|_| ValidationError("invalid month".into()))?;
463 let day = today.day().min(month.length(year));
464 Date::from_calendar_date(year, month, day).map_err(|_| ValidationError("invalid date".into()))
465}
466
467impl Catalog {
468 pub fn retain_recent(&mut self, today: &str, months: u8) -> Result<(), ValidationError> {
470 let cutoff = months_before(today, months)?;
471 self.models.retain(|model| {
472 model
473 .recency()
474 .and_then(|(day, _)| date(day).ok())
475 .is_some_and(|day| day >= cutoff)
476 });
477 Ok(())
478 }
479 pub fn parse(raw: &str) -> Result<Self, ValidationError> {
480 Self::parse_as(raw, false)
481 }
482 pub fn parse_local(raw: &str) -> Result<Self, ValidationError> {
484 Self::parse_as(raw, true)
485 }
486 pub fn has_local(&self) -> bool {
488 self.models
489 .iter()
490 .any(|model| model.provenance == EntryProvenance::Local)
491 }
492 fn parse_as(raw: &str, local: bool) -> Result<Self, ValidationError> {
493 let mut result: Self = parse_document(raw)?;
494 require(
495 (2..=SCHEMA_VERSION).contains(&result.schema_version)
496 && (local || !result.models.is_empty()),
497 "unsupported or empty catalog",
498 )?;
499 require(
500 !local
501 || result
502 .models
503 .iter()
504 .all(|model| model.provenance == EntryProvenance::Local),
505 "the local catalog only holds models you added",
506 )?;
507 timestamp(&result.generated_at)?;
508 for model in &result.models {
509 require(
510 result.schema_version >= 3
511 || (model.provenance.is_curated() && model.added_at.is_none()),
512 "schema v2 catalogs cannot carry v3 fields",
513 )?;
514 model.validate()?;
515 }
516 for model in &mut result.models {
517 use crate::reports::strip_control;
518 model.id = strip_control(&model.id);
519 model.family = strip_control(&model.family);
520 for value in [&mut model.source.ollama, &mut model.source.hf]
521 .into_iter()
522 .flatten()
523 {
524 *value = strip_control(value);
525 }
526 if let Some(source) = &mut model.source.gguf {
527 source.file = strip_control(&source.file);
528 }
529 if let Some(source) = &mut model.source.mlx {
530 for file in &mut source.files {
531 file.file = strip_control(&file.file);
532 }
533 }
534 for quant in &mut model.quantizations {
535 quant.name = strip_control(&quant.name);
536 }
537 if let Some(drafter) = &mut model.drafter {
538 *drafter = strip_control(drafter);
539 }
540 }
541 let mut ids = HashSet::new();
542 for model in &result.models {
543 require(ids.insert(&model.id), "duplicate catalog model id")?;
544 }
545 for model in &result.models {
546 if model.drafter.is_none() {
547 continue;
548 }
549 require(
550 result.schema_version >= 4,
551 "drafters require catalog schema v4",
552 )?;
553 let draft = result
554 .drafter_of(model)
555 .ok_or_else(|| ValidationError("unknown or self-referencing drafter".into()))?;
556 require(
557 draft.family == model.family,
558 "drafter must share the target family",
559 )?;
560 require(
561 draft.drafter.is_none(),
562 "a drafter cannot itself have a drafter",
563 )?;
564 require(
565 draft.source.gguf.is_some() && model.source.gguf.is_some(),
566 "drafter and target need pinned GGUF artifacts",
567 )?;
568 }
569 Ok(result)
570 }
571 pub fn drafter_of(&self, model: &CatalogModel) -> Option<&CatalogModel> {
573 let id = model.drafter.as_deref()?;
574 (id != model.id)
575 .then(|| self.models.iter().find(|entry| entry.id == id))
576 .flatten()
577 }
578}
579
580#[derive(Debug, Clone, Deserialize, Serialize)]
581#[serde(rename_all = "camelCase", deny_unknown_fields)]
582pub struct Provenance {
583 pub value: f64,
584 pub trust_tier: String,
585 pub basis_bytes_per_token: f64,
586 pub url: String,
587}
588#[derive(Debug, Clone, Deserialize, Serialize)]
589#[serde(rename_all = "camelCase", deny_unknown_fields)]
590pub struct PerfSources {
591 pub bandwidth: String,
592 pub efficiency: String,
593 #[serde(skip_serializing_if = "Option::is_none")]
594 pub efficiency_by_backend: Option<BTreeMap<String, Provenance>>,
595}
596#[derive(Debug, Clone, Deserialize, Serialize)]
597#[serde(rename_all = "camelCase", deny_unknown_fields)]
598pub struct PerfClass {
599 pub id: String,
600 pub label: String,
601 pub vendor: String,
602 pub kind: String,
603 #[serde(rename = "memBandwidthGBps")]
604 pub mem_bandwidth_gbps: f64,
605 pub efficiency: f64,
606 #[serde(skip_serializing_if = "Option::is_none")]
607 pub efficiency_by_backend: Option<BTreeMap<String, f64>>,
608 pub min_bytes: f64,
609 pub max_bytes: f64,
610 pub sources: PerfSources,
611}
612#[derive(Debug, Clone, Deserialize, Serialize)]
613#[serde(rename_all = "camelCase", deny_unknown_fields)]
614pub struct PerfDataset {
615 pub schema_version: u8,
616 pub generated_at: String,
617 pub classes: Vec<PerfClass>,
618}
619impl PerfDataset {
620 pub fn parse(raw: &str) -> Result<Self, ValidationError> {
621 let mut result: Self = parse_document(raw)?;
622 require(
623 result.schema_version == 1 && !result.classes.is_empty(),
624 "unsupported or empty performance data",
625 )?;
626 timestamp(&result.generated_at)?;
627 for (index, class) in result.classes.iter().enumerate() {
628 require(
629 matches(&class.id, r"^[a-z0-9-]+$")
630 && !class.label.is_empty()
631 && VENDORS.contains(&class.vendor.as_str())
632 && ["discrete", "unified", "cpu"].contains(&class.kind.as_str()),
633 "invalid performance class",
634 )?;
635 require(
636 class.mem_bandwidth_gbps > 0.0
637 && class.efficiency > 0.0
638 && class.efficiency <= 1.0
639 && integer(class.min_bytes, 0.0)
640 && integer(class.max_bytes, 1.0)
641 && class.max_bytes > class.min_bytes,
642 "invalid performance figures",
643 )?;
644 nonempty(&class.sources.bandwidth)?;
645 nonempty(&class.sources.efficiency)?;
646 let scalars = class.efficiency_by_backend.clone().unwrap_or_default();
647 let provenance = class
648 .sources
649 .efficiency_by_backend
650 .clone()
651 .unwrap_or_default();
652 require(
653 scalars.keys().eq(provenance.keys()),
654 "efficiency provenance mismatch",
655 )?;
656 for (backend, scalar) in scalars {
657 let source = &provenance[&backend];
658 require(
659 BACKENDS.contains(&backend.as_str())
660 && scalar > 0.0
661 && scalar <= 1.0
662 && source.value == scalar
663 && ["session-verified", "spec-grade"].contains(&source.trust_tier.as_str())
664 && source.basis_bytes_per_token > 0.0
665 && url::Url::parse(&source.url).is_ok(),
666 "invalid efficiency provenance",
667 )?;
668 }
669 for prior in &result.classes[..index] {
670 require(prior.id != class.id, "duplicate performance id")?;
671 require(
672 prior.vendor != class.vendor
673 || prior.kind != class.kind
674 || prior.min_bytes >= class.max_bytes
675 || class.min_bytes >= prior.max_bytes,
676 "overlapping performance ranges",
677 )?;
678 }
679 }
680 for class in &mut result.classes {
681 use crate::reports::strip_control;
682 class.label = strip_control(&class.label);
683 class.sources.bandwidth = strip_control(&class.sources.bandwidth);
684 class.sources.efficiency = strip_control(&class.sources.efficiency);
685 if let Some(sources) = &mut class.sources.efficiency_by_backend {
686 for source in sources.values_mut() {
687 source.url = strip_control(&source.url);
688 }
689 }
690 }
691 Ok(result)
692 }
693}
694
695#[derive(Debug, Serialize)]
696pub struct ResolutionError {
697 pub code: &'static str,
698 pub message: String,
699 pub candidates: Vec<String>,
700}
701#[derive(Debug, Serialize)]
702pub struct Resolved<'a> {
703 pub model: &'a CatalogModel,
704 #[serde(skip_serializing_if = "Option::is_none")]
705 pub quant: Option<&'a Quantization>,
706}
707fn resolution_error(message: String, candidates: Vec<String>, validation: bool) -> ResolutionError {
708 ResolutionError {
709 code: if validation {
710 "VALIDATION_ERROR"
711 } else {
712 "MODEL_RESOLUTION_ERROR"
713 },
714 message,
715 candidates,
716 }
717}
718fn finalize(resolved: Resolved<'_>) -> Result<Resolved<'_>, ResolutionError> {
719 for id in [
720 Some(&resolved.model.id),
721 resolved.model.source.ollama.as_ref(),
722 ]
723 .into_iter()
724 .flatten()
725 {
726 if id.contains("..") || !matches(id, r"^[a-z0-9._:/][a-z0-9._:/-]*$") {
727 return Err(resolution_error(
728 "unsafe catalog model id".into(),
729 vec![],
730 true,
731 ));
732 }
733 }
734 Ok(resolved)
735}
736pub fn resolve<'a>(catalog: &'a Catalog, input: &str) -> Result<Resolved<'a>, ResolutionError> {
737 let query = input.trim().to_lowercase();
738 if query.is_empty() || query.contains("..") || !matches(&query, r"^[a-z0-9._:/-]+$") {
739 return Err(resolution_error("invalid model name".into(), vec![], true));
740 }
741 if let Some(model) = catalog
742 .models
743 .iter()
744 .find(|model| model.id.to_lowercase() == query)
745 {
746 return finalize(Resolved { model, quant: None });
747 }
748 let quant_matches: Vec<Resolved<'_>> = catalog
749 .models
750 .iter()
751 .flat_map(|model| {
752 model.quantizations.iter().filter_map(|quant| {
753 (format!("{}-{}", model.id, quant.name).to_lowercase() == query).then_some(
754 Resolved {
755 model,
756 quant: Some(quant),
757 },
758 )
759 })
760 })
761 .collect();
762 let family: Vec<Resolved<'_>> = catalog
763 .models
764 .iter()
765 .filter(|model| model.family.to_lowercase() == query)
766 .map(|model| Resolved { model, quant: None })
767 .collect();
768 let prefix: Vec<Resolved<'_>> = catalog
769 .models
770 .iter()
771 .filter(|model| {
772 model.id.to_lowercase().starts_with(&query)
773 || model.family.to_lowercase().starts_with(&query)
774 })
775 .map(|model| Resolved { model, quant: None })
776 .collect();
777 for mut tier in [quant_matches, family, prefix] {
778 if tier.len() == 1 {
779 return finalize(tier.remove(0));
780 }
781 if !tier.is_empty() {
782 let mut candidates: Vec<String> =
783 tier.iter().map(|entry| entry.model.id.clone()).collect();
784 candidates.sort();
785 return Err(resolution_error(
786 format!(
787 "\"{query}\" is ambiguous; candidates: {}",
788 candidates.join(", ")
789 ),
790 candidates,
791 false,
792 ));
793 }
794 }
795 Err(resolution_error(
796 format!("no model matches \"{query}\""),
797 vec![],
798 false,
799 ))
800}