23  Evaluation and provenance channels — one program, either transport

Verbs: eval_embeddings (with cohorts) · eval_per_query · eval_compare · eval_inference (classification and NER) · register_channel · add_channel_columns · list_channels · jammi.testing.LiveServer · Background: retrieval and inference evaluation as an engine verb — precision@k / recall@k / MRR / nDCG, accuracy / F1, entity-span precision/recall — and the evidence-provenance channel as a typed, append-only, tenant-scoped registry (Kleppmann 2017) · Checked: measurement (the reports’ own identities) + parity (the remote report equals the embedded one, value for value) + tenancy (channel isolation, measured).

An evaluation run in-process is one call on the embedded engine. The same verbs are on a jammi-server, and a program written against a Session runs unchanged on either. This chapter makes that a measured property rather than a claim: it writes the evaluation once, as one function, runs it against an in-process engine and against a live server, and asserts the two reports are the same.

import tempfile
import uuid

import jammi
from jammi.testing import LiveServer
from jammi_cookbook import datasets, fixtures, keystone, scale
from jammi_cookbook.claims import claim

SCALE = scale.current()
TENANTS = (str(uuid.uuid4()), str(uuid.uuid4()))

23.1 The evaluation, written once

Four evaluations and one provenance sequence, over a Session of either kind:

  • eval_embeddings scores the papers’ raw embeddings on same-subject retrieval, with each query tagged by its cohort — the time-split era its paper belongs to — so the report can be sliced; eval_per_query reads the run’s persisted per-query rows back;
  • eval_compare scores the raw and graph-propagated tables side by side, with a paired significance test on the difference;
  • eval_inference runs a model’s forward pass and scores it: classification (accuracy / F1 against a label set) and NER (entity-span precision / recall against character-offset gold spans), on the cookbook’s small fixture models;
  • the channel sequence registers two provenance channels under one tenant, appends columns, and reads the registry from both tenants and from no tenant.
def evaluate(db) -> dict:
    arxiv = datasets.arxiv(db, SCALE)
    raw = keystone.embed(db, arxiv, SCALE)
    propagated = keystone.propagate(db, arxiv, raw)
    golden = keystone.subject_golden(db, arxiv)
    era = {pid: name for name, ids in arxiv.split.items() for pid in ids}
    queries = db.sql(f"SELECT DISTINCT query_id FROM {golden}").column(0).to_pylist()

    retrieval = db.eval_embeddings(
        source=arxiv.papers, golden_source=golden, embedding_table=raw, k=10,
        cohorts={q: {"era": era[q]} for q in queries},
    )
    per_query = db.eval_per_query(retrieval["eval_run_id"])
    compared = db.eval_compare(
        embedding_tables=[raw, propagated], source=arxiv.papers, golden_source=golden, k=10,
    )

    db.add_source("corpus", url=fixtures.url("tiny_corpus.parquet"), format="parquet")
    db.add_source("labels", url=fixtures.url("tiny_labels.csv"), format="csv")
    classification = db.eval_inference(
        model=fixtures.model("tiny_modernbert_classifier"), source="corpus",
        columns=["content"], task="classification",
        golden_source="labels.public.tiny_labels", label_column="label",
    )
    db.add_source("ner_corpus", url=fixtures.url("tiny_ner_corpus.parquet"), format="parquet")
    db.add_source("ner_gold", url=fixtures.url("tiny_ner_gold.csv"), format="csv")
    ner = db.eval_inference(
        model=fixtures.model("tiny_modernbert_ner"), source="ner_corpus",
        columns=["text"], task="ner",
        golden_source="ner_gold.public.tiny_ner_gold", label_column="label",
    )

    a, b = TENANTS
    with db.tenant_scope(a):
        db.register_channel("scored_by", priority=50,
                            columns=[("score", "Float64"), ("model", "Utf8")])
        db.register_channel("annotated_by", priority=10, columns=[("label", "Utf8")])
        db.add_channel_columns("annotated_by",
                               columns=[("confidence", "Float32"), ("rank", "Int32")])
    with db.tenant_scope(b):
        seen_by_b = db.list_channels()
        db.register_channel("scored_by", priority=3, columns=[("note", "Utf8")])
        b_channels = db.list_channels()
    with db.tenant_scope(a):
        a_channels = db.list_channels()

    return {
        "retrieval": retrieval, "per_query": per_query, "compared": compared,
        "classification": classification, "ner": ner,
        "channels": {"a": a_channels, "b_before": seen_by_b, "b": b_channels,
                     "unbound": db.list_channels()},
    }

