|
- """Retrieval benchmark driver (spec AC-04). Run through tests/retrieval-benchmark.sh, which provisions a throw-away
- tenant and switches the embedding provider off for the lexical baseline.
-
- python -I run_benchmark.py load <base> <key> <namespace_id> <fixtures.json> <ids.json>
- python -I run_benchmark.py run <base> <key> <fixtures.json> <ids.json> <expected_strategy> <out.json>
- python -I run_benchmark.py report <fixtures.json> <hybrid.json> <lexical.json>
-
- Metrics per query kind: hit@5 (share of queries with a relevant item in the first 5 results), MRR@10 (mean of 1/rank
- of the first relevant item, 0 when none in the first 10) and, for "none" queries, the false positive rate (share of
- queries that return any result). report exits 1 when a threshold in fixtures.json is not met.
- """
- import json
- import sys
- import urllib.error
- import urllib.request
-
-
- def call(base, key, method, path, body=None):
- data = None if body is None else json.dumps(body).encode("utf-8")
- req = urllib.request.Request(base + path, data=data, method=method,
- headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
- try:
- with urllib.request.urlopen(req, timeout=120) as r:
- raw = r.read().decode("utf-8")
- return r.status, (json.loads(raw) if raw else None)
- except urllib.error.HTTPError as e:
- raw = e.read().decode("utf-8")
- try:
- return e.code, json.loads(raw)
- except ValueError:
- return e.code, raw
-
-
- def load_json(path):
- with open(path, encoding="utf-8") as f:
- return json.load(f)
-
-
- def save_json(path, value):
- with open(path, "w", encoding="utf-8") as f:
- json.dump(value, f, ensure_ascii=False, indent=1)
-
-
- def load(base, key, ns, fixtures_path, ids_path):
- fx = load_json(fixtures_path)
- ids = {}
- for m in fx["memories"]:
- st, d = call(base, key, "POST", "/remember",
- {"namespace_id": ns, "type": m["type"], "title": m["title"], "content": m["content"]})
- if st != 201:
- sys.exit("remember %s failed: %s %s" % (m["key"], st, d))
- mid = d.get("id") or d["data"]["id"]
- st, d = call(base, key, "POST", "/memories/%s/verifications" % mid,
- {"result": "verified", "method": "manual", "revision": 1})
- if st != 200:
- sys.exit("verify %s failed: %s %s" % (m["key"], st, d))
- ids[m["key"]] = mid
- for doc in fx["documents"]:
- st, d = call(base, key, "POST", "/ingestion/jobs",
- {"namespace_id": ns, "title": doc["title"], "source_uri": doc["source_uri"],
- "format": doc["format"], "content": doc["content"]})
- if st != 201:
- sys.exit("ingest %s failed: %s %s" % (doc["key"], st, d))
- ids[doc["key"]] = d["document_id"]
- save_json(ids_path, ids)
- print("loaded %d memories, %d documents" % (len(fx["memories"]), len(fx["documents"])))
-
-
- def labels_of(endpoint, results, by_id):
- out = []
- for r in results:
- if endpoint == "recall":
- out.append(by_id.get(r.get("id"), "?"))
- else:
- out.append("%s#%s" % (by_id.get(r.get("document_id"), "?"), r.get("heading_path") or ""))
- return out
-
-
- def is_relevant(label, relevant):
- for rel in relevant:
- if "#" in rel:
- doc, section = rel.split("#", 1)
- if label.startswith(doc + "#") and label.endswith(section):
- return True
- elif label == rel:
- return True
- return False
-
-
- def has_evidence(endpoint, r):
- # Evidence = what lets a caller check and cite a result: the exact revision, its verification state and author for a
- # memory; the document, its revision, source and locator and the trust label for a passage.
- if endpoint == "recall":
- return (r.get("revision") is not None and bool(r.get("verification_status")) and bool(r.get("created_by"))
- and r.get("relevance_score") is not None)
- return (bool(r.get("document_id")) and r.get("document_revision") is not None and bool(r.get("source_uri"))
- and isinstance(r.get("locator"), dict) and r.get("content_trust") == "untrusted_reference")
-
-
- def run(base, key, fixtures_path, ids_path, expected, out_path):
- fx = load_json(fixtures_path)
- by_id = {v: k for k, v in load_json(ids_path).items()}
- rows = []
- for q in fx["queries"]:
- st, d = call(base, key, "POST", "/" + q["endpoint"], {"query": q["text"], "max_results": 10})
- if st != 200:
- sys.exit("query %s failed: %s %s" % (q["id"], st, d))
- results = d.get("results") or []
- labels = labels_of(q["endpoint"], results, by_id)
- rank = None
- for i, lab in enumerate(labels):
- if is_relevant(lab, q["relevant"]):
- rank = i + 1
- break
- rows.append({"id": q["id"], "kind": q["kind"], "endpoint": q["endpoint"], "strategy": d.get("strategy"),
- "rank": rank, "results": len(results), "top": labels[:5],
- "evidence_ok": all(has_evidence(q["endpoint"], r) for r in results)})
- wrong = [r["id"] for r in rows if r["strategy"] != expected]
- if wrong:
- sys.exit("expected strategy %s, got another one for %s (is the embedding provider %s?)"
- % (expected, ", ".join(wrong), "up" if expected == "hybrid" else "stopped"))
- save_json(out_path, rows)
- print("%s run: %d queries" % (expected, len(rows)))
-
-
- def metrics(rows):
- m = {}
- for kind in ("exact", "paraphrase"):
- rs = [r for r in rows if r["kind"] == kind]
- m[kind + "_hit_at_5"] = sum(1 for r in rs if r["rank"] and r["rank"] <= 5) / len(rs)
- m[kind + "_mrr"] = sum(1.0 / r["rank"] for r in rs if r["rank"]) / len(rs)
- rs = [r for r in rows if r["kind"] != "none"]
- m["all_mrr"] = sum(1.0 / r["rank"] for r in rs if r["rank"]) / len(rs)
- rs = [r for r in rows if r["kind"] == "none"]
- m["none_false_positive_rate"] = sum(1 for r in rs if r["results"] > 0) / len(rs)
- m["evidence_ok"] = all(r["evidence_ok"] for r in rows)
- return m
-
-
- def report(fixtures_path, hybrid_path, lexical_path):
- th = load_json(fixtures_path)["thresholds"]
- hy, lx = load_json(hybrid_path), load_json(lexical_path)
- mh, ml = metrics(hy), metrics(lx)
- print("%-28s %8s %8s" % ("metric", "hybrid", "lexical"))
- for k in mh:
- a, b = mh[k], ml[k]
- fmt = "%-28s %8s %8s" if isinstance(a, bool) else "%-28s %8.3f %8.3f"
- print(fmt % (k, a, b))
- checks = [
- ("hybrid exact hit@5 >= %.2f" % th["hybrid_exact_hit_at_5"], mh["exact_hit_at_5"] >= th["hybrid_exact_hit_at_5"]),
- ("hybrid paraphrase hit@5 >= %.2f" % th["hybrid_paraphrase_hit_at_5"],
- mh["paraphrase_hit_at_5"] >= th["hybrid_paraphrase_hit_at_5"]),
- ("hybrid none false positives <= %.2f" % th["hybrid_none_false_positive_rate_max"],
- mh["none_false_positive_rate"] <= th["hybrid_none_false_positive_rate_max"]),
- ]
- if th.get("hybrid_mrr_not_below_lexical"):
- checks.append(("hybrid MRR >= lexical MRR", mh["all_mrr"] >= ml["all_mrr"]))
- if th.get("evidence_on_every_result"):
- checks.append(("evidence on every result", mh["evidence_ok"] and ml["evidence_ok"]))
- print("")
- for name, ok in checks:
- print("%s %s" % ("PASS" if ok else "FAIL", name))
- misses = [r for r in hy if r["kind"] != "none" and not (r["rank"] and r["rank"] <= 5)]
- noisy = [r for r in hy if r["kind"] == "none" and r["results"] > 0]
- if misses or noisy:
- print("")
- print("hybrid misses (no relevant item in the first 5):")
- for r in misses:
- print(" %s %-10s rank=%s top=%s" % (r["id"], r["kind"], r["rank"], ",".join(r["top"])))
- for r in noisy:
- print(" %s none returned %d result(s): %s" % (r["id"], r["results"], ",".join(r["top"])))
- ok = all(c[1] for c in checks)
- print("")
- print("passed: %d failed: %d" % (sum(1 for c in checks if c[1]), sum(1 for c in checks if not c[1])))
- sys.exit(0 if ok else 1)
-
-
- if __name__ == "__main__":
- a = sys.argv[1:]
- if a and a[0] == "load" and len(a) == 6:
- load(*a[1:])
- elif a and a[0] == "run" and len(a) == 7:
- run(*a[1:])
- elif a and a[0] == "report" and len(a) == 4:
- report(*a[1:])
- else:
- sys.exit(__doc__)
|