|
| 1 | +"""Offline validation for the vendored CAS shared evaluation contract.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +import math |
| 8 | +import re |
| 9 | +from datetime import datetime |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +CONTRACT_VERSION = "0.1.0" |
| 14 | +VENDOR_DIR = Path(__file__).parents[2] / "vendor" / "cas-contracts" / "v0.1.0" |
| 15 | +PROVENANCE_PATH = VENDOR_DIR / "provenance.json" |
| 16 | + |
| 17 | +_ACTOR_TYPES = {"human", "agent", "service", "workflow"} |
| 18 | +_OUTCOMES = {"passed", "failed", "inconclusive"} |
| 19 | +_RESULT_FIELDS = { |
| 20 | + "correlationId", |
| 21 | + "promptId", |
| 22 | + "runId", |
| 23 | + "repo", |
| 24 | + "actor", |
| 25 | + "timestamp", |
| 26 | + "schemaVersion", |
| 27 | + "traceContext", |
| 28 | + "kind", |
| 29 | + "evaluator", |
| 30 | + "outcome", |
| 31 | + "metrics", |
| 32 | +} |
| 33 | +_TRACEPARENT = re.compile(r"^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$") |
| 34 | +_REPO = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") |
| 35 | + |
| 36 | + |
| 37 | +class ContractValidationError(ValueError): |
| 38 | + """Raised when shared-contract provenance or an emitted result is invalid.""" |
| 39 | + |
| 40 | + |
| 41 | +def _load_json(path: Path) -> dict[str, Any]: |
| 42 | + return json.loads(path.read_text(encoding="utf-8")) |
| 43 | + |
| 44 | + |
| 45 | +def _require_string(value: Any, field: str, minimum: int = 1, maximum: int = 128) -> str: |
| 46 | + if not isinstance(value, str) or not minimum <= len(value) <= maximum: |
| 47 | + raise ContractValidationError(f"{field} must be a string with length {minimum}..{maximum}") |
| 48 | + return value |
| 49 | + |
| 50 | + |
| 51 | +def verify_vendored_contract() -> dict[str, Any]: |
| 52 | + """Verify immutable provenance and expected identities of vendored schemas.""" |
| 53 | + provenance = _load_json(PROVENANCE_PATH) |
| 54 | + for filename, expected in provenance["schemas"].items(): |
| 55 | + path = VENDOR_DIR / filename |
| 56 | + digest = hashlib.sha256(path.read_bytes()).hexdigest() |
| 57 | + if digest != expected["sha256"]: |
| 58 | + raise ContractValidationError(f"vendored schema digest mismatch: {filename}") |
| 59 | + |
| 60 | + common = _load_json(VENDOR_DIR / "common.schema.json") |
| 61 | + evaluation = _load_json(VENDOR_DIR / "evaluation-result.schema.json") |
| 62 | + if common.get("$id") != "https://schemas.coding-autopilot.dev/v0.1/common.schema.json": |
| 63 | + raise ContractValidationError("unexpected common schema identity") |
| 64 | + if evaluation.get("$id") != "https://schemas.coding-autopilot.dev/v0.1/evaluation-result.schema.json": |
| 65 | + raise ContractValidationError("unexpected evaluation schema identity") |
| 66 | + if evaluation["allOf"][0].get("$ref") != "common.schema.json#/$defs/lifecycleMetadata": |
| 67 | + raise ContractValidationError("evaluation schema does not reference the vendored common schema") |
| 68 | + return provenance |
| 69 | + |
| 70 | + |
| 71 | +def validate_evaluation_result(result: dict[str, Any]) -> None: |
| 72 | + """Validate the complete constraint surface of shared EvaluationResult v0.1.0.""" |
| 73 | + verify_vendored_contract() |
| 74 | + if not isinstance(result, dict): |
| 75 | + raise ContractValidationError("evaluation result must be an object") |
| 76 | + missing = sorted(_RESULT_FIELDS - result.keys()) |
| 77 | + extra = sorted(result.keys() - _RESULT_FIELDS) |
| 78 | + if missing: |
| 79 | + raise ContractValidationError(f"evaluation result missing fields: {', '.join(missing)}") |
| 80 | + if extra: |
| 81 | + raise ContractValidationError(f"evaluation result has unevaluated fields: {', '.join(extra)}") |
| 82 | + |
| 83 | + for field in ("correlationId", "promptId", "runId"): |
| 84 | + _require_string(result[field], field) |
| 85 | + repo = _require_string(result["repo"], "repo", maximum=512) |
| 86 | + if not _REPO.fullmatch(repo): |
| 87 | + raise ContractValidationError("repo must use owner/name format") |
| 88 | + if result["schemaVersion"] != CONTRACT_VERSION: |
| 89 | + raise ContractValidationError(f"schemaVersion must be {CONTRACT_VERSION}") |
| 90 | + |
| 91 | + actor = result["actor"] |
| 92 | + if not isinstance(actor, dict) or set(actor) - {"id", "type", "displayName"}: |
| 93 | + raise ContractValidationError("actor contains invalid fields") |
| 94 | + if not {"id", "type"} <= actor.keys(): |
| 95 | + raise ContractValidationError("actor requires id and type") |
| 96 | + _require_string(actor["id"], "actor.id", maximum=256) |
| 97 | + if actor["type"] not in _ACTOR_TYPES: |
| 98 | + raise ContractValidationError("actor.type is invalid") |
| 99 | + if "displayName" in actor: |
| 100 | + _require_string(actor["displayName"], "actor.displayName", maximum=256) |
| 101 | + |
| 102 | + timestamp = _require_string(result["timestamp"], "timestamp", maximum=64) |
| 103 | + try: |
| 104 | + datetime.fromisoformat(timestamp.replace("Z", "+00:00")) |
| 105 | + except ValueError as error: |
| 106 | + raise ContractValidationError("timestamp must be an ISO 8601 date-time") from error |
| 107 | + |
| 108 | + trace = result["traceContext"] |
| 109 | + if not isinstance(trace, dict) or not {"traceparent"} <= trace.keys() or set(trace) - {"traceparent", "tracestate"}: |
| 110 | + raise ContractValidationError("traceContext is invalid") |
| 111 | + if not isinstance(trace["traceparent"], str) or not _TRACEPARENT.fullmatch(trace["traceparent"]): |
| 112 | + raise ContractValidationError("traceContext.traceparent is invalid") |
| 113 | + if "tracestate" in trace: |
| 114 | + _require_string(trace["tracestate"], "traceContext.tracestate", maximum=512) |
| 115 | + |
| 116 | + if result["kind"] != "EvaluationResult": |
| 117 | + raise ContractValidationError("kind must be EvaluationResult") |
| 118 | + _require_string(result["evaluator"], "evaluator", maximum=256) |
| 119 | + if result["outcome"] not in _OUTCOMES: |
| 120 | + raise ContractValidationError("outcome is invalid") |
| 121 | + metrics = result["metrics"] |
| 122 | + if not isinstance(metrics, dict) or not metrics: |
| 123 | + raise ContractValidationError("metrics must be a non-empty object") |
| 124 | + for name, value in metrics.items(): |
| 125 | + _require_string(name, "metric name", maximum=256) |
| 126 | + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): |
| 127 | + raise ContractValidationError(f"metric {name} must be a finite number") |
0 commit comments