23.2 Run it in process, then against a server

jammi.connect("file://…") runs the engine in this process; jammi.testing.LiveServer starts a real jammi-server (the jammi-server wheel puts one on PATH) on ports the kernel assigns, and jammi.connect(server.endpoint) is a grpc:// session to it. The same function runs on each.

with jammi.connect(f"file://{tempfile.mkdtemp()}") as embedded:
    local = evaluate(embedded)

with LiveServer(tempfile.mkdtemp()) as server, jammi.connect(server.endpoint) as remote:
    served = evaluate(remote)
print(f"evaluated in process and at {server.endpoint}")
2026-10-03T07:42:27.473278Z  WARN jammi_kernels::admission: fused-kernel domain check failed; falling back to the eager composition op="attention_block_fused" predicate="head_dim_is_attention_block_fixed_head_dim"
evaluated in process and at grpc://127.0.0.1:35893

23.3 The reports

Retrieval quality of the raw embeddings, overall and by cohort. The engine never interprets a cohort tag; it carries each query’s tags on its per-query record, so a slice is a group-by over those records. The golden asks its first 200 papers by id, so which eras those queries fall in is a property of the scale’s paper set — the slice reports the eras the queries carry:

from collections import defaultdict

agg = local["retrieval"]["aggregate"]
print("  ".join(f"{m} {agg[m]:.3f}" for m in ("precision_at_k", "recall_at_k", "mrr", "ndcg")))
by_era = defaultdict(list)
for record in local["retrieval"]["per_query"]:
    by_era[record["cohorts"]["era"]].append(record["metrics"]["precision"])
for era, scores in sorted(by_era.items()):
    print(f"  era={era:<5}  queries {len(scores):>3}  precision@10 {sum(scores) / len(scores):.3f}")
print(f"persisted per-query rows: {len(local['per_query'])}")
precision_at_k 0.403  recall_at_k 0.028  mrr 0.570  ndcg 0.411
  era=test   queries   2  precision@10 0.750
  era=train  queries 131  precision@10 0.358
  era=valid  queries  67  precision@10 0.482
persisted per-query rows: 200

The comparison: the propagated table’s precision@10 against the raw baseline, with the paired test’s confidence interval on the difference.

treated = local["compared"]["per_table"][1]
delta = treated["delta"]["precision_at_k"]
significance = treated["delta"]["significance"]["precision_at_k"]
print(f"propagated − raw precision@10: {delta['absolute']:+.3f}  "
      f"(95% CI {significance['ci_lower']:+.3f} … {significance['ci_upper']:+.3f}, "
      f"p = {significance['p_value']:.4f})")
propagated − raw precision@10: +0.023  (95% CI -0.013 … +0.059, p = 0.8972)

And the inference evaluations. The fixture models are small and randomly initialised, so their scores are low — what is under test here is the verb, not the model: a forward pass scored against labels, and against gold entity spans.

cls, ner = local["classification"]["aggregate"], local["ner"]["aggregate"]
print(f"classification: accuracy {cls['accuracy']:.3f}  f1 {cls['f1']:.3f}")
print(f"ner:            precision {ner['precision']:.3f}  recall {ner['recall']:.3f}  "
      f"f1 {ner['f1']:.3f}")
classification: accuracy 0.400  f1 0.286
ner:            precision 0.000  recall 0.000  f1 0.000
baseline = local["compared"]["per_table"][0]["embedding_eval"]["aggregate"]["precision_at_k"]
propagated = treated["embedding_eval"]["aggregate"]["precision_at_k"]
claim("the report is persisted one row per query",
      len(local["per_query"]) == len(local["retrieval"]["per_query"]))
claim("the comparison's delta is the propagated table's precision@10 less the raw table's",
      abs(delta["absolute"] - (propagated - baseline)) < 1e-9,
      f"{propagated:.3f} − {baseline:.3f}")
claim("propagation raises precision@10", delta["absolute"] > 0, f"{delta['absolute']:+.3f}")
✓ the report is persisted one row per query
✓ the comparison's delta is the propagated table's precision@10 less the raw table's (0.427 − 0.403)
✓ propagation raises precision@10 (+0.023)

23.4 The same report from either transport

The server’s report must equal the in-process one: the same keys at every level and the same values. Two things legitimately differ and are set aside — identifiers each engine mints for itself (the run id, the embedding table’s name), and the order of per-query and per-record rows, which the report does not promise.

