harn-vm 0.9.19

Async bytecode virtual machine for the Harn programming language
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
use std::collections::{BTreeMap, BTreeSet};

use super::*;

pub fn validate_artifact(artifact: &ProviderCatalogArtifact) -> ProviderCatalogValidation {
    let mut result = ProviderCatalogValidation::default();
    if artifact.schema_version != PROVIDER_CATALOG_SCHEMA_VERSION {
        result.errors.push(format!(
            "schema_version must be {}, got {}",
            PROVIDER_CATALOG_SCHEMA_VERSION, artifact.schema_version
        ));
    }
    if artifact.providers.is_empty() {
        result.errors.push("catalog has no providers".to_string());
    }
    if artifact.models.is_empty() {
        result.errors.push("catalog has no models".to_string());
    }

    let provider_ids: BTreeSet<_> = artifact.providers.iter().map(|p| p.id.as_str()).collect();
    for provider in &artifact.providers {
        if provider.id.trim().is_empty() {
            result
                .errors
                .push("provider id cannot be empty".to_string());
        }
        if provider.display_name.trim().is_empty() {
            result.errors.push(format!(
                "provider {} display_name cannot be empty",
                provider.id
            ));
        }
        if provider.endpoint.chat_endpoint.trim().is_empty() {
            result.errors.push(format!(
                "provider {} chat_endpoint cannot be empty",
                provider.id
            ));
        }
        if provider.auth.required
            && provider.auth.env.is_empty()
            && provider.auth.style != "aws_sigv4"
        {
            result.errors.push(format!(
                "provider {} requires auth but declares no auth env keys",
                provider.id
            ));
        }
        if let Some(rate_limits) = &provider.rate_limits {
            validate_rate_limits(
                &format!("provider {}", provider.id),
                rate_limits,
                &mut result,
            );
        }
        if let Some(performance) = &provider.performance {
            validate_performance(
                &format!("provider {}", provider.id),
                performance,
                &mut result,
            );
        }
        validate_extra_headers(provider, &mut result);
        if let Some(healthcheck) = &provider.healthcheck {
            validate_provider_healthcheck(provider, healthcheck, &mut result);
        }
        if let Some(local_runtime) = &provider.local_runtime {
            validate_local_runtime(&provider.id, local_runtime, &mut result);
        }
    }

    let mut alias_names = BTreeSet::new();
    for alias in &artifact.aliases {
        if alias.name.trim().is_empty() {
            result.errors.push("alias name cannot be empty".to_string());
        }
        if !alias_names.insert(alias.name.as_str()) {
            result
                .errors
                .push(format!("duplicate alias name {}", alias.name));
        }
        if !provider_ids.contains(alias.provider.as_str()) {
            result.errors.push(format!(
                "alias {} references unknown provider {}",
                alias.name, alias.provider
            ));
        }
    }

    let mut model_ids = BTreeSet::new();
    let mut model_pairs = BTreeSet::new();
    let mut dispatch_pairs = BTreeSet::new();
    for model in &artifact.models {
        if !model_ids.insert(model.id.as_str()) {
            result
                .errors
                .push(format!("duplicate model id {}", model.id));
        }
        model_pairs.insert((model.provider.as_str(), model.id.as_str()));
        if model.deprecation.status == DeprecationStatus::Active {
            dispatch_pairs.insert((
                model.provider.clone(),
                model.wire_model.clone().unwrap_or_else(|| model.id.clone()),
            ));
        }
        if model.name.trim().is_empty() {
            result
                .errors
                .push(format!("model {} name cannot be empty", model.id));
        }
        if !provider_ids.contains(model.provider.as_str()) {
            result.errors.push(format!(
                "model {} references unknown provider {}",
                model.id, model.provider
            ));
        }
        validate_token_field(model, "family", &model.family, &mut result);
        validate_token_field(model, "lineage", &model.lineage, &mut result);
        for family in &model.complementary_with {
            validate_token_field(model, "complementary_with", family, &mut result);
        }
        for selector in &model.avoid_as_reviewer_for {
            validate_reviewer_selector(model, selector, &mut result);
        }
        if model.context_window == 0 {
            result.errors.push(format!(
                "model {} context_window must be positive",
                model.id
            ));
        }
        if let Some(pricing) = &model.pricing {
            validate_pricing(model, pricing, &mut result);
        }
        if let Some(rate_limits) = &model.rate_limits {
            validate_rate_limits(&format!("model {}", model.id), rate_limits, &mut result);
        }
        if let Some(performance) = &model.performance {
            validate_performance(&format!("model {}", model.id), performance, &mut result);
        }
        if let Some(architecture) = &model.architecture {
            validate_architecture(model, architecture, &mut result);
        }
        if let Some(memory) = &model.local_memory {
            validate_local_memory(model, memory, &mut result);
        }
        if model.deprecation.status == DeprecationStatus::Deprecated
            && model
                .deprecation
                .note
                .as_deref()
                .unwrap_or("")
                .trim()
                .is_empty()
        {
            result.errors.push(format!(
                "deprecated model {} must include deprecation.note",
                model.id
            ));
        }
        if let Some(fast) = &model.fast_mode {
            if let Some(pricing) = &fast.pricing {
                validate_pricing(model, pricing, &mut result);
            }
            if let Some(status) = fast.status.as_deref() {
                if !matches!(status, "ga" | "research_preview" | "deprecated") {
                    result.warnings.push(format!(
                        "model {} fast_mode.status {:?} is not one of ga|research_preview|deprecated",
                        model.id, status
                    ));
                }
            }
        }
        let has_batch_tag = model.capability_tags.iter().any(|tag| tag == "batch");
        match (&model.batch, has_batch_tag) {
            (Some(batch), true) => validate_batch_support(model, batch, &mut result),
            (Some(_), false) => result.errors.push(format!(
                "model {} declares batch support but capability_tags omits batch",
                model.id
            )),
            (None, true) => result.errors.push(format!(
                "model {} capability_tags includes batch but model.batch is missing",
                model.id
            )),
            (None, false) => {}
        }
    }

    let mut route_pairs = BTreeSet::new();
    for route in &artifact.routing_routes {
        if route.provider.trim().is_empty() {
            result
                .errors
                .push("routing route provider cannot be empty".to_string());
        }
        if route.model.trim().is_empty() {
            result
                .errors
                .push("routing route model cannot be empty".to_string());
        }
        if !provider_ids.contains(route.provider.as_str()) {
            result.errors.push(format!(
                "routing route {}:{} references unknown provider {}",
                route.provider, route.model, route.provider
            ));
        }
        if !route_pairs.insert((route.provider.as_str(), route.model.as_str())) {
            result.errors.push(format!(
                "duplicate routing route {}:{}",
                route.provider, route.model
            ));
        }
        if !dispatch_pairs.contains(&(route.provider.clone(), route.model.clone())) {
            result.errors.push(format!(
                "routing route {}:{} does not match an active catalog model wire route",
                route.provider, route.model
            ));
        }
        if let Some(timeout_ms) = route.timeout_ms {
            if timeout_ms == 0 {
                result.errors.push(format!(
                    "routing route {}:{} timeout_ms must be positive",
                    route.provider, route.model
                ));
            }
        }
        if let Some(family) = route.family.as_deref() {
            validate_route_token(&route.provider, &route.model, "family", family, &mut result);
        }
        for capability in &route.capabilities {
            if capability.trim().is_empty() {
                result.errors.push(format!(
                    "routing route {}:{} capability cannot be empty",
                    route.provider, route.model
                ));
            }
        }
    }

    // Structured supersession pointers must reference a real catalog row so
    // `superseded_by` can be trusted as a migration target by downstream
    // tooling. A dangling pointer is a soft warning (the row is still
    // usable) rather than a hard error, mirroring how `note` is advisory.
    for model in &artifact.models {
        if let Some(target) = model.deprecation.superseded_by.as_deref() {
            if !model_ids.contains(target) {
                result.warnings.push(format!(
                    "model {} declares superseded_by {} with no matching catalog row",
                    model.id, target
                ));
            }
        }
    }

    // Tier is a CAPABILITY of the logical model, not of who hosts it. The
    // model-agnostic routing/escalation layer reads `tier` to decide
    // "already capable, do not escalate" vs "escalate me" — so if the same
    // weights are tiered `frontier` on one provider row and `mid` on another,
    // the identical model gets different escalation eligibility purely by host.
    // Enforce one tier per `equivalence_group` at catalog-build time so the
    // divergence cannot be reintroduced silently. Deprecated rows are excluded
    // (a superseded row may legitimately keep a stale tier until removed).
    {
        let mut tiers_by_group: BTreeMap<&str, BTreeMap<&str, BTreeSet<&str>>> = BTreeMap::new();
        for model in &artifact.models {
            if model.deprecation.status == DeprecationStatus::Deprecated {
                continue;
            }
            let Some(group) = model.equivalence_group.as_deref() else {
                continue;
            };
            if group.trim().is_empty() {
                continue;
            }
            tiers_by_group
                .entry(group)
                .or_default()
                .entry(model.tier.as_str())
                .or_default()
                .insert(model.id.as_str());
        }
        for (group, tiers) in &tiers_by_group {
            if tiers.len() > 1 {
                let detail = tiers
                    .iter()
                    .map(|(tier, ids)| {
                        format!(
                            "{tier} ({})",
                            ids.iter().copied().collect::<Vec<_>>().join(", ")
                        )
                    })
                    .collect::<Vec<_>>()
                    .join("; ");
                result.errors.push(format!(
                    "equivalence_group {group} declares conflicting tiers across its \
                     provider rows: {detail}. tier is a capability of the logical model — \
                     give every active row in the group the same tier (the conservative \
                     least-capable host baseline), not a per-provider value."
                ));
            }
        }
    }

    // GAMING GUARD (L3): within an equivalence_group, a LOCAL-runtime host row
    // must not be decorated with MORE strengths than the least-decorated host in
    // the group. `strengths` feeds the routing layer's "already capable, do not
    // escalate" verdict (a local route claiming "agentic" reads as capable and
    // SUPPRESSES a needed escalation). If a local route inherited a decorated
    // cloud row's strengths it would gain capability it never earned on the
    // local serving stack and inflate apparent local convergence — so a local
    // row's strengths must be a SUBSET of every co-grouped row's strengths (the
    // conservative weights-intrinsic baseline), never a superset. Providers with
    // a `local_runtime` descriptor are the local hosts; this is data-driven, not
    // a hardcoded name list. Deprecated rows are excluded.
    {
        let local_provider_ids: BTreeSet<&str> = artifact
            .providers
            .iter()
            .filter(|p| p.local_runtime.is_some())
            .map(|p| p.id.as_str())
            .collect();
        // Group active rows by equivalence_group, keeping each row's strengths.
        let mut rows_by_group: BTreeMap<&str, Vec<&CatalogModel>> = BTreeMap::new();
        for model in &artifact.models {
            if model.deprecation.status == DeprecationStatus::Deprecated {
                continue;
            }
            let Some(group) = model.equivalence_group.as_deref() else {
                continue;
            };
            if group.trim().is_empty() {
                continue;
            }
            rows_by_group.entry(group).or_default().push(model);
        }
        for (group, rows) in &rows_by_group {
            // The group's conservative baseline is the intersection of every
            // row's strengths — what holds for the weights regardless of host.
            let mut baseline: Option<BTreeSet<&str>> = None;
            for model in rows {
                let row: BTreeSet<&str> = model.strengths.iter().map(String::as_str).collect();
                baseline = Some(match baseline {
                    None => row,
                    Some(acc) => acc.intersection(&row).copied().collect(),
                });
            }
            let baseline = baseline.unwrap_or_default();
            for model in rows {
                if !local_provider_ids.contains(model.provider.as_str()) {
                    continue;
                }
                let row: BTreeSet<&str> = model.strengths.iter().map(String::as_str).collect();
                let extras: Vec<&str> = row.difference(&baseline).copied().collect();
                if !extras.is_empty() {
                    result.errors.push(format!(
                        "local-runtime row {}/{} in equivalence_group {group} claims strengths \
                         [{}] beyond the group's conservative baseline [{}]. A local route must \
                         not inherit a cloud peer's decoration — strengths must be the \
                         least-capable host baseline (a subset of every co-grouped row), or the \
                         local route reads as already-capable and suppresses real escalations.",
                        model.provider,
                        model.id,
                        extras.join(", "),
                        baseline.iter().copied().collect::<Vec<_>>().join(", "),
                    ));
                }
            }
        }
    }

    // Index models by (provider, id) so alias tool_format can be checked
    // against the target model's declared tool support. An alias is the one
    // place a harness author can pin `native` / `text` per model, so a typo
    // or a format the model can't serve must be caught at catalog-build time
    // rather than silently degrading at call time.
    let model_by_pair: BTreeMap<(&str, &str), &CatalogModel> = artifact
        .models
        .iter()
        .map(|model| ((model.provider.as_str(), model.id.as_str()), model))
        .collect();

    let dedicated_pairs: BTreeSet<(&str, &str)> = artifact
        .models
        .iter()
        .filter(|model| model.availability == ModelAvailabilityStatus::Dedicated)
        .map(|model| (model.provider.as_str(), model.id.as_str()))
        .collect();
    for alias in &artifact.aliases {
        if !model_pairs.contains(&(alias.provider.as_str(), alias.model_id.as_str())) {
            result.errors.push(format!(
                "alias {} targets {}/{} without a catalog row",
                alias.name, alias.provider, alias.model_id
            ));
        }
        if let Some(format) = alias.tool_format.as_deref() {
            // `json` (fenced-JSON) and `text` (tagged/heredoc) are both
            // TEXT-channel formats and validate against `tool_support.text`;
            // `native` validates against `tool_support.native`.
            if format != "native" && format != "text" && format != "json" {
                result.errors.push(format!(
                    "alias {} declares tool_format {:?}; must be \"native\", \"text\", or \"json\"",
                    alias.name, format
                ));
            } else if let Some(model) =
                model_by_pair.get(&(alias.provider.as_str(), alias.model_id.as_str()))
            {
                if format == "native" && !model.tool_support.native {
                    result.errors.push(format!(
                        "alias {} pins tool_format \"native\" but model {}/{} does not support native tool calling",
                        alias.name, alias.provider, alias.model_id
                    ));
                }
                if (format == "text" || format == "json") && !model.tool_support.text {
                    result.errors.push(format!(
                        "alias {} pins tool_format {:?} (a text-channel format) but model {}/{} does not support text tool calling",
                        alias.name, format, alias.provider, alias.model_id
                    ));
                }
            }
        }
        if is_tier_alias(&alias.name)
            && dedicated_pairs.contains(&(alias.provider.as_str(), alias.model_id.as_str()))
        {
            result.warnings.push(format!(
                "tier alias {} targets dedicated-only model {}/{}; serverless callers will fail until the dedicated endpoint is provisioned",
                alias.name, alias.provider, alias.model_id
            ));
        }
    }

    for variant in &artifact.variants {
        if variant.id.trim().is_empty() {
            result.errors.push("variant id cannot be empty".to_string());
        }
        if !provider_ids.contains(variant.provider.as_str()) {
            result.errors.push(format!(
                "variant {} references unknown provider {}",
                variant.id, variant.provider
            ));
        }
        if !model_pairs.contains(&(variant.provider.as_str(), variant.model_id.as_str())) {
            result.errors.push(format!(
                "variant {} targets {}/{} without a catalog row",
                variant.id, variant.provider, variant.model_id
            ));
        }
    }

    result
}

pub fn validate_current() -> ProviderCatalogValidation {
    validate_artifact(&artifact())
}