"""Validated evaluation-profile configuration for one Skill experiment.""" from __future__ import annotations import hashlib from dataclasses import dataclass, field from pathlib import Path from typing import Any, Literal, Mapping from .instrumentation import get_instrumentation_definition from .models import deep_freeze, deep_thaw PROFILE_SCHEMA_VERSION = "skill-evaluation/v3" EVALUATOR_FAMILIES = ("execution", "trace") @dataclass(frozen=True) class InstrumentationConfig: protocol: str event_carriers: tuple[str, ...] def to_dict(self) -> dict[str, Any]: return {"protocol": self.protocol, "event_carriers": list(self.event_carriers)} @dataclass(frozen=True) class EvaluatorConfig: evaluator_id: str params: Mapping[str, Any] = field(default_factory=dict) llm: Mapping[str, Any] | None = None annotate: bool = False def __post_init__(self) -> None: if not isinstance(self.annotate, bool): raise ValueError("evaluator annotate must be boolean") object.__setattr__(self, "params", deep_freeze(self.params)) if self.llm is not None: object.__setattr__(self, "llm", deep_freeze(self.llm)) def to_dict(self) -> dict[str, Any]: value: dict[str, Any] = { "id": self.evaluator_id, "params": deep_thaw(self.params), "annotate": self.annotate, } if self.llm is not None: value["llm"] = deep_thaw(self.llm) return value @dataclass(frozen=True) class SkillEvaluationConfig: """A parsed profile; definition-specific validation happens in build_evaluators().""" schema_version: str instrumentation: InstrumentationConfig execution: tuple[EvaluatorConfig, ...] trace: tuple[EvaluatorConfig, ...] source_path: str profile_hash: str @classmethod def resolve( cls, skill_root: str | Path, explicit_profile: str | Path | None = None, ) -> "SkillEvaluationConfig": root = Path(skill_root).resolve() if root.is_file(): root = root.parent profile_path = Path(explicit_profile).resolve() if explicit_profile is not None else root / "skill.yaml" if not profile_path.is_file(): origin = "explicit evaluation profile" if explicit_profile is not None else "Skill-local evaluation profile" raise FileNotFoundError(f"{origin} does not exist: {profile_path}") return cls.load(profile_path) @classmethod def load(cls, path: str | Path) -> "SkillEvaluationConfig": profile_path = Path(path).resolve() if not profile_path.is_file(): raise FileNotFoundError(f"evaluation profile does not exist: {profile_path}") try: import yaml raw = yaml.safe_load(profile_path.read_text(encoding="utf-8")) except ImportError as exc: raise RuntimeError("skill evaluation profile requires PyYAML") from exc if not isinstance(raw, dict): raise ValueError("skill evaluation profile must contain an object") cls._require_keys(raw, required={"schema_version", "evaluation"}, allowed={"schema_version", "evaluation"}, context="profile") if raw["schema_version"] != PROFILE_SCHEMA_VERSION: raise ValueError(f"evaluation profile schema_version must be {PROFILE_SCHEMA_VERSION}") evaluation = raw["evaluation"] if not isinstance(evaluation, dict): raise ValueError("evaluation profile evaluation must be an object") cls._require_keys( evaluation, required={"instrumentation", "evaluators"}, allowed={"instrumentation", "evaluators"}, context="evaluation", ) instrumentation = cls._parse_instrumentation(evaluation["instrumentation"]) evaluators = evaluation["evaluators"] if not isinstance(evaluators, dict): raise ValueError("evaluation.evaluators must be an object") cls._require_keys( evaluators, required=set(EVALUATOR_FAMILIES), allowed=set(EVALUATOR_FAMILIES), context="evaluation.evaluators", ) cls._validate_json_schema(raw) execution = cls._parse_evaluators(evaluators["execution"], "execution") trace = cls._parse_evaluators(evaluators["trace"], "trace") if not execution and not trace: raise ValueError("evaluation profile must configure at least one evaluator") return cls( PROFILE_SCHEMA_VERSION, instrumentation, execution, trace, profile_path.as_posix(), hashlib.sha256(profile_path.read_bytes()).hexdigest(), ) @staticmethod def _require_keys(value: dict[str, Any], *, required: set[str], allowed: set[str], context: str) -> None: missing = required - set(value) unknown = set(value) - allowed if missing: raise ValueError(f"{context} is missing required fields: {sorted(missing)}") if unknown: raise ValueError(f"{context} contains unknown fields: {sorted(unknown)}") @classmethod def _parse_instrumentation(cls, value: Any) -> InstrumentationConfig: if not isinstance(value, dict): raise ValueError("evaluation.instrumentation must be an object") cls._require_keys( value, required={"protocol", "event_carriers"}, allowed={"protocol", "event_carriers"}, context="evaluation.instrumentation", ) protocol = value["protocol"] if not isinstance(protocol, str) or not protocol: raise ValueError("evaluation.instrumentation.protocol must be a non-empty string") definition = get_instrumentation_definition(protocol) event_carriers = value["event_carriers"] if not isinstance(event_carriers, list) or not event_carriers or any(not isinstance(item, str) or not item for item in event_carriers): raise ValueError("evaluation.instrumentation.event_carriers must be a non-empty string list") if len(set(event_carriers)) != len(event_carriers): raise ValueError("evaluation.instrumentation.event_carriers must not contain duplicates") unsupported = sorted(set(event_carriers) - definition.supported_carriers) if unsupported: raise ValueError(f"unknown eval event carriers: {unsupported}") return InstrumentationConfig(protocol, tuple(event_carriers)) @classmethod def _parse_evaluators(cls, value: Any, family: str) -> tuple[EvaluatorConfig, ...]: if not isinstance(value, list): raise ValueError(f"evaluation.evaluators.{family} must be a list") entries: list[EvaluatorConfig] = [] for index, entry in enumerate(value): context = f"evaluation.evaluators.{family}[{index}]" if not isinstance(entry, dict): raise ValueError(f"{context} must be an object") cls._require_keys( entry, required={"id", "params"}, allowed={"id", "params", "llm", "annotate"}, context=context, ) evaluator_id = entry["id"] if not isinstance(evaluator_id, str) or not evaluator_id or "." in evaluator_id or ":" in evaluator_id: raise ValueError(f"{context}.id must be a non-empty family-local string") params = entry["params"] if not isinstance(params, dict): raise ValueError(f"{context}.params must be an object") llm = entry.get("llm") if llm is not None: if not isinstance(llm, dict): raise ValueError(f"{context}.llm must be an object") if set(llm) - {"backend", "model"}: raise ValueError(f"{context}.llm contains only runtime fields backend/model") if "backend" in llm and (not isinstance(llm["backend"], str) or not llm["backend"]): raise ValueError(f"{context}.llm.backend must be a non-empty string") if "model" in llm and llm["model"] is not None and ( not isinstance(llm["model"], str) or not llm["model"] ): raise ValueError(f"{context}.llm.model must be a non-empty string or null") entries.append(EvaluatorConfig( evaluator_id=evaluator_id, params=dict(params), llm=dict(llm) if llm is not None else None, annotate=entry.get("annotate", False), )) return tuple(entries) @staticmethod def _validate_json_schema(raw: Mapping[str, Any]) -> None: """Run the shared JSON Schema validator before semantic normalization.""" try: from jsonschema import Draft202012Validator except ImportError as exc: # pragma: no cover - dependency is shared with datasets raise RuntimeError("evaluation profile requires jsonschema") from exc llm_schema = { "type": "object", "additionalProperties": False, "properties": { "backend": {"type": "string", "minLength": 1}, "model": {"type": ["string", "null"], "minLength": 1}, }, } evaluator_schema = { "type": "object", "required": ["id", "params"], "additionalProperties": False, "properties": { "id": {"type": "string", "minLength": 1, "pattern": "^[^.:]+$"}, "params": {"type": "object"}, "llm": llm_schema, "annotate": {"type": "boolean", "default": False}, }, } schema = { "type": "object", "required": ["schema_version", "evaluation"], "additionalProperties": False, "properties": { "schema_version": {"const": PROFILE_SCHEMA_VERSION}, "evaluation": { "type": "object", "required": ["instrumentation", "evaluators"], "additionalProperties": False, "properties": { "instrumentation": { "type": "object", "required": ["protocol", "event_carriers"], "additionalProperties": False, "properties": { "protocol": {"type": "string", "minLength": 1}, "event_carriers": {"type": "array", "minItems": 1, "uniqueItems": True, "items": {"type": "string", "minLength": 1}}, }, }, "evaluators": { "type": "object", "required": list(EVALUATOR_FAMILIES), "additionalProperties": False, "properties": { family: {"type": "array", "items": evaluator_schema} for family in EVALUATOR_FAMILIES }, }, }, }, }, } errors = sorted(Draft202012Validator(schema).iter_errors(raw), key=lambda error: list(error.path)) if errors: error = errors[0] location = ".".join(str(item) for item in error.path) or "profile" raise ValueError(f"{location}: {error.message}") def evaluators_for(self, family: Literal["execution", "trace"]) -> tuple[EvaluatorConfig, ...]: return self.execution if family == "execution" else self.trace def params_for(self, family: Literal["execution", "trace"], evaluator_id: str) -> dict[str, Any] | None: for entry in self.evaluators_for(family): if entry.evaluator_id == evaluator_id: return deep_thaw(entry.params) return None def to_dict(self) -> dict[str, Any]: return { "schema_version": self.schema_version, "evaluation": { "instrumentation": self.instrumentation.to_dict(), "evaluators": { "execution": [entry.to_dict() for entry in self.execution], "trace": [entry.to_dict() for entry in self.trace], }, }, } def reference_dict(self) -> dict[str, Any]: return { "source": self.source_path, "schema_version": self.schema_version, "sha256": self.profile_hash, "config": self.to_dict(), }