MINTED = {"eval_run_id", "table_name", "embedding_table"}


def canonical(value):
    """A report with minted identifiers dropped and row lists in key order."""
    if isinstance(value, dict):
        return {k: canonical(v) for k, v in value.items() if k not in MINTED}
    if isinstance(value, list):
        rows = [canonical(v) for v in value]
        key = next((k for k in ("query_id", "record_id", "channel_id") if rows and
                    isinstance(rows[0], dict) and k in rows[0]), None)
        return sorted(rows, key=lambda r: r[key]) if key else rows
    return value


def differences(a, b, path=""):
    """Every path at which two canonical reports disagree."""
    if isinstance(a, dict) and isinstance(b, dict):
        return [d for k in a.keys() | b.keys()
                for d in differences(a.get(k), b.get(k), f"{path}.{k}")]
    if isinstance(a, list) and isinstance(b, list) and len(a) == len(b):
        return [d for i, (x, y) in enumerate(zip(a, b)) for d in differences(x, y, f"{path}[{i}]")]
    if isinstance(a, float) and isinstance(b, float):
        return [] if abs(a - b) <= 1e-6 * max(1.0, abs(a), abs(b)) else [path]
    return [] if a == b else [path]


for verb in local:
    print(f"{verb:<15} remote == embedded: {not differences(canonical(local[verb]), canonical(served[verb]))}")
retrieval       remote == embedded: True
per_query       remote == embedded: True
compared        remote == embedded: True
classification  remote == embedded: True
ner             remote == embedded: True
channels        remote == embedded: True
claim("the server's report equals the in-process one, verb by verb",
      all(not differences(canonical(local[verb]), canonical(served[verb])) for verb in local),
      ", ".join(local))
✓ the server's report equals the in-process one, verb by verb (retrieval, per_query, compared, classification, ner, channels)

23.5 Provenance channels — typed, append-only, tenant-scoped

An evidence-provenance channel attaches typed columns of provenance to records: a channel is an id, a priority, and (name, dtype) columns, and its columns can be appended to but never changed. The registry is scoped per tenant, and the sequence above read it from each side:

channels = local["channels"]
annotated = next(c for c in channels["a"] if c["channel_id"] == "annotated_by")
a_scored = next(c for c in channels["a"] if c["channel_id"] == "scored_by")
b_scored = next(c for c in channels["b"] if c["channel_id"] == "scored_by")
leak = {"scored_by", "annotated_by"} & {c["channel_id"] for c in channels["b_before"]}
print(f"annotated_by columns (appended after the original): "
      f"{[c['name'] for c in annotated['columns']]}")
print(f"tenant B saw A's channels: {sorted(leak) or 'none'}")
print(f"scored_by — A: {[c['name'] for c in a_scored['columns']]}  "
      f"B: {[c['name'] for c in b_scored['columns']]}")
print(f"unbound listing: {sorted(c['channel_id'] for c in channels['unbound'])}")
annotated_by columns (appended after the original): ['label', 'confidence', 'rank']
tenant B saw A's channels: none
scored_by — A: ['score', 'model']  B: ['note']
unbound listing: ['bm25', 'inference', 'vector']
claim("a channel's columns are appended to, never changed",
      [c["name"] for c in annotated["columns"]] == ["label", "confidence", "rank"])
claim("tenant B sees none of A's channels and registers its own scored_by",
      not leak and a_scored["columns"] != b_scored["columns"])
claim("a session bound to no tenant sees only the engine's own channels",
      {c["channel_id"] for c in channels["unbound"]} == {"vector", "inference", "bm25"})
✓ a channel's columns are appended to, never changed
✓ tenant B sees none of A's channels and registers its own scored_by
✓ a session bound to no tenant sees only the engine's own channels

Tenant B cannot see tenant A’s channels, and registers its own scored_by — different columns, no collision with A’s. A session bound to no tenant sees only the global channels every engine seeds, one per way the engine itself produces evidence: vector (similarity search), inference (a model’s output), and bm25 (lexical scoring).

23.6 Bridge note

Evaluation is an engine verb, on every transport. Retrieval quality (eval_embeddings, sliced by cohort and read back per query), comparison (eval_compare, with a paired significance test), and inference quality (eval_inference for classification and NER) return the same nested report from an in-process engine and from a server — measured here on every run, not asserted once. The provenance channel registry is the typed, append-only, per-tenant complement: the engine’s isolation applied to the catalog of provenance columns.

Kleppmann, Martin. 2017. Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems. O’Reilly Media.