provable_contracts/schema/
parser.rs1use std::path::Path;
2
3use crate::error::ContractError;
4use crate::schema::types::{Contract, ContractKind, KaizenRecord, CONTRACT_TOP_LEVEL_FIELDS};
5
6pub fn parse_contract(path: &Path) -> Result<Contract, ContractError> {
16 let content = std::fs::read_to_string(path)?;
17 parse_contract_str(&content)
18}
19
20const NON_CONTRACT_FILENAMES: [&str; 4] = [
34 "binding.yaml",
35 "binding.yml",
36 "external-corpora.yaml",
37 "ontology.yaml",
42];
43
44#[must_use]
53pub fn is_contract_yaml(path: &Path) -> bool {
54 if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
55 return false;
56 }
57 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
58 return false;
59 };
60 !name.starts_with('.') && !NON_CONTRACT_FILENAMES.contains(&name)
61}
62
63pub fn parse_contract_str(yaml: &str) -> Result<Contract, ContractError> {
81 let mut contract: Contract = serde_yaml::from_str(yaml)?;
82 contract.unknown_top_level_keys = unknown_top_level_keys(yaml);
83 contract.kind_declared = kind_is_declared(yaml);
84 contract.strict_yaml_error = strict_yaml_error(yaml);
85 contract.falsification_tests_declared = top_level_key_written(yaml, "falsification_tests");
86 contract.kaizen_record = kaizen_record(yaml, contract.kind())?;
87 Ok(contract)
88}
89
90fn kaizen_record(yaml: &str, kind: ContractKind) -> Result<Option<KaizenRecord>, ContractError> {
105 if kind != ContractKind::Kaizen {
106 return Ok(None);
107 }
108 Ok(Some(serde_yaml::from_str::<KaizenRecord>(yaml)?))
109}
110
111fn unknown_top_level_keys(yaml: &str) -> Vec<String> {
126 use serde::de::IgnoredAny;
127 use std::collections::BTreeMap;
128
129 let Ok(map) = serde_yaml::from_str::<BTreeMap<String, IgnoredAny>>(yaml) else {
130 return Vec::new();
131 };
132 map.into_keys()
133 .filter(|k| !CONTRACT_TOP_LEVEL_FIELDS.contains(&k.as_str()))
134 .collect()
135}
136
137fn kind_is_declared(yaml: &str) -> bool {
158 use serde::de::IgnoredAny;
159 use std::collections::BTreeMap;
160
161 #[derive(serde::Deserialize)]
162 struct KindProbe {
163 metadata: BTreeMap<String, IgnoredAny>,
164 }
165
166 serde_yaml::from_str::<KindProbe>(yaml).is_ok_and(|probe| probe.metadata.contains_key("kind"))
167}
168
169fn top_level_key_written(yaml: &str, key: &str) -> bool {
176 use serde::de::IgnoredAny;
177 use std::collections::BTreeMap;
178
179 serde_yaml::from_str::<BTreeMap<String, IgnoredAny>>(yaml)
180 .is_ok_and(|map| map.contains_key(key))
181}
182
183fn strict_yaml_error(yaml: &str) -> Option<String> {
194 serde_yaml::from_str::<serde_yaml::Value>(yaml)
195 .err()
196 .map(|e| e.to_string())
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 const MINIMAL_CONTRACT: &str = r#"
204metadata:
205 version: "1.0.0"
206 description: "Test contract"
207 references:
208 - "Test paper (2024)"
209equations:
210 test_eq:
211 formula: "f(x) = x + 1"
212proof_obligations: []
213falsification_tests: []
214"#;
215
216 #[test]
227 fn kind_is_declared_reads_metadata_and_survives_a_duplicate_nested_key() {
228 assert!(
229 !kind_is_declared(MINIMAL_CONTRACT),
230 "no metadata.kind is written, so none was declared"
231 );
232 let declared = MINIMAL_CONTRACT.replace(
233 " description: \"Test contract\"",
234 " description: \"Test contract\"\n kind: pattern",
235 );
236 assert!(
237 kind_is_declared(&declared),
238 "metadata.kind is written, whatever its value"
239 );
240
241 let with_duplicate =
242 format!("{declared}commands:\n root:\n subcommands: [a]\n subcommands: [b]\n");
243 assert!(
244 serde_yaml::from_str::<std::collections::BTreeMap<String, serde_yaml::Value>>(
245 &with_duplicate
246 )
247 .is_err(),
248 "anti-vacuity: this fixture must be a document a whole-file Value parse REFUSES, \
249 otherwise the next assertion proves nothing"
250 );
251 assert!(
252 kind_is_declared(&with_duplicate),
253 "a duplicate key under an unknown top-level block must not make a declared kind \
254 read as absent"
255 );
256
257 assert!(
258 !kind_is_declared("not: a contract\n"),
259 "a document with no metadata declared no kind"
260 );
261 }
262
263 #[test]
264 fn parse_minimal_contract() {
265 let contract = parse_contract_str(MINIMAL_CONTRACT).unwrap();
266 assert_eq!(contract.metadata.version, "1.0.0");
267 assert_eq!(contract.metadata.description, "Test contract");
268 assert_eq!(contract.equations.len(), 1);
269 assert!(contract.equations.contains_key("test_eq"));
270 }
271
272 #[test]
273 fn parse_contract_with_all_fields() {
274 let yaml = r#"
275metadata:
276 version: "1.0.0"
277 created: "2026-02-18"
278 author: "Test Author"
279 description: "Full contract"
280 references:
281 - "Paper A (2024)"
282 - "Paper B (2025)"
283equations:
284 softmax:
285 formula: "σ(x)_i = exp(x_i - max(x)) / Σ exp(x_j - max(x))"
286 domain: "x ∈ ℝ^n, n ≥ 1"
287 codomain: "σ(x) ∈ (0,1)^n"
288 invariants:
289 - "sum(output) = 1.0"
290 - "output_i > 0"
291proof_obligations:
292 - type: invariant
293 property: "Output sums to 1"
294 formal: "|sum(softmax(x)) - 1.0| < ε"
295 tolerance: 1.0e-6
296 applies_to: all
297 - type: equivalence
298 property: "SIMD matches scalar"
299 tolerance: 8.0
300 applies_to: simd
301kernel_structure:
302 phases:
303 - name: find_max
304 description: "Find max element"
305 invariant: "max >= all elements"
306 - name: exp_subtract
307 description: "Compute exp(x_i - max)"
308 invariant: "all values in (0, 1]"
309simd_dispatch:
310 softmax:
311 scalar: "softmax_scalar"
312 avx2: "softmax_avx2"
313enforcement:
314 normalization:
315 description: "Output sums to 1.0"
316 check: "contract_tests::FALSIFY-SM-001"
317 severity: "ERROR"
318falsification_tests:
319 - id: FALSIFY-SM-001
320 rule: "Normalization"
321 prediction: "sum(output) ≈ 1.0"
322 test: "proptest with random vectors"
323 if_fails: "Missing max-subtraction trick"
324kani_harnesses:
325 - id: KANI-SM-001
326 obligation: SM-INV-001
327 property: "Softmax sums to 1.0"
328 bound: 16
329 strategy: stub_float
330 solver: cadical
331 harness: verify_softmax_normalization
332qa_gate:
333 id: F-SM-001
334 name: "Softmax Contract"
335 checks:
336 - "normalization"
337 pass_criteria: "All falsification tests pass"
338 falsification: "Introduce off-by-one in max reduction"
339"#;
340
341 let contract = parse_contract_str(yaml).unwrap();
342 assert_eq!(contract.metadata.version, "1.0.0");
343 assert_eq!(contract.metadata.references.len(), 2);
344 assert_eq!(contract.equations.len(), 1);
345 assert_eq!(contract.proof_obligations.len(), 2);
346 assert!(contract.kernel_structure.is_some());
347 let ks = contract.kernel_structure.unwrap();
348 assert_eq!(ks.phases.len(), 2);
349 assert_eq!(contract.simd_dispatch.len(), 1);
350 assert_eq!(contract.enforcement.len(), 1);
351 assert_eq!(contract.falsification_tests.len(), 1);
352 assert_eq!(contract.falsification_tests[0].id, "FALSIFY-SM-001");
353 assert_eq!(contract.kani_harnesses.len(), 1);
354 assert_eq!(contract.kani_harnesses[0].bound, Some(16));
355 assert!(contract.qa_gate.is_some());
356 }
357
358 #[test]
359 fn parse_invalid_yaml_returns_error() {
360 let result = parse_contract_str("not: [valid: yaml: {{");
361 assert!(result.is_err());
362 }
363
364 #[test]
365 fn parse_missing_metadata_returns_error() {
366 let yaml = r#"
367equations:
368 test:
369 formula: "f(x) = x"
370"#;
371 let result = parse_contract_str(yaml);
372 assert!(result.is_err());
373 }
374
375 #[test]
376 fn parse_obligation_types() {
377 let yaml = r#"
378metadata:
379 version: "1.0.0"
380 description: "type test"
381equations:
382 f:
383 formula: "f(x) = x"
384proof_obligations:
385 - type: invariant
386 property: "test"
387 if_fails: ""
388 - type: equivalence
389 property: "test"
390 - type: bound
391 property: "test"
392 - type: monotonicity
393 property: "test"
394 - type: idempotency
395 property: "test"
396 - type: linearity
397 property: "test"
398 - type: symmetry
399 property: "test"
400 - type: associativity
401 property: "test"
402 - type: conservation
403 property: "test"
404falsification_tests: []
405"#;
406 let contract = parse_contract_str(yaml).unwrap();
407 assert_eq!(contract.proof_obligations.len(), 9);
408 }
409
410 #[test]
411 fn parse_dbc_obligation_types() {
412 use crate::schema::types::ObligationType;
413
414 let yaml = r#"
415metadata:
416 version: "1.0.0"
417 description: "DbC type test"
418 depends_on: ["parent-v1"]
419equations:
420 f:
421 formula: "f(x) = x"
422proof_obligations:
423 - type: precondition
424 property: "input finite"
425 formal: "isFinite(x)"
426 - type: postcondition
427 property: "output bounded"
428 requires: "PRE-001"
429 - type: frame
430 property: "input unchanged"
431 - type: loop_invariant
432 property: "max tracks true max"
433 applies_to_phase: "find_max"
434 - type: loop_variant
435 property: "remaining decreasing"
436 applies_to_phase: "accumulate"
437 - type: old_state
438 property: "cache grows"
439 - type: subcontract
440 property: "refines parent"
441 parent_contract: "parent-v1"
442falsification_tests: []
443"#;
444 let contract = parse_contract_str(yaml).unwrap();
445 assert_eq!(contract.proof_obligations.len(), 7);
446 assert_eq!(
447 contract.proof_obligations[0].obligation_type,
448 ObligationType::Precondition
449 );
450 assert_eq!(
451 contract.proof_obligations[1].obligation_type,
452 ObligationType::Postcondition
453 );
454 assert_eq!(
455 contract.proof_obligations[1].requires.as_deref(),
456 Some("PRE-001")
457 );
458 assert_eq!(
459 contract.proof_obligations[2].obligation_type,
460 ObligationType::Frame
461 );
462 assert_eq!(
463 contract.proof_obligations[3].obligation_type,
464 ObligationType::LoopInvariant
465 );
466 assert_eq!(
467 contract.proof_obligations[3].applies_to_phase.as_deref(),
468 Some("find_max")
469 );
470 assert_eq!(
471 contract.proof_obligations[4].obligation_type,
472 ObligationType::LoopVariant
473 );
474 assert_eq!(
475 contract.proof_obligations[5].obligation_type,
476 ObligationType::OldState
477 );
478 assert_eq!(
479 contract.proof_obligations[6].obligation_type,
480 ObligationType::Subcontract
481 );
482 assert_eq!(
483 contract.proof_obligations[6].parent_contract.as_deref(),
484 Some("parent-v1")
485 );
486 }
487
488 #[test]
489 fn parse_contract_with_kind_model_family() {
490 use crate::schema::types::ContractKind;
491
492 let yaml = r#"
496metadata:
497 version: "1.0.0"
498 description: "Google BERT architecture family metadata"
499 kind: model-family
500 references:
501 - "https://arxiv.org/abs/1810.04805"
502 - "https://huggingface.co/google-bert"
503# Custom top-level fields ignored by the kernel schema,
504# consumed by the downstream crate that owns the file.
505family: bert
506display_name: "Google BERT"
507vendor: Google
508architectures:
509 - BertModel
510 - BertForMaskedLM
511size_variants:
512 base:
513 parameters: "110M"
514 hidden_dim: 768
515"#;
516 let contract = parse_contract_str(yaml).unwrap();
517 assert_eq!(contract.kind(), ContractKind::ModelFamily);
518 assert!(!contract.requires_proofs());
519 assert!(!contract.is_registry());
520 let violations = crate::schema::validate_contract(&contract);
522 let errors: Vec<_> = violations
523 .iter()
524 .filter(|v| v.severity == crate::error::Severity::Error)
525 .collect();
526 assert!(
527 errors.is_empty(),
528 "model-family YAML should validate with no errors, got: {errors:?}",
529 );
530 }
531
532 #[test]
533 fn parse_contract_defaults_to_kernel_kind() {
534 use crate::schema::types::ContractKind;
535
536 let contract = parse_contract_str(MINIMAL_CONTRACT).unwrap();
537 assert_eq!(contract.kind(), ContractKind::Kernel);
538 assert!(contract.requires_proofs());
539 }
540
541 #[test]
542 fn parse_kani_strategies() {
543 use crate::schema::types::KaniStrategy;
544
545 let yaml = r#"
546metadata:
547 version: "1.0.0"
548 description: "kani test"
549equations:
550 f:
551 formula: "f(x) = x"
552kani_harnesses:
553 - id: K1
554 obligation: OBL-1
555 strategy: exhaustive
556 - id: K2
557 obligation: OBL-2
558 strategy: stub_float
559 - id: K3
560 obligation: OBL-3
561 strategy: compositional
562falsification_tests: []
563"#;
564 let contract = parse_contract_str(yaml).unwrap();
565 assert_eq!(contract.kani_harnesses.len(), 3);
566 assert_eq!(
567 contract.kani_harnesses[0].strategy,
568 Some(KaniStrategy::Exhaustive)
569 );
570 assert_eq!(
571 contract.kani_harnesses[1].strategy,
572 Some(KaniStrategy::StubFloat)
573 );
574 assert_eq!(
575 contract.kani_harnesses[2].strategy,
576 Some(KaniStrategy::Compositional)
577 );
578 }
579}