Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(benchmarks): add a phase-1 benchmark harness for memory systems (#1860)

Kevin079b0e85180f
diff --git a/semantica/benchmarks/README.md b/semantica/benchmarks/README.md
new file mode 100644
index 00000000..f74b49c0
--- /dev/null
+++ b/semantica/benchmarks/README.md
@@ -0,0 +1,111 @@
+# Benchmarks
+
+Run memory systems over question-answering benchmarks and score them the same
+way, so a number from this harness and a number from `semantica.evals` mean the
+same thing.
+
+This is phase 1. It is a working harness with adapters, not a leaderboard: no
+dataset ships with it beyond a tiny hand-written smoke set, and no result table
+is published yet.
+
+## Run it
+
+Nothing needs installing for the offline sample:
+
+```bash
+python -m semantica.benchmarks list
+python -m semantica.benchmarks run --dataset sample --system lexical --system semantica
+```
+
+Datasets that are too large to vendored are read from a local file you obtained
+yourself:
+
+```bash
+python -m semantica.benchmarks run \
+ --dataset hotpotqa --data hotpotqa=/path/to/hotpot_dev_distractor_v1.json \
+ --system lexical --limit 200 --markdown report.md
+```
+
+The harness never downloads anything. Each loader documents its own licence and
+expects the file's usual upstream format.
+
+## Datasets
+
+| name | shape | scope | licence | upstream | note |
+| --- | --- | --- | --- | --- | --- |
+| `sample` | 6 questions | per case | CC0-1.0 | bundled, `datasets/sample.py` | hand-written, for smoke tests |
+| `hotpotqa` | official JSON or HF export | per case | CC BY-SA 4.0 | https://hotpotqa.github.io/ | distractor setting |
+| `musique` | JSONL | per case | CC BY 4.0 | https://github.com/StonyBrookNLP/musique | answerable split |
+| `locomo` | `locomo10.json` | corpus | CC BY-NC 4.0 | https://github.com/snap-research/locomo/blob/main/LICENSE.txt | **non-commercial**, adapter only |
+
+Each licence was checked against its upstream on 2026-10-01. One thing worth
+knowing: the `hotpotqa/hotpot` code repository is Apache-2.0, but the dataset
+itself is CC BY-SA 4.0. This harness reads only the data file, so the dataset
+terms are the ones that apply here.
+
+`locomo` is deliberately excluded from defaults. Its licence is non-commercial,
+so shipping its data inside this repo would pass that restriction on to everyone
+who clones it. The loader stays so you can point it at your own copy.
+
+## Scope
+
+A dataset is either `per_case` or `corpus`, and the difference is who owns the
+memory.
+
+- `per_case` — each question comes with its own passages. The system is reset
+ and fed only those passages before answering. This is reading comprehension,
+ and it is what HotPotQA and MuSiQue measure.
+- `corpus` — every passage is ingested once and then all questions query the
+ same long-lived memory. This is what LoCoMo measures, and it is the setting a
+ memory system should actually be judged in.
+
+Getting this wrong flatters a system: a retrieval index rebuilt per question can
+look strong on `per_case` while having no memory at all.
+
+## Systems
+
+| name | backed by | availability |
+| --- | --- | --- |
+| `lexical` | in-repo BM25 + sentence pick | always |
+| `semantica` | `semantica.context.AgentMemory` | always |
+| `mem0` | `mem0` | needs the package |
+| `graphiti` | `graphiti-core` + a configured client | needs the package and a client |
+| `cognee` | `cognee` | needs the package |
+
+Importing this package imports none of the vendor SDKs. A missing backend is
+recorded as a skipped row and the rest of the run continues; `--strict` turns
+that into a failure instead, which is what CI wants.
+
+The three hosted adapters take an injected client, so your own credentials never
+have to live in this repo or in a test.
+
+## Scoring
+
+Predictions go to `semantica.evals.evaluate`, not to a private copy of the
+metrics. The primary metric is `token_f1` (SQuAD-style normalization), reported
+next to `normalized_exact_match`.
+
+Every system defaults to the same dependency-free extractive reader: the
+sentence with the most question-word overlap. That is deliberate, because it
+keeps the *retrieval* layer the only thing that differs between systems unless
+you supply a real reader with `reader=`. It is also why the sample dataset's
+exact-match column is zero: predictions are whole sentences, and a whole
+sentence is not a short answer.
+
+## Add your own
+
+A system is anything that implements four methods:
+
+```python
+class MemorySystem(Protocol):
+ name: str
+ def reset(self) -> None: ...
+ def ingest(self, passages, *, case_id="") -> None: ...
+ def answer(self, question, *, case_id="") -> str: ...
+```
+
+Register it with `register_system`, or hand an instance in directly with
+`run_benchmark(..., system_options={"name": {...}})`.
+
+A dataset is a `Dataset` of `BenchmarkCase`. Put a loader next to the existing
+ones and call `register_dataset`.
diff --git a/semantica/benchmarks/__init__.py b/semantica/benchmarks/__init__.py
new file mode 100644
index 00000000..7d27786f
--- /dev/null
+++ b/semantica/benchmarks/__init__.py
@@ -0,0 +1,65 @@
+"""Open benchmark harness: run memory systems over QA datasets, fairly.
+
+Phase 1 delivers the plumbing, not the leaderboard: one case shape, one system
+protocol, one scorer — so that adding a dataset or a backend is a small, local
+change and every number in a report came from the same code path.
+
+Typical use::
+
+ from semantica.benchmarks import load_dataset, run_benchmark
+
+ report = run_benchmark(
+ [load_dataset("sample")],
+ ["lexical", "semantica"],
+ )
+ print(report.to_markdown_table())
+
+From the shell::
+
+ python -m semantica.benchmarks list
+ python -m semantica.benchmarks run --dataset sample --system lexical
+
+Scoring reuses :mod:`semantica.evals` (``token_f1`` by default, plus
+``normalized_exact_match`` as a secondary column), so the harness has no metric
+code of its own to drift out of sync.
+"""
+
+from .datasets import list_datasets, load_dataset, register_dataset
+from .runner import run_benchmark, run_from_spec, run_system
+from .systems import (
+ MemorySystem,
+ SystemUnavailable,
+ get_system,
+ list_systems,
+ register_system,
+)
+from .types import (
+ CORPUS,
+ PER_CASE,
+ BenchmarkCase,
+ BenchmarkReport,
+ Dataset,
+ Prediction,
+ SystemResult,
+)
+
+__all__ = [
+ "BenchmarkCase",
+ "BenchmarkReport",
+ "CORPUS",
+ "Dataset",
+ "MemorySystem",
+ "PER_CASE",
+ "Prediction",
+ "SystemResult",
+ "SystemUnavailable",
+ "get_system",
+ "list_datasets",
+ "list_systems",
+ "load_dataset",
+ "register_dataset",
+ "register_system",
+ "run_benchmark",
+ "run_from_spec",
+ "run_system",
+]
diff --git a/semantica/benchmarks/__main__.py b/semantica/benchmarks/__main__.py
new file mode 100644
index 00000000..6423dc41
--- /dev/null
+++ b/semantica/benchmarks/__main__.py
@@ -0,0 +1,224 @@
+"""Command line entry point: ``python -m semantica.benchmarks``.
+
+ list show the registered datasets and systems
+ run --dataset D --system S run and print a system x dataset table
+
+Datasets that ship no data (``hotpotqa``, ``musique``, ``locomo``) take their
+file via ``--data NAME=PATH``. Nothing is downloaded.
+"""
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Dict, List
+
+from ..evals import list_evaluators
+from .datasets import list_datasets, load_dataset
+from .runner import run_benchmark
+from .systems import list_systems
+from .types import BenchmarkReport
+
+# Datasets whose loader needs a local file, and the licence we must surface.
+_FILE_DATASETS = {
+ "hotpotqa": "CC BY-SA 4.0",
+ "musique": "CC BY 4.0",
+ "locomo": "CC BY-NC 4.0 (NON-COMMERCIAL)",
+}
+
+
+def _cmd_list(_args) -> int:
+ print("datasets:")
+ for name in list_datasets():
+ licence = _FILE_DATASETS.get(name, "bundled / in-repo")
+ print(f" {name:<12} {licence}")
+ print("systems:")
+ for name in list_systems():
+ print(f" {name}")
+ return 0
+
+
+def _parse_data(pairs: List[str]) -> Dict[str, str]:
+ out: Dict[str, str] = {}
+ for pair in pairs or []:
+ if "=" not in pair:
+ raise SystemExit(f"--data expects NAME=PATH, got {pair!r}")
+ name, path = pair.split("=", 1)
+ out[name.strip()] = path.strip()
+ return out
+
+
+def _load(specs: List[str], data: Dict[str, str], limit):
+ datasets = []
+ for name in specs:
+ options = {}
+ if name in _FILE_DATASETS:
+ if name not in data:
+ raise SystemExit(
+ f"--dataset {name} needs --data {name}=/path/to/file "
+ f"(licence: {_FILE_DATASETS[name]}; the file is not bundled)"
+ )
+ options["path"] = data[name]
+ if limit is not None:
+ options["limit"] = limit
+ datasets.append(load_dataset(name, **options))
+ return datasets
+
+
+def _cmd_run(args) -> int:
+ if args.metric not in list_evaluators():
+ # A typo'd --metric used to average silently to 0.0; surface it instead.
+ raise SystemExit(
+ f"unknown --metric {args.metric!r}; registered evaluators: "
+ f"{', '.join(list_evaluators())}"
+ )
+ if args.system in (["all"],):
+ systems = list_systems()
+ else:
+ systems = args.system
+ datasets = _load(args.dataset, _parse_data(args.data), args.limit)
+
+ for dataset in datasets:
+ scope = dataset.scope
+ licence = dataset.license
+ print(
+ f"# {dataset.name}: {len(dataset)} cases, "
+ f"scope={scope}, licence={licence}"
+ )
+
+ def progress(system, dataset, done, total):
+ if args.quiet:
+ return
+ sys.stderr.write(f"\r {system} on {dataset}: {done}/{total}")
+ sys.stderr.flush()
+ if done == total:
+ sys.stderr.write("\n")
+
+ report = run_benchmark(
+ datasets,
+ systems,
+ primary_metric=args.metric,
+ on_error="raise" if args.strict else "skip",
+ progress=None if args.quiet else progress,
+ )
+
+ print()
+ print(f"primary metric: {report.primary_metric}")
+ print(report.to_markdown_table())
+ if report.skipped:
+ print("\nskipped (backend unavailable):")
+ for entry in report.skipped:
+ print(f" {entry['system']} / {entry['dataset']}: {entry['reason']}")
+
+ if args.json:
+ Path(args.json).write_text(
+ json.dumps(report.as_dict(include_predictions=args.predictions), indent=2),
+ encoding="utf-8",
+ )
+ print(f"\nwrote {args.json}")
+ if args.markdown:
+ Path(args.markdown).write_text(
+ _markdown(report), encoding="utf-8"
+ )
+ print(f"wrote {args.markdown}")
+ return 0
+
+
+def _markdown(report: BenchmarkReport) -> str:
+ lines = [
+ "# semantica benchmark report",
+ "",
+ f"- created: {report.created_at}",
+ f"- primary metric: `{report.primary_metric}`",
+ "",
+ report.to_markdown_table(),
+ "",
+ ]
+ if report.skipped:
+ lines += ["## Skipped", ""]
+ lines += [
+ f"- `{e['system']}` on `{e['dataset']}`: {e['reason']}"
+ for e in report.skipped
+ ]
+ lines.append("")
+ lines += [
+ "## Per system x dataset",
+ "",
+ "| system | dataset | n | mean | exact match | errors | wall (s) |",
+ "| --- | --- | --- | --- | --- | --- | --- |",
+ ]
+ for result in report.results:
+ lines.append(
+ f"| {result.system} | {result.dataset} | {result.n} | "
+ f"{result.mean_score:.4f} | {result.exact_match_rate:.4f} | "
+ f"{result.errors} | {result.wall_s:.1f} |"
+ )
+ lines.append("")
+ return "\n".join(lines)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="python -m semantica.benchmarks",
+ description=(
+ "Run memory systems over QA benchmarks and score them with "
+ "semantica.evals."
+ ),
+ )
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ sub.add_parser("list", help="show registered datasets and systems")
+
+ run = sub.add_parser("run", help="run benchmarks and print a table")
+ run.add_argument(
+ "--dataset",
+ action="append",
+ required=True,
+ help=(
+ "dataset name; repeat for several "
+ "(e.g. --dataset sample --dataset musique)"
+ ),
+ )
+ run.add_argument(
+ "--system",
+ action="append",
+ required=True,
+ help="system name, or 'all' for every registered system",
+ )
+ run.add_argument(
+ "--data",
+ action="append",
+ default=[],
+ help="NAME=PATH for datasets that are not bundled (hotpotqa, musique, locomo)",
+ )
+ run.add_argument("--limit", type=int, default=None, help="cap cases per dataset")
+ run.add_argument(
+ "--metric",
+ default="token_f1",
+ help="primary evaluator from semantica.evals (default: token_f1)",
+ )
+ run.add_argument("--json", default=None, help="write the full report as JSON")
+ run.add_argument("--markdown", default=None, help="write the report as Markdown")
+ run.add_argument(
+ "--predictions",
+ action="store_true",
+ help="include per-case predictions in the JSON output",
+ )
+ run.add_argument("--quiet", action="store_true", help="suppress progress output")
+ run.add_argument(
+ "--strict",
+ action="store_true",
+ help="fail instead of skipping a system whose backend is unavailable",
+ )
+ return parser
+
+
+def main(argv=None) -> int:
+ args = build_parser().parse_args(argv)
+ if args.command == "list":
+ return _cmd_list(args)
+ return _cmd_run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/semantica/benchmarks/datasets/__init__.py b/semantica/benchmarks/datasets/__init__.py
new file mode 100644
index 00000000..bce87f2c
--- /dev/null
+++ b/semantica/benchmarks/datasets/__init__.py
@@ -0,0 +1,49 @@
+"""Dataset loaders and their registry.
+
+A loader turns a local file (or a bundled literal) into a
+:class:`~semantica.benchmarks.types.Dataset`. Loaders are registered by name so
+the CLI and the runner can enumerate what is available without importing each
+module by hand:
+
+ >>> from semantica.benchmarks import datasets
+ >>> datasets.list_datasets() # doctest: +SKIP
+ ['hotpotqa', 'locomo', 'musique', 'sample']
+
+Licences differ per dataset and the harness never downloads or redistributes
+data — the user supplies the file. See each loader's docstring.
+"""
+
+from typing import Callable, Dict, List
+
+from ..types import Dataset
+
+LOADERS: Dict[str, Callable[..., Dataset]] = {}
+
+
+def register_dataset(name: str, loader: Callable[..., Dataset]) -> None:
+ """Register ``loader`` under ``name`` (overwrites a same-named entry)."""
+ LOADERS[name] = loader
+
+
+def list_datasets() -> List[str]:
+ """Registered dataset names, sorted."""
+ return sorted(LOADERS)
+
+
+def get_loader(name: str) -> Callable[..., Dataset]:
+ """Return the loader for ``name`` or raise ``KeyError`` with the options."""
+ if name not in LOADERS:
+ raise KeyError(
+ f"unknown dataset {name!r}. Registered: {list_datasets()}"
+ )
+ return LOADERS[name]
+
+
+def load_dataset(name: str, **options) -> Dataset:
+ """Load a registered dataset by name, forwarding ``**options``."""
+ return get_loader(name)(**options)
+
+
+# Importing these modules runs their ``register_dataset`` calls. Kept at the
+# bottom so the registry names above exist before any loader imports them.
+from . import hotpotqa, locomo, musique, sample # noqa: E402,F401
diff --git a/semantica/benchmarks/datasets/_io.py b/semantica/benchmarks/datasets/_io.py
new file mode 100644
index 00000000..50246ccd
--- /dev/null
+++ b/semantica/benchmarks/datasets/_io.py
@@ -0,0 +1,77 @@
+"""Small file-reading helpers shared by the dataset loaders.
+
+Every loader reads a local file the user downloaded themselves — the harness
+never fetches datasets over the network, because the benchmark suites have
+different licences (see each loader's docstring) and shipping bytes would
+re-distribute them.
+"""
+
+import json
+from pathlib import Path
+from typing import Any, Iterator, Union
+
+PathLike = Union[str, Path]
+
+
+def read_json(path: PathLike) -> Any:
+ """Parse a JSON file, or raise ``FileNotFoundError`` with a useful hint."""
+ p = Path(path)
+ if not p.exists():
+ raise FileNotFoundError(
+ f"dataset file not found: {p}. Download it yourself and pass the "
+ f"local path; the harness does not fetch datasets."
+ )
+ with p.open("r", encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+def read_jsonl(path: PathLike) -> Iterator[dict]:
+ """Yield one parsed object per non-blank line of a JSON Lines file."""
+ p = Path(path)
+ if not p.exists():
+ raise FileNotFoundError(
+ f"dataset file not found: {p}. Download it yourself and pass the "
+ f"local path; the harness does not fetch datasets."
+ )
+ with p.open("r", encoding="utf-8") as handle:
+ for lineno, line in enumerate(handle, start=1):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ yield json.loads(line)
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"{p}:{lineno}: invalid JSON ({exc})") from exc
+
+
+def as_list(value: Any) -> list:
+ """Coerce ``None`` to ``[]`` and a bare string to a one-element list.
+
+ Upstream datasets are inconsistent about singular vs plural answer fields
+ (``answer`` vs ``answers``) and about wrapping, so normalizing here keeps
+ every loader from repeating the same three-branch dance.
+ """
+ if value is None:
+ return []
+ if isinstance(value, str):
+ return [value]
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def as_answers(*values: Any) -> list:
+ """Collect non-blank gold answers from one or more upstream fields.
+
+ Upstream files occasionally carry an empty ``answer`` string or a blank
+ alias. Those must not become a case: an empty gold would make every
+ prediction score zero and quietly poison the aggregate. Order is preserved
+ and duplicates are dropped, so the first field listed wins.
+ """
+ out: list = []
+ for value in values:
+ for item in as_list(value):
+ text = str(item).strip()
+ if text and text not in out:
+ out.append(text)
+ return out
diff --git a/semantica/benchmarks/datasets/hotpotqa.py b/semantica/benchmarks/datasets/hotpotqa.py
new file mode 100644
index 00000000..4184f246
--- /dev/null
+++ b/semantica/benchmarks/datasets/hotpotqa.py
@@ -0,0 +1,96 @@
+"""HotPotQA loader (multi-hop reading comprehension).
+
+Licence: CC BY-SA 4.0 — the harness reads a local copy, never redistributes it.
+Get it from https://hotpotqa.github.io/ (``hotpot_dev_distractor_v1.json`` is
+the usual evaluation file) or the ``hotpot_qa`` dataset on Hugging Face.
+
+Two shapes are accepted, because the official JSON and the Hugging Face export
+disagree about how context is nested:
+
+official::
+
+ {"_id": ..., "question": ..., "answer": ...,
+ "context": [["Title", ["sent 1", "sent 2"]], ...]}
+
+Hugging Face::
+
+ {"id": ..., "question": ..., "answer": ...,
+ "context": {"title": [...], "sentences": [["sent 1"], ["sent 2"]]}}
+
+Both collapse to the same ``context`` list of ``"Title: sent. sent."``
+passages, so downstream systems see one format.
+"""
+
+from typing import Any, List, Optional
+
+from ..types import PER_CASE, BenchmarkCase, Dataset
+from . import register_dataset
+from ._io import as_list, as_answers, read_json
+
+_CITATION = "https://hotpotqa.github.io/"
+
+
+def _passages(context: Any, titles: Any = None, sentences: Any = None) -> List[str]:
+ """Normalize either context shape into ``["Title: text", ...]``."""
+ passages: List[str] = []
+
+ if isinstance(context, dict):
+ # Hugging Face: {"title": [...], "sentences": [[...], ...]}
+ titles = context.get("title") or []
+ sentences = context.get("sentences") or []
+ for title, sents in zip(titles, sentences):
+ text = " ".join(str(s) for s in as_list(sents))
+ passages.append(f"{title}: {text}" if title else text)
+ return passages
+
+ for entry in as_list(context):
+ if isinstance(entry, (list, tuple)) and len(entry) == 2:
+ title, sents = entry
+ text = " ".join(str(s) for s in as_list(sents))
+ else:
+ title, text = "", str(entry)
+ passages.append(f"{title}: {text}" if title else text)
+ return passages
+
+
+def load_hotpotqa(path: str, limit: Optional[int] = None) -> Dataset:
+ """Load a local HotPotQA JSON file into a :class:`Dataset`."""
+ raw = read_json(path)
+ records = raw.get("data") if isinstance(raw, dict) and "data" in raw else raw
+ if isinstance(records, dict):
+ # Some exports wrap the questions in a single dict of id -> record.
+ records = list(records.values())
+
+ cases: List[BenchmarkCase] = []
+ for index, record in enumerate(records):
+ answers = as_answers(record.get("answer"), record.get("answers"))
+ if not answers or not record.get("question"):
+ continue
+ case_id = str(record.get("_id") or record.get("id") or f"hotpotqa-{index}")
+ cases.append(
+ BenchmarkCase(
+ case_id=case_id,
+ question=record["question"],
+ answers=answers,
+ context=_passages(record.get("context")),
+ metadata={
+ "type": record.get("type"),
+ "level": record.get("level"),
+ "supporting_facts": record.get("supporting_facts"),
+ },
+ )
+ )
+
+ dataset = Dataset(
+ name="hotpotqa",
+ license="CC BY-SA 4.0",
+ scope=PER_CASE,
+ cases=cases,
+ version="distractor-v1",
+ source=_CITATION,
+ notes="Distractor setting: each question ships its own 10-paragraph bundle.",
+ )
+ return dataset.limit(limit)
+
+
+register_dataset("hotpotqa", load_hotpotqa)
diff --git a/semantica/benchmarks/datasets/locomo.py b/semantica/benchmarks/datasets/locomo.py
new file mode 100644
index 00000000..c41fb91b
--- /dev/null
+++ b/semantica/benchmarks/datasets/locomo.py
@@ -0,0 +1,152 @@
+"""LoCoMo loader (very long-term conversational memory) — adapter only.
+
+Licence: **CC BY-NC 4.0** — non-commercial. The harness only *reads* a copy the
+user obtained themselves and never redistributes it. Because the licence is
+restrictive, this loader is shipped as an adapter without any bundled data and
+is deliberately excluded from the default dataset set: pass
+``--dataset locomo --data locomo=/path/to/locomo10.json`` explicitly if you have
+accepted the terms.
+
+Source: https://github.com/snap-research/locomo (``data/locomo10.json``).
+
+Shape of each sample::
+
+ {"sample_id": "conv-26",
+ "conversation": {"speaker_a": ..., "speaker_b": ...,
+ "session_1": [{"speaker":..., "dia_id":..., "text":...}],
+ "session_1_date_time": ..., "session_2": [...], ...},
+ "qa": [{"question": ..., "answer": ..., "evidence": [...],
+ "category": 1, "adversarial_answer": ...}, ...]}
+
+Scope is ``corpus``: every session of a conversation is ingested once, and all
+of that conversation's questions then query the same long-lived memory. That is
+what makes LoCoMo a memory benchmark rather than a reading-comprehension one.
+
+Categories: 1 multi-hop, 2 temporal, 3 open-domain, 4 single-hop, 5 adversarial.
+"""
+
+from typing import List, Optional
+
+from ..types import CORPUS, BenchmarkCase, Dataset
+from . import register_dataset
+from ._io import as_answers, read_json
+
+_CITATION = "https://github.com/snap-research/locomo"
+
+CATEGORY_NAMES = {
+ 1: "multi-hop",
+ 2: "temporal",
+ 3: "open-domain",
+ 4: "single-hop",
+ 5: "adversarial",
+}
+
+
+def _sessions(conversation: dict) -> List[str]:
+ """Flatten a conversation's sessions into dated, speaker-prefixed lines."""
+ if not isinstance(conversation, dict):
+ return []
+
+ def session_number(key: str) -> int:
+ suffix = key.rsplit("_", 1)[-1]
+ return int(suffix) if suffix.isdigit() else 0
+
+ # Session keys look like "session_1"; "session_1_date_time" holds the date.
+ session_ids = sorted(
+ (
+ key
+ for key in conversation
+ if key.startswith("session_") and not key.endswith("_date_time")
+ ),
+ key=session_number,
+ )
+
+ lines: List[str] = []
+ for session_id in session_ids:
+ date = conversation.get(f"{session_id}_date_time")
+ if date:
+ lines.append(f"[{date}]")
+ for turn in conversation.get(session_id) or []:
+ if not isinstance(turn, dict):
+ continue
+ speaker = turn.get("speaker") or turn.get("role") or ""
+ text = turn.get("text") or turn.get("content") or ""
+ lines.append(f"{speaker}: {text}" if speaker else str(text))
+ return lines
+
+
+def load_locomo(
+ path: str,
+ limit: Optional[int] = None,
+ categories: Optional[List[int]] = None,
+) -> Dataset:
+ """Load a local ``locomo10.json`` into a corpus-scoped :class:`Dataset`.
+
+ ``categories`` optionally keeps only the given question categories (e.g.
+ ``[1, 2, 4]`` to drop the adversarial and open-domain splits).
+ """
+ raw = read_json(path)
+ samples = raw if isinstance(raw, list) else [raw]
+
+ cases: List[BenchmarkCase] = []
+ for sample_index, sample in enumerate(samples):
+ sample_id = str(sample.get("sample_id") or f"locomo-{sample_index}")
+ lines = _sessions(sample.get("conversation") or {})
+
+ for qa_index, qa in enumerate(sample.get("qa") or []):
+ question = qa.get("question")
+ category = qa.get("category")
+ if not question:
+ continue
+ if categories is not None and category not in categories:
+ continue
+
+ # Category 5 questions are adversarial: they carry a
+ # tempting-but-wrong ``adversarial_answer`` alongside the real gold
+ # ``answer``. The distractor is kept in metadata only — it must never
+ # enter the gold list, or the harness would credit a system for
+ # falling for the trap. Questions with no real ``answer`` are
+ # skipped rather than scored against the distractor.
+ answers = as_answers(qa.get("answer"))
+ if not answers:
+ continue
+
+ cases.append(
+ BenchmarkCase(
+ case_id=f"{sample_id}-q{qa_index:04d}",
+ question=question,
+ answers=answers,
+ # The same conversation serves every question of a sample;
+ # the runner de-duplicates when it builds the corpus, so
+ # sharing the list object here costs nothing.
+ context=lines,
+ metadata={
+ "sample_id": sample_id,
+ "category": category,
+ "category_name": CATEGORY_NAMES.get(category, "unknown"),
+ "evidence": qa.get("evidence"),
+ "adversarial_answer": qa.get("adversarial_answer"),
+ },
+ )
+ )
+
+ dataset = Dataset(
+ name="locomo",
+ license="CC BY-NC 4.0 (NON-COMMERCIAL)",
+ scope=CORPUS,
+ cases=cases,
+ version="locomo10",
+ source=_CITATION,
+ # Each sample is a *separate* long conversation with its own questions;
+ # the runner must give every conversation its own memory instead of
+ # merging all ten into one blob.
+ group_by="sample_id",
+ notes=(
+ "Non-commercial licence: results from this dataset must not be "
+ "used commercially. Adapter only; no data is bundled."
+ ),
+ )
+ return dataset.limit(limit)
+
+
+register_dataset("locomo", load_locomo)
diff --git a/semantica/benchmarks/datasets/musique.py b/semantica/benchmarks/datasets/musique.py
new file mode 100644
index 00000000..00949548
--- /dev/null
+++ b/semantica/benchmarks/datasets/musique.py
@@ -0,0 +1,69 @@
+"""MuSiQue loader (multi-hop question answering).
+
+Licence: CC BY 4.0 — read locally, never redistributed by the harness.
+Get it from https://github.com/StonyBrookNLP/musique (``musique_ans_v1.0_dev.jsonl``).
+
+Each JSONL line looks like::
+
+ {"id": "...", "question": "...", "answer": "...",
+ "answer_aliases": ["..."],
+ "paragraphs": [{"idx": 0, "title": "...", "paragraph_text": "...",
+ "is_supporting": true}, ...],
+ "question_decomposition": [...]}
+
+``answer_aliases`` is folded into the gold answer list so a correct paraphrase
+is not scored as a miss.
+"""
+
+from typing import List
+
+from ..types import PER_CASE, BenchmarkCase, Dataset
+from . import register_dataset
+from ._io import as_answers, read_jsonl
+
+_CITATION = "https://github.com/StonyBrookNLP/musique"
+
+
+def _passages(paragraphs: List[dict]) -> List[str]:
+ passages = []
+ for para in paragraphs or []:
+ title = para.get("title") or ""
+ text = para.get("paragraph_text") or ""
+ passages.append(f"{title}: {text}" if title else text)
+ return passages
+
+
+def load_musique(path: str, limit=None) -> Dataset:
+ """Load a local MuSiQue JSONL file into a :class:`Dataset`."""
+ cases: List[BenchmarkCase] = []
+ for index, record in enumerate(read_jsonl(path)):
+ question = record.get("question")
+ answers = as_answers(record.get("answer"), record.get("answer_aliases"))
+ if not question or not answers:
+ continue
+ cases.append(
+ BenchmarkCase(
+ case_id=str(record.get("id") or f"musique-{index}"),
+ question=question,
+ answers=answers,
+ context=_passages(record.get("paragraphs")),
+ metadata={
+ "decomposition": record.get("question_decomposition"),
+ "answerable": record.get("answerable"),
+ },
+ )
+ )
+
+ dataset = Dataset(
+ name="musique",
+ license="CC BY 4.0",
+ scope=PER_CASE,
+ cases=cases,
+ version="ans-v1.0",
+ source=_CITATION,
+ notes="Answerable split; each question ships exactly its own paragraphs.",
+ )
+ return dataset.limit(limit)
+
+
+register_dataset("musique", load_musique)
diff --git a/semantica/benchmarks/datasets/sample.py b/semantica/benchmarks/datasets/sample.py
new file mode 100644
index 00000000..95acda61
--- /dev/null
+++ b/semantica/benchmarks/datasets/sample.py
@@ -0,0 +1,120 @@
+"""A tiny bundled dataset so benchmarks run offline (CI, smoke tests).
+
+This is not a real benchmark: it is six hand-written questions with their
+evidence passages, embedded as a Python literal so no data file has to be
+shipped or downloaded. It exists so ``python -m semantica.benchmarks run`` has
+something to chew on in a fresh checkout, and so the harness has an end-to-end
+test that never touches the network.
+
+The evidence is written so that the sentence carrying the answer is also the
+sentence that shares the most content words with the question. That keeps the
+default *extractive* reader (which has no model — see
+:func:`semantica.benchmarks.text.best_sentence`) above a trivial floor, so the
+smoke test can assert that retrieval plus scoring actually did something. It
+inherits the weaknesses of any extractive reader: predictions are whole
+sentences, so ``normalized_exact_match`` stays at zero here even when the answer
+is present. Plug in a real reader (``reader=`` on any system) for QA-grade
+numbers.
+"""
+
+from typing import List, Optional
+
+from ..types import PER_CASE, BenchmarkCase, Dataset
+from . import register_dataset
+
+# (question, gold answer, accepted aliases, evidence passages)
+_CASES = [
+ (
+ "Who wrote the novel Neuromancer?",
+ "William Gibson",
+ ["Gibson", "William Ford Gibson"],
+ [
+ "The novel Neuromancer was written by William Gibson and published "
+ "in 1984.",
+ "Neuromancer won the Nebula Award and helped define the cyberpunk genre.",
+ "William Gibson was born in Conway, South Carolina in 1948.",
+ ],
+ ),
+ (
+ "Which country was the telephone inventor born in?",
+ "Scotland",
+ ["Scottish"],
+ [
+ "The telephone inventor Alexander Graham Bell was born in Scotland "
+ "in 1847.",
+ "The telephone was patented in the United States in 1876.",
+ "Bell later emigrated to Canada and then to the United States.",
+ ],
+ ),
+ (
+ "How many strings does a standard cello have?",
+ "four",
+ ["4"],
+ [
+ "A standard cello has four strings, tuned in fifths.",
+ "A cello is larger than a violin and smaller than a double bass.",
+ "Yo-Yo Ma is a cellist known for his recordings of the Bach cello suites.",
+ ],
+ ),
+ (
+ "Which ocean lies off the coast of Queensland?",
+ "Coral Sea",
+ ["the Coral Sea"],
+ [
+ "The Coral Sea lies off the coast of Queensland, Australia.",
+ "Queensland is a state in the north-east of Australia.",
+ "The Great Barrier Reef is a coral reef system in that sea.",
+ ],
+ ),
+ (
+ "Who founded the company that makes the iPhone?",
+ "Steve Jobs",
+ ["Steven Jobs", "Jobs"],
+ [
+ "The company that makes the iPhone, Apple, was founded by Steve "
+ "Jobs in 1976.",
+ "The iPhone was released by Apple in 2007.",
+ "Apple is headquartered in Cupertino, California.",
+ ],
+ ),
+ (
+ "In which country was the painter of The Persistence of Memory born?",
+ "Spain",
+ ["Spanish"],
+ [
+ "The painter of The Persistence of Memory, Salvador Dali, was born "
+ "in Spain in 1904.",
+ "The Persistence of Memory is a 1931 painting by Salvador Dali.",
+ "Dali later worked in Paris and in the United States.",
+ ],
+ ),
+]
+
+
+def load_sample(limit: Optional[int] = None) -> Dataset:
+ """Return the bundled offline sample dataset."""
+ cases: List[BenchmarkCase] = []
+ for index, (question, answer, aliases, context) in enumerate(_CASES):
+ answers = [answer] + [a for a in aliases if a != answer]
+ cases.append(
+ BenchmarkCase(
+ case_id=f"sample-{index:03d}",
+ question=question,
+ answers=answers,
+ context=list(context),
+ metadata={"kind": "extractive-smoke"},
+ )
+ )
+ dataset = Dataset(
+ name="sample",
+ license="CC0-1.0 (hand-written for this repo)",
+ scope=PER_CASE,
+ cases=cases,
+ version="1",
+ source="in-repo",
+ notes="Synthetic smoke-test set; not a published benchmark.",
+ )
+ return dataset.limit(limit)
+
+
+register_dataset("sample", load_sample)
diff --git a/semantica/benchmarks/runner.py b/semantica/benchmarks/runner.py
new file mode 100644
index 00000000..2a1ff748
--- /dev/null
+++ b/semantica/benchmarks/runner.py
@@ -0,0 +1,249 @@
+"""The benchmark driver: ``datasets x systems``, scored by ``semantica.evals``.
+
+Two scopes, defined by the dataset (see :mod:`semantica.benchmarks.types`):
+
+``per_case``
+ Each case ships its own evidence. The system is reset and fed only that
+ case's passages before it answers — SQuAD-style reading comprehension.
+
+``corpus``
+ The union of every case's passages is ingested once and every question then
+ queries the same long-lived memory — the setting a *memory* benchmark
+ (LoCoMo) actually cares about. When the dataset carries a ``group_by`` key,
+ each group is ingested into its *own* memory and answered separately, so a
+ multi-conversation suite is never flattened into one shared blob.
+
+Scoring is deliberately not reimplemented here. Predictions are handed to
+:func:`semantica.evals.evaluate`, so the harness and the repo's evaluator
+library can never drift apart.
+"""
+
+import statistics
+import time
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional, Sequence, Tuple
+
+from ..evals import evaluate, list_evaluators
+from .datasets import load_dataset
+from .systems import SystemUnavailable, get_system
+from .types import (
+ CORPUS,
+ PER_CASE,
+ BenchmarkCase,
+ BenchmarkReport,
+ Dataset,
+ Prediction,
+ SystemResult,
+)
+
+EXACT_MATCH = "normalized_exact_match"
+
+
+def _check_metric(metric: str) -> None:
+ """Fail fast on a typo'd metric instead of silently averaging to zero.
+
+ A misspelled ``--metric`` used to be invisible: every case simply reported
+ no score for that name and the run averaged to ``0.0``. Validating against
+ the evaluator registry turns a silent wrong answer into a clear error.
+ """
+ available = list_evaluators()
+ if metric not in available:
+ raise ValueError(
+ f"unknown primary_metric {metric!r}; registered evaluators: "
+ f"{', '.join(available)}"
+ )
+
+
+def _case_texts(cases: Sequence[BenchmarkCase]) -> List[str]:
+ """Order-preserving union of the given cases' passages."""
+ return list(dict.fromkeys(str(p) for case in cases for p in case.context))
+
+
+def _group_cases(dataset: Dataset) -> List[Tuple[str, List[BenchmarkCase]]]:
+ """Split ``dataset`` into the independent memories the runner must keep apart.
+
+ Without ``group_by`` the whole dataset is one group (a single shared memory,
+ the historical ``corpus`` behaviour). With it — LoCoMo's ``sample_id`` — the
+ cases of each distinct key become their own group, so every conversation gets
+ a private memory and cannot retrieve another conversation's evidence.
+ """
+ if not dataset.group_by:
+ return [(dataset.name, list(dataset.cases))]
+
+ groups: Dict[str, List[BenchmarkCase]] = {}
+ for case in dataset.cases:
+ key = str(case.metadata.get(dataset.group_by, dataset.name))
+ groups.setdefault(key, []).append(case)
+ return list(groups.items())
+
+
+def _prepare(system, texts: Sequence[str], case_id: str) -> Optional[str]:
+ """Reset ``system`` and ingest ``texts``; return an error string, or ``None``.
+
+ The memory set-up is wrapped exactly like ``answer`` is: a backend that
+ raises while loading its memory is recorded as an errored case rather than
+ aborting the whole run. ``texts`` is ingested only when non-empty, so a case
+ with no evidence simply leaves the system freshly reset.
+ """
+ try:
+ system.reset()
+ if texts:
+ system.ingest(list(texts), case_id=case_id)
+ except Exception as exc: # noqa: BLE001 - memory prep must not kill the run
+ return f"{type(exc).__name__}: {exc}"
+ return None
+
+
+def run_system(
+ system_name: str,
+ dataset: Dataset,
+ *,
+ primary_metric: str = "token_f1",
+ system_options: Optional[Dict[str, Any]] = None,
+ progress=None,
+) -> SystemResult:
+ """Run one system over one dataset and score the predictions.
+
+ A system that raises while answering is recorded as a prediction with an
+ ``error`` rather than aborting the run: one flaky question should not throw
+ away the other 199, and the error count is reported next to the score.
+ """
+ _check_metric(primary_metric)
+ system = get_system(system_name, **(system_options or {}))
+ predictions: List[Prediction] = []
+ total = len(dataset.cases)
+ done = 0
+
+ started = time.perf_counter()
+ for group_label, group_cases in _group_cases(dataset):
+ # Corpus scope: one long-lived memory per group, ingested once up front.
+ # Per-case scope: memory is reset and refilled for every question below.
+ group_error = None
+ if dataset.scope == CORPUS:
+ group_error = _prepare(system, _case_texts(group_cases), group_label)
+
+ for case in group_cases:
+ if dataset.scope == PER_CASE:
+ case_error = _prepare(system, case.context, case.case_id)
+ else:
+ case_error = group_error
+
+ case_started = time.perf_counter()
+ answer, error = "", case_error
+ if error is None:
+ try:
+ answer = system.answer(case.question, case_id=case.case_id)
+ except Exception as exc: # noqa: BLE001
+ # One bad question must not throw away the whole run.
+ error = f"{type(exc).__name__}: {exc}"
+ predictions.append(
+ Prediction(
+ case_id=case.case_id,
+ answer=answer if error is None else "",
+ retrieved=list(getattr(system, "last_retrieved", None) or []),
+ latency_s=time.perf_counter() - case_started,
+ error=error,
+ )
+ )
+ done += 1
+ if progress is not None:
+ progress(system_name, dataset.name, done, total)
+ wall_s = time.perf_counter() - started
+
+ by_id = {case.case_id: case for case in dataset.cases}
+ eval_cases = [
+ {
+ "id": prediction.case_id,
+ "expected": by_id[prediction.case_id].answers,
+ "actual": prediction.answer,
+ }
+ for prediction in predictions
+ ]
+ evaluators = list(dict.fromkeys([primary_metric, EXACT_MATCH]))
+ summary = evaluate(eval_cases, evaluators)
+
+ scores = [
+ result.metrics[primary_metric].score
+ for result in summary.cases
+ if primary_metric in result.metrics
+ ]
+ exact = [
+ result.metrics[EXACT_MATCH].score
+ for result in summary.cases
+ if EXACT_MATCH in result.metrics
+ ]
+
+ return SystemResult(
+ system=system_name,
+ dataset=dataset.name,
+ n=len(predictions),
+ mean_score=statistics.fmean(scores) if scores else 0.0,
+ exact_match_rate=statistics.fmean(exact) if exact else 0.0,
+ errors=sum(1 for prediction in predictions if prediction.error),
+ wall_s=wall_s,
+ primary_metric=primary_metric,
+ summary=summary,
+ predictions=predictions,
+ )
+
+
+def run_benchmark(
+ datasets: Sequence[Dataset],
+ systems: Sequence[str],
+ *,
+ primary_metric: str = "token_f1",
+ system_options: Optional[Dict[str, Any]] = None,
+ on_error: str = "skip",
+ progress=None,
+) -> BenchmarkReport:
+ """Run every (system, dataset) pair and return one report.
+
+ ``on_error`` controls what happens when a system cannot start (missing SDK
+ or credential). ``"skip"`` records it in :attr:`BenchmarkReport.skipped` and
+ continues, which is what you want for a laptop run where only one of the
+ three hosted backends is configured; ``"raise"`` propagates the error.
+ """
+ if on_error not in {"skip", "raise"}:
+ raise ValueError(f"on_error must be 'skip' or 'raise', got {on_error!r}")
+
+ report = BenchmarkReport(
+ created_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
+ primary_metric=primary_metric,
+ datasets=[dataset.name for dataset in datasets],
+ systems=list(systems),
+ )
+
+ for system_name in systems:
+ for dataset in datasets:
+ try:
+ result = run_system(
+ system_name,
+ dataset,
+ primary_metric=primary_metric,
+ system_options=(system_options or {}).get(system_name),
+ progress=progress,
+ )
+ except SystemUnavailable as exc:
+ if on_error == "raise":
+ raise
+ report.skipped.append(
+ {"system": system_name, "dataset": dataset.name, "reason": str(exc)}
+ )
+ continue
+ report.results.append(result)
+ report.scores[f"{system_name}/{dataset.name}"] = result.mean_score
+
+ return report
+
+
+def run_from_spec(
+ dataset_specs: Sequence[Dict[str, Any]],
+ systems: Sequence[str],
+ **kwargs: Any,
+) -> BenchmarkReport:
+ """Convenience wrapper: load datasets from ``{"name": ..., **options}`` specs."""
+ datasets = [
+ load_dataset(spec["name"], **{k: v for k, v in spec.items() if k != "name"})
+ for spec in dataset_specs
+ ]
+ return run_benchmark(datasets, systems, **kwargs)
diff --git a/semantica/benchmarks/systems/__init__.py b/semantica/benchmarks/systems/__init__.py
new file mode 100644
index 00000000..1d7e820f
--- /dev/null
+++ b/semantica/benchmarks/systems/__init__.py
@@ -0,0 +1,16 @@
+"""The systems under test and their registry.
+
+Importing this package registers every adapter, but imports no vendor SDK —
+each adapter defers its ``mem0``/``graphiti``/``cognee`` import to factory call
+time, so listing systems works in a bare checkout.
+"""
+
+from . import external, lexical, semantica_memory # noqa: F401,E402
+from .base import ( # noqa: F401
+ SYSTEMS,
+ MemorySystem,
+ SystemUnavailable,
+ get_system,
+ list_systems,
+ register_system,
+)
diff --git a/semantica/benchmarks/systems/base.py b/semantica/benchmarks/systems/base.py
new file mode 100644
index 00000000..1d4076bc
--- /dev/null
+++ b/semantica/benchmarks/systems/base.py
@@ -0,0 +1,80 @@
+"""The memory-system abstraction and its registry.
+
+To compare memory backends fairly, the harness talks to every system through
+one tiny protocol instead of importing each vendor SDK directly:
+
+ reset() -> forget everything
+ ingest(passages) -> write evidence into memory
+ answer(question) -> read memory and produce a free-form answer
+
+That is the whole surface. A system that can honour those three calls can be
+benchmarked next to any other, and the runner never needs to know whether the
+implementation is an in-process lexical index, semantica's own memory layer, or
+a hosted graph service.
+
+Systems are registered as **factories** (``() -> MemorySystem``) rather than
+instances, so importing this package never imports an optional vendor SDK —
+``mem0`` and friends are only touched when a run actually selects them.
+"""
+
+from typing import Callable, Dict, List, Protocol, Sequence, runtime_checkable
+
+
+class SystemUnavailable(RuntimeError):
+ """Raised when a registered system cannot run (missing dep or credential)."""
+
+
+@runtime_checkable
+class MemorySystem(Protocol):
+ """Minimal contract every benchmarked memory backend implements."""
+
+ name: str
+
+ def reset(self) -> None:
+ """Drop all remembered content so the next dataset starts clean."""
+
+ def ingest(self, passages: Sequence[str], *, case_id: str = "") -> None:
+ """Write ``passages`` into memory (``case_id`` is an optional hint)."""
+
+ def answer(self, question: str, *, case_id: str = "") -> str:
+ """Return a free-form answer to ``question`` from what is in memory."""
+
+
+SYSTEMS: Dict[str, Callable[..., MemorySystem]] = {}
+
+
+def register_system(name: str, factory: Callable[..., MemorySystem]) -> None:
+ """Register a system factory under ``name``.
+
+ A factory takes **options and returns a ready :class:`MemorySystem`. The
+ runner passes its own options through, and each factory uses what it needs
+ and ignores the rest — so new run options never require touching every
+ adapter.
+ """
+ SYSTEMS[name] = factory
+
+
+def list_systems() -> List[str]:
+ """Registered system names, sorted."""
+ return sorted(SYSTEMS)
+
+
+def get_system(name: str, **options) -> MemorySystem:
+ """Instantiate a registered system, or raise ``SystemUnavailable``.
+
+ Unknown names and unavailable optional dependencies both surface as
+ ``SystemUnavailable`` with an actionable message, so a caller can skip a
+ system instead of crashing a whole benchmark run.
+ """
+ if name not in SYSTEMS:
+ raise SystemUnavailable(
+ f"unknown system {name!r}. Registered: {list_systems()}"
+ )
+ try:
+ return SYSTEMS[name](**options)
+ except SystemUnavailable:
+ raise
+ except ImportError as exc:
+ raise SystemUnavailable(
+ f"system {name!r} is registered but its backend is not installed: {exc}"
+ ) from exc
diff --git a/semantica/benchmarks/systems/external.py b/semantica/benchmarks/systems/external.py
new file mode 100644
index 00000000..7acc44ff
--- /dev/null
+++ b/semantica/benchmarks/systems/external.py
@@ -0,0 +1,271 @@
+"""Adapters for third-party memory systems: Mem0, Graphiti (Zep), Cognee.
+
+Each adapter is a thin translation from the vendor's own client to the
+:class:`~semantica.benchmarks.systems.base.MemorySystem` protocol. Two rules
+shape them:
+
+1. **Nothing is imported until a run selects the system.** The vendors' SDKs are
+ optional dependencies, so the import lives inside the factory and a missing
+ package surfaces as :class:`SystemUnavailable` rather than an ImportError at
+ package import.
+2. **A ready client can always be injected** (``client=...``). Hosted graph
+ services need credentials and, for Graphiti, a running Neo4j; rather than
+ guessing at a connection recipe, the adapter accepts a client the caller has
+ already configured, and only tries to build a default when none is given.
+
+Status: these three adapters are **not exercised in CI** — they need network
+access, API keys and (Graphiti) a database, none of which a test runner should
+assume. They are written against each vendor's documented public API; any run
+that uses them prints a reminder that the numbers are only meaningful once the
+backend is reachable.
+"""
+
+import asyncio
+from datetime import datetime, timezone
+from typing import Any, List, Optional, Sequence
+from uuid import uuid4
+
+from ..text import best_sentence
+from .base import SystemUnavailable, register_system
+
+
+def _run(coro):
+ """Run a coroutine from sync code, refusing to nest inside a live loop."""
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ return asyncio.run(coro)
+ raise SystemUnavailable(
+ "this adapter calls an async client; run the benchmark from sync code "
+ "(do not call it from inside an active event loop)"
+ )
+
+
+def _texts_from(results: Any, *keys: str) -> List[str]:
+ """Best-effort extraction of answer texts from a vendor's result objects."""
+ texts: List[str] = []
+ for item in results or []:
+ if isinstance(item, str):
+ texts.append(item)
+ continue
+ for key in keys:
+ if isinstance(item, dict):
+ value = item.get(key)
+ else:
+ value = getattr(item, key, None)
+ if value:
+ texts.append(str(value))
+ break
+ else:
+ texts.append(str(item))
+ return texts
+
+
+# --------------------------------------------------------------------------- mem0
+
+
+class Mem0Memory:
+ """Mem0's OSS memory layer (``pip install mem0ai``)."""
+
+ name = "mem0"
+
+ def __init__(
+ self,
+ client: Optional[Any] = None,
+ config: Optional[dict] = None,
+ user_id: str = "semantica-bench",
+ top_k: int = 5,
+ reader=None,
+ ):
+ self.user_id = user_id
+ self.top_k = int(top_k)
+ self._reader = reader
+ self.last_retrieved: List[str] = []
+ if client is None:
+ try:
+ from mem0 import Memory
+ except ImportError as exc:
+ raise SystemUnavailable(
+ "mem0 is not installed (pip install mem0ai); mem0 also needs "
+ "an LLM and embedder configured before it can be benchmarked"
+ ) from exc
+ client = Memory.from_config(config) if config else Memory()
+ self._client = client
+
+ def reset(self) -> None:
+ self.last_retrieved = []
+ reset = getattr(self._client, "reset", None)
+ if reset is None:
+ raise SystemUnavailable(
+ "mem0 client exposes no reset(); cannot isolate runs"
+ )
+ reset()
+
+ def ingest(self, passages: Sequence[str], *, case_id: str = "") -> None:
+ for passage in passages:
+ text = str(passage).strip()
+ if text:
+ self._client.add(text, user_id=self.user_id)
+
+ def answer(self, question: str, *, case_id: str = "") -> str:
+ results = self._client.search(question, user_id=self.user_id, limit=self.top_k)
+ passages = _texts_from(results, "memory", "text", "content")
+ self.last_retrieved = list(passages)
+ if not passages:
+ return ""
+ if self._reader is not None:
+ return self._reader(question, passages)
+ return best_sentence(question, passages)
+
+
+# ------------------------------------------------------------------------ graphiti
+
+
+class GraphitiMemory:
+ """Graphiti / Zep temporal knowledge graph (``pip install graphiti-core``).
+
+ Graphiti has no cheap "wipe everything" call, so runs are isolated by
+ ``group_id`` instead: :meth:`reset` rotates to a fresh group. Supply a
+ ``client`` you have already pointed at Neo4j (or another supported driver).
+ """
+
+ name = "graphiti"
+
+ def __init__(
+ self,
+ client: Optional[Any] = None,
+ top_k: int = 5,
+ reader=None,
+ group_id: Optional[str] = None,
+ **client_options: Any,
+ ):
+ self.top_k = int(top_k)
+ self._reader = reader
+ self.last_retrieved: List[str] = []
+ self.group_id = group_id or "semantica-bench"
+ if client is None:
+ if not client_options:
+ raise SystemUnavailable(
+ "graphiti needs a configured client (Neo4j or another driver, "
+ "plus LLM credentials). Build one and pass client=..., or pass "
+ "client_options for your setup."
+ )
+ try:
+ from graphiti_core import Graphiti
+ except ImportError as exc:
+ raise SystemUnavailable(
+ "graphiti-core is not installed (pip install graphiti-core)"
+ ) from exc
+ client = Graphiti(**client_options)
+ self._client = client
+
+ def reset(self) -> None:
+ # Rotating the group id is the only isolation Graphiti can offer cheaply;
+ # it is also the safest, since it never deletes a user's real graph.
+ self.last_retrieved = []
+ self.group_id = f"semantica-bench-{uuid4().hex[:8]}"
+
+ def _episode_type(self):
+ try:
+ from graphiti_core.nodes import EpisodeType
+
+ return EpisodeType.text
+ except Exception: # noqa: BLE001 - version drift between graphiti releases
+ return "text"
+
+ def ingest(self, passages: Sequence[str], *, case_id: str = "") -> None:
+ for index, passage in enumerate(passages):
+ text = str(passage).strip()
+ if not text:
+ continue
+ _run(
+ self._client.add_episode(
+ name=f"{case_id or 'passage'}-{index}",
+ episode_body=text,
+ source=self._episode_type(),
+ source_description="semantica benchmark passage",
+ reference_time=datetime.now(timezone.utc),
+ group_id=self.group_id,
+ )
+ )
+
+ def answer(self, question: str, *, case_id: str = "") -> str:
+ results = _run(
+ self._client.search(query=question, group_ids=[self.group_id])
+ )
+ passages = _texts_from(results, "fact", "content", "name")
+ self.last_retrieved = list(passages)
+ if not passages:
+ return ""
+ if self._reader is not None:
+ return self._reader(question, passages)
+ return best_sentence(question, passages)
+
+
+# -------------------------------------------------------------------------- cognee
+
+
+class CogneeMemory:
+ """Cognee's memory/graph pipeline (``pip install cognee``)."""
+
+ name = "cognee"
+
+ def __init__(
+ self,
+ client: Optional[Any] = None,
+ top_k: int = 5,
+ reader=None,
+ ):
+ self.top_k = int(top_k)
+ self._reader = reader
+ self.last_retrieved: List[str] = []
+ if client is None:
+ try:
+ import cognee
+ except ImportError as exc:
+ raise SystemUnavailable(
+ "cognee is not installed (pip install cognee)"
+ ) from exc
+ client = cognee
+ self._client = client
+
+ def reset(self) -> None:
+ """Prune cognee's store, failing loudly if the version has no prune API.
+
+ A silent no-op here would let one dataset's content leak into the next
+ and quietly corrupt every number in the run, so an unrecognised prune
+ surface is an error rather than a warning.
+ """
+ self.last_retrieved = []
+ prune = getattr(self._client, "prune", None)
+ for name in ("prune_all", "prune_data"):
+ fn = getattr(prune, name, None)
+ if callable(fn):
+ _run(fn())
+ return
+ raise SystemUnavailable(
+ "could not find cognee.prune.prune_all/prune_data in this version; "
+ "reset cognee manually before benchmarking so runs stay isolated"
+ )
+
+ def ingest(self, passages: Sequence[str], *, case_id: str = "") -> None:
+ texts = [str(p).strip() for p in passages if str(p).strip()]
+ if not texts:
+ return
+ _run(self._client.add("\n".join(texts)))
+ _run(self._client.cognify())
+
+ def answer(self, question: str, *, case_id: str = "") -> str:
+ results = _run(self._client.search(question))
+ passages = _texts_from(results, "text", "content", "answer")
+ self.last_retrieved = list(passages)
+ if not passages:
+ return ""
+ if self._reader is not None:
+ return self._reader(question, passages)
+ return best_sentence(question, passages)
+
+
+register_system("mem0", Mem0Memory)
+register_system("graphiti", GraphitiMemory)
+register_system("cognee", CogneeMemory)
diff --git a/semantica/benchmarks/systems/lexical.py b/semantica/benchmarks/systems/lexical.py
new file mode 100644
index 00000000..7f8f9803
--- /dev/null
+++ b/semantica/benchmarks/systems/lexical.py
@@ -0,0 +1,49 @@
+"""A dependency-free reference system (BM25 retrieval + extractive answer).
+
+This is **not** a memory system and its numbers are not a claim about memory
+quality — it is the floor. It exists so that (a) the harness has a system that
+always runs, with no API key, no service and no model, and (b) every published
+number has a cheap baseline next to it. If a real memory backend cannot beat
+BM25-over-the-same-passages on HotPotQA/MuSiQue, that is worth knowing.
+
+``reset`` drops the index, so per-case datasets give it a clean slate while
+corpus datasets hand it the whole conversation at once.
+"""
+
+from typing import List, Sequence
+
+from ..text import BM25, best_sentence
+from .base import register_system
+
+
+class LexicalMemory:
+ """BM25 index over ingested passages, answered extractively."""
+
+ name = "lexical"
+
+ def __init__(self, top_k: int = 5, reader=None):
+ self.top_k = int(top_k)
+ self._reader = reader
+ self._index = BM25()
+ self.last_retrieved: List[str] = []
+
+ def reset(self) -> None:
+ self._index.clear()
+ self.last_retrieved = []
+
+ def ingest(self, passages: Sequence[str], *, case_id: str = "") -> None:
+ texts = [str(p) for p in passages if str(p).strip()]
+ if texts:
+ self._index.add(texts)
+
+ def answer(self, question: str, *, case_id: str = "") -> str:
+ retrieved = self._index.search(question, top_k=self.top_k)
+ self.last_retrieved = list(retrieved)
+ if not retrieved:
+ return ""
+ if self._reader is not None:
+ return self._reader(question, retrieved)
+ return best_sentence(question, retrieved)
+
+
+register_system("lexical", LexicalMemory)
diff --git a/semantica/benchmarks/systems/semantica_memory.py b/semantica/benchmarks/systems/semantica_memory.py
new file mode 100644
index 00000000..4b380005
--- /dev/null
+++ b/semantica/benchmarks/systems/semantica_memory.py
@@ -0,0 +1,79 @@
+"""semantica's own memory layer, adapted to the benchmark protocol.
+
+Wraps :class:`semantica.context.AgentMemory`:
+
+``ingest`` -> ``AgentMemory.store(passage)``
+``answer`` -> ``AgentMemory.retrieve(question)`` then read the hits
+
+The read step is pluggable. By default the harness answers *extractively* from
+the retrieved passages (see :func:`semantica.benchmarks.text.best_sentence`) so
+that every system is compared on the same reader and the only thing that varies
+is memory. Pass ``reader=callable(question, passages) -> str`` to plug in an
+LLM reader and measure end-to-end QA quality instead.
+
+Configuration is passed straight through, so a caller can hand in a fully built
+memory object (``memory=...``) or let the adapter build the default one. The
+import of ``AgentMemory`` is deferred to construction time, so importing this
+module never pulls the memory stack into a process that only wants to list
+systems.
+"""
+
+from typing import Any, Dict, List, Optional, Sequence
+
+from ..text import best_sentence
+from .base import SystemUnavailable, register_system
+
+
+class SemanticaMemory:
+ """Adapter from ``AgentMemory`` to the harness protocol."""
+
+ name = "semantica"
+
+ def __init__(
+ self,
+ memory: Optional[Any] = None,
+ top_k: int = 5,
+ reader=None,
+ **memory_options: Any,
+ ):
+ self.top_k = int(top_k)
+ self._reader = reader
+ if memory is None:
+ try:
+ from semantica.context.agent_memory import AgentMemory
+ except ImportError as exc: # pragma: no cover - env dependent
+ raise SystemUnavailable(
+ f"semantica memory layer unavailable: {exc}"
+ ) from exc
+ memory = AgentMemory(**memory_options) if memory_options else AgentMemory()
+ self._memory = memory
+ self.last_retrieved: List[str] = []
+
+ def reset(self) -> None:
+ clear = getattr(self._memory, "clear", None)
+ if clear is None:
+ raise SystemUnavailable("AgentMemory has no clear(); cannot reset")
+ clear()
+ self.last_retrieved = []
+
+ def ingest(self, passages: Sequence[str], *, case_id: str = "") -> None:
+ metadata: Optional[Dict[str, Any]] = {"case_id": case_id} if case_id else None
+ for passage in passages:
+ text = str(passage).strip()
+ if text:
+ self._memory.store(text, metadata=metadata)
+
+ def answer(self, question: str, *, case_id: str = "") -> str:
+ hits: List[Dict[str, Any]] = self._memory.retrieve(
+ question, max_results=self.top_k
+ )
+ passages = [str(hit.get("content", "")) for hit in hits if hit.get("content")]
+ self.last_retrieved = list(passages)
+ if not passages:
+ return ""
+ if self._reader is not None:
+ return self._reader(question, passages)
+ return best_sentence(question, passages)
+
+
+register_system("semantica", SemanticaMemory)
diff --git a/semantica/benchmarks/text.py b/semantica/benchmarks/text.py
new file mode 100644
index 00000000..a37e8cbe
--- /dev/null
+++ b/semantica/benchmarks/text.py
@@ -0,0 +1,109 @@
+"""Tiny text helpers shared by the reference systems.
+
+Kept dependency-free on purpose: the point of a benchmark harness is that its
+scaffolding does not drag in a tokenizer, a model, or a service.
+"""
+
+import math
+import re
+from collections import Counter
+from typing import Dict, List, Sequence
+
+_TOKEN_RE = re.compile(r"[a-z0-9]+")
+_SENTENCE_RE = re.compile(r"(?<=[.!?])\s+")
+
+
+def tokenize(text: str) -> List[str]:
+ """Lowercase alphanumeric tokens."""
+ return _TOKEN_RE.findall(str(text).lower())
+
+
+def split_sentences(text: str) -> List[str]:
+ """Split on sentence-final punctuation, dropping empties."""
+ return [s.strip() for s in _SENTENCE_RE.split(str(text)) if s.strip()]
+
+
+def overlap_score(question: str, candidate: str) -> float:
+ """Share of the question's distinct content words present in ``candidate``.
+
+ A cheap, deterministic proxy for relevance — good enough to pick the least
+ bad sentence out of retrieved passages as an extractive answer.
+ """
+ q = set(tokenize(question))
+ if not q:
+ return 0.0
+ c = set(tokenize(candidate))
+ return len(q & c) / len(q)
+
+
+def best_sentence(question: str, passages: Sequence[str]) -> str:
+ """Return the sentence with the most question overlap, else ``""``.
+
+ This is the default extractive "reader": no model, no labels, just the
+ sentence that shares the most words with the question. Every system in the
+ harness can fall back to it, which keeps the *retrieval* layer the only
+ thing that differs between systems unless a real reader is supplied.
+ """
+ best, best_score = "", 0.0
+ for passage in passages:
+ for sentence in split_sentences(passage) or [str(passage)]:
+ score = overlap_score(question, sentence)
+ if score > best_score:
+ best, best_score = sentence, score
+ return best
+
+
+class BM25:
+ """Small in-memory BM25 index (k1=1.2, b=0.75).
+
+ Only ever used by the dependency-free reference system; it is not part of
+ semantica's production retrieval path.
+ """
+
+ def __init__(self, k1: float = 1.2, b: float = 0.75):
+ self.k1 = k1
+ self.b = b
+ self._texts: List[str] = []
+ self._docs: List[List[str]] = []
+ self._df: Counter = Counter()
+ self._avgdl: float = 0.0
+
+ def __len__(self) -> int:
+ return len(self._docs)
+
+ def add(self, texts: Sequence[str]) -> None:
+ for text in texts:
+ self._texts.append(str(text))
+ tokens = tokenize(text)
+ self._docs.append(tokens)
+ self._df.update(set(tokens))
+ total = sum(len(d) for d in self._docs)
+ self._avgdl = (total / len(self._docs)) if self._docs else 0.0
+
+ def clear(self) -> None:
+ self._texts.clear()
+ self._docs.clear()
+ self._df.clear()
+ self._avgdl = 0.0
+
+ def _idf(self, term: str) -> float:
+ n = len(self._docs)
+ df = self._df.get(term, 0)
+ return math.log((n - df + 0.5) / (df + 0.5) + 1.0)
+
+ def search(self, query: str, top_k: int = 5) -> List[str]:
+ """Return the top ``top_k`` documents by BM25 score."""
+ if not self._docs:
+ return []
+ scores: Dict[int, float] = {}
+ for term in set(tokenize(query)):
+ idf = self._idf(term)
+ for index, doc in enumerate(self._docs):
+ tf = doc.count(term)
+ if not tf:
+ continue
+ norm = self.k1 * (1 - self.b + self.b * len(doc) / (self._avgdl or 1))
+ numerator = idf * tf * (self.k1 + 1)
+ scores[index] = scores.get(index, 0.0) + numerator / (tf + norm)
+ ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
+ return [self._texts[i] for i, _ in ranked[:top_k]]
diff --git a/semantica/benchmarks/types.py b/semantica/benchmarks/types.py
new file mode 100644
index 00000000..1419c7d0
--- /dev/null
+++ b/semantica/benchmarks/types.py
@@ -0,0 +1,184 @@
+"""Data model for the open benchmark harness.
+
+A benchmark run is ``datasets x systems``. This module defines the small,
+dependency-free types that flow through it:
+
+- :class:`BenchmarkCase` / :class:`Dataset` — the evaluation inputs, normalized
+ to a single shape regardless of which upstream dataset they came from.
+- :class:`Prediction` / :class:`SystemResult` / :class:`BenchmarkReport` — the
+ outputs, aggregated per (system, dataset) pair.
+
+Keeping the case shape fixed is what lets one harness drive HotPotQA, MuSiQue
+and LoCoMo the same way, and score every system with the same evaluators.
+"""
+
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+# Dataset scopes -----------------------------------------------------------------
+# ``per_case``: each question ships its own evidence bundle; memory is reset
+# between cases (SQuAD-style reading comprehension, HotPotQA, MuSiQue).
+# ``corpus``: one long-lived context is ingested once and every question queries
+# the shared memory (long-conversation suites, LoCoMo).
+PER_CASE = "per_case"
+CORPUS = "corpus"
+SCOPES = (PER_CASE, CORPUS)
+
+
+@dataclass(frozen=True)
+class BenchmarkCase:
+ """One question plus everything needed to answer and score it."""
+
+ case_id: str
+ question: str
+ answers: List[str]
+ context: List[str] = field(default_factory=list)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+ def __post_init__(self):
+ if not self.answers:
+ raise ValueError(f"case {self.case_id!r} has no gold answers")
+
+
+@dataclass(frozen=True)
+class Dataset:
+ """A named, licensed collection of cases at a fixed scope.
+
+ ``group_by`` names an optional :attr:`BenchmarkCase.metadata` key that splits
+ a ``corpus`` dataset into **independent** memories. LoCoMo sets it to
+ ``"sample_id"`` because each sample is a separate conversation: without it the
+ runner would merge every conversation into one blob and let one sample's
+ evidence leak into another's answers. Left empty, a corpus dataset is a single
+ shared memory (the whole thing is ingested once).
+ """
+
+ name: str
+ license: str
+ scope: str
+ cases: List[BenchmarkCase]
+ version: str = ""
+ source: str = ""
+ notes: str = ""
+ group_by: str = ""
+
+ def __post_init__(self):
+ if self.scope not in SCOPES:
+ raise ValueError(f"unknown scope {self.scope!r}; expected one of {SCOPES}")
+
+ def __len__(self) -> int:
+ return len(self.cases)
+
+ def limit(self, n: Optional[int]) -> "Dataset":
+ """Return a copy truncated to the first ``n`` cases (``None`` = all)."""
+ if n is None or n >= len(self.cases):
+ return self
+ return Dataset(
+ name=self.name,
+ license=self.license,
+ scope=self.scope,
+ cases=list(self.cases[:n]),
+ version=self.version,
+ source=self.source,
+ notes=self.notes,
+ group_by=self.group_by,
+ )
+
+
+@dataclass
+class Prediction:
+ """A system's answer to one case, with timing and retrieved evidence."""
+
+ case_id: str
+ answer: str
+ retrieved: List[str] = field(default_factory=list)
+ latency_s: float = 0.0
+ error: Optional[str] = None
+
+ def as_dict(self) -> Dict[str, Any]:
+ return {
+ "case_id": self.case_id,
+ "answer": self.answer,
+ "retrieved": list(self.retrieved),
+ "latency_s": round(self.latency_s, 6),
+ "error": self.error,
+ }
+
+
+@dataclass
+class SystemResult:
+ """Scored outcome of one (system, dataset) pair."""
+
+ system: str
+ dataset: str
+ n: int
+ mean_score: float
+ exact_match_rate: float
+ errors: int
+ wall_s: float
+ primary_metric: str
+ summary: Any = None # semantica.evals EvalSummary
+ predictions: List[Prediction] = field(default_factory=list)
+
+ def as_dict(self, include_predictions: bool = False) -> Dict[str, Any]:
+ out = {
+ "system": self.system,
+ "dataset": self.dataset,
+ "n": self.n,
+ "primary_metric": self.primary_metric,
+ "mean_score": round(self.mean_score, 6),
+ "exact_match_rate": round(self.exact_match_rate, 6),
+ "errors": self.errors,
+ "wall_s": round(self.wall_s, 3),
+ }
+ if include_predictions:
+ out["predictions"] = [p.as_dict() for p in self.predictions]
+ return out
+
+
+@dataclass
+class BenchmarkReport:
+ """A full run: every (system, dataset) cell plus the run metadata."""
+
+ created_at: str
+ primary_metric: str
+ datasets: List[str] = field(default_factory=list)
+ systems: List[str] = field(default_factory=list)
+ results: List[SystemResult] = field(default_factory=list)
+ scores: Dict[str, Any] = field(default_factory=dict)
+ skipped: List[Dict[str, str]] = field(default_factory=list)
+
+ def as_dict(self, include_predictions: bool = False) -> Dict[str, Any]:
+ return {
+ "created_at": self.created_at,
+ "primary_metric": self.primary_metric,
+ "datasets": list(self.datasets),
+ "systems": list(self.systems),
+ "results": [r.as_dict(include_predictions) for r in self.results],
+ "skipped": list(self.skipped),
+ }
+
+ def to_markdown_table(self) -> str:
+ """Render a system x dataset matrix of the primary metric.
+
+ Cells are mean scores; systems that were not run on a dataset render as
+ an em dash so the table can be pasted into a README unchanged.
+ """
+ header = ["system"] + list(self.datasets)
+ lines = [
+ "| " + " | ".join(header) + " |",
+ "| " + " | ".join(["---"] * len(header)) + " |",
+ ]
+ for system in self.systems:
+ row = [system]
+ for dataset in self.datasets:
+ cell = next(
+ (
+ r
+ for r in self.results
+ if r.system == system and r.dataset == dataset
+ ),
+ None,
+ )
+ row.append(f"{cell.mean_score:.4f}" if cell else "—")
+ lines.append("| " + " | ".join(row) + " |")
+ return "\n".join(lines)
diff --git a/semantica/evals/__init__.py b/semantica/evals/__init__.py
index 352422c0..c318bb68 100644
--- a/semantica/evals/__init__.py
+++ b/semantica/evals/__init__.py
@@ -6,6 +6,8 @@ runner for measuring decision records, audit trails, and reasoning output.
from . import decision_evaluators # noqa: F401 (registers decision_scores)
from . import evaluators # noqa: F401 (registers the generic evaluators)
+from . import qa_evaluators # noqa: F401 (registers token_f1, normalized_exact_match)
+from .qa_evaluators import normalize_answer
from .registry import get_evaluator, list_evaluators
from .runner import evaluate, evaluate_repeated
from .types import (
@@ -23,6 +25,7 @@ __all__ = [
"evaluate_repeated",
"get_evaluator",
"list_evaluators",
+ "normalize_answer",
"CaseResult",
"EvalMetric",
"EvalSummary",
diff --git a/semantica/evals/qa_evaluators.py b/semantica/evals/qa_evaluators.py
new file mode 100644
index 00000000..c9e699d7
--- /dev/null
+++ b/semantica/evals/qa_evaluators.py
@@ -0,0 +1,126 @@
+"""QA-style evaluators: SQuAD-normalized token F1 and exact match.
+
+Reading-comprehension and open-domain QA suites (SQuAD, HotPotQA, MuSiQue,
+Natural Questions, ...) all score free-form answers with the same recipe:
+lowercase the text, drop punctuation and articles, collapse whitespace, then
+compare the predicted and gold answers as token bags. ``token_f1`` and
+``normalized_exact_match`` implement exactly that normalization, so the numbers
+they produce line up with the published baselines for those datasets instead of
+drifting because of casing or trailing periods.
+
+Both accept ``expected`` as either a single gold string or a list of acceptable
+golds (these datasets routinely ship several alternatives); the score is the
+best match over the gold set, which is also the standard convention.
+"""
+
+import re
+from collections import Counter
+from typing import Any, Dict, List, Tuple
+
+from .registry import register
+from .types import EvalMetric
+
+_ARTICLE_RE = re.compile(r"\b(a|an|the)\b")
+_PUNCT_RE = re.compile(r"[^\w\s]")
+
+
+def normalize_answer(text: Any) -> str:
+ """Apply the SQuAD answer normalization to ``text``.
+
+ Lowercases, **deletes** punctuation (the official SQuAD recipe removes it
+ rather than replacing it with a space, so ``"U.S."`` and ``"US"`` become the
+ same token), removes articles (a/an/the) and collapses runs of whitespace.
+ Kept as a public helper so callers can reuse the exact normalization the
+ evaluators apply.
+ """
+ text = str(text).lower()
+ text = _PUNCT_RE.sub("", text)
+ text = _ARTICLE_RE.sub(" ", text)
+ return " ".join(text.split())
+
+
+def _as_golds(expected: Any) -> Tuple[List[str], str]:
+ """Return ``(golds, error)``; ``error`` is "" when ``expected`` is usable."""
+ if expected is None:
+ return [], "expected is required (a gold answer or list of golds)"
+ if isinstance(expected, str):
+ return [expected], ""
+ if isinstance(expected, (list, tuple, set)):
+ golds = [g for g in expected if isinstance(g, str)]
+ if not golds:
+ return [], "expected list contains no string answers"
+ return golds, ""
+ return [], (
+ f"expected must be a string or list of strings, got {type(expected).__name__}"
+ )
+
+
+def _pair_overlap(gold: str, pred: str) -> Tuple[int, int, int]:
+ """Return ``(overlap, len(pred), len(gold))`` over normalized token bags."""
+ pred_tokens = normalize_answer(pred).split()
+ gold_tokens = normalize_answer(gold).split()
+ overlap = sum((Counter(pred_tokens) & Counter(gold_tokens)).values())
+ return overlap, len(pred_tokens), len(gold_tokens)
+
+
+def _f1(pred: str, gold: str) -> float:
+ """Token F1 between one prediction and one gold (SQuAD `f1_score`)."""
+ overlap, n_pred, n_gold = _pair_overlap(gold, pred)
+ if n_pred == 0 or n_gold == 0:
+ # If either side is empty the only way to score is exact emptiness.
+ return 1.0 if n_pred == n_gold else 0.0
+ if overlap == 0:
+ return 0.0
+ precision = overlap / n_pred
+ recall = overlap / n_gold
+ return 2 * precision * recall / (precision + recall)
+
+
+@register("token_f1")
+def token_f1(actual, expected=None, config=None, **kwargs):
+ """SQuAD-normalized token F1 between ``actual`` and the best gold.
+
+ ``expected`` may be a single gold string or a list of acceptable golds.
+ Passes when the best F1 reaches ``threshold`` (default 0.0, i.e. any
+ non-zero overlap) — mirroring ``rouge``. The raw F1 is always reported as
+ ``score``, which is what benchmark aggregation reads.
+ """
+ cfg = config or {}
+ threshold = cfg.get("threshold", 0.0)
+ golds, error = _as_golds(expected)
+ if error:
+ return EvalMetric(0.0, False, {"error": error})
+ if actual is None:
+ return EvalMetric(0.0, False, {"error": "actual is required"})
+
+ scores: Dict[str, float] = {g: _f1(str(actual), g) for g in golds}
+ best_gold, best = max(scores.items(), key=lambda kv: kv[1])
+ return EvalMetric(
+ score=best,
+ passed=best > 0.0 and best >= threshold,
+ meta={"f1": best, "best_gold": best_gold, "threshold": threshold},
+ )
+
+
+@register("normalized_exact_match")
+def normalized_exact_match(actual, expected=None, config=None, **kwargs):
+ """Exact match after SQuAD normalization, against any gold.
+
+ Passes (score 1.0) when the normalized prediction equals the normalization
+ of any gold; 0.0 otherwise. This is the datasets' "EM" column.
+ """
+ golds, error = _as_golds(expected)
+ if error:
+ return EvalMetric(0.0, False, {"error": error})
+ if actual is None:
+ return EvalMetric(0.0, False, {"error": "actual is required"})
+
+ normalized = normalize_answer(actual)
+ matched = next((g for g in golds if normalize_answer(g) == normalized), None)
+ return EvalMetric(
+ score=1.0 if matched is not None else 0.0,
+ passed=matched is not None,
+ meta={} if matched is not None else {
+ "reason": f"normalized {normalized!r} matched no gold",
+ },
+ )
diff --git a/tests/evals/test_benchmarks.py b/tests/evals/test_benchmarks.py
new file mode 100644
index 00000000..fd6c5f64
--- /dev/null
+++ b/tests/evals/test_benchmarks.py
@@ -0,0 +1,600 @@
+"""Tests for the phase-1 benchmark harness (``semantica.benchmarks``).
+
+Everything here must run offline: the harness ships one hand-written sample
+dataset and every other loader is exercised against small inline temp files, so
+the suite never touches the network or a vendor SDK.
+"""
+import json
+
+import pytest
+
+from semantica.benchmarks import (
+ CORPUS,
+ PER_CASE,
+ get_system,
+ list_datasets,
+ list_systems,
+ load_dataset,
+ run_benchmark,
+)
+from semantica.benchmarks import text as bt
+from semantica.benchmarks.datasets import get_loader
+from semantica.benchmarks.systems import SystemUnavailable, register_system
+from semantica.benchmarks.types import BenchmarkCase, BenchmarkReport, Dataset
+
+
+class _RecordingMemory:
+ """A memory system that records what each group wrote and read.
+
+ Used to prove the runner keeps separate memories apart: ``reset`` drops the
+ current memory, ``ingest`` replaces it, and every answer snapshots it.
+ """
+
+ def __init__(self):
+ self.memory = []
+ self.ingest_log = []
+ self.answers = []
+ self.last_retrieved = []
+
+ def reset(self):
+ self.memory = []
+ self.last_retrieved = []
+
+ def ingest(self, passages, *, case_id=""):
+ self.memory = [str(p) for p in passages]
+ self.ingest_log.append((case_id, list(self.memory)))
+
+ def answer(self, question, *, case_id=""):
+ self.last_retrieved = list(self.memory)
+ self.answers.append((question, list(self.memory)))
+ return " ".join(self.memory)
+
+
+class _FailingMemory:
+ """A memory system whose ``reset`` or ``ingest`` blows up on demand."""
+
+ def __init__(self, fail):
+ self._fail = fail
+ self.last_retrieved = []
+ self.answered = False
+
+ def reset(self):
+ if self._fail == "reset":
+ raise RuntimeError("backing store offline")
+
+ def ingest(self, passages, *, case_id=""):
+ if self._fail == "ingest":
+ raise RuntimeError("write rejected")
+
+ def answer(self, question, *, case_id=""):
+ self.answered = True
+ return "unreachable"
+
+
+# --------------------------------------------------------------------------- #
+# registry + sample dataset
+# --------------------------------------------------------------------------- #
+class TestRegistry:
+ def test_known_datasets_are_registered(self):
+ names = list_datasets()
+ for name in ("sample", "hotpotqa", "musique", "locomo"):
+ assert name in names
+
+ def test_unknown_dataset_raises_keyerror(self):
+ with pytest.raises(KeyError):
+ get_loader("does-not-exist")
+
+ def test_load_dataset_dispatches_to_loader(self):
+ dataset = load_dataset("sample")
+ assert dataset.name == "sample"
+ assert dataset.scope == PER_CASE
+
+
+class TestSampleDataset:
+ def test_has_cases_with_gold_answers(self):
+ dataset = load_dataset("sample")
+ assert len(dataset) == 6
+ for case in dataset.cases:
+ assert case.question
+ assert case.answers
+ assert case.context
+
+ def test_limit_truncates(self):
+ assert len(load_dataset("sample", limit=2)) == 2
+
+ def test_is_per_case_scoped(self):
+ assert load_dataset("sample").scope == PER_CASE
+
+
+# --------------------------------------------------------------------------- #
+# file-backed loaders
+# --------------------------------------------------------------------------- #
+class TestHotPotQALoader:
+ def _write(self, tmp_path, payload):
+ path = tmp_path / "hotpot.json"
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return str(path)
+
+ def test_official_context_shape(self, tmp_path):
+ payload = [
+ {
+ "_id": "q1",
+ "question": "Which city?",
+ "answer": "Paris",
+ "context": [
+ ["France", ["Paris is the capital.", "It is on the Seine."]]
+ ],
+ }
+ ]
+ dataset = load_dataset("hotpotqa", path=self._write(tmp_path, payload))
+ assert len(dataset) == 1
+ case = dataset.cases[0]
+ assert case.case_id == "q1"
+ assert case.answers == ["Paris"]
+ assert case.context == ["France: Paris is the capital. It is on the Seine."]
+
+ def test_huggingface_context_shape(self, tmp_path):
+ payload = [
+ {
+ "id": "q2",
+ "question": "Which city?",
+ "answer": "Paris",
+ "context": {
+ "title": ["France"],
+ "sentences": [["Paris is the capital."]],
+ },
+ }
+ ]
+ dataset = load_dataset("hotpotqa", path=self._write(tmp_path, payload))
+ assert dataset.cases[0].context == ["France: Paris is the capital."]
+
+ def test_records_without_answer_are_skipped(self, tmp_path):
+ payload = [
+ {"_id": "ok", "question": "q", "answer": "a", "context": []},
+ {"_id": "bad", "question": "q", "answer": "", "context": []},
+ ]
+ dataset = load_dataset("hotpotqa", path=self._write(tmp_path, payload))
+ assert [c.case_id for c in dataset.cases] == ["ok"]
+
+ def test_missing_file_raises(self, tmp_path):
+ with pytest.raises(FileNotFoundError):
+ load_dataset("hotpotqa", path=str(tmp_path / "nope.json"))
+
+
+class TestMuSiQueLoader:
+ def _write(self, tmp_path, records):
+ path = tmp_path / "musique.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in records), encoding="utf-8")
+ return str(path)
+
+ def test_parses_jsonl_and_folds_aliases(self, tmp_path):
+ records = [
+ {
+ "id": "m1",
+ "question": "Who?",
+ "answer": "Bach",
+ "answer_aliases": ["Johann Sebastian Bach"],
+ "paragraphs": [
+ {"title": "Composer", "paragraph_text": "Bach wrote it."}
+ ],
+ }
+ ]
+ dataset = load_dataset("musique", path=self._write(tmp_path, records))
+ case = dataset.cases[0]
+ assert case.answers == ["Bach", "Johann Sebastian Bach"]
+ assert case.context == ["Composer: Bach wrote it."]
+
+ def test_records_without_answer_are_skipped(self, tmp_path):
+ records = [
+ {"id": "ok", "question": "q", "answer": "a", "paragraphs": []},
+ {"id": "bad", "question": "q", "answer": "", "paragraphs": []},
+ ]
+ dataset = load_dataset("musique", path=self._write(tmp_path, records))
+ assert [c.case_id for c in dataset.cases] == ["ok"]
+
+
+class TestLoCoMoLoader:
+ def _write(self, tmp_path, payload):
+ path = tmp_path / "locomo.json"
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return str(path)
+
+ def _payload(self):
+ return [
+ {
+ "sample_id": "conv-1",
+ "conversation": {
+ "speaker_a": "Alice",
+ "speaker_b": "Bob",
+ "session_1_date_time": "1 Jan 2024",
+ "session_1": [
+ {"speaker": "Alice", "text": "I love hiking."},
+ {"speaker": "Bob", "text": "I prefer chess."},
+ ],
+ "session_2_date_time": "2 Jan 2024",
+ "session_2": [{"speaker": "Alice", "text": "I went hiking again."}],
+ },
+ "qa": [
+ {
+ "question": "What does Alice love?",
+ "answer": "hiking",
+ "category": 4,
+ },
+ {"question": "Who likes chess?", "answer": "Bob", "category": 2},
+ ],
+ }
+ ]
+
+ def test_scope_is_corpus(self, tmp_path):
+ dataset = load_dataset("locomo", path=self._write(tmp_path, self._payload()))
+ assert dataset.scope == CORPUS
+
+ def test_sessions_are_flattened_with_dates_and_speakers(self, tmp_path):
+ dataset = load_dataset("locomo", path=self._write(tmp_path, self._payload()))
+ context = dataset.cases[0].context
+ assert "[1 Jan 2024]" in context
+ assert "Alice: I love hiking." in context
+ assert "[2 Jan 2024]" in context
+
+ def test_category_filter(self, tmp_path):
+ path = self._write(tmp_path, self._payload())
+ dataset = load_dataset("locomo", path=path, categories=[4])
+ assert len(dataset) == 1
+ assert dataset.cases[0].metadata["category_name"] == "single-hop"
+
+ def test_license_surfaced_as_non_commercial(self, tmp_path):
+ dataset = load_dataset("locomo", path=self._write(tmp_path, self._payload()))
+ assert "NON-COMMERCIAL" in dataset.license
+
+ def test_group_by_is_sample_id(self, tmp_path):
+ dataset = load_dataset("locomo", path=self._write(tmp_path, self._payload()))
+ assert dataset.group_by == "sample_id"
+
+ def test_adversarial_answer_is_metadata_only(self, tmp_path):
+ # Category 5 ships a tempting wrong answer next to the real one; it must
+ # never reach the gold list, or a system would be credited for the trap.
+ payload = [
+ {
+ "sample_id": "conv-9",
+ "conversation": {"session_1": [{"speaker": "A", "text": "hi"}]},
+ "qa": [
+ {
+ "question": "Where does Alice live?",
+ "answer": "Paris",
+ "category": 5,
+ "adversarial_answer": "London",
+ }
+ ],
+ }
+ ]
+ dataset = load_dataset("locomo", path=self._write(tmp_path, payload))
+ case = dataset.cases[0]
+ assert case.answers == ["Paris"]
+ assert "London" not in case.answers
+ assert case.metadata["adversarial_answer"] == "London"
+
+ def test_question_without_real_answer_is_skipped(self, tmp_path):
+ # An adversarial question with no real gold answer must be dropped, not
+ # scored against its distractor.
+ payload = [
+ {
+ "sample_id": "conv-9",
+ "conversation": {"session_1": [{"speaker": "A", "text": "hi"}]},
+ "qa": [
+ {
+ "question": "Trap?",
+ "category": 5,
+ "adversarial_answer": "London",
+ },
+ {"question": "Real?", "answer": "Paris", "category": 5},
+ ],
+ }
+ ]
+ dataset = load_dataset("locomo", path=self._write(tmp_path, payload))
+ assert [case.question for case in dataset.cases] == ["Real?"]
+
+
+# --------------------------------------------------------------------------- #
+# text helpers
+# --------------------------------------------------------------------------- #
+class TestTextHelpers:
+ def test_tokenize_lowercases_and_drops_punctuation(self):
+ assert bt.tokenize("The Quick, brown FOX!") == ["the", "quick", "brown", "fox"]
+
+ def test_split_sentences(self):
+ assert bt.split_sentences("One. Two! Three?") == ["One.", "Two!", "Three?"]
+
+ def test_overlap_score_is_share_of_question_words(self):
+ assert bt.overlap_score("red apple", "the apple is red") == pytest.approx(1.0)
+ assert bt.overlap_score("red apple", "blue car") == 0.0
+
+ def test_best_sentence_picks_highest_overlap(self):
+ passages = ["The capital of France is Paris.", "Paris is a large city."]
+ assert bt.best_sentence("What is the capital of France?", passages) == (
+ "The capital of France is Paris."
+ )
+
+ def test_best_sentence_empty_input(self):
+ assert bt.best_sentence("q", []) == ""
+
+ def test_bm25_returns_source_texts_not_tokens(self):
+ index = bt.BM25()
+ index.add(["alpha beta gamma", "delta epsilon"])
+ hits = index.search("alpha")
+ assert hits == ["alpha beta gamma"]
+
+ def test_bm25_ranks_best_match_first(self):
+ index = bt.BM25()
+ index.add(["unrelated text here", "alpha beta gamma alpha"])
+ assert index.search("alpha beta", top_k=1) == ["alpha beta gamma alpha"]
+
+ def test_bm25_empty_index_returns_empty(self):
+ assert bt.BM25().search("anything") == []
+
+ def test_bm25_clear_empties_index(self):
+ index = bt.BM25()
+ index.add(["alpha"])
+ index.clear()
+ assert len(index) == 0
+ assert index.search("alpha") == []
+
+
+# --------------------------------------------------------------------------- #
+# systems
+# --------------------------------------------------------------------------- #
+class TestSystemRegistry:
+ def test_reference_systems_are_listed(self):
+ names = list_systems()
+ assert "lexical" in names
+ assert "semantica" in names
+
+ def test_unknown_system_raises_unavailable(self):
+ with pytest.raises(SystemUnavailable):
+ get_system("no-such-system")
+
+
+class TestLexicalSystem:
+ def test_extracts_the_answer_sentence(self):
+ system = get_system("lexical")
+ system.reset()
+ system.ingest(
+ [
+ "The telephone inventor Alexander Graham Bell was born in Scotland.",
+ "The telephone was patented in the United States.",
+ ],
+ case_id="c1",
+ )
+ answer = system.answer(
+ "Which country was the telephone inventor born in?", case_id="c1"
+ )
+ assert answer == (
+ "The telephone inventor Alexander Graham Bell was born in Scotland."
+ )
+
+ def test_reset_clears_memory(self):
+ system = get_system("lexical")
+ system.ingest(["only passage"], case_id="c1")
+ system.reset()
+ assert system.answer("only passage?", case_id="c1") == ""
+
+ def test_answer_records_retrieved_passages(self):
+ system = get_system("lexical")
+ system.reset()
+ system.ingest(["alpha bravo", "charlie delta"], case_id="c1")
+ system.answer("alpha bravo?", case_id="c1")
+ assert system.last_retrieved == ["alpha bravo"]
+
+ def test_reset_clears_retrieved_passages(self):
+ system = get_system("lexical")
+ system.ingest(["alpha"], case_id="c1")
+ system.answer("alpha", case_id="c1")
+ system.reset()
+ assert system.last_retrieved == []
+
+
+# --------------------------------------------------------------------------- #
+# end-to-end (offline)
+# --------------------------------------------------------------------------- #
+class TestRunBenchmark:
+ def test_sample_plus_lexical_scores_above_floor(self):
+ report = run_benchmark([load_dataset("sample")], ["lexical"])
+ assert isinstance(report, BenchmarkReport)
+ assert report.scores["lexical/sample"] > 0.0
+ result = report.results[0]
+ assert result.n == 6
+ assert result.errors == 0
+
+ def test_unavailable_system_is_skipped_not_fatal(self):
+ report = run_benchmark([load_dataset("sample")], ["no-such-system"])
+ assert report.results == []
+ assert [entry["system"] for entry in report.skipped] == ["no-such-system"]
+
+ def test_strict_mode_raises_on_unavailable_system(self):
+ with pytest.raises(SystemUnavailable):
+ run_benchmark(
+ [load_dataset("sample")], ["no-such-system"], on_error="raise"
+ )
+
+ def test_markdown_table_mentions_system_and_dataset(self):
+ report = run_benchmark([load_dataset("sample")], ["lexical"])
+ table = report.to_markdown_table()
+ assert "lexical" in table
+ assert "sample" in table
+
+ def test_report_serializes(self):
+ report = run_benchmark([load_dataset("sample")], ["lexical"])
+ payload = report.as_dict()
+ assert payload["systems"] == ["lexical"]
+ assert payload["datasets"] == ["sample"]
+ assert "skipped" in payload
+
+ def test_corpus_scope_ingests_once(self):
+ dataset = Dataset(
+ name="mini",
+ license="test",
+ scope=CORPUS,
+ cases=[
+ BenchmarkCase(case_id="a", question="Where is Paris?",
+ answers=["France"], context=["Paris is in France."]),
+ BenchmarkCase(case_id="b", question="Where is Paris?",
+ answers=["France"], context=["Paris is in France."]),
+ ],
+ )
+ report = run_benchmark([dataset], ["lexical"])
+ assert report.results[0].n == 2
+ assert report.results[0].errors == 0
+
+ def test_predictions_carry_retrieved_passages(self):
+ report = run_benchmark([load_dataset("sample")], ["lexical"])
+ predictions = report.results[0].predictions
+ assert predictions
+ # Every sample question shares content words with its evidence, so the
+ # lexical floor always retrieves something; the report must show it,
+ # otherwise per-case retrieval (the main debugging surface) is invisible.
+ assert all(prediction.retrieved for prediction in predictions)
+ by_id = {prediction.case_id: prediction for prediction in predictions}
+ assert by_id["sample-000"].retrieved[0] == (
+ "The novel Neuromancer was written by William Gibson and published in 1984."
+ )
+
+ def _two_conversations(self):
+ return Dataset(
+ name="two-conversations",
+ license="test",
+ scope=CORPUS,
+ group_by="sample_id",
+ cases=[
+ BenchmarkCase(
+ case_id="a1",
+ question="qa",
+ answers=["alpha"],
+ context=["alpha evidence"],
+ metadata={"sample_id": "conv-a"},
+ ),
+ BenchmarkCase(
+ case_id="b1",
+ question="qb",
+ answers=["bravo"],
+ context=["bravo evidence"],
+ metadata={"sample_id": "conv-b"},
+ ),
+ ],
+ )
+
+ def test_group_by_gives_each_conversation_its_own_memory(self):
+ probe = _RecordingMemory()
+ register_system("probe-grouped-memory", lambda **options: probe)
+
+ report = run_benchmark([self._two_conversations()], ["probe-grouped-memory"])
+
+ assert report.results[0].errors == 0
+ # One memory per conversation, each holding only its own evidence.
+ assert probe.ingest_log == [
+ ("conv-a", ["alpha evidence"]),
+ ("conv-b", ["bravo evidence"]),
+ ]
+ # ...and no answer could see the other conversation's evidence.
+ assert probe.answers == [
+ ("qa", ["alpha evidence"]),
+ ("qb", ["bravo evidence"]),
+ ]
+
+ def test_corpus_without_group_by_uses_one_shared_memory(self):
+ probe = _RecordingMemory()
+ register_system("probe-shared-memory", lambda **options: probe)
+ dataset = self._two_conversations()
+ dataset = Dataset(
+ name=dataset.name,
+ license=dataset.license,
+ scope=CORPUS,
+ cases=dataset.cases,
+ )
+
+ run_benchmark([dataset], ["probe-shared-memory"])
+
+ # Without group_by the whole corpus is a single memory, ingested once.
+ assert len(probe.ingest_log) == 1
+ assert probe.ingest_log[0][1] == ["alpha evidence", "bravo evidence"]
+
+ def test_reset_failure_is_recorded_not_fatal(self):
+ probe = _FailingMemory("reset")
+ register_system("probe-failing-reset", lambda **options: probe)
+ dataset = Dataset(
+ name="mini",
+ license="test",
+ scope=PER_CASE,
+ cases=[
+ BenchmarkCase(case_id="c1", question="q", answers=["a"], context=["x"]),
+ BenchmarkCase(case_id="c2", question="q", answers=["a"], context=["x"]),
+ ],
+ )
+
+ result = run_benchmark([dataset], ["probe-failing-reset"]).results[0]
+
+ assert result.n == 2
+ assert result.errors == 2
+ assert all(
+ "RuntimeError" in prediction.error for prediction in result.predictions
+ )
+ # A failed set-up must short-circuit the question, not answer on stale state.
+ assert probe.answered is False
+
+ def test_corpus_prep_failure_marks_every_case_in_the_group(self):
+ probe = _FailingMemory("ingest")
+ register_system("probe-failing-ingest", lambda **options: probe)
+ dataset = Dataset(
+ name="mini-corpus",
+ license="test",
+ scope=CORPUS,
+ cases=[
+ BenchmarkCase(case_id="c1", question="q", answers=["a"], context=["x"]),
+ BenchmarkCase(case_id="c2", question="q", answers=["a"], context=["x"]),
+ ],
+ )
+
+ result = run_benchmark([dataset], ["probe-failing-ingest"]).results[0]
+
+ assert result.errors == 2
+ assert all(
+ "RuntimeError" in prediction.error for prediction in result.predictions
+ )
+
+ def test_unknown_primary_metric_raises_instead_of_scoring_zero(self):
+ with pytest.raises(ValueError):
+ run_benchmark(
+ [load_dataset("sample")], ["lexical"], primary_metric="tokn_f1"
+ )
+
+
+# --------------------------------------------------------------------------- #
+# CLI
+# --------------------------------------------------------------------------- #
+class TestCli:
+ def test_list_command_exits_cleanly(self, capsys):
+ from semantica.benchmarks.__main__ import main
+
+ assert main(["list"]) == 0
+ out = capsys.readouterr().out
+ assert "sample" in out
+
+ def test_run_command_offline(self, capsys):
+ from semantica.benchmarks.__main__ import main
+
+ code = main(["run", "--dataset", "sample", "--system", "lexical", "--quiet"])
+ assert code == 0
+ assert "lexical" in capsys.readouterr().out
+
+ def test_unknown_metric_exits_with_error(self):
+ from semantica.benchmarks.__main__ import main
+
+ argv = [
+ "run",
+ "--dataset",
+ "sample",
+ "--system",
+ "lexical",
+ "--metric",
+ "tpyo",
+ ]
+ with pytest.raises(SystemExit):
+ main(argv)
diff --git a/tests/evals/test_qa_evaluators.py b/tests/evals/test_qa_evaluators.py
new file mode 100644
index 00000000..66cdd268
--- /dev/null
+++ b/tests/evals/test_qa_evaluators.py
@@ -0,0 +1,102 @@
+"""Tests for QA-style evaluators: token_f1 and normalized_exact_match."""
+import pytest
+
+from semantica.evals import registry as reg
+from semantica.evals.qa_evaluators import normalize_answer
+
+
+class TestNormalizeAnswer:
+ def test_lowercases_and_strips_punctuation(self):
+ assert normalize_answer("The Eiffel Tower!") == "eiffel tower"
+
+ def test_deletes_punctuation_instead_of_spacing_it(self):
+ # The official SQuAD recipe removes punctuation rather than replacing it
+ # with a space, so an abbreviation collapses to a single token.
+ assert normalize_answer("U.S.") == "us"
+ assert normalize_answer("U.S.") == normalize_answer("US")
+
+ def test_drops_articles(self):
+ assert normalize_answer("a cat and an owl") == "cat and owl"
+
+ def test_collapses_whitespace(self):
+ assert normalize_answer(" hello world ") == "hello world"
+
+
+class TestTokenF1:
+ def _f1(self, actual, expected, config=None):
+ return reg.get_evaluator("token_f1")(actual, expected, config=config)
+
+ def test_perfect_match_scores_one(self):
+ r = self._f1("Paris", "paris")
+ assert r.score == pytest.approx(1.0)
+ assert r.passed
+
+ def test_partial_overlap_between_zero_and_one(self):
+ r = self._f1("the quick brown fox", "quick brown fox jumps")
+ # normalization drops "the": pred = 3 tokens, gold = 4, overlap = 3.
+ precision, recall = 3 / 3, 3 / 4
+ expected = 2 * precision * recall / (precision + recall)
+ assert r.score == pytest.approx(expected)
+
+ def test_no_overlap_is_zero(self):
+ assert self._f1("apple", "orange").score == 0.0
+
+ def test_multi_gold_takes_best(self):
+ r = self._f1("Barack Obama", ["Obama", "Barack Obama"])
+ assert r.score == pytest.approx(1.0)
+ assert r.meta["best_gold"] == "Barack Obama"
+
+ def test_normalization_makes_article_insensitive(self):
+ assert self._f1("the Paris", "Paris").score == pytest.approx(1.0)
+
+ def test_missing_expected_is_error(self):
+ r = self._f1("x", None)
+ assert r.meta.get("error")
+ assert not r.passed
+
+ def test_bad_expected_type_is_error(self):
+ r = self._f1("x", 123)
+ assert r.meta.get("error")
+
+ def test_threshold_gates_pass(self):
+ r = self._f1("quick brown fox", "quick brown fox", config={"threshold": 0.5})
+ assert r.passed
+ r2 = self._f1("apple", "orange", config={"threshold": 0.5})
+ assert not r2.passed
+
+
+class TestNormalizedExactMatch:
+ def _em(self, actual, expected, config=None):
+ evaluator = reg.get_evaluator("normalized_exact_match")
+ return evaluator(actual, expected, config=config)
+
+ def test_match_after_normalization(self):
+ r = self._em("The University of Oxford.", "university of oxford")
+ assert r.passed and r.score == 1.0
+
+ def test_mismatch(self):
+ r = self._em("Oxford", "Cambridge")
+ assert not r.passed and r.score == 0.0
+
+ def test_any_gold_matches(self):
+ assert self._em("NYC", ["New York City", "NYC"]).passed
+
+ def test_missing_expected_is_error(self):
+ assert self._em("x", None).meta.get("error")
+
+
+class TestRegistration:
+ def test_both_are_registered(self):
+ names = reg.list_evaluators()
+ assert "token_f1" in names
+ assert "normalized_exact_match" in names
+
+ def test_runner_accepts_token_f1(self):
+ from semantica.evals import evaluate
+
+ summary = evaluate(
+ [{"id": "a", "expected": ["Paris"], "actual": "the Paris"}],
+ evaluators=["token_f1"],
+ )
+ assert summary.cases[0].status == "pass"
+ assert summary.cases[0].metrics["token_f1"].score == pytest.approx(1.0)