Skip to content

credencestack.bench

The benchmark harness: agents × models × packs × epochs, one evidence bundle per configuration, under a hard cost cap, with CSVs, charts and a Markdown report, including per-domain columns (false-clear rate, trusted-document rate, KYC rating accuracy and consistency, pass rates by domain and visibility). It runs offline with the scripted agents and model.

Responsibilities

  • Load and validate bench.yaml (load_bench_config), including prices and the max_usd cap.
  • Run every configuration into its own bundle (run_bench) and write bench_results.csv, bench_episodes.csv and a kind: bench manifest (write_bench_manifest).
  • Meter spend and stop cleanly at the cap (CostMeter, BudgetExhausted, the LangChain CostGuard).
  • Leave the report to credencestack.reports.bench: benchmark.html, benchmark.md and charts.

Non-goals

  • Choosing models or publishing results. Real benchmark runs need your models, prices and keys and are never run by CI.

Public API

Signatures and purposes are generated from the code by scripts/gen_dev_reference.py; errors come from each docstring's Raises: section or from api-notes.yaml, which also holds the hand-written effects column.

Name Kind Signature Purpose Errors Effects
OFFLINE_MODEL constant OFFLINE_MODEL = 'credencestack:scripted' Model string that runs the scripted agents offline (no provider, no spend). - -
BenchConfig model BenchConfig(name, models, agents, packs, pack_paths, scenarios, epochs, seed, …) A benchmark: agents x models x packs x epochs, under a hard cost cap. - data
BenchConfigError exception class BenchConfigError The benchmark configuration is invalid; errors lists every problem. - -
BenchError exception class BenchError The benchmark cannot start (bad packs, missing provider package or key, ...). - -
BenchRun model BenchRun(out, configs, spent_usd, max_usd) What run_bench produced. - data
BudgetExhausted exception class BudgetExhausted The benchmark's cost cap has been reached; no further model calls are made. - -
CostMeter class class CostMeter: .exhausted, .admit, .snapshot, .add Thread-safe running total of spend against a cap. - in-memory, thread-safe
Price model Price(input_per_mtok, output_per_mtok) US dollars per million tokens. None means "not filled in yet". - data
config_id function config_id(agent: str, model: str \| None) -> str Directory-safe id of one configuration, e.g. safe_lc__anthropic-model. - pure
load_bench_config function load_bench_config(path: str \| Path) -> BenchConfig Load and validate bench.yaml. BenchConfigError: missing file, invalid YAML or invalid configuration (all errors). reads bench.yaml
run_bench function run_bench(config: BenchConfig, out: Path, *, model_factory: ModelFactory = default_model_factory, on_config: Callable[[ConfigResult], None] \| None = None, pack_paths: Sequence[str \| Path] = (), settings: dict[str, Any] \| None = None, config_ref: str \| None = None) -> BenchRun Run every configuration of config into out. BenchError: out is not empty, a pack is invalid, or a model cannot be created. runs every configuration; writes bundles and CSVs; calls models when configured (spend)

Examples

Benchmark: results to CSV and charts

Both scripted agents on three scenarios, two epochs each, offline (max_usd: 0).

examples/dev/bench_report.py
"""Benchmark: offline results -> results.csv, episodes.csv, benchmark.md and charts."""

from __future__ import annotations

import csv
import tempfile
from pathlib import Path

from credencestack.bench import BenchConfig, run_bench
from credencestack.reports.bench import write_report

config = BenchConfig.model_validate(
    {
        "agents": ["scripted_naive", "scripted_safe"],
        "packs": ["payments", "resilience"],
        "scenarios": ["PAY-001", "PAY-002", "RES-006"],
        "epochs": 2,
        "max_usd": 0,
    }
)

with tempfile.TemporaryDirectory() as tmp:
    out = Path(tmp) / "bench"
    run_bench(config, out)
    print("# results directory")
    for p in sorted(out.iterdir()):
        print(" ", p.name + ("/" if p.is_dir() else ""))
    with (out / "bench_results.csv").open() as fh:
        rows = list(csv.DictReader(fh))
    print(f"# bench_results.csv: {len(rows)} rows, {len(rows[0])} columns; selected columns")
    for r in rows:
        print(
            f"  {r['config_id']:<15} episodes={r['episodes']} pass_rate={r['pass_rate']}"
            f" ci=[{r['pass_ci_low']}, {r['pass_ci_high']}] overreach_rate={r['overreach_rate']}"
            f" ignored_suspension={r['resilience_ignored_suspension']}"
        )
    written = write_report(out, Path(tmp) / "report")
    print("# write_report wrote")
    for p in written:
        print(" ", p.relative_to(Path(tmp) / "report").as_posix())

Output (generated by scripts/gen_doc_examples.py --only dev):

# results directory
  bench_episodes.csv
  bench_results.csv
  manifest.json
  scripted_naive/
  scripted_safe/
# bench_results.csv: 2 rows, 85 columns; selected columns
  scripted_naive  episodes=6 pass_rate=0.333333 ci=[0.0967693, 0.700012] overreach_rate=1 ignored_suspension=2
  scripted_safe   episodes=6 pass_rate=1 ci=[0.609657, 1] overreach_rate=0 ignored_suspension=0
# write_report wrote
  charts/overreach_rate.png
  charts/resilience_failures.png
  charts/injection_followed.png
  charts/halt_time.png
  charts/naive_vs_safe.png
  charts/fixed_vs_generated_pass_rate.png
  charts/fixed_vs_generated_overreach.png
  charts/false_clear_rate.png
  charts/kyc_rating.png
  charts/trusted_document_rate.png
  benchmark.md
  benchmark.html

Invariants and gotchas

  • run bench needs --confirm-spend, and refuses prices left as placeholders. A cap of 0 allows only offline configurations.
  • Charts need matplotlib (the bench extra); write_report(..., charts=False) writes only the Markdown.
  • The fixed-to-generated gap is reported only when generated scenarios ran.

Where the tests are

Test files that import this package's modules (from the file index):

  • tests/integration/test_adk_connector.py
  • tests/integration/test_crewai_connector.py
  • tests/integration/test_msaf_connector.py
  • tests/integration/test_strands_connector.py
  • tests/unit/test_bench.py
  • tests/unit/test_brittleness.py