Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(evals): add per-metric objective support to runner (closes #1091) (#1092)

Kevin30a91a3a7872
diff --git a/.gitignore b/.gitignore
index 0e5128d7..79197d52 100644
Binary files a/.gitignore and b/.gitignore differ
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16cf2957..b2c56f41 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -151,6 +151,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Also fixed, on the JSON-LD paths**: the first fix covered the Turtle, N-Triples and RDF/XML serializers, and left both JSON-LD writers interpolating the entity's own text into `f"semantica:entity/{text}"` and the endpoints into `f"semantica:rel/{source}_{target}"`. Three consequences, all live in 0.6.5: an entity whose text contained a space produced an invalid IRI, and a JSON-LD parser dropped that node in full rather than reporting it, so the entity disappeared from the export; every relationship carrying `source`/`target` rather than `source_id`/`target_id` minted the identical `semantica:rel/_`, collapsing all of them onto one node whose types and endpoints merged; and the JSON-LD `@id` disagreed with the Turtle IRI for the same entity, so the two serializations of one knowledge graph were two different graphs. Both JSON-LD writers now use `mint_entity_iri`/`mint_relationship_iri`, and `JSONExporter.export_entities`/`export_relationships` declare the `semantica` prefix their `@context` was already writing `semantica:entities` against — without it a processor reads that as an IRI in the scheme `semantica`, which is the original #1101 defect on a third path
- `tests/export/test_jsonld_iri_minting.py` parses each export with a real JSON-LD processor and asserts the entity survives, the relationships stay distinct, no term expands into the `semantica` scheme, and the JSON-LD `@id` equals the Turtle IRI
- 236 export and ontology tests pass
+- **`semantica.evals` runner gains per-metric objectives** (#1091)
+ - `evaluate()` now accepts `config={"<evaluator>": {"objective": {"direction": "maximize"|"minimize", "threshold": X}}}` to override the evaluator's default pass verdict with a threshold; `{"objective": {"expect": bool}}` expresses a Boolean expectation
+ - `minimize` requires a `threshold` — omitting it or setting it to `None` raises `ValueError`; `maximize` without a threshold is a no-op (the evaluator's own verdict stands); `expect` cannot be combined with `direction`/`threshold`; invalid config raises `ValueError` before any evaluator runs
+ - Error metrics are never affected by objectives (error wins over fail)
+ - Backward compatible: no `objective` key → existing behavior unchanged
+ - New tests in `tests/evals/test_runner.py::TestObjective`
+- **`semantica.evals` is now a fully implemented evaluation module** (was a "Coming Soon" stub in the package layout)
+ - `evaluate(cases, evaluators, config=None, target_fn=None)` runner with per-case `pass`/`fail`/`error` status and an aggregate `pass_rate`, using a registry of named evaluators (`list_evaluators()`)
+ - 10 built-in evaluators: `exact_match`, `regex_match`, `numeric_range`, `temporal_range`, `length_range`, `keyword_check`, `levenshtein` (edit-distance similarity), `rouge` (in-house token F1, no new dependencies), `llm_as_judge` (lazy: caller-supplied `judge_fn`), and `decision_scores` (composite over `semantica.context.Decision`)
+ - `decision_scores` validates field-level (expected outcome, confidence bounds, non-empty maker/reasoning/scenario) and governance-level (provenance record presence; opt-in `PolicyEngine.check_compliance`) checks, coercing dict inputs via `Decision(**actual)` and never crashing on malformed input; an interface slot for causal-chain/embedding checks is reserved and raises `NotImplementedError` (V2)
+ - `__version__` is `0.1.0`, and the module ships a usage guide at `semantica/evals/usage.md` with worked import/run/interpret examples
+ - `semantica.evals` is reachable through the root package lazy module proxy (`semantica.evals`)
+ - 99 unit tests in `tests/evals/` covering every evaluator, registry errors, runner aggregation, decision coercion, and per-metric objectives; `python -m pytest tests/evals -q` → 99 passed
- **First-class CrewAI integration** (#988, closes #962) by @Shindevrp
- New `pip install semantica[crewai]` extra (`crewai>=0.80.0`) — crewai core provides `BaseTool`/`BaseKnowledgeSource`, so `crewai-tools` is intentionally not included, and the extra is intentionally **not** part of the `all` bundle: crewai hard-requires `chromadb~=1.1.0`, which is affected by the unpatched pre-auth code-injection CVE-2026-45829 (see `integrations/crewai/README.md`)
diff --git a/docs/superpowers/plans/2026-08-19-evals-objective.md b/docs/superpowers/plans/2026-08-19-evals-objective.md
new file mode 100644
index 00000000..61a65dad
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-19-evals-objective.md
@@ -0,0 +1,338 @@
+# Objective Layer for semantica.evals Runner — Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Add per-metric objective support (direction + threshold, or Boolean expectation) to the `evaluate()` runner, overriding evaluator default pass verdicts, backward-compatible when no objective is configured.
+
+**Architecture:** The runner already iterates evaluators and computes per-case status. Objectives are read from `config["<name>"]["objective"]`, validated up front, and applied to each returned metric's `passed` field (and `details`) before aggregation. Error metrics always win over objectives.
+
+**Tech Stack:** Python 3.8+, stdlib only (typing, dataclasses). pytest for tests.
+
+## Global Constraints
+
+- Python >= 3.8: use `typing.Dict/List/Optional/Union`, never builtin generics or `|`.
+- Zero new dependencies.
+- Do not change the `EvalMetric` shape, the `evaluate()` signature, or the evaluator function signature.
+- Existing behavior with no `objective` configured must be byte-for-byte unchanged (all 62 existing tests keep passing).
+- Error metrics (`meta` contains `"error"`) always classify the case as `error`, regardless of objective.
+- Config errors are programmer errors: raise `ValueError` from `evaluate()` before any evaluator runs (fail-fast).
+- Tests go in `tests/evals/`, pytest class style, no new files outside the listed paths.
+
+---
+
+### Task 1: Objective parsing, validation, and re-decision in the runner
+
+**Files:**
+- Modify: `semantica/evals/runner.py`
+- Test: `tests/evals/test_runner.py`
+
+**Interfaces:**
+- Consumes: `EvalMetric` from `.types` (fields: `score`, `passed`, `meta`); `evaluate(cases, evaluators, config=None, target_fn=None)` existing signature.
+- Produces: private helpers `_parse_objective(name, eval_config) -> Optional[Dict]` (returns `None` when no objective configured, raises `ValueError` on invalid config) and `_apply_objective(metric, objective) -> bool` (returns the re-decided `passed`). Public `evaluate()` behavior extended as specified.
+
+- [ ] **Step 1: Write the failing tests**
+
+Append a new test class to `tests/evals/test_runner.py`:
+
+```python
+class TestObjective:
+ def test_maximize_with_threshold_pass(self):
+ # levenshtein similarity 1.0 for identical, objective demands >= 0.5
+ result = evaluate(
+ [("apple", "apple")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.5}}},
+ )
+ assert result.cases[0].status == "pass"
+ assert result.cases[0].metrics["levenshtein"].passed is True
+
+ def test_maximize_with_threshold_fail(self):
+ result = evaluate(
+ [("apple", "aple")], # similarity < 1.0
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.99}}},
+ )
+ assert result.cases[0].status == "fail"
+ assert result.cases[0].metrics["levenshtein"].passed is False
+ assert "levenshtein" in result.cases[0].details
+
+ def test_minimize_with_threshold_pass(self):
+ # edit distance normalized ~0.2; objective: distance <= 0.5
+ result = evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.5}}},
+ )
+ assert result.cases[0].status == "pass"
+ assert result.cases[0].metrics["levenshtein"].passed is True
+
+ def test_minimize_with_threshold_fail(self):
+ result = evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.1}}},
+ )
+ assert result.cases[0].status == "fail"
+
+ def test_expect_true_on_boolean_metric(self):
+ result = evaluate(
+ [("ok", "ok")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": True}}},
+ )
+ assert result.cases[0].status == "pass"
+
+ def test_expect_false_overrides_passing_metric(self):
+ # exact_match passes (score 1.0) but expectation is false -> fail
+ result = evaluate(
+ [("ok", "ok")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": False}}},
+ )
+ assert result.cases[0].status == "fail"
+ assert result.cases[0].metrics["exact_match"].passed is False
+ assert "exact_match" in result.cases[0].details
+
+ def test_maximize_without_threshold_is_noop(self):
+ # identical behavior to no objective: evaluator's own verdict stands
+ result = evaluate(
+ [("ok", "no")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"direction": "maximize"}}},
+ )
+ assert result.cases[0].status == "fail"
+
+ def test_minimize_without_threshold_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize"}}},
+ )
+
+ def test_bad_direction_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "sideways", "threshold": 0.5}}},
+ )
+
+ def test_expect_with_direction_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"expect": True, "direction": "maximize"}}},
+ )
+
+ def test_error_metric_wins_over_objective(self):
+ result = evaluate(
+ [("[invalid", "x")],
+ evaluators=["regex_match"],
+ config={"regex_match": {"objective": {"direction": "maximize", "threshold": 0.0}}},
+ )
+ assert result.cases[0].status == "error"
+ assert result.errors == 1
+ assert result.failed == 0
+
+ def test_no_objective_unchanged(self):
+ result = evaluate([("ok", "no")], evaluators=["exact_match"])
+ assert result.cases[0].status == "fail"
+```
+
+- [ ] **Step 2: Run tests to verify they fail**
+
+Run: `python3 -m pytest tests/evals/test_runner.py -q`
+Expected: the new `TestObjective` tests fail (objective config ignored → `exact_match` passes under `expect:false` etc.); the pre-existing tests in the file still pass.
+
+- [ ] **Step 3: Implement objective parsing, validation, and re-decision**
+
+In `semantica/evals/runner.py`, add two helpers before `evaluate` and wire them into the evaluator loop.
+
+```python
+def _parse_objective(name, eval_config):
+ """Return the validated objective dict, or None when not configured.
+
+ Raises ValueError for invalid configurations (programmer error).
+ """
+ objective = (eval_config or {}).get("objective")
+ if objective is None:
+ return None
+ direction = objective.get("direction")
+ threshold = objective.get("threshold")
+ expect = objective.get("expect")
+
+ if expect is not None:
+ if direction is not None or threshold is not None:
+ raise ValueError(
+ f"objective for '{name}': 'expect' cannot be combined with "
+ "'direction' or 'threshold'"
+ )
+ return {"expect": bool(expect)}
+ if direction == "minimize":
+ if threshold is None:
+ raise ValueError(
+ f"objective for '{name}': 'minimize' requires a 'threshold'"
+ )
+ return {"direction": "minimize", "threshold": float(threshold)}
+ if direction == "maximize":
+ if threshold is None:
+ # no bar to re-decide against; treat as absent (evaluator default stands)
+ return None
+ return {"direction": "maximize", "threshold": float(threshold)}
+ raise ValueError(
+ f"objective for '{name}': 'direction' must be 'maximize' or 'minimize' "
+ f"(got {direction!r})"
+ )
+
+
+def _apply_objective(metric, objective):
+ """Return the objective-adjusted pass verdict for a non-error metric."""
+ if "expect" in objective:
+ return bool(metric.score) == objective["expect"]
+ if objective["direction"] == "minimize":
+ return metric.score <= objective["threshold"]
+ return metric.score >= objective["threshold"]
+```
+
+Then modify the evaluator loop in `evaluate()` so the parsed objective is computed once per case (outside the evaluator loop, since it only depends on merged config), and applied inside the loop:
+
+```python
+ objective_by_name = {
+ name: _parse_objective(name, merged.get(name) or {})
+ for name in evaluators
+ }
+ metrics: Dict[str, EvalMetric] = {}
+ details: Dict[str, Any] = {}
+ failed, errored = False, False
+ for name in evaluators:
+ eval_config = merged.get(name) or {}
+ try:
+ metric = get_evaluator(name)(actual, expected, config=eval_config)
+ objective = objective_by_name.get(name)
+ if objective is not None and "error" not in metric.meta:
+ metric = EvalMetric(metric.score, _apply_objective(metric, objective), metric.meta)
+ metrics[name] = metric
+ if "error" in metric.meta:
+ errored = True
+ details[name] = metric.meta
+ elif not metric.passed:
+ failed = True
+ details[name] = metric.meta
+ except Exception as exc: # noqa: BLE001
+ errored = True
+ metrics[name] = EvalMetric(0.0, False, {"error": str(exc)})
+ details[name] = {"error": str(exc)}
+```
+
+Note: `objective_by_name` is computed once per case (it depends only on merged config), so invalid config raises `ValueError` at the first case — satisfying the fail-fast requirement. `EvalMetric` is a frozen dataclass, so the re-verdict constructs a new instance preserving score/meta.
+
+- [ ] **Step 4: Run tests to verify they pass**
+
+Run: `python3 -m pytest tests/evals/test_runner.py -q`
+Expected: all `TestObjective` tests pass; pre-existing tests still pass.
+
+- [ ] **Step 5: Run the full evals suite**
+
+Run: `python3 -m pytest tests/evals -q`
+Expected: 62 existing + new tests all pass (no regressions).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add semantica/evals/runner.py tests/evals/test_runner.py
+git commit -m "feat(evals): add per-metric objective support to runner"
+```
+
+---
+
+### Task 2: Documentation — usage.md and CHANGELOG
+
+**Files:**
+- Modify: `semantica/evals/usage.md`
+- Modify: `CHANGELOG.md`
+
+**Interfaces:**
+- Consumes: the objective config surface implemented in Task 1 (exact keys: `objective.direction`, `objective.threshold`, `objective.expect`; validation rules).
+- Produces: docs only.
+
+- [ ] **Step 1: Add objective section to usage.md**
+
+Append a section after the existing "Run the runner over decision records" section:
+
+```markdown
+## Set per-evaluator objectives
+
+By default each evaluator decides its own pass/fail. To override that
+verdict at the run level, configure an **objective** per evaluator name:
+
+```python
+from semantica.evals import evaluate
+
+# Require a minimum similarity (default direction is maximize):
+evaluate(
+ [("apple", "aple")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.7}}},
+)
+
+# Lower is better — override the direction:
+evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.5}}},
+)
+
+# Boolean expectation on a 0/1 metric:
+evaluate(
+ [("ok", "ok")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": False}}},
+)
+```
+
+Rules:
+
+- `maximize` + `threshold`: pass iff `score >= threshold`. `maximize` without
+ a threshold is a no-op (the evaluator's own verdict stands).
+- `minimize` + `threshold`: pass iff `score <= threshold`. `minimize`
+ **requires** a threshold — omitting it raises `ValueError`.
+- `expect` (`true`/`false`): pass iff `bool(score)` matches; cannot be
+ combined with `direction`/`threshold`.
+- A metric whose `meta` contains `"error"` is always an error, never affected
+ by an objective.
+- Invalid objective config raises `ValueError` before any evaluator runs.
+```
+
+- [ ] **Step 2: Add CHANGELOG entry**
+
+Under `## [Unreleased]` → `### Added`, insert a new bullet at the top (before the `semantica.evals` module entry), following existing style:
+
+```markdown
+- **`semantica.evals` runner gains per-metric objectives** (#1091)
+ - `evaluate()` now accepts `config={"<evaluator>": {"objective": {"direction": "maximize"|"minimize", "threshold": X}}}` to override the evaluator's default pass verdict with a threshold; `{"objective": {"expect": bool}}` expresses a Boolean expectation
+ - `minimize` requires a `threshold`; `maximize` without one is a no-op; `expect` cannot be combined with `direction`/`threshold`; invalid config raises `ValueError` before any evaluator runs
+ - Error metrics are never affected by objectives (error wins over fail)
+ - Backward compatible: no `objective` key → existing behavior unchanged
+ - New tests in `tests/evals/test_runner.py::TestObjective`
+```
+
+- [ ] **Step 3: Verify docs examples run**
+
+Run the three examples from Step 1 as a Python script (import `evaluate`, run each snippet) to confirm they don't raise unexpectedly. No test output assertion needed beyond "no exception" and sensible status values.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add semantica/evals/usage.md CHANGELOG.md
+git commit -m "docs(evals): document per-metric objectives"
+```
+
+---
+
+## Self-Review Notes
+
+- **Spec coverage:** §3.1 (config surface) → Task 1 helpers + Task 2 docs; §3.2 (semantics: maximize/minimize/expect) → Task 1 `_apply_objective`; §3.3 (error wins) → Task 1 error branch + `test_error_metric_wins_over_objective`; §3.4 rules 1-3 (validation) → Task 1 `_parse_objective` + 4 validation tests; §3.4 rule 4 → error branch; §3.5 (aggregation unchanged, details on final verdict) → Task 1 loop + `test_expect_false_overrides_passing_metric` asserts `details`; §4 (fail-fast ValueError) → `_parse_objective` at case top; §5 (tests) → Task 1 test class; §6 (compat) → `test_no_objective_unchanged` + full-suite green.
+- **Type consistency:** `_parse_objective(name, eval_config) -> Optional[Dict]`, `_apply_objective(metric, objective) -> bool`; `EvalMetric(score, passed, meta)` positional construction preserved everywhere.
+- **Backward compat:** objective parsed to `None` for absent config → loop behavior identical to before.
diff --git a/docs/superpowers/specs/2026-08-19-evals-objective-design.md b/docs/superpowers/specs/2026-08-19-evals-objective-design.md
new file mode 100644
index 00000000..b2cd7e2f
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-19-evals-objective-design.md
@@ -0,0 +1,115 @@
+# Design: Objective layer for `semantica.evals` runner
+
+**Date:** 2026-08-19
+**Issue:** semantica-agi/semantica#1091 (assigned to pkupt)
+**Base:** PR #1090 (`semantica.evals` module)
+
+## 1. Problem
+
+`semantica.evals` runs named evaluators and aggregates per-case pass/fail, but the pass judgement is hard-coded inside each evaluator — a higher score always means "better". There is no way to express an evaluation objective at the run level:
+
+- apply a threshold the evaluator does not encode (e.g. "F1 must be ≥ 0.7");
+- reverse the direction (e.g. "lower edit distance is better");
+- express a Boolean expectation (e.g. "this metric should be `false`").
+
+This blocks the domain-specific benchmark harnesses `docs/community-projects.md` says `semantica.evals` supports. Palantir AIP Evals models exactly this: each metric has an **objective** (Boolean expected value, or numeric `maximize`/`minimize` direction with an optional threshold), and a test case passes when **all** its metrics meet their objectives.
+
+## 2. Scope
+
+In scope:
+
+- A per-metric objective configuration consumed by the `evaluate()` runner.
+- Runner-level pass/fail re-decision for numeric scores and Boolean metrics.
+- Backward-compatible behavior when no objective is configured.
+- Tests and docs.
+
+Out of scope:
+
+- Changing the evaluator signature or the `EvalMetric` shape.
+- Multi-iteration test cases (AIP Evals has them; Semantica's runner is single-iteration per case).
+- Objective-aware aggregation beyond per-case `pass`/`fail` (existing `pass_rate` semantics are kept).
+
+## 3. Design
+
+### 3.1 Configuration surface
+
+Objective is configured per evaluator inside the runner's `config`, under the evaluator name:
+
+```python
+config = {
+ "<evaluator_name>": {
+ "objective": {
+ "direction": "maximize" | "minimize",
+ "threshold": <float>, # optional
+ }
+ }
+}
+```
+
+Boolean-form objective (shorthand): for metrics whose score is Boolean-like (0.0/1.0) or for semantic clarity, `{"objective": {"expect": true}}` / `{"objective": {"expect": false}}` is also supported.
+
+### 3.2 Evaluation semantics
+
+For each metric produced by an evaluator during a case run, if an objective exists for that evaluator name, the runner recomputes the metric's pass verdict:
+
+- **maximize**: pass iff `score >= threshold`. If no `threshold` is given, the objective is treated as absent (evaluator's own verdict stands) — see 3.4 rule 2.
+- **minimize**: pass iff `score <= threshold` (threshold required, see 3.4 rule 1).
+- **expect**: pass iff `bool(score)` equals `expect` (for Boolean-style metrics).
+
+When an objective is present, the runner **overrides** `metric.passed` with the objective verdict. When absent, `metric.passed` is used unchanged (existing behavior).
+
+The `objective` key is a **reserved runner-level key**: it is consumed by the runner and is passed through to the evaluator function inside `eval_config` (evaluators already ignore unknown config keys via `cfg.get(...)`, so this is harmless); evaluators must not rely on it. The runner re-decision happens on the metric the evaluator returns, so no evaluator change is required.
+
+### 3.3 Interaction with errors
+
+An `EvalMetric` whose `meta` contains `"error"` remains classified as an error regardless of objective (error wins over fail, per the existing contract). Objectives only affect non-error metrics.
+
+### 3.4 Ambiguity rules (explicit decisions)
+
+1. **`minimize` without `threshold`** is rejected at config-validation time with a clear error (`ValueError`), because "lowest is best" has no absolute pass bar without a threshold. (AIP Evals allows direction-only; we require threshold to keep pass/fail well-defined.) — *Chosen for determinism; revisit if a use case demands direction-only minimize.*
+2. **`maximize` without `threshold`** behaves like no objective (pass iff evaluator's own `passed`), because the evaluator's default is already "higher is better".
+3. **`expect` with a numeric `direction`/`threshold`** is a config error (`ValueError`): pick one form.
+4. **Objective on a metric that errors** → the error wins (3.3), objective ignored.
+
+### 3.5 Aggregation
+
+Unchanged:
+
+- Case `status`: `"error"` if any metric errored, else `"fail"` if any failed, else `"pass"`.
+- `pass_rate` = passed / total (1.0 on empty).
+- `metrics` dict holds the (possibly re-verdict'd) `EvalMetric`; the re-verdict is observable via `metric.passed`.
+- `details[name]` is populated when a metric ends up failed **after** objective re-decision (i.e. objective-failed metrics appear in `details`; metrics that pass under objective are not recorded there). This mirrors the existing "record failures in details" behavior applied to the final verdict.
+
+### 3.6 Files
+
+- `semantica/evals/runner.py` — add objective parsing/validation and re-decision inside the evaluator loop.
+- `tests/evals/test_runner.py` — new test class(es) for objective semantics.
+- `semantica/evals/usage.md` — document the objective config and examples.
+- `CHANGELOG.md` — `[Unreleased]` entry.
+
+No new dependencies; Python ≥ 3.8 (stdlib `typing`).
+
+## 4. Error handling
+
+- Invalid objective config (`direction` not in {maximize, minimize}, both `expect` and `direction`, `minimize` without threshold, non-numeric threshold) → `ValueError` raised at runner config parse, before any evaluator runs. Deterministic, fail-fast.
+- These are programmer errors, not per-case data errors — no per-case `error` status involved.
+
+## 5. Testing
+
+New tests in `tests/evals/test_runner.py`:
+
+1. maximize + threshold: score ≥ threshold → pass; below → fail.
+2. minimize + threshold: score ≤ threshold → pass; above → fail (e.g. levenshtein on a close pair).
+3. minimize without threshold → `ValueError`.
+4. expect=true / expect=false on a Boolean metric (exact_match) — pass/fail per expectation.
+5. no objective → existing behavior unchanged (evaluator's own verdict).
+6. objective + error metric → error wins (status=error, not fail).
+7. config error (bad direction) → `ValueError` raised by `evaluate()`.
+8. objective turns a passing metric into failing → `details` records it; case status becomes fail.
+9. backward-compat: all existing 62 tests keep passing.
+
+## 6. Compatibility
+
+- Public API (`evaluate`, `list_evaluators`, `get_evaluator`, types) unchanged in signature.
+- `EvalMetric` shape unchanged (score, passed, meta) — only `passed` may be recomputed by the runner.
+- Existing configs (no `objective` key) behave identically.
diff --git a/semantica/evals/__init__.py b/semantica/evals/__init__.py
index 8cc78b97..af1dd7af 100644
--- a/semantica/evals/__init__.py
+++ b/semantica/evals/__init__.py
@@ -1,10 +1,21 @@
-"""
-Semantica Evals Module
+"""Semantica Evals — evaluation layer for decision intelligence outputs.
-Coming Soon
+Provides a small library of deterministic and model-backed evaluators plus a
+runner for measuring decision records, audit trails, and reasoning output.
"""
-__version__ = "0.1.1"
-__status__ = "coming_soon"
-__all__ = []
+from . import decision_evaluators # noqa: F401 (registers decision_scores)
+from . import evaluators # noqa: F401 (registers the generic evaluators)
+from .registry import get_evaluator, list_evaluators
+from .runner import evaluate
+from .types import CaseResult, EvalMetric, EvalSummary
+__version__ = "0.1.0"
+__all__ = [
+ "evaluate",
+ "get_evaluator",
+ "list_evaluators",
+ "CaseResult",
+ "EvalMetric",
+ "EvalSummary",
+]
diff --git a/semantica/evals/decision_evaluators.py b/semantica/evals/decision_evaluators.py
new file mode 100644
index 00000000..93304f13
--- /dev/null
+++ b/semantica/evals/decision_evaluators.py
@@ -0,0 +1,90 @@
+"""Decision-specialized evaluator.
+
+``decision_scores`` validates a ``Decision`` (or dict) against field-level and
+governance-level checks: expected outcome, confidence bounds, non-empty
+required fields, provenance presence, and (when configured) policy compliance
+via ``PolicyEngine.check_compliance``.
+"""
+
+from typing import Any, Dict, Optional
+
+from .registry import register
+from .types import EvalMetric
+
+
+def _coerce_decision(actual: Any):
+ """Return a Decision or None; never raise for dict inputs."""
+ from semantica.context.decision_models import Decision
+
+ if isinstance(actual, Decision):
+ return actual
+ if isinstance(actual, dict):
+ try:
+ return Decision(**actual)
+ except (TypeError, ValueError, KeyError):
+ return None
+ return None
+
+
+@register("decision_scores")
+def decision_scores(actual, expected=None, config=None, **kwargs):
+ """Composite evaluator over a Decision; see module docstring for sub-checks."""
+ cfg = config or {}
+ decision = _coerce_decision(actual)
+ if decision is None:
+ return EvalMetric(0.0, False, {"error": "input is not a valid Decision or dict"})
+
+ checks: Dict[str, bool] = {}
+ reasons: Dict[str, str] = {}
+
+ expected_outcome = cfg.get("expected_outcome", expected)
+ if expected_outcome is not None:
+ checks["decision_outcome"] = decision.outcome == expected_outcome
+ if not checks["decision_outcome"]:
+ reasons["decision_outcome"] = f"expected {expected_outcome!r}, got {decision.outcome!r}"
+
+ lo = cfg.get("min_confidence", 0.0)
+ hi = cfg.get("max_confidence", 1.0)
+ checks["decision_confidence"] = lo <= decision.confidence <= hi
+ if not checks["decision_confidence"]:
+ reasons["decision_confidence"] = f"{decision.confidence} not in [{lo}, {hi}]"
+
+ for field in ("decision_maker", "reasoning", "scenario"):
+ value = getattr(decision, field, None)
+ checks[field] = isinstance(value, str) and bool(value.strip())
+ if not checks[field]:
+ reasons[field] = f"field {field!r} is empty"
+
+ metadata = decision.metadata if isinstance(decision.metadata, dict) else {}
+ prov = metadata.get(cfg.get("provenance_key", "provenance"))
+ checks["provenance"] = bool(prov)
+ if not checks["provenance"]:
+ reasons["provenance"] = "no provenance record found in metadata"
+
+ policy_engine = cfg.get("policy_engine")
+ policy_id = cfg.get("policy_id")
+ if policy_engine is not None and policy_id is not None:
+ try:
+ compliant = bool(policy_engine.check_compliance(decision, policy_id))
+ checks["policy"] = compliant == cfg.get("expected_policy_compliant", True)
+ if not checks["policy"]:
+ reasons["policy"] = f"compliance={compliant}"
+ except Exception as exc: # noqa: BLE001
+ checks["policy"] = False
+ reasons["policy"] = str(exc)
+
+ if cfg.get("causal_chain_exists"):
+ raise NotImplementedError(
+ "decision_scores causal_chain_exists is an interface slot reserved for V2"
+ )
+
+ passed_count = sum(checks.values())
+ total = len(checks)
+ passed = total > 0 and passed_count == total
+ meta = dict(checks)
+ meta["reasons"] = reasons
+ return EvalMetric(
+ score=passed_count / total if total else 0.0,
+ passed=passed,
+ meta=meta,
+ )
diff --git a/semantica/evals/evaluators.py b/semantica/evals/evaluators.py
new file mode 100644
index 00000000..e041e846
--- /dev/null
+++ b/semantica/evals/evaluators.py
@@ -0,0 +1,181 @@
+"""Generic (non-decision) evaluators for the evals module.
+
+Each evaluator takes ``(actual, expected, config=None, **kwargs)`` and returns
+an ``EvalMetric``. Config uses ``min``/``max`` bounds where relevant.
+"""
+
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+from .registry import register
+from .types import EvalMetric
+
+
+def _default_config(config):
+ return config or {}
+
+
+@register("exact_match")
+def exact_match(actual, expected, config=None, **kwargs):
+ """Score 1.0 if ``actual`` equals ``expected`` (scalar or list)."""
+ matched = actual == expected
+ return EvalMetric(
+ score=1.0 if matched else 0.0,
+ passed=matched,
+ meta={} if matched else {"reason": f"expected {expected!r}, got {actual!r}"},
+ )
+
+
+@register("regex_match")
+def regex_match(actual, expected, config=None, **kwargs):
+ """Score 1.0 if string ``actual`` matches regex ``expected``."""
+ import re
+ try:
+ matched = re.search(expected, actual) is not None
+ return EvalMetric(
+ score=1.0 if matched else 0.0,
+ passed=matched,
+ meta={} if matched else {"reason": f"'{actual}' does not match {expected}"},
+ )
+ except re.error as exc:
+ return EvalMetric(0.0, False, {"error": str(exc)})
+
+
+@register("numeric_range")
+def numeric_range(actual, expected=None, config=None, **kwargs):
+ """Score 1.0 if number ``actual`` is within inclusive ``[min, max]``."""
+ cfg = _default_config(config)
+ lo, hi = cfg.get("min"), cfg.get("max")
+ passed = lo is not None and hi is not None and lo <= actual <= hi
+ return EvalMetric(
+ score=1.0 if passed else 0.0,
+ passed=passed,
+ meta={} if passed else {"reason": f"{actual} not in [{lo}, {hi}]"},
+ )
+
+
+@register("temporal_range")
+def temporal_range(actual, expected=None, config=None, **kwargs):
+ """Score 1.0 if datetime ``actual`` is within inclusive ISO-datetime window."""
+ cfg = _default_config(config)
+ try:
+ stamp = datetime.fromisoformat(actual)
+ lo = datetime.fromisoformat(cfg["min"])
+ hi = datetime.fromisoformat(cfg["max"])
+ passed = lo <= stamp <= hi
+ return EvalMetric(
+ score=1.0 if passed else 0.0,
+ passed=passed,
+ meta={} if passed else {"reason": f"{actual} not in [{cfg['min']}, {cfg['max']}]"},
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ return EvalMetric(0.0, False, {"error": str(exc)})
+
+
+@register("length_range")
+def length_range(actual, expected=None, config=None, **kwargs):
+ """Score 1.0 if length of ``actual`` is within inclusive ``[min, max]``."""
+ cfg = _default_config(config)
+ size = len(actual)
+ lo = cfg.get("min", 0)
+ hi = cfg.get("max")
+ passed = hi is not None and lo <= size <= hi
+ return EvalMetric(
+ score=1.0 if passed else 0.0,
+ passed=passed,
+ meta={} if passed else {"reason": f"length {size} not in [{lo}, {hi}]"},
+ )
+
+
+@register("keyword_check")
+def keyword_check(actual, expected=None, config=None, **kwargs):
+ """Score 1.0 if all required terms appear in ``actual`` (word-boundary matching)."""
+ cfg = _default_config(config)
+ required = cfg.get("required") or (expected or [])
+ import re
+ tokens = set(re.findall(r"\w+", str(actual).lower()))
+ missing = [term for term in required if str(term).lower() not in tokens]
+ passed = not missing
+ return EvalMetric(
+ score=1.0 if passed else 0.0,
+ passed=passed,
+ meta={} if passed else {"missing": missing},
+ )
+
+
+def _levenshtein(a: str, b: str) -> int:
+ """Classic Levenshtein edit distance."""
+ if a == b:
+ return 0
+ if not a:
+ return len(b)
+ if not b:
+ return len(a)
+ prev = list(range(len(b) + 1))
+ for i, ca in enumerate(a, 1):
+ cur = [i]
+ for j, cb in enumerate(b, 1):
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
+ prev = cur
+ return prev[-1]
+
+
+@register("levenshtein")
+def levenshtein(actual, expected, config=None, **kwargs):
+ """Score normalized similarity (1 - distance/max_len) vs ``threshold`` (default 0.8)."""
+ cfg = _default_config(config)
+ threshold = cfg.get("threshold", 0.8)
+ a, b = str(actual), str(expected)
+ max_len = max(len(a), len(b))
+ similarity = 1.0 if max_len == 0 else 1.0 - _levenshtein(a, b) / max_len
+ passed = similarity >= threshold
+ return EvalMetric(
+ score=similarity,
+ passed=passed,
+ meta={"similarity": similarity},
+ )
+
+
+def _tokenize(text: str) -> List[str]:
+ import re
+ return re.findall(r"\w+", str(text).lower())
+
+
+@register("rouge")
+def rouge(actual, expected, config=None, **kwargs):
+ """ROUGE-1 precision/recall/F1 over tokens; pass on F1 >= ``threshold`` (default 0.0)."""
+ cfg = _default_config(config)
+ threshold = cfg.get("threshold", 0.0)
+ hyp, ref = _tokenize(actual), _tokenize(expected)
+ from collections import Counter
+ hyp_c, ref_c = Counter(hyp), Counter(ref)
+ overlap = sum((hyp_c & ref_c).values())
+ precision = overlap / len(hyp) if hyp else 0.0
+ recall = overlap / len(ref) if ref else 0.0
+ f1 = 0.0 if (precision + recall) == 0 else 2 * precision * recall / (precision + recall)
+ passed = f1 > 0 and f1 >= threshold
+ return EvalMetric(
+ score=f1,
+ passed=passed,
+ meta={"precision": precision, "recall": recall, "f1": f1},
+ )
+
+
+@register("llm_as_judge")
+def llm_as_judge(actual, expected, config=None, **kwargs):
+ """Score 1.0 when a caller-supplied ``judge_fn(actual, expected) -> bool`` passes.
+
+ The judge resolver stays lazy: no LLM backend is imported unless the caller
+ provides one in config.
+ """
+ cfg = _default_config(config)
+ judge_fn = cfg.get("judge_fn")
+ if judge_fn is None:
+ return EvalMetric(
+ 0.0, False, {"error": "config['judge_fn'] required (callable(actual, expected) -> bool)"}
+ )
+ try:
+ verdict = bool(judge_fn(actual, expected))
+ return EvalMetric(score=1.0 if verdict else 0.0, passed=verdict)
+ except Exception as exc: # noqa: BLE001
+ return EvalMetric(0.0, False, {"error": str(exc)})
diff --git a/semantica/evals/registry.py b/semantica/evals/registry.py
new file mode 100644
index 00000000..be650eba
--- /dev/null
+++ b/semantica/evals/registry.py
@@ -0,0 +1,34 @@
+"""Evaluator registry for the evals module.
+
+Evaluators are plain functions ``fn(actual, expected, config=None, **kwargs)
+-> EvalMetric`` registered under a stable string name so the runner and users
+can select them by name without importing individual modules.
+"""
+
+from typing import Callable, Dict, List
+
+from .types import EvalMetric
+
+EVALUATORS: Dict[str, Callable] = {}
+
+
+def register(name: str) -> Callable:
+ """Decorator registering an evaluator function under ``name``."""
+ def _register(fn: Callable) -> Callable:
+ if name in EVALUATORS:
+ raise ValueError(f"evaluator already registered: {name}")
+ EVALUATORS[name] = fn
+ return fn
+ return _register
+
+
+def list_evaluators() -> List[str]:
+ """Return sorted names of all registered evaluators."""
+ return sorted(EVALUATORS)
+
+
+def get_evaluator(name: str) -> Callable:
+ """Look up an evaluator by name, raising ValueError with a hint otherwise."""
+ if name not in EVALUATORS:
+ raise ValueError(f"unknown evaluator '{name}'. Available: {list_evaluators()}")
+ return EVALUATORS[name]
diff --git a/semantica/evals/runner.py b/semantica/evals/runner.py
new file mode 100644
index 00000000..815c4762
--- /dev/null
+++ b/semantica/evals/runner.py
@@ -0,0 +1,211 @@
+"""Evaluation runner: orchestrates evaluators over a list of cases."""
+
+import math
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+
+from .registry import get_evaluator
+from .types import CaseResult, EvalMetric, EvalSummary
+
+Case = Union[Dict[str, Any], Tuple[Any, Any]]
+
+
+def _coerce_threshold(name, threshold):
+ """Convert ``threshold`` to a finite float, raising ``ValueError`` otherwise.
+
+ Accepts any value that ``float()`` accepts (int, float, bool, numeric
+ strings) as long as the result is finite. Raises ``ValueError`` — never
+ ``TypeError`` — for non-convertible types, NaN, and infinity so that
+ all invalid objective config produces the same exception type.
+ """
+ try:
+ value = float(threshold)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(
+ f"objective for '{name}': 'threshold' must be a finite number "
+ f"(got {threshold!r})"
+ ) from exc
+ if not math.isfinite(value):
+ raise ValueError(
+ f"objective for '{name}': 'threshold' must be a finite number "
+ f"(got {threshold!r})"
+ )
+ return value
+
+
+def _parse_objective(name, eval_config):
+ """Return the validated objective dict, or None when not configured.
+
+ Raises ValueError for invalid configurations (programmer error).
+ """
+ objective = (eval_config or {}).get("objective")
+ if objective is None:
+ return None
+ if not isinstance(objective, dict):
+ raise ValueError(
+ f"objective for '{name}': expected a dict, got {type(objective).__name__}"
+ )
+ direction = objective.get("direction")
+ threshold = objective.get("threshold")
+ expect = objective.get("expect")
+
+ if expect is not None:
+ if not isinstance(expect, bool):
+ raise ValueError(
+ f"objective for '{name}': 'expect' must be a bool (got {expect!r})"
+ )
+ if direction is not None or threshold is not None:
+ raise ValueError(
+ f"objective for '{name}': 'expect' cannot be combined with "
+ "'direction' or 'threshold'"
+ )
+ return {"expect": expect}
+ if direction == "minimize":
+ if threshold is None:
+ raise ValueError(
+ f"objective for '{name}': 'minimize' requires a 'threshold'"
+ )
+ return {"direction": "minimize", "threshold": _coerce_threshold(name, threshold)}
+ if direction == "maximize":
+ if threshold is None:
+ # no bar to re-decide against; treat as absent (evaluator default stands)
+ return None
+ return {"direction": "maximize", "threshold": _coerce_threshold(name, threshold)}
+ raise ValueError(
+ f"objective for '{name}': 'direction' must be 'maximize' or 'minimize' "
+ f"(got {direction!r})"
+ )
+
+
+def _apply_objective(metric, objective):
+ """Return the objective-adjusted pass verdict for a non-error metric."""
+ if "expect" in objective:
+ return bool(metric.score) == objective["expect"]
+ if objective["direction"] == "minimize":
+ return metric.score <= objective["threshold"]
+ return metric.score >= objective["threshold"]
+
+
+def _extract(case: Case, target_fn: Optional[Callable]):
+ """Return (case_id, expected, actual, config, per_case_target_fn)."""
+ if isinstance(case, tuple):
+ expected, actual = case[0], (case[1] if len(case) > 1 else None)
+ return str(id(case)), expected, actual, {}, None
+ case_id = case.get("id") or f"case-{id(case)}"
+ expected = case.get("expected")
+ actual = case.get("actual")
+ config = case.get("config") or {}
+ per_fn = case.get("target_fn")
+ return case_id, expected, actual, config, per_fn
+
+
+def _merge_config(default_config: Dict[str, Any], case_config: Dict[str, Any]) -> Dict[str, Any]:
+ """Deep-merge per-case config over the global config (two levels deep).
+
+ Level 1 (top-level keys, e.g. evaluator names): merged key-by-key so a
+ per-case override of one evaluator's settings does not erase the whole
+ global evaluator entry.
+
+ Level 2 (evaluator config keys, e.g. ``"objective"``): also merged
+ key-by-key so a per-case override that specifies only some objective fields
+ (e.g. just ``"threshold"``) inherits the rest from the global objective
+ (e.g. ``"direction"``). Per-case values always take precedence.
+
+ Depth-3+ values are replaced wholesale, consistent with the previous
+ single-level behaviour (no evaluator config currently nests beyond two
+ levels). Neither the caller's global config nor the case config is
+ mutated.
+ """
+ merged = dict(default_config)
+ for key, value in (case_config or {}).items():
+ if isinstance(value, dict) and isinstance(merged.get(key), dict):
+ # Merge level-1 dict (evaluator config) key-by-key.
+ current = dict(merged[key])
+ for k, v in value.items():
+ if isinstance(v, dict) and isinstance(current.get(k), dict):
+ # Merge level-2 dict (e.g. objective sub-dict) key-by-key.
+ inner = dict(current[k])
+ inner.update(v)
+ current[k] = inner
+ else:
+ current[k] = v
+ merged[key] = current
+ else:
+ merged[key] = value
+ return merged
+
+
+def evaluate(
+ cases: List[Case],
+ evaluators: List[str],
+ config: Optional[Dict[str, Any]] = None,
+ target_fn: Optional[Callable] = None,
+) -> EvalSummary:
+ """Run named evaluators over each case and aggregate metrics.
+
+ A per-case or top-level ``target_fn`` produces ``actual`` when the case
+ does not already carry one. Evaluator failures become ``error`` results.
+ """
+ default_config = config or {}
+ case_results: List[CaseResult] = []
+
+ # Validate objective config for every case up front so an invalid objective
+ # rejects the run before any target_fn or evaluator executes (fail-fast),
+ # regardless of which case carries it.
+ pre_resolved = []
+ for case in cases:
+ _, _, _, case_config, _ = _extract(case, target_fn)
+ merged = _merge_config(default_config, case_config)
+ pre_resolved.append(
+ {
+ name: _parse_objective(name, merged.get(name) or {})
+ for name in evaluators
+ }
+ )
+
+ for case, objective_by_name in zip(cases, pre_resolved):
+ case_id, expected, actual, case_config, per_fn = _extract(case, target_fn)
+ merged = _merge_config(default_config, case_config)
+ if expected is None:
+ expected = merged.get("expected")
+ resolver = per_fn or target_fn
+ if actual is None and resolver is not None:
+ try:
+ actual = resolver(case)
+ except Exception as exc: # noqa: BLE001
+ case_results.append(
+ CaseResult(case_id, "error", {}, {"target_fn": str(exc)})
+ )
+ continue
+ metrics: Dict[str, EvalMetric] = {}
+ details: Dict[str, Any] = {}
+ failed, errored = False, False
+ for name in evaluators:
+ eval_config = merged.get(name) or {}
+ try:
+ metric = get_evaluator(name)(actual, expected, config=eval_config)
+ objective = objective_by_name.get(name)
+ if objective is not None and "error" not in metric.meta:
+ metric = EvalMetric(metric.score, _apply_objective(metric, objective), metric.meta)
+ metrics[name] = metric
+ if "error" in metric.meta:
+ errored = True
+ details[name] = metric.meta
+ elif not metric.passed:
+ failed = True
+ details[name] = metric.meta
+ except Exception as exc: # noqa: BLE001
+ errored = True
+ metrics[name] = EvalMetric(0.0, False, {"error": str(exc)})
+ details[name] = {"error": str(exc)}
+ status = "error" if errored else ("fail" if failed else "pass")
+ case_results.append(CaseResult(case_id, status, metrics, details))
+
+ total = len(case_results)
+ passed = sum(1 for c in case_results if c.status == "pass")
+ failed = sum(1 for c in case_results if c.status == "fail")
+ errors = sum(1 for c in case_results if c.status == "error")
+ pass_rate = (passed / total) if total else 1.0
+ return EvalSummary(
+ total, passed, failed, errors, pass_rate,
+ cases=case_results,
+ )
diff --git a/semantica/evals/types.py b/semantica/evals/types.py
new file mode 100644
index 00000000..54b01edf
--- /dev/null
+++ b/semantica/evals/types.py
@@ -0,0 +1,37 @@
+"""Evals result data models.
+
+Defines the metric and result shapes produced by the evals module.
+"""
+
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, NamedTuple
+
+
+@dataclass(frozen=True)
+class EvalMetric:
+ """One evaluator's numeric score plus pass/fail verdict."""
+
+ score: float
+ passed: bool
+ meta: Dict[str, Any] = field(default_factory=dict)
+
+
+class CaseResult(NamedTuple):
+ """Evaluation output for a single case."""
+
+ case_id: str
+ status: str
+ metrics: Dict[str, EvalMetric]
+ details: Dict[str, Any]
+
+
+@dataclass
+class EvalSummary:
+ """Aggregate evaluation output across cases."""
+
+ total: int
+ passed: int
+ failed: int
+ errors: int
+ pass_rate: float
+ cases: List[CaseResult] = field(default_factory=list)
diff --git a/semantica/evals/usage.md b/semantica/evals/usage.md
new file mode 100644
index 00000000..aab237ae
--- /dev/null
+++ b/semantica/evals/usage.md
@@ -0,0 +1,176 @@
+# Semantica Evals — Usage
+
+The evals module measures decision intelligence outputs: decision records,
+audit trails, and reasoning output — with deterministic and model-backed
+evaluators plus a small runner.
+
+## Import
+
+```python
+import semantica.evals as evals # through the root lazy proxy
+from semantica.evals import evaluate, list_evaluators
+```
+
+## Discover evaluators
+
+```python
+>>> evals.list_evaluators()
+['decision_scores', 'exact_match', 'keyword_check', 'length_range',
+ 'levenshtein', 'llm_as_judge', 'numeric_range', 'regex_match', 'rouge',
+ 'temporal_range']
+```
+
+`list_evaluators` returns every name registered by importing the package —
+the import wiring runs each evaluator module's `register()` side effects.
+
+## Run the runner over decision records
+
+`evaluate(cases, evaluators, config=None)` accepts a list of cases; each case is
+a dict with `expected`, `actual`, optional `config`, and optional `id`. The
+`actual` can be a finished `Decision` object or its dict form.
+
+```python
+from datetime import datetime
+from semantica.context.decision_models import Decision
+from semantica.evals import evaluate
+
+decision = Decision(
+ decision_id="d-1",
+ category="loan",
+ scenario="loan-request",
+ reasoning="vetted by policy",
+ outcome="approve",
+ confidence=0.87,
+ timestamp=datetime.now(),
+ decision_maker="approver-a",
+ metadata={"provenance": "workflow:loan/v3"},
+)
+
+cases = [
+ {
+ "id": "loan-001",
+ "actual": decision,
+ "config": {
+ "decision_scores": {
+ "expected_outcome": "approve",
+ "min_confidence": 0.7,
+ }
+ },
+ },
+ {
+ "id": "loan-002",
+ "actual": {
+ "decision_id": "d-2",
+ "category": "loan",
+ "scenario": "loan-request",
+ "reasoning": "auto",
+ "outcome": "reject",
+ "confidence": 0.9,
+ "timestamp": datetime.now().isoformat(),
+ "decision_maker": "system",
+ "metadata": {},
+ },
+ "config": {
+ "decision_scores": {
+ "expected_outcome": "approve",
+ "min_confidence": 0.7,
+ }
+ },
+ },
+]
+
+summary = evaluate(cases, ["decision_scores"])
+```
+
+`evaluate` also runs high-level names like `exact_match`, `keyword_check`, or
+`llm_as_judge`; per-case or top-level `config` may carry per-evaluator settings
+(e.g. `config={"exact_match": {...}}`).
+
+## Set per-evaluator objectives
+
+By default each evaluator decides its own pass/fail. To override that
+verdict at the run level, configure an **objective** per evaluator name:
+
+```python
+from semantica.evals import evaluate
+
+# Require a minimum similarity (levenshtein's default bar is >= 0.8; here we set 0.7):
+evaluate(
+ [("apple", "aple")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.7}}},
+)
+
+# Lower is better — override the direction:
+evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.7}}},
+)
+
+# Boolean expectation — the metric matches (score 1), but we expect it not to:
+evaluate(
+ [("ok", "ok")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": False}}},
+)
+```
+
+Rules:
+
+- `maximize` + `threshold`: pass iff `score >= threshold`. `maximize` without
+ a threshold is a no-op (the evaluator's own verdict stands).
+- `minimize` + `threshold`: pass iff `score <= threshold`. `minimize`
+ **requires** a threshold — omitting it or setting it to `None` raises
+ `ValueError`.
+- `expect` (`true`/`false`): pass iff `bool(score)` matches; cannot be
+ combined with `direction`/`threshold`. `expect` must be a real boolean
+ (a string like `"false"` is rejected).
+- A metric whose `meta` contains `"error"` is always an error, never affected
+ by an objective.
+- Invalid objective config (non-dict objective, bad `direction`, non-bool
+ `expect`, missing `minimize` threshold) raises `ValueError` before any
+ evaluator runs.
+
+## Interpret the summary
+
+```python
+>>> summary.total, summary.passed, summary.failed, summary.errors
+(2, 1, 1, 0)
+>>> summary.pass_rate
+0.5
+
+>>> for case in summary.cases:
+... print(case.case_id, case.status)
+... for name, metric in case.metrics.items():
+... print(" ", name, metric.score, metric.passed)
+... print(" ", metric.meta.get("reasons"))
+loan-001 pass
+ decision_scores 1.0 True
+ {}
+loan-002 fail
+ decision_scores 0.667 False
+ {'decision_outcome': "expected 'approve', got 'reject'",
+ 'provenance': 'no provenance record found in metadata'}
+```
+
+`EvalSummary` fields:
+
+- `total` / `passed` / `failed` / `errors` — case counts by status.
+- `pass_rate` — `passed / total` (1.0 on an empty case list).
+- `cases` — one `CaseResult` per input case: `case_id`, `status`
+ (`pass` | `fail` | `error`), `metrics` (name → `EvalMetric` with `score`,
+ `passed`, `meta`), and `details`.
+
+Evaluator failures do not crash the run; they surface as `status="error"` on
+the affected case with the exception text captured in the metric meta.
+
+## Notes
+
+- **`llm_as_judge` needs `config["judge_fn"]`**: a callable
+ `judge_fn(actual, expected) -> bool` supplied by the caller. Without it the
+ evaluator fails with `config['judge_fn'] required`.
+- **`decision_scores` governance checks are opt-in**: policy compliance is only
+ evaluated when both `config["policy_engine"]` and `config["policy_id"]` are
+ provided; otherwise those checks are skipped. The reserved
+ `causal_chain_exists` slot is not yet implemented.
\ No newline at end of file
diff --git a/tests/evals/test_decision_evaluators.py b/tests/evals/test_decision_evaluators.py
new file mode 100644
index 00000000..a9d17c35
--- /dev/null
+++ b/tests/evals/test_decision_evaluators.py
@@ -0,0 +1,136 @@
+"""Tests for the decision_scores composite evaluator."""
+import pytest
+from datetime import datetime
+
+from semantica.context.decision_models import Decision
+from semantica.evals import registry as reg
+
+
+def _decision(**overrides):
+ base = dict(
+ decision_id="d1",
+ category="loan",
+ scenario="mortgage application",
+ reasoning="strong credit history",
+ outcome="approved",
+ confidence=0.95,
+ timestamp=datetime(2026, 1, 1),
+ decision_maker="loan_officer",
+ )
+ base.update(overrides)
+ return Decision(**base)
+
+
+class TestDecisionScores:
+ def test_full_pass(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(
+ d, config={"expected_outcome": "approved"}
+ )
+ assert r.passed
+ assert r.meta["decision_outcome"] is True
+ assert r.meta["provenance"] is True
+
+ def test_outcome_mismatch(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(
+ d, config={"expected_outcome": "denied"}
+ )
+ assert not r.passed
+ assert r.meta["decision_outcome"] is False
+
+ def test_outcome_from_expected_argument(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(d, expected="approved")
+ assert r.passed
+ assert r.meta["decision_outcome"] is True
+
+ def test_outcome_mismatch_via_expected_argument(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(d, expected="denied")
+ assert not r.passed
+ assert r.meta["decision_outcome"] is False
+ assert "decision_outcome" in r.meta["reasons"]
+
+ def test_outcome_check_skipped_when_no_expected(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(d)
+ assert "decision_outcome" not in r.meta
+
+ def test_confidence_out_of_range(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}}, confidence=0.4)
+ r = reg.get_evaluator("decision_scores")(
+ d, config={"expected_outcome": "approved", "min_confidence": 0.8}
+ )
+ assert not r.passed
+ assert r.meta["decision_confidence"] is False
+
+ def test_missing_provenance_fails(self):
+ d = _decision(metadata={})
+ r = reg.get_evaluator("decision_scores")(d, config={"expected_outcome": "approved"})
+ assert not r.passed
+ assert r.meta["provenance"] is False
+
+ def test_missing_required_fields(self):
+ d = _decision(reasoning="")
+ r = reg.get_evaluator("decision_scores")(d, config={"expected_outcome": "approved"})
+ assert not r.passed
+ assert r.meta["reasoning"] is False
+
+ def test_dict_input_coerced(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ as_dict = d.to_dict()
+ r = reg.get_evaluator("decision_scores")(
+ as_dict, config={"expected_outcome": "approved"}
+ )
+ assert r.passed
+
+ def test_malformed_dict_is_error_not_crash(self):
+ r = reg.get_evaluator("decision_scores")({"foo": "bar"}, config={})
+ assert not r.passed
+ assert r.meta.get("error")
+
+ def test_non_dict_metadata_is_error_not_crash(self):
+ bad = _decision(metadata="not-a-dict")
+ r = reg.get_evaluator("decision_scores")(bad, config={})
+ assert not r.passed
+ assert r.meta["provenance"] is False
+
+ def test_policy_compliance_check(self):
+ class FakePolicyEngine:
+ def check_compliance(self, decision, policy_id):
+ return True
+
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(
+ d, config={
+ "expected_outcome": "approved",
+ "policy_engine": FakePolicyEngine(),
+ "policy_id": "p1",
+ "expected_policy_compliant": True,
+ }
+ )
+ assert r.meta["policy"] is True
+
+ def test_policy_mismatch_fails(self):
+ class FakePolicyEngine:
+ def check_compliance(self, decision, policy_id):
+ return False
+
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}})
+ r = reg.get_evaluator("decision_scores")(
+ d, config={
+ "policy_engine": FakePolicyEngine(),
+ "policy_id": "p1",
+ "expected_policy_compliant": True,
+ }
+ )
+ assert not r.passed
+ assert r.meta["policy"] is False
+
+ def test_causal_chain_gate(self):
+ d = _decision(metadata={"provenance": {"prov_record": "rid-1"}}, decision_id="only-decision")
+ with pytest.raises(NotImplementedError):
+ reg.get_evaluator("decision_scores")(
+ d, config={"causal_chain_exists": True, "graph_store": object()}
+ )
diff --git a/tests/evals/test_evaluators_part1.py b/tests/evals/test_evaluators_part1.py
new file mode 100644
index 00000000..f4c8f52e
--- /dev/null
+++ b/tests/evals/test_evaluators_part1.py
@@ -0,0 +1,81 @@
+"""Tests for generic evaluators: exact, regex, ranges, length."""
+import pytest
+
+from semantica.evals import registry as reg
+
+
+class TestExactMatch:
+ def test_exact_str(self):
+ r = reg.get_evaluator("exact_match")("approved", "approved")
+ assert r.passed and r.score == 1.0
+
+ def test_exact_str_negative(self):
+ r = reg.get_evaluator("exact_match")("approved", "denied")
+ assert not r.passed and r.score == 0.0
+
+ def test_exact_number(self):
+ r = reg.get_evaluator("exact_match")(5, 5)
+ assert r.passed
+
+ def test_exact_array(self):
+ r = reg.get_evaluator("exact_match")([1, 2], [1, 2])
+ assert r.passed
+
+
+class TestRegexMatch:
+ def test_matching(self):
+ r = reg.get_evaluator("regex_match")("abc123", r"^[a-z]+\d+$")
+ assert r.passed
+
+ def test_non_matching(self):
+ r = reg.get_evaluator("regex_match")("ABC", r"^[a-z]+$")
+ assert not r.passed
+ assert "ABC" in r.meta.get("reason", "")
+
+ def test_invalid_regex_is_error_metric(self):
+ r = reg.get_evaluator("regex_match")("x", "[invalid")
+ assert not r.passed
+ assert r.meta.get("error")
+
+
+class TestNumericRange:
+ def test_inside(self):
+ r = reg.get_evaluator("numeric_range")(0.9, config={"min": 0.8, "max": 1.0})
+ assert r.passed and r.score == 1.0
+
+ def test_outside(self):
+ r = reg.get_evaluator("numeric_range")(0.5, config={"min": 0.8, "max": 1.0})
+ assert not r.passed and r.score == 0.0
+
+ def test_bounds_inclusive(self):
+ assert reg.get_evaluator("numeric_range")(0.8, config={"min": 0.8, "max": 0.8}).passed
+
+
+class TestTemporalRange:
+ def test_inside_window(self):
+ r = reg.get_evaluator("temporal_range")(
+ "2026-01-15T10:00:00",
+ config={"min": "2026-01-01T00:00:00", "max": "2026-02-01T00:00:00"},
+ )
+ assert r.passed
+
+ def test_outside_window(self):
+ r = reg.get_evaluator("temporal_range")(
+ "2026-03-01T00:00:00",
+ config={"min": "2026-01-01T00:00:00", "max": "2026-02-01T00:00:00"},
+ )
+ assert not r.passed
+
+
+class TestLengthRange:
+ def test_ok(self):
+ r = reg.get_evaluator("length_range")("hello", config={"min": 3, "max": 5})
+ assert r.passed
+
+ def test_too_long(self):
+ r = reg.get_evaluator("length_range")([1, 2, 3], config={"min": 1, "max": 2})
+ assert not r.passed
+
+ def test_min_not_given_defaults_zero(self):
+ r = reg.get_evaluator("length_range")("abc", config={"max": 5})
+ assert r.passed
diff --git a/tests/evals/test_evaluators_part2.py b/tests/evals/test_evaluators_part2.py
new file mode 100644
index 00000000..3392b035
--- /dev/null
+++ b/tests/evals/test_evaluators_part2.py
@@ -0,0 +1,67 @@
+"""Tests for generic evaluators: keyword, levenshtein, rouge, llm-as-judge."""
+import pytest
+
+from semantica.evals import registry as reg
+
+
+class TestKeywordCheck:
+ def test_all_required_present(self):
+ r = reg.get_evaluator("keyword_check")(
+ "the loan was approved", expected=["loan", "approved"]
+ )
+ assert r.passed
+
+ def test_missing_keyword(self):
+ r = reg.get_evaluator("keyword_check")(
+ "the loan was approved", expected=["loan", "denied"]
+ )
+ assert not r.passed
+ assert "denied" in r.meta.get("missing", [])
+
+ def test_short_words_ignored(self):
+ r = reg.get_evaluator("keyword_check")("x and y", expected=["and"])
+ assert r.passed
+
+
+class TestLevenshtein:
+ def test_identical(self):
+ r = reg.get_evaluator("levenshtein")("credit approved", "credit approved")
+ assert r.passed
+
+ def test_close_above_threshold(self):
+ r = reg.get_evaluator("levenshtein")(
+ "credit approved", "credit denied", config={"threshold": 0.8}
+ )
+ assert not r.passed
+
+ def test_default_threshold(self):
+ assert reg.get_evaluator("levenshtein")("a", "a").passed
+
+
+class TestRouge:
+ def test_identical(self):
+ r = reg.get_evaluator("rouge")("loan approved by committee", "loan approved by committee")
+ assert r.passed
+ assert r.meta["f1"] == pytest.approx(1.0)
+
+ def test_no_overlap(self):
+ r = reg.get_evaluator("rouge")("one two three", "four five six")
+ assert not r.passed
+
+ def test_partial_sets_meta(self):
+ r = reg.get_evaluator("rouge")("a b c", "a b d", config={"threshold": 0.5})
+ assert "precision" in r.meta and "recall" in r.meta
+
+
+class TestLlmAsJudge:
+ def test_uses_supplied_judge(self):
+ judge = lambda actual, expected: actual == expected # noqa: E731
+ r = reg.get_evaluator("llm_as_judge")(
+ "x", "x", config={"judge_fn": judge}
+ )
+ assert r.passed
+
+ def test_missing_judge_is_error(self):
+ r = reg.get_evaluator("llm_as_judge")("x", "y", config={})
+ assert not r.passed
+ assert r.meta.get("error")
diff --git a/tests/evals/test_public_api.py b/tests/evals/test_public_api.py
new file mode 100644
index 00000000..e76eb4b8
--- /dev/null
+++ b/tests/evals/test_public_api.py
@@ -0,0 +1,32 @@
+"""Tests for the evals public package API."""
+from semantica import evals
+from semantica.evals import evaluate, get_evaluator, list_evaluators
+
+
+class TestPublicAPI:
+ def test_imports(self):
+ assert callable(evaluate)
+ assert callable(list_evaluators)
+ assert callable(get_evaluator)
+
+ def test_version_present(self):
+ assert hasattr(evals, "__version__")
+
+ def test_module_proxy_via_root(self):
+ # semantica.evals must resolve through the lazy proxy
+ assert hasattr(evals, "evaluate")
+
+ def test_all_populated(self):
+ assert len(evals.__all__) >= 2
+ assert "evaluate" in evals.__all__
+ assert "list_evaluators" in evals.__all__
+ assert "get_evaluator" in evals.__all__
+
+ def test_register_discovery(self):
+ names = evals.list_evaluators()
+ for expected in (
+ "exact_match", "regex_match", "numeric_range", "temporal_range",
+ "length_range", "keyword_check", "levenshtein", "rouge",
+ "llm_as_judge", "decision_scores",
+ ):
+ assert expected in names
diff --git a/tests/evals/test_registry.py b/tests/evals/test_registry.py
new file mode 100644
index 00000000..f8014aab
--- /dev/null
+++ b/tests/evals/test_registry.py
@@ -0,0 +1,36 @@
+"""Tests for the evaluator registry."""
+import pytest
+
+from semantica.evals import registry as reg
+from semantica.evals.types import EvalMetric
+
+# A unique name that will not collide with any production evaluator.
+_TEST_EVAL_NAME = "test_registry_demo_eval"
+
+
+class TestRegistry:
+ def teardown_method(self, method):
+ # Remove the test evaluator after each test that may have registered it,
+ # so re-runs and randomised collection cannot see stale state.
+ reg.EVALUATORS.pop(_TEST_EVAL_NAME, None)
+
+ def test_register_and_get(self):
+ @reg.register(_TEST_EVAL_NAME)
+ def demo(actual, expected, config=None, **kwargs):
+ return EvalMetric(1.0, True)
+
+ assert reg.get_evaluator(_TEST_EVAL_NAME) is demo
+ assert _TEST_EVAL_NAME in reg.list_evaluators()
+
+ def test_registration_is_immutable_after_commit(self):
+ with pytest.raises(ValueError):
+ reg.get_evaluator("does_not_exist")
+
+ def test_unknown_evaluator_failure_message(self):
+ with pytest.raises(ValueError) as exc:
+ reg.get_evaluator("nope")
+ msg = str(exc.value)
+ assert "nope" in msg
+ # The error message lists available evaluators; verify using a name
+ # that is always registered at import time (independent of test order).
+ assert "exact_match" in msg
diff --git a/tests/evals/test_runner.py b/tests/evals/test_runner.py
new file mode 100644
index 00000000..f084c0b9
--- /dev/null
+++ b/tests/evals/test_runner.py
@@ -0,0 +1,459 @@
+"""Tests for the evals runner."""
+import pytest
+
+from semantica.evals.runner import evaluate
+
+
+class TestEvaluate:
+ def test_raw_tuple_cases(self):
+ result = evaluate(
+ [("approved", "approved"), ("approved", "denied")],
+ evaluators=["exact_match"],
+ )
+ assert result.total == 2
+ assert result.passed == 1
+ assert result.failed == 1
+ assert result.errors == 0
+ assert result.pass_rate == 0.5
+
+ def test_dict_cases_with_target_fn(self):
+ def fn(case):
+ return "ok" if case["id"] == "good" else "no"
+
+ result = evaluate(
+ [{"id": "good"}, {"id": "bad"}],
+ evaluators=["exact_match"],
+ target_fn=fn,
+ config={"expected": "ok"},
+ )
+ assert result.passed == 1
+ assert result.failed == 1
+
+ def test_error_capture(self):
+ result = evaluate([("x", "y")], evaluators=["does_not_exist"])
+ assert result.errors == 1
+ assert result.failed == 0
+ assert result.pass_rate == 0.0
+
+ def test_error_metric_classified_as_error(self):
+ result = evaluate(
+ [("[invalid", "x")],
+ evaluators=["regex_match"],
+ )
+ assert result.errors == 1
+ assert result.failed == 0
+ assert result.cases[0].status == "error"
+
+ def test_error_metric_and_fail_combine_as_error(self):
+ result = evaluate(
+ [("[invalid", "apple pie")],
+ evaluators=["regex_match", "exact_match"],
+ )
+ assert result.errors == 1
+ assert result.failed == 0
+ assert result.cases[0].status == "error"
+
+ def test_per_case_details(self):
+ result = evaluate([("a", "b")], evaluators=["exact_match"])
+ case = result.cases[0]
+ assert case.status == "fail"
+ assert "exact_match" in case.details
+
+ def test_empty_cases(self):
+ result = evaluate([], evaluators=["exact_match"])
+ assert result.total == 0 and result.pass_rate == 1.0
+
+ def test_multiple_evaluators(self):
+ result = evaluate(
+ [("apple pie", "apple pie")],
+ evaluators=["exact_match", "keyword_check"],
+ config={"keyword_check": {"required": ["apple"]}},
+ )
+ assert result.passed == 1
+ assert "exact_match" in result.cases[0].metrics
+ assert "keyword_check" in result.cases[0].metrics
+
+
+class TestObjective:
+ def test_maximize_with_threshold_pass(self):
+ # levenshtein similarity 1.0 for identical, objective demands >= 0.5
+ result = evaluate(
+ [("apple", "apple")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.5}}},
+ )
+ assert result.cases[0].status == "pass"
+ assert result.cases[0].metrics["levenshtein"].passed is True
+
+ def test_maximize_with_threshold_fail(self):
+ result = evaluate(
+ [("apple", "aple")], # similarity < 1.0
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.99}}},
+ )
+ assert result.cases[0].status == "fail"
+ assert result.cases[0].metrics["levenshtein"].passed is False
+ assert "levenshtein" in result.cases[0].details
+
+ def test_minimize_with_threshold_pass(self):
+ # levenshtein similarity 0.6 for ("night", "nacht"); objective: similarity <= 0.7
+ result = evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.7}}},
+ )
+ assert result.cases[0].status == "pass"
+ assert result.cases[0].metrics["levenshtein"].passed is True
+
+ def test_minimize_with_threshold_fail(self):
+ result = evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.1}}},
+ )
+ assert result.cases[0].status == "fail"
+
+ def test_expect_true_on_boolean_metric(self):
+ result = evaluate(
+ [("ok", "ok")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": True}}},
+ )
+ assert result.cases[0].status == "pass"
+
+ def test_expect_false_overrides_passing_metric(self):
+ # exact_match passes (score 1.0) but expectation is false -> fail
+ result = evaluate(
+ [("ok", "ok")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": False}}},
+ )
+ assert result.cases[0].status == "fail"
+ assert result.cases[0].metrics["exact_match"].passed is False
+ assert "exact_match" in result.cases[0].details
+
+ def test_maximize_without_threshold_is_noop(self):
+ # identical behavior to no objective: evaluator's own verdict stands
+ result = evaluate(
+ [("ok", "no")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"direction": "maximize"}}},
+ )
+ assert result.cases[0].status == "fail"
+
+ def test_minimize_without_threshold_raises(self):
+ # direction-only minimize has no well-defined pass bar; must be rejected
+ with pytest.raises(ValueError, match="'minimize' requires a 'threshold'"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize"}}},
+ )
+
+ def test_minimize_with_explicit_none_threshold_raises(self):
+ # explicit threshold=None is the same as omitting it; must also be rejected
+ with pytest.raises(ValueError, match="'minimize' requires a 'threshold'"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": None}}},
+ )
+
+ def test_bad_direction_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "sideways", "threshold": 0.5}}},
+ )
+
+ def test_expect_with_direction_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"expect": True, "direction": "maximize"}}},
+ )
+
+ def test_error_metric_wins_over_objective(self):
+ result = evaluate(
+ [("[invalid", "x")],
+ evaluators=["regex_match"],
+ config={"regex_match": {"objective": {"direction": "maximize", "threshold": 0.0}}},
+ )
+ assert result.cases[0].status == "error"
+ assert result.errors == 1
+ assert result.failed == 0
+
+ def test_no_objective_unchanged(self):
+ result = evaluate([("ok", "no")], evaluators=["exact_match"])
+ assert result.cases[0].status == "fail"
+
+ def test_non_dict_objective_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": "maximize"}},
+ )
+
+ def test_non_bool_expect_raises(self):
+ with pytest.raises(ValueError):
+ evaluate(
+ [("a", "b")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"expect": "false"}}},
+ )
+
+ def test_invalid_per_case_objective_fails_fast_before_target_fn(self):
+ calls = []
+
+ def side_effectful_target_fn(case):
+ calls.append(case)
+ return "line"
+
+ with pytest.raises(ValueError):
+ evaluate(
+ [{"id": "c1"}, {"id": "c2", "config": {"levenshtein": {"objective": {"direction": "diagonal"}}}}],
+ evaluators=["levenshtein"],
+ target_fn=side_effectful_target_fn,
+ )
+ # validation must reject the run before any case is processed
+ assert calls == []
+
+ def test_case_config_keeps_global_objective(self):
+ # global objective on the evaluator must survive a per-case override
+ # that touches other settings for the same evaluator (deep merge)
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"ignore_case": False}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.0}}},
+ )
+ # levenshtein("abc","abd") == 1 > 0 -> objective fails the case
+ assert result.cases[0].status == "fail"
+
+
+class TestMergeConfig:
+ """Focused tests for _merge_config two-level deep-merge semantics."""
+
+ def test_partial_per_case_objective_inherits_global_direction(self):
+ # Per-case overrides only threshold; direction must come from global.
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"objective": {"threshold": 0.99}}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.0}}},
+ )
+ # Effective objective: minimize, threshold=0.99.
+ # levenshtein("abc","abd") similarity ~0.667; 0.667 <= 0.99 -> pass.
+ assert result.cases[0].status == "pass"
+ assert result.cases[0].metrics["levenshtein"].passed is True
+
+ def test_partial_per_case_objective_inherits_global_threshold(self):
+ # Per-case overrides only direction; threshold must come from global.
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"objective": {"direction": "maximize"}}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.99}}},
+ )
+ # Effective objective: maximize, threshold=0.99.
+ # levenshtein("abc","abd") similarity ~0.667; 0.667 >= 0.99 -> fail.
+ assert result.cases[0].status == "fail"
+ assert result.cases[0].metrics["levenshtein"].passed is False
+
+ def test_per_case_threshold_overrides_global_threshold(self):
+ # Global: minimize, threshold=0.0 (would fail for any positive score).
+ # Per-case: threshold=0.99 (almost everything passes minimize).
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"objective": {"threshold": 0.99}}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.0}}},
+ )
+ # Effective: minimize, threshold=0.99 -> ~0.667 <= 0.99 -> pass.
+ assert result.cases[0].status == "pass"
+
+ def test_per_case_direction_overrides_global_direction(self):
+ # Global: maximize, threshold=0.99 (would fail for ~0.667).
+ # Per-case: direction=minimize (with inherited threshold=0.99).
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"objective": {"direction": "minimize"}}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.99}}},
+ )
+ # Effective: minimize, threshold=0.99 -> ~0.667 <= 0.99 -> pass.
+ assert result.cases[0].status == "pass"
+
+ def test_fully_specified_per_case_objective_replaces_global(self):
+ # Both direction and threshold specified per-case; nothing from global.
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"objective": {"direction": "maximize", "threshold": 0.5}}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.0}}},
+ )
+ # Effective: maximize, threshold=0.5 -> ~0.667 >= 0.5 -> pass.
+ assert result.cases[0].status == "pass"
+
+ def test_per_case_non_objective_keys_do_not_erase_global_objective(self):
+ # Per-case touches only non-objective evaluator keys; global objective intact.
+ result = evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd",
+ "config": {"levenshtein": {"threshold": 0.5}}}],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.0}}},
+ )
+ # Effective: minimize, threshold=0.0 -> ~0.667 > 0.0 -> fail.
+ assert result.cases[0].status == "fail"
+
+ def test_no_objective_anywhere_unchanged(self):
+ # No objectives anywhere; evaluator's own verdict stands throughout.
+ result = evaluate(
+ [{"id": "c1", "expected": "ok", "actual": "ok",
+ "config": {"exact_match": {"some_key": "v"}}}],
+ evaluators=["exact_match"],
+ config={"exact_match": {"other_key": "w"}},
+ )
+ assert result.cases[0].status == "pass"
+
+ def test_global_config_not_mutated(self):
+ import copy
+ global_config = {"levenshtein": {"objective": {"direction": "minimize", "threshold": 0.5}}}
+ case_config = {"levenshtein": {"objective": {"threshold": 0.2}}}
+ original_global = copy.deepcopy(global_config)
+ original_case = copy.deepcopy(case_config)
+ evaluate(
+ [{"id": "c1", "expected": "abc", "actual": "abd", "config": case_config}],
+ evaluators=["levenshtein"],
+ config=global_config,
+ )
+ assert global_config == original_global
+ assert case_config == original_case
+
+
+class TestThresholdValidation:
+ """Threshold coercion and validation: types, NaN, infinity."""
+
+ # --- valid numeric thresholds ---
+
+ def test_maximize_integer_threshold(self):
+ # int is a valid threshold; coerced to float
+ result = evaluate(
+ [("apple", "apple")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": 1}}},
+ )
+ assert result.cases[0].status == "pass"
+ assert result.cases[0].metrics["levenshtein"].passed is True
+
+ def test_minimize_integer_threshold(self):
+ result = evaluate(
+ [("night", "nacht")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": 1}}},
+ )
+ # similarity 0.6 <= 1 -> pass
+ assert result.cases[0].status == "pass"
+
+ # --- invalid threshold types ---
+
+ def test_non_numeric_string_threshold_raises(self):
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": "high"}}},
+ )
+
+ def test_list_threshold_raises_value_error(self):
+ # Must be ValueError, not TypeError
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": [0.5]}}},
+ )
+
+ def test_dict_threshold_raises_value_error(self):
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": {"v": 1}}}},
+ )
+
+ # --- NaN and infinity ---
+
+ def test_nan_threshold_raises(self):
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": float("nan")}}},
+ )
+
+ def test_positive_infinity_threshold_raises(self):
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": float("inf")}}},
+ )
+
+ def test_negative_infinity_threshold_raises(self):
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "maximize", "threshold": float("-inf")}}},
+ )
+
+ def test_nan_minimize_threshold_raises(self):
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": float("nan")}}},
+ )
+
+ # --- preserved behaviors ---
+
+ def test_maximize_without_threshold_still_noop(self):
+ # maximize without threshold remains a no-op regardless of threshold validation
+ result = evaluate(
+ [("ok", "no")],
+ evaluators=["exact_match"],
+ config={"exact_match": {"objective": {"direction": "maximize"}}},
+ )
+ assert result.cases[0].status == "fail"
+
+ def test_minimize_explicit_none_threshold_still_raises(self):
+ # threshold=None for minimize hits the None check before coercion
+ with pytest.raises(ValueError, match="'minimize' requires a 'threshold'"):
+ evaluate(
+ [("a", "b")],
+ evaluators=["levenshtein"],
+ config={"levenshtein": {"objective": {"direction": "minimize", "threshold": None}}},
+ )
+
+ def test_threshold_errors_are_fail_fast(self):
+ # Invalid threshold on case 2 must reject the whole run before case 1 executes
+ calls = []
+
+ def recording_fn(case):
+ calls.append(case)
+ return "x"
+
+ with pytest.raises(ValueError, match="'threshold' must be a finite number"):
+ evaluate(
+ [
+ {"id": "c1"},
+ {"id": "c2", "config": {"levenshtein": {"objective": {"direction": "maximize", "threshold": [0.5]}}}},
+ ],
+ evaluators=["levenshtein"],
+ target_fn=recording_fn,
+ )
+ assert calls == []
diff --git a/tests/evals/test_types.py b/tests/evals/test_types.py
new file mode 100644
index 00000000..71255590
--- /dev/null
+++ b/tests/evals/test_types.py
@@ -0,0 +1,43 @@
+"""Tests for evals result models."""
+import pytest
+
+from semantica.evals.types import CaseResult, EvalMetric, EvalSummary
+
+
+class TestEvalMetric:
+ def test_construction(self):
+ m = EvalMetric(score=1.0, passed=True, meta={"threshold": 1.0})
+ assert m.score == 1.0 and m.passed and m.meta["threshold"] == 1.0
+
+ def test_default_meta(self):
+ m = EvalMetric(0.0, False)
+ assert m.meta == {}
+
+ def test_default_meta_is_not_shared(self):
+ m1 = EvalMetric(0.0, False)
+ m2 = EvalMetric(0.0, False)
+ m1.meta["mutated"] = True
+ assert "mutated" not in m2.meta
+
+
+class TestCaseResult:
+ def test_status_fail_on_any_failed_metric(self):
+ r = CaseResult(
+ case_id="c1",
+ status="fail",
+ metrics={"exact_match": EvalMetric(0.0, False)},
+ details={},
+ )
+ assert r.status == "fail"
+ assert r.metrics["exact_match"].passed is False
+
+
+class TestEvalSummary:
+ def test_pass_rate(self):
+ s = EvalSummary(total=10, passed=8, failed=1, errors=1, pass_rate=0.8)
+ assert s.pass_rate == 0.8
+
+ def test_cases_are_mutable(self):
+ s = EvalSummary(0, 0, 0, 0, 1.0)
+ s.cases.append(CaseResult("c", "pass", {}, {}))
+ assert len(s.cases) == 1