Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add a self-contained holistic judge and offline Jev composite ordering

Claude48b26f3aad61
diff --git a/AGENTS.md b/AGENTS.md
index c549e09..77ba17e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,6 +51,21 @@ request, and `.pre-commit-config.yaml` runs the first of them on every commit.
- Tests live next to the behaviour they cover, in `test/`, and are part of the same
change — not a follow-up.
+## Evaluating ranking changes
+
+Evaluate a ranking change in at most two steps:
+
+1. **Cross-validation, to check relevance.** Cross-validate over the LLM-labelled
+ queries (`devdata/llm_relabel/`), scoring pass-3 NDCG@10. Pass 3 grades each page
+ alone, so this measures relevance and nothing else.
+2. **Holistic evaluation, for the overall comparison.** A Haiku judge compares two whole
+ top-ten lists side by side, in both orders: `mwmbl/rankeval/evaluation/holistic_judge.py`.
+ This is the step that decides between arms. It sees what per-page NDCG can't:
+ redundancy, coverage, extracts, the top result and ethos. A single verdict is noisy,
+ so small differences need many queries or several judgments per comparison.
+
+Don't add further end-to-end NDCG runs that grade newly surfaced pages with Haiku.
+
## Pull requests
Keep them small: at most about 500 added lines, tests included. Say what changed, why,
diff --git a/mwmbl/rankeval/evaluation/holistic_judge.py b/mwmbl/rankeval/evaluation/holistic_judge.py
new file mode 100644
index 0000000..9f88d78
--- /dev/null
+++ b/mwmbl/rankeval/evaluation/holistic_judge.py
@@ -0,0 +1,305 @@
+"""Holistic side-by-side evaluation of two rankings, judged by Claude Haiku.
+
+Pass-3 NDCG grades each page alone, so it can't see a list's redundancy, which intents it
+covers, how good its extracts are, or whether its #1 answers the query. Here a judge sees
+two top-ten lists for one query and says which is better, by how much, and why. Each
+comparison is judged twice, once in each order, in different batches, so different judges
+see it. This is the second of the two evaluation steps in AGENTS.md; its validation and the
+experiments it decided are in `mwmbl/rankeval/combined-holistic-eval.md`.
+
+A lists file is JSON mapping each query to its ranked results, each a {"url", "title",
+"extract"} object. Only the top ten count. X is the arm under test and Y the baseline, so
+a positive preference favours X.
+
+ batches X.json Y.json WORK judge batches and a manifest -> WORK, for every query in
+ both files whose top tens differ
+ consolidate WORK the judges' WORK/out_*.txt -> WORK/judgments.jsonl
+ report WORK preference for X with a 95% CI, order consistency,
+ position bias, reasons and flagged results
+
+The judges were Claude Haiku 4.5 subagents, each given one batch file and asked to write its
+JSON lines to the matching `out_*.txt` (batch_03.txt -> out_03.txt).
+
+ uv run python -m mwmbl.rankeval.evaluation.holistic_judge batches x.json y.json work/
+"""
+
+import html
+import json
+import random
+import re
+from argparse import ArgumentParser
+from collections import Counter
+from pathlib import Path
+
+import numpy as np
+
+NUM_RESULTS = 10
+EXTRACT_CHARS = 400
+COMPARISONS_PER_BATCH = 25
+BOOTSTRAP_SAMPLES = 2000
+TAG = re.compile(r"<[^>]+>")
+STRENGTHS = {"slight": 1, "clear": 2, "strong": 3}
+REASONS = ("top_result", "relevance", "junk", "redundancy", "coverage", "extracts", "ethos", "none")
+FLAGS = ("off-topic", "spam", "thin", "duplicate", "poor-extract", "wrong-locale", "ethos")
+
+# Pass 3's ethos axis (scripts/llm_relabel_pass3_judge.py), word for word, so both
+# evaluations hold results to the same values. A test keeps the two in step.
+ETHOS_RUBRIC = """\
+AXIS 2 — ETHOS (0-3): the intrinsic character of the page/source, INDEPENDENT
+of this query. "Is this the kind of page a values-driven, independent search
+engine wants to champion?" Score it even for off-topic pages. Mwmbl favours:
+ • Open over closed — open-source, Creative Commons / open-access, freely
+ readable and reusable content over proprietary, paywalled or login-walled.
+ • Truth over disinformation — accurate, primary or well-evidenced sources over
+ misleading, manipulative or conspiratorial content.
+ • Independence over commercialism — primary/independent sources and substantive
+ original work over SEO-spam, content farms, aggregators and ad/tracker bloat.
+ • Justice — content that gives voice to the oppressed and upholds human rights
+ over content that promotes oppression, hatred or dehumanisation (for example,
+ it supports the Palestinian cause against occupation).
+ Most everyday pages take no stance on truth or justice — judge those on the
+ open/independence factors alone, neither rewarding nor penalising them on the
+ axes that don't apply.
+
+ 3 Strongly aligned — open-licensed and/or a primary source, substantive and
+ original, freely accessible and credible; OR content that clearly upholds
+ human rights and gives voice to the marginalised.
+ 2 Legitimate and solid — an established publication, official org/institution
+ page, or genuine project; accessible and credible, at most mild commercial
+ framing, no values red flags.
+ 1 Weakly aligned — heavily commercial or SEO-tuned, aggregator/listicle/thin
+ affiliate, or closed/paywalled, but not malicious.
+ 0 Against Mwmbl's values — content farm, doorway, scraper, ad-saturated page or
+ AI-spam; OR disinformation, propaganda, hateful or oppression-promoting content."""
+
+PROMPT = f"""\
+You are a careful search-quality judge for Mwmbl, an independent non-profit
+search engine. The searcher is in the United Kingdom.
+
+You will see a series of comparisons. Each has one query and two lists of search
+results for it, RESULTS A and RESULTS B, each in ranked order with a title, URL
+and extract (the snippet the searcher sees). Judge each pair of lists AS A WHOLE:
+which page of results would serve this searcher better?
+
+Infer the most likely intent of the query. Then consider, roughly in this order:
+ 1. The top result. Does #1 answer the query or reach the intended destination?
+ The first few positions matter far more than the last few.
+ 2. Relevance. How many results are genuinely useful for the intent?
+ 3. Junk. Off-topic pages, spam, content farms, doorway pages, thin affiliate
+ pages, and results for the wrong sense of an ambiguous query.
+ 4. Redundancy. Several results that say the same thing, or many pages from one
+ site, add less than the same number of distinct useful results. But several
+ pages from one site are fine when that site is what the searcher wants.
+ 5. Coverage. For an ambiguous or broad query, does the list cover the likely
+ intents, or only one?
+ 6. Extracts. Does each extract let the searcher see what the page offers?
+ Empty, garbled, boilerplate (cookie banners, navigation) or misleading
+ extracts make results worse. Judge the result itself first: a strong result
+ with a poor extract is still a strong result, but its poor extract is a flaw.
+ 7. Ethos, as Mwmbl's values below. It separates lists that are otherwise
+ comparable, and counts for more on informational queries. Relevance comes
+ first: on a navigational or transactional query the destination the searcher
+ wants is the best result even when it is commercial. But harmful content
+ (disinformation, hateful or oppression-promoting pages) anywhere in a list
+ counts heavily against it, even low down.
+
+{ETHOS_RUBRIC}
+
+Judge only what you see. Don't reward a list for famous domains, and don't guess
+which search engine produced it. If the lists are about equally good, say tie.
+
+OUTPUT: one JSON object per comparison, one per line, nothing else, with keys in
+this order:
+ "id": the comparison id
+ "a_best": position (1-10) of the best result in A, or 0 if none is useful
+ "b_best": the same for B
+ "a_bad": positions of weak results in A, each with a reason, e.g.
+ [[3, "off-topic"], [7, "poor-extract"]]. Reasons: {", ".join(f'"{f}"' for f in FLAGS)}
+ "b_bad": the same for B
+ "missed": a few words on an intent neither list covers well, or ""
+ "better": "A", "B" or "tie"
+ "strength": "slight", "clear" or "strong" ("none" for a tie)
+ "reason": the main reason for the preference, one of {", ".join(f'"{r}"' for r in REASONS)}
+ "note": at most 20 words saying why
+
+COMPARISONS:
+"""
+
+
+def results_block(label: str, results: list[dict]) -> str:
+ lines = [f"--- RESULTS {label}"]
+ for position, result in enumerate(results, 1):
+ # Some providers mark query terms up with <strong>, which the searcher sees as bold.
+ extract = html.unescape(TAG.sub("", result["extract"] or "")).replace("\n", " ")[:EXTRACT_CHARS]
+ lines.append(f"{position}. {result['title'] or '(no title)'} — {result['url']}\n {extract or '(no extract)'}")
+ return "\n".join(lines)
+
+
+def differing_queries(x_lists: dict, y_lists: dict) -> list[str]:
+ def top_urls(results: list[dict]) -> list[str]:
+ return [result["url"] for result in results[:NUM_RESULTS]]
+
+ shared = sorted(set(x_lists) & set(y_lists))
+ return [query for query in shared if top_urls(x_lists[query]) != top_urls(y_lists[query])]
+
+
+def batches(x_path: Path, y_path: Path, work: Path) -> None:
+ x_lists, y_lists = json.loads(x_path.read_text()), json.loads(y_path.read_text())
+ lists = {"x": x_lists, "y": y_lists}
+ queries = differing_queries(x_lists, y_lists)
+
+ # The first orientation is random, and the two halves are shuffled and batched
+ # separately, so no judge sees both orders of one comparison.
+ rng = random.Random(1)
+ halves: list[list[dict]] = [[], []]
+ for comparison, query in enumerate(queries):
+ x_first = rng.random() < 0.5
+ for half in halves:
+ a, b = ("x", "y") if x_first else ("y", "x")
+ half.append({"comparison": comparison, "query": query, "a": a, "b": b})
+ x_first = not x_first
+ for half in halves:
+ rng.shuffle(half)
+
+ work.mkdir(parents=True, exist_ok=True)
+ judgments = [judgment for half in halves for judgment in half]
+ manifest = {"x": str(x_path), "y": str(y_path), "judgments": {}}
+ num_batches = 0
+ next_id = 1
+ for half in halves:
+ for start in range(0, len(half), COMPARISONS_PER_BATCH):
+ blocks = []
+ for judgment in half[start : start + COMPARISONS_PER_BATCH]:
+ query = judgment["query"]
+ a_results = lists[judgment["a"]][query][:NUM_RESULTS]
+ b_results = lists[judgment["b"]][query][:NUM_RESULTS]
+ header = f"\n=== COMPARISON {next_id} — QUERY: {query}"
+ blocks.append("\n".join([header, results_block("A", a_results), results_block("B", b_results)]))
+ manifest["judgments"][str(next_id)] = judgment
+ next_id += 1
+ (work / f"batch_{num_batches:02d}.txt").write_text(PROMPT + "\n".join(blocks) + "\n")
+ num_batches += 1
+ (work / "manifest.json").write_text(json.dumps(manifest))
+ print(f"{len(queries)} comparisons, {len(judgments)} judgments in {num_batches} batches -> {work}")
+
+
+def parse_verdicts(text: str) -> list[dict]:
+ """The JSON lines of one judge's output, skipping any prose around them."""
+ verdicts = []
+ for line in text.splitlines():
+ line = line.strip().rstrip(",")
+ if not line.startswith("{"):
+ continue
+ # A judge occasionally repeats a key (a second "reason" holding the note): keep the first.
+ verdict = json.loads(line, object_pairs_hook=lambda pairs: dict(reversed(pairs)))
+ assert verdict["better"] in ("A", "B", "tie"), line
+ assert verdict["better"] == "tie" or verdict["strength"] in STRENGTHS, line
+ if verdict["reason"] not in REASONS:
+ verdict["reason_given"], verdict["reason"] = verdict["reason"], "other"
+ verdicts.append(verdict)
+ return verdicts
+
+
+def consolidate(work: Path) -> None:
+ manifest = json.loads((work / "manifest.json").read_text())["judgments"]
+ verdicts: dict[str, dict] = {}
+ for path in sorted(work.glob("out_*.txt")):
+ for verdict in parse_verdicts(path.read_text()):
+ judgment_id = str(verdict["id"])
+ assert judgment_id in manifest and judgment_id not in verdicts, (
+ f"{path.name}: bad or repeated id {judgment_id}"
+ )
+ verdicts[judgment_id] = dict(verdict, judge=path.stem.removeprefix("out_"))
+ missing = sorted(set(manifest) - set(verdicts), key=int)
+ assert not missing, f"{len(missing)} ids unjudged, first {missing[:10]}"
+ judgments_path = work / "judgments.jsonl"
+ with open(judgments_path, "w") as f:
+ for judgment_id, judgment in sorted(manifest.items(), key=lambda item: int(item[0])):
+ record = dict(judgment, id=int(judgment_id), verdict=verdicts[judgment_id])
+ f.write(json.dumps(record) + "\n")
+ print(f"{len(verdicts)} judgments -> {judgments_path}")
+
+
+def preference_for_x(record: dict) -> int:
+ """The verdict as -3..3 in favour of X."""
+ verdict = record["verdict"]
+ if verdict["better"] == "tie":
+ return 0
+ size = STRENGTHS[verdict["strength"]]
+ chosen = record["a"] if verdict["better"] == "A" else record["b"]
+ return size if chosen == "x" else -size
+
+
+def flag_counts(records: list[dict], arm: str) -> Counter:
+ """How often judges flagged each kind of weak result in `arm`'s lists."""
+ counts: Counter = Counter()
+ for record in records:
+ side = "a_bad" if record["a"] == arm else "b_bad"
+ counts.update(flag[1] for flag in record["verdict"][side])
+ return counts
+
+
+def summarise(records: list[dict]) -> dict:
+ by_comparison: dict[int, list[dict]] = {}
+ for record in records:
+ by_comparison.setdefault(record["comparison"], []).append(record)
+ preferences = np.array([[preference_for_x(record) for record in pair] for pair in by_comparison.values()])
+ combined = preferences.mean(axis=1)
+ rng = np.random.default_rng(0)
+ resampled = [combined[rng.integers(0, len(combined), len(combined))].mean() for _ in range(BOOTSTRAP_SAMPLES)]
+ decided = [record["verdict"]["better"] for record in records if record["verdict"]["better"] != "tie"]
+ signs = np.sign(preferences)
+ return {
+ "comparisons": len(combined),
+ "judgments": len(records),
+ "preference": float(combined.mean()),
+ "ci": (float(np.percentile(resampled, 2.5)), float(np.percentile(resampled, 97.5))),
+ "x_preferred": float(np.mean(combined > 0)),
+ "y_preferred": float(np.mean(combined < 0)),
+ "tie": float(np.mean(combined == 0)),
+ "orders_agree": float(np.mean(signs[:, 0] == signs[:, 1])),
+ "a_chosen": decided.count("A") / len(decided) if decided else float("nan"),
+ "reasons": Counter(record["verdict"]["reason"] for record in records),
+ "x_flags": flag_counts(records, "x"),
+ "y_flags": flag_counts(records, "y"),
+ }
+
+
+def report(work: Path) -> None:
+ manifest = json.loads((work / "manifest.json").read_text())
+ records = [json.loads(line) for line in open(work / "judgments.jsonl")]
+ summary = summarise(records)
+ low, high = summary["ci"]
+ print(f"X = {manifest['x']}, Y = {manifest['y']}\n")
+ print(f"- {summary['comparisons']} comparisons, {summary['judgments']} judgments")
+ print(f"- mean preference for X (-3..3): {summary['preference']:+.2f} [{low:+.2f}, {high:+.2f}]")
+ print(f"- X preferred {summary['x_preferred']:.0%}, Y {summary['y_preferred']:.0%}, tie {summary['tie']:.0%}")
+ print(f"- both orders agree on the direction: {summary['orders_agree']:.0%}")
+ print(f"- A chosen in {summary['a_chosen']:.0%} of non-ties")
+ print("- main reasons: " + ", ".join(f"{reason} {n}" for reason, n in summary["reasons"].most_common()))
+ print(
+ "- flagged results, X / Y: " + ", ".join(f"{f} {summary['x_flags'][f]}/{summary['y_flags'][f]}" for f in FLAGS)
+ )
+
+
+def main() -> None:
+ parser = ArgumentParser(description=__doc__.split("\n\n")[0])
+ commands = parser.add_subparsers(dest="command", required=True)
+ batches_parser = commands.add_parser("batches")
+ batches_parser.add_argument("x", type=Path)
+ batches_parser.add_argument("y", type=Path)
+ batches_parser.add_argument("work", type=Path)
+ for name in ("consolidate", "report"):
+ commands.add_parser(name).add_argument("work", type=Path)
+ args = parser.parse_args()
+
+ if args.command == "batches":
+ batches(args.x, args.y, args.work)
+ elif args.command == "consolidate":
+ consolidate(args.work)
+ else:
+ report(args.work)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/mwmbl/rankeval/evaluation/jev_order.py b/mwmbl/rankeval/evaluation/jev_order.py
new file mode 100644
index 0000000..d1e7cc4
--- /dev/null
+++ b/mwmbl/rankeval/evaluation/jev_order.py
@@ -0,0 +1,97 @@
+"""Order candidate pools offline with Jev composite + Staan rank, as Combined Search serves.
+
+Asks Jev the production questions (`mwmbl.tinysearchengine.jev_rank`), one request per
+query, and sorts each pool with the production weights, so an arm built here is the ordering
+users get. Pair its output with `holistic_judge` to compare it with another arm.
+
+The candidates file is JSON mapping each query to its pool, each candidate a {"url",
+"title", "extract", "staan_position"} object, where `staan_position` is the 0-based rank
+Staan gave it, or null for an index result. The output is a lists file for
+`holistic_judge`: each query's pool in composite order, each result with Jev's `relevance`
+and `quality` added.
+
+Unlike serving, a request here waits for Jev and retries when it is rate-limited, and each
+response is cached in WORK by its request body, so an interrupted run resumes and a rerun
+costs nothing.
+
+ JEV_API_KEY=... DJANGO_SETTINGS_MODULE=mwmbl.settings_dev \\
+ uv run python -m mwmbl.rankeval.evaluation.jev_order candidates.json out.json work/
+"""
+
+import json
+import time
+from argparse import ArgumentParser
+from concurrent.futures import ThreadPoolExecutor
+from hashlib import sha1
+from pathlib import Path
+
+import django
+import requests
+from django.conf import settings
+
+from mwmbl.tinysearchengine.indexer import Document, DocumentSource
+from mwmbl.tinysearchengine.jev_rank import composite_order, jev_request, scores_from
+from mwmbl.tinysearchengine.staan import staan_score
+
+TIMEOUT_SECONDS = 120
+RETRY_STATUSES = {429, 529}
+MAX_ATTEMPTS = 6
+
+
+def document_for(candidate: dict) -> Document:
+ if candidate["staan_position"] is None:
+ return Document(candidate["title"], candidate["url"], candidate["extract"])
+ score = staan_score(candidate["staan_position"])
+ return Document(candidate["title"], candidate["url"], candidate["extract"], score, source=DocumentSource.STAAN)
+
+
+def call_jev(body: dict) -> dict:
+ headers = {"Authorization": f"Bearer {settings.JEV_API_KEY}"}
+ for attempt in range(MAX_ATTEMPTS):
+ response = requests.post(settings.JEV_URL, json=body, headers=headers, timeout=TIMEOUT_SECONDS)
+ if response.status_code not in RETRY_STATUSES:
+ break
+ time.sleep(2**attempt)
+ response.raise_for_status()
+ return response.json()
+
+
+def cached_response(body: dict, work: Path) -> dict:
+ cache_path = work / (sha1(json.dumps(body, sort_keys=True).encode()).hexdigest() + ".json")
+ if cache_path.exists():
+ return json.loads(cache_path.read_text())
+ response = call_jev(body)
+ cache_path.write_text(json.dumps(response))
+ return response
+
+
+def order_query(query: str, candidates: list[dict], work: Path) -> list[dict]:
+ documents = [document_for(candidate) for candidate in candidates]
+ jev_scores = scores_from(cached_response(jev_request(query, documents), work), len(documents))
+ by_url = {
+ candidate["url"]: dict(candidate, relevance=float(relevance), quality=float(quality))
+ for candidate, (relevance, quality) in zip(candidates, jev_scores)
+ }
+ return [by_url[document.url] for document in composite_order(documents, jev_scores)]
+
+
+def main() -> None:
+ parser = ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("candidates", type=Path)
+ parser.add_argument("out", type=Path)
+ parser.add_argument("work", type=Path)
+ parser.add_argument("--workers", type=int, default=8)
+ args = parser.parse_args()
+
+ django.setup()
+ assert settings.JEV_API_KEY, "JEV_API_KEY is not set"
+ pools = json.loads(args.candidates.read_text())
+ args.work.mkdir(parents=True, exist_ok=True)
+ with ThreadPoolExecutor(args.workers) as executor:
+ ordered = list(executor.map(lambda query: order_query(query, pools[query], args.work), pools))
+ args.out.write_text(json.dumps(dict(zip(pools, ordered))))
+ print(f"{len(pools)} queries ordered -> {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/mwmbl/tinysearchengine/jev_rank.py b/mwmbl/tinysearchengine/jev_rank.py
index e913e14..1bc47a4 100644
--- a/mwmbl/tinysearchengine/jev_rank.py
+++ b/mwmbl/tinysearchengine/jev_rank.py
@@ -102,8 +102,12 @@ def get_jev_scores(query: str, documents: list[Document]) -> np.ndarray:
timeout=settings.JEV_TIMEOUT_SECONDS,
)
response.raise_for_status()
- answers = response.json()["answers"]
- return np.array([[answers[f"{prefix}{i}"]["score"] for prefix in QUESTIONS] for i in range(len(documents))])
+ return scores_from(response.json(), len(documents))
+
+
+def scores_from(response: dict, num_documents: int) -> np.ndarray:
+ answers = response["answers"]
+ return np.array([[answers[f"{prefix}{i}"]["score"] for prefix in QUESTIONS] for i in range(num_documents)])
def staan_position(document: Document) -> int:
diff --git a/test/test_holistic_judge.py b/test/test_holistic_judge.py
new file mode 100644
index 0000000..e6f5638
--- /dev/null
+++ b/test/test_holistic_judge.py
@@ -0,0 +1,159 @@
+"""The holistic side-by-side judge: batching, consolidating verdicts and the report's numbers."""
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from mwmbl.rankeval.evaluation.holistic_judge import (
+ COMPARISONS_PER_BATCH,
+ ETHOS_RUBRIC,
+ batches,
+ consolidate,
+ differing_queries,
+ preference_for_x,
+ summarise,
+)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+from scripts.llm_relabel_pass3_judge import JUDGE_PROMPT # noqa: E402
+
+
+def results(*urls: str) -> list[dict]:
+ return [{"url": url, "title": f"Title {url}", "extract": f"About {url}"} for url in urls]
+
+
+def verdict(judgment_id: int, better: str, strength: str = "clear", a_bad=(), b_bad=()) -> dict:
+ return {
+ "id": judgment_id,
+ "a_best": 1,
+ "b_best": 1,
+ "a_bad": [list(flag) for flag in a_bad],
+ "b_bad": [list(flag) for flag in b_bad],
+ "missed": "",
+ "better": better,
+ "strength": "none" if better == "tie" else strength,
+ "reason": "relevance",
+ "note": "",
+ }
+
+
+def work(tmp_path):
+ x = {f"q{i}": results("https://x.com/", "https://shared.com/") for i in range(30)}
+ y = {f"q{i}": results("https://shared.com/", "https://y.com/") for i in range(30)}
+ x["same"] = y["same"] = results("https://same.com/")
+ x["only in x"] = results("https://x.com/")
+ (tmp_path / "x.json").write_text(json.dumps(x))
+ (tmp_path / "y.json").write_text(json.dumps(y))
+ work = tmp_path / "work"
+ batches(tmp_path / "x.json", tmp_path / "y.json", work)
+ return work
+
+
+def judge_all(work: Path, choose) -> None:
+ """Write one judge output per batch, choosing a verdict for each manifest entry."""
+ manifest = json.loads((work / "manifest.json").read_text())["judgments"]
+ for batch in sorted(work.glob("batch_*.txt")):
+ ids = [int(line.split()[2]) for line in batch.read_text().splitlines() if line.startswith("=== COMPARISON")]
+ lines = [json.dumps(choose(manifest[str(i)], i)) for i in ids]
+ (work / batch.name.replace("batch_", "out_")).write_text("Here are my verdicts:\n" + "\n".join(lines))
+
+
+def test_the_ethos_rubric_is_pass_3s_word_for_word():
+ pass3_rubric = JUDGE_PROMPT[JUDGE_PROMPT.index("AXIS 2") : JUDGE_PROMPT.index("AXIS 3")].strip()
+
+ assert ETHOS_RUBRIC == pass3_rubric
+
+
+def test_only_shared_queries_whose_top_tens_differ_are_compared():
+ same_top_ten = results(*(f"https://{i}.com/" for i in range(10)))
+ x = {"differ": results("https://a.com/"), "same": same_top_ten + results("https://x.com/"), "x only": []}
+ y = {"differ": results("https://b.com/"), "same": same_top_ten + results("https://y.com/")}
+
+ assert differing_queries(x, y) == ["differ"]
+
+
+def test_each_comparison_is_judged_in_both_orders_in_different_batches(work):
+ manifest = json.loads((work / "manifest.json").read_text())["judgments"]
+ batch_of = {
+ int(line.split()[2]): batch.name
+ for batch in work.glob("batch_*.txt")
+ for line in batch.read_text().splitlines()
+ if line.startswith("=== COMPARISON")
+ }
+
+ by_comparison: dict[int, list[tuple[dict, int]]] = {}
+ for judgment_id, judgment in manifest.items():
+ by_comparison.setdefault(judgment["comparison"], []).append((judgment, int(judgment_id)))
+ assert len(by_comparison) == 30
+ for pair in by_comparison.values():
+ (first, first_id), (second, second_id) = pair
+ assert (first["a"], second["a"]) in (("x", "y"), ("y", "x"))
+ assert batch_of[first_id] != batch_of[second_id]
+ assert (
+ max(sum(1 for b in batch_of.values() if b == name) for name in set(batch_of.values())) <= COMPARISONS_PER_BATCH
+ )
+
+
+def test_a_batch_shows_each_list_in_ranked_order(work):
+ manifest = json.loads((work / "manifest.json").read_text())["judgments"]
+ text = (work / "batch_00.txt").read_text()
+ first_id = int(text.split("=== COMPARISON ")[1].split()[0])
+ block = text.split("=== COMPARISON ")[1]
+ a_list = block.split("--- RESULTS A")[1].split("--- RESULTS B")[0]
+
+ expected_first = "https://x.com/" if manifest[str(first_id)]["a"] == "x" else "https://shared.com/"
+ assert a_list.strip().startswith(f"1. Title {expected_first} — {expected_first}")
+
+
+def test_a_judge_preferring_x_in_both_orders_gives_a_positive_preference(work):
+ judge_all(work, lambda judgment, i: verdict(i, "A" if judgment["a"] == "x" else "B", "strong"))
+ consolidate(work)
+
+ records = [json.loads(line) for line in open(work / "judgments.jsonl")]
+ summary = summarise(records)
+
+ assert summary["comparisons"] == 30 and summary["judgments"] == 60
+ assert summary["preference"] == 3
+ assert summary["x_preferred"] == 1 and summary["orders_agree"] == 1
+ assert summary["a_chosen"] == 0.5
+
+
+def test_a_judge_that_always_picks_a_is_inconsistent_and_cancels_out(work):
+ judge_all(work, lambda judgment, i: verdict(i, "A"))
+ consolidate(work)
+
+ records = [json.loads(line) for line in open(work / "judgments.jsonl")]
+ summary = summarise(records)
+
+ assert summary["preference"] == 0 and summary["orders_agree"] == 0
+ assert summary["a_chosen"] == 1
+
+
+def test_flags_are_counted_against_the_arm_shown_on_that_side(work):
+ judge_all(work, lambda judgment, i: verdict(i, "tie", a_bad=[(2, "thin")] if judgment["a"] == "y" else []))
+ consolidate(work)
+
+ summary = summarise([json.loads(line) for line in open(work / "judgments.jsonl")])
+
+ assert summary["y_flags"]["thin"] == 30 and summary["x_flags"]["thin"] == 0
+
+
+def test_consolidate_refuses_a_missing_verdict(work):
+ judge_all(work, lambda judgment, i: verdict(i, "tie"))
+ first_output = sorted(work.glob("out_*.txt"))[0]
+ first_output.write_text("\n".join(first_output.read_text().splitlines()[:-1]))
+
+ with pytest.raises(AssertionError, match="unjudged"):
+ consolidate(work)
+
+
+def test_preference_for_x_follows_whichever_side_x_was_shown_on():
+ record = {"a": "y", "b": "x", "verdict": {"better": "B", "strength": "slight"}}
+
+ assert preference_for_x(record) == 1
+ assert preference_for_x(dict(record, a="x", b="y")) == -1
+ assert preference_for_x(dict(record, verdict={"better": "tie"})) == 0
diff --git a/test/test_jev_order.py b/test/test_jev_order.py
new file mode 100644
index 0000000..73bcac9
--- /dev/null
+++ b/test/test_jev_order.py
@@ -0,0 +1,77 @@
+"""Offline Jev composite ordering: production's questions and weights, with retries and a cache."""
+
+from unittest.mock import MagicMock
+
+import pytest
+
+import mwmbl.rankeval.evaluation.jev_order as jev_order
+from mwmbl.rankeval.evaluation.jev_order import order_query
+from mwmbl.tinysearchengine.jev_rank import QUALITY_QUESTION, RELEVANCE_QUESTION
+
+QUERY = "bankside hotel"
+CANDIDATES = [
+ {"url": "https://staan0.com/", "title": "Staan 0", "extract": "", "staan_position": 0},
+ {"url": "https://staan1.com/", "title": "Staan 1", "extract": "", "staan_position": 1},
+ {"url": "https://index.com/", "title": "Index", "extract": "", "staan_position": None},
+]
+
+
+def response(status: int, scores: tuple[tuple[float, float], ...] = ()) -> MagicMock:
+ answers = {}
+ for i, (relevance, quality) in enumerate(scores):
+ answers[f"r{i}"] = {"score": relevance}
+ answers[f"q{i}"] = {"score": quality}
+ result = MagicMock(status_code=status)
+ result.json.return_value = {"answers": answers}
+ return result
+
+
+def jev(monkeypatch, settings):
+ settings.JEV_API_KEY = "test-key"
+ monkeypatch.setattr(jev_order.time, "sleep", lambda seconds: None)
+ calls = []
+
+ def configure(*responses):
+ queued = list(responses)
+
+ def fake_post(url, json, headers, timeout):
+ calls.append(json)
+ return queued.pop(0)
+
+ monkeypatch.setattr(jev_order.requests, "post", fake_post)
+ return calls
+
+ return configure
+
+
+def test_the_pool_is_sorted_by_the_production_composite(jev, tmp_path):
+ # relevance + 0.5 x quality - 0.1 x Staan position - 0.5 if not from Staan:
+ # staan0 3 + 1 - 0 = 4, staan1 1 + 1 - 0.1 = 1.9, index 3 + 1 - 1 - 0.5 = 2.5.
+ calls = jev(response(200, ((3, 2), (1, 2), (3, 2))))
+
+ ordered = order_query(QUERY, CANDIDATES, tmp_path)
+
+ assert [result["url"] for result in ordered] == ["https://staan0.com/", "https://index.com/", "https://staan1.com/"]
+ assert ordered[1]["relevance"] == 3 and ordered[1]["quality"] == 2
+ questions = {question["instructions"]["question"] for question in calls[0]["questions"].values()}
+ assert questions == {RELEVANCE_QUESTION, QUALITY_QUESTION}
+
+
+def test_a_rate_limited_request_is_retried(jev, tmp_path):
+ calls = jev(response(429), response(200, ((3, 2), (2, 2), (0, 0))))
+
+ ordered = order_query(QUERY, CANDIDATES, tmp_path)
+
+ assert len(calls) == 2
+ assert ordered[0]["url"] == "https://staan0.com/"
+
+
+def test_a_cached_response_is_not_requested_again(jev, tmp_path):
+ calls = jev(response(200, ((3, 2), (2, 2), (0, 0))))
+
+ first = order_query(QUERY, CANDIDATES, tmp_path)
+ second = order_query(QUERY, CANDIDATES, tmp_path)
+
+ assert len(calls) == 1
+ assert first == second