rigspark-runtime 3.1.0

Hardware detection, backend adapters, lifecycle, memory and harness runtime for rigspark.
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
use crate::catalog_update::MAX_ARTIFACT_BYTES;
use rigspark_core::catalog::{Catalog, CatalogModel};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use thiserror::Error;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};

pub const MINIMUM_PERCENT: usize = 90;
pub const EVIDENCE_MAX_AGE_DAYS: i64 = 7;

#[derive(Debug, Error)]
#[error("invalid catalog quality evidence: {0}")]
pub struct QualityError(pub &'static str);

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Evidence {
    policy_version: u8,
    scopes: Vec<Scope>,
    observations: Vec<Observation>,
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Scope {
    name: String,
    checked_at: String,
    source: String,
    complete: bool,
    variants: Vec<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Observation {
    id: String,
    checked_at: String,
    sources: Vec<String>,
    /// A full observed model, or `facts` for the subset the collector could source.
    #[serde(default)]
    model: Option<CatalogModel>,
    #[serde(default)]
    facts: Option<BTreeMap<String, serde_json::Value>>,
}

/// Facts a partial observation may assert, each compared in the catalog's own representation.
pub const PARTIAL_FACTS: [&str; 6] = [
    "activeParams",
    "architecture",
    "contextLength",
    "defaultQuantization",
    "kvBytesPerToken",
    "license",
];

fn catalog_fact(model: &CatalogModel, field: &str) -> Result<serde_json::Value, QualityError> {
    let value = serde_json::to_value(model).map_err(|_| QualityError("invalid model facts"))?;
    Ok(if field == "defaultQuantization" {
        let index = rigspark_core::registry_collector::pulled_quantization(model).unwrap_or(0);
        facts(model)?["quantizations"][index].clone()
    } else {
        value.get(field).cloned().unwrap_or(serde_json::Value::Null)
    })
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EntryResult {
    id: String,
    checked_at: Option<String>,
    sources: Vec<String>,
    fresh: bool,
    verified: bool,
    reason: &'static str,
    /// Facts a partial observation verified; absent when the whole entry was observed.
    #[serde(skip_serializing_if = "Option::is_none")]
    checked_fields: Option<Vec<String>>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QualityReport {
    pub policy_version: u8,
    pub evaluated_at: String,
    pub catalog_sha256: String,
    pub evidence_sha256: String,
    pub minimum_percent: usize,
    pub evidence_max_age_days: i64,
    pub catalog_entries: usize,
    pub fresh_entries: usize,
    pub verified_entries: usize,
    pub eligible_variants: usize,
    pub covered_variants: usize,
    pub coverage_percent: Option<f64>,
    pub recency_percent: f64,
    pub freshness_percent: Option<f64>,
    pub correctness_percent: f64,
    pub passed: bool,
    pub blockers: Vec<String>,
    pub missing_variants: Vec<String>,
    pub scopes: Vec<Scope>,
    pub entries: Vec<EntryResult>,
}

fn recent(raw: &str, now: OffsetDateTime) -> Result<bool, QualityError> {
    let checked =
        OffsetDateTime::parse(raw, &Rfc3339).map_err(|_| QualityError("invalid timestamp"))?;
    if checked > now {
        return Err(QualityError("future verification date"));
    }
    Ok(now - checked <= time::Duration::days(EVIDENCE_MAX_AGE_DAYS))
}

/// Whether evidence checked at `checked_at` is still within the gate's freshness window at `now`.
pub fn evidence_fresh(checked_at: &str, now: &str) -> bool {
    OffsetDateTime::parse(now, &Rfc3339).is_ok_and(|now| recent(checked_at, now).unwrap_or(false))
}

fn source_url(raw: &str) -> bool {
    url::Url::parse(raw).is_ok_and(|url| {
        url.scheme() == "https"
            && url.host_str().is_some()
            && url.username().is_empty()
            && url.password().is_none()
            && url.port_or_known_default() == Some(443)
            && url.query().is_none()
            && url.fragment().is_none()
    })
}

fn facts(model: &CatalogModel) -> Result<serde_json::Value, QualityError> {
    let mut value = serde_json::to_value(model).map_err(|_| QualityError("invalid model facts"))?;
    for quant in value["quantizations"].as_array_mut().unwrap() {
        for field in ["minRamBytes", "minVramBytes", "digestVerified"] {
            quant.as_object_mut().unwrap().remove(field);
        }
    }
    Ok(value)
}

fn citations_match(observation: &Observation, model: &CatalogModel) -> bool {
    if observation.model.is_none() {
        // Partial observations read only Ollama; they must cite exactly those reads.
        return partial_citations_match(observation, model);
    }
    let source = &observation.model.as_ref().unwrap_or(model).source;
    let cites_repo = |repo: &str| {
        let root = format!("https://huggingface.co/{repo}");
        observation
            .sources
            .iter()
            .any(|url| url == &root || url.starts_with(&format!("{root}/")))
    };
    if source.hf.as_deref().is_some_and(|repo| !cites_repo(repo))
        || source
            .gguf
            .as_ref()
            .is_some_and(|gguf| !cites_repo(&gguf.repo))
        || source
            .mlx
            .as_ref()
            .is_some_and(|mlx| !cites_repo(&mlx.repo))
    {
        return false;
    }
    if let Some(reference) = &source.ollama {
        let (repo, tag) = rigspark_core::registry_collector::parse_reference(reference);
        let repo = if repo.contains('/') {
            repo.to_string()
        } else {
            format!("library/{repo}")
        };
        let manifest = format!("https://registry.ollama.ai/v2/{repo}/manifests/{tag}");
        if !observation.sources.contains(&manifest) {
            return false;
        }
        if source.hf.is_none() {
            let page = format!("https://ollama.com/{repo}:{tag}");
            if !observation.sources.contains(&page) {
                return false;
            }
        }
    }
    source.hf.is_some() || source.ollama.is_some() || source.gguf.is_some() || source.mlx.is_some()
}

fn partial_citations_match(observation: &Observation, model: &CatalogModel) -> bool {
    let Some(reference) = &model.source.ollama else {
        return false;
    };
    let (repo, tag) = rigspark_core::registry_collector::parse_reference(reference);
    let repo = if repo.contains('/') {
        repo.to_string()
    } else {
        format!("library/{repo}")
    };
    observation.sources.contains(&format!(
        "https://registry.ollama.ai/v2/{repo}/manifests/{tag}"
    )) && observation
        .sources
        .contains(&format!("https://ollama.com/{repo}:{tag}"))
}

fn matches_facts(model: &CatalogModel, observed: &CatalogModel) -> Result<bool, QualityError> {
    let mut observed = observed.clone();
    if model.kv_bytes_per_token.is_none() {
        observed.kv_bytes_per_token = None;
    }
    if model.benchmark_proxy.is_none() {
        observed.benchmark_proxy = None;
    }
    Ok(facts(model)? == facts(&observed)?)
}

fn pinned(model: &CatalogModel) -> bool {
    if model.source.ollama.is_some() {
        model
            .quantizations
            .iter()
            .all(|quant| quant.sha256.is_some())
    } else {
        model.source.gguf.is_some() || model.source.mlx.is_some()
    }
}

fn percent(numerator: usize, denominator: usize) -> f64 {
    if denominator == 0 {
        0.0
    } else {
        numerator as f64 * 100.0 / denominator as f64
    }
}

pub fn evaluate(
    catalog_raw: &str,
    evidence_raw: &str,
    now: &str,
) -> Result<QualityReport, QualityError> {
    if catalog_raw.len() > MAX_ARTIFACT_BYTES || evidence_raw.len() > MAX_ARTIFACT_BYTES {
        return Err(QualityError("input exceeds 16 MiB"));
    }
    let catalog = Catalog::parse(catalog_raw).map_err(|_| QualityError("catalog schema"))?;
    if catalog.models.is_empty() {
        return Err(QualityError("empty catalog"));
    }
    let evidence: Evidence = rigspark_core::catalog::parse_document(evidence_raw)
        .map_err(|_| QualityError("evidence schema"))?;
    if evidence.policy_version != 1
        || evidence.scopes.len() > 32
        || evidence.observations.len() > 10000
    {
        return Err(QualityError("unsupported policy or collection limit"));
    }
    let clock =
        OffsetDateTime::parse(now, &Rfc3339).map_err(|_| QualityError("evaluation date"))?;
    recent(&catalog.generated_at, clock)?;
    let mut blockers = Vec::new();
    let mut inventory = BTreeSet::new();
    let mut names = BTreeSet::new();
    let mut inventory_known = !evidence.scopes.is_empty();
    for scope in &evidence.scopes {
        if scope.name.is_empty()
            || !names.insert(scope.name.clone())
            || !source_url(&scope.source)
            || scope.variants.len() > 10000
        {
            return Err(QualityError("invalid coverage scope"));
        }
        if !recent(&scope.checked_at, clock)? || !scope.complete || scope.variants.is_empty() {
            inventory_known = false;
        }
        for variant in &scope.variants {
            if variant.is_empty()
                || variant.len() > 256
                || variant.chars().any(char::is_control)
                || !inventory.insert(variant.clone())
            {
                return Err(QualityError("duplicate or invalid inventory variant"));
            }
        }
    }
    if !names.contains("ollama-local-variants") {
        inventory_known = false;
    }
    if !inventory_known {
        blockers.push(
            "Upstream variant inventory is missing, incomplete, empty, or older than 7 days."
                .into(),
        );
    }
    let models: BTreeMap<_, _> = catalog
        .models
        .iter()
        .map(|model| (model.id.as_str(), model))
        .collect();
    let mut observations = BTreeMap::new();
    for observation in &evidence.observations {
        let Some(model) = models.get(observation.id.as_str()) else {
            return Err(QualityError("duplicate, unbound, or uncited observation"));
        };
        match (&observation.model, &observation.facts) {
            (Some(observed), None) => {
                if observed.id != observation.id {
                    return Err(QualityError("duplicate, unbound, or uncited observation"));
                }
                let observed_catalog = serde_json::json!({"schemaVersion":rigspark_core::catalog::SCHEMA_VERSION,"generatedAt":observation.checked_at,"models":[observed]});
                Catalog::parse(&observed_catalog.to_string())
                    .map_err(|_| QualityError("observed model facts"))?;
            }
            (None, Some(facts)) => {
                // Partial verification always includes artifact integrity.
                if !facts.contains_key("defaultQuantization")
                    || !facts
                        .keys()
                        .all(|key| PARTIAL_FACTS.contains(&key.as_str()))
                {
                    return Err(QualityError(
                        "partial observation asserts unsupported facts",
                    ));
                }
            }
            _ => {
                return Err(QualityError(
                    "observation needs exactly one of model or facts",
                ));
            }
        }
        if observations
            .insert(observation.id.as_str(), observation)
            .is_some()
            || observation.sources.is_empty()
            || observation.sources.len() > 16
            || !observation.sources.iter().all(|source| source_url(source))
            || !citations_match(observation, model)
        {
            return Err(QualityError("duplicate, unbound, or uncited observation"));
        }
        recent(&observation.checked_at, clock)?;
    }
    let mut entries = Vec::new();
    let mut fresh_entries = 0;
    let mut verified_entries = 0;
    for model in &catalog.models {
        let mut entry = EntryResult {
            id: model.id.clone(),
            checked_at: None,
            sources: Vec::new(),
            fresh: false,
            verified: false,
            reason: "missing evidence",
            checked_fields: None,
        };
        if inventory_known && !inventory.contains(&model.id) {
            blockers.push(format!(
                "{}: catalog entry excluded from declared coverage scope",
                model.id
            ));
        }
        if let Some(observation) = observations.get(model.id.as_str()) {
            entry.checked_at = Some(observation.checked_at.clone());
            entry.sources = observation.sources.clone();
            entry.fresh = recent(&observation.checked_at, clock)?;
            let agrees = match (&observation.model, &observation.facts) {
                (Some(observed), _) => matches_facts(model, observed)?,
                (None, Some(facts)) => {
                    entry.checked_fields = Some(facts.keys().cloned().collect());
                    let mut agrees = true;
                    for (field, value) in facts {
                        agrees &= catalog_fact(model, field)? == *value;
                    }
                    agrees
                }
                (None, None) => false,
            };
            if !agrees {
                entry.reason = "authoritative facts contradict catalog";
                blockers.push(format!(
                    "{}: authoritative facts contradict catalog",
                    model.id
                ));
            } else if !pinned(model) {
                entry.reason = "required artifact integrity evidence missing";
            } else if !entry.fresh {
                entry.reason = "verification evidence older than 7 days";
            } else {
                entry.verified = true;
                entry.reason = "verified";
            }
        }
        fresh_entries += usize::from(entry.fresh);
        verified_entries += usize::from(entry.verified);
        entries.push(entry);
    }
    let missing_variants: Vec<_> = inventory
        .iter()
        .filter(|id| !models.contains_key(id.as_str()))
        .cloned()
        .collect();
    let covered_variants = inventory.len() - missing_variants.len();
    let coverage_percent = inventory_known.then(|| percent(covered_variants, inventory.len()));
    let recency_percent = percent(fresh_entries, catalog.models.len());
    let freshness_percent = coverage_percent.map(|coverage| coverage.min(recency_percent));
    let correctness_percent = percent(verified_entries, catalog.models.len());
    let passed = blockers.is_empty()
        && inventory_known
        && covered_variants * 100 >= inventory.len() * MINIMUM_PERCENT
        && fresh_entries * 100 >= catalog.models.len() * MINIMUM_PERCENT
        && verified_entries * 100 >= catalog.models.len() * MINIMUM_PERCENT;
    Ok(QualityReport {
        policy_version: 1,
        evaluated_at: now.into(),
        catalog_sha256: format!("{:x}", Sha256::digest(catalog_raw.as_bytes())),
        evidence_sha256: format!("{:x}", Sha256::digest(evidence_raw.as_bytes())),
        minimum_percent: MINIMUM_PERCENT,
        evidence_max_age_days: EVIDENCE_MAX_AGE_DAYS,
        catalog_entries: catalog.models.len(),
        fresh_entries,
        verified_entries,
        eligible_variants: inventory.len(),
        covered_variants,
        coverage_percent,
        recency_percent,
        freshness_percent,
        correctness_percent,
        passed,
        blockers,
        missing_variants,
        scopes: evidence.scopes,
        entries,
    })
}

pub fn sign_reviewed_catalog(
    payload: crate::catalog_update::CatalogPayload,
    evidence: &str,
    seed: &[u8; 32],
    public_key: &[u8; 32],
) -> Result<(Vec<u8>, Vec<u8>), QualityError> {
    use crate::catalog_update::{SignedCatalog, sign_catalog};
    use ed25519_dalek::{Signer, SigningKey};
    let report = evaluate(&payload.catalog, evidence, &payload.published_at)?;
    if !report.passed {
        return Err(QualityError(
            "both scores must be at least 90% with no hard blockers",
        ));
    }
    let revision = payload.revision;
    let artifact = sign_catalog(payload, seed, public_key)
        .map_err(|_| QualityError("catalog signing failed"))?;
    let report_payload = serde_json::json!({
        "reportType":"rigspark-catalog-quality", "reportVersion":1,
        "revision":revision, "catalogArtifactSha256":format!("{:x}", Sha256::digest(&artifact)),
        "quality":report, "evidence":evidence
    })
    .to_string();
    let signature = SigningKey::from_bytes(seed)
        .sign(report_payload.as_bytes())
        .to_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect();
    let quality = serde_json::to_vec(&SignedCatalog {
        payload: report_payload,
        signature,
    })
    .map_err(|_| QualityError("report encoding"))?;
    if quality.len() > MAX_ARTIFACT_BYTES {
        return Err(QualityError("signed quality report exceeds 16 MiB"));
    }
    Ok((artifact, quality))
}