An open source, non-profit web search engine
Super Search: add gov.uk + imdb sources; re-ranker is the real NDCG lever
Daoud Clarke0d10c78f740c
diff --git a/mwmbl/rankeval/SUPER_SEARCH_ADD_SOURCES_FINDINGS.md b/mwmbl/rankeval/SUPER_SEARCH_ADD_SOURCES_FINDINGS.mdnew file mode 100644index 0000000..33932b5--- /dev/null+++ b/mwmbl/rankeval/SUPER_SEARCH_ADD_SOURCES_FINDINGS.md@@ -0,0 +1,217 @@+# Super Search: adding high-gold-mass domains as sources — findings++_Branch `super-search-intent-feature`, June 2026._++## Why this exists++Earlier work tried to improve Super Search NDCG by tuning **source selection**+(which ~10 of ~130 sources to query) — a contextual bandit, then an offline+gold-grounded selector. A feasibility gate killed that framing: our current source+domains carry only **~0.36% of the gold relevance mass** (rankeval train+test,+click-weighted top-10), so no selection policy can move the needle. See+`SUPER_SEARCH_EVAL_FINDINGS.md` and `scripts/super_search_coverage.py`.++The inverse question — *which high-value domains are we missing?* — pointed at+adding sources instead of selecting them.++## Where the gold relevance actually lives++Ranking gold domains we **don't** have as sources, by click-weighted mass+(`scripts/super_search_coverage.py` inverse analysis):++- Current sources (registrable match): **~1%** of gold mass.+- Top-10 missing domains: **26.6%**; top-20: **31.8%**; top-40: **37.6%**.++Top 25 missing domains (rankeval train+test, before gov.uk/imdb were added —+`scripts/super_search_coverage.py missing`). `mass` is click-weighted gold relevance+(top-10 positions only); `rank1-3` is how many of the hits sat at ranks 1–3.++| # | domain | mass | %mass | queries | rows | rank1-3 |+|---:|---|---:|---:|---:|---:|---:|+| 1 | wikipedia.org | 1827.6 | 11.4% | 6300 | 11512 | 7401 |+| 2 | instagram.com | 428.2 | 2.7% | 2976 | 4948 | 1695 |+| 3 | imdb.com ✅ | 348.1 | 2.2% | 1648 | 2755 | 1717 |+| 4 | reddit.com | 327.3 | 2.0% | 3017 | 4301 | 1057 |+| 5 | facebook.com | 302.4 | 1.9% | 2918 | 4488 | 826 |+| 6 | youtube.com | 247.8 | 1.5% | 1966 | 3478 | 683 |+| 7 | google.com | 245.2 | 1.5% | 1096 | 2839 | 806 |+| 8 | bbc.com | 235.1 | 1.5% | 1382 | 2278 | 855 |+| 9 | gov.uk ✅ | 196.8 | 1.2% | 474 | 1213 | 848 |+| 10 | rottentomatoes.com | 111.4 | 0.7% | 944 | 1352 | 402 |+| 11 | amazon.com | 96.1 | 0.6% | 828 | 1011 | 335 |+| 12 | apple.com | 91.1 | 0.6% | 737 | 1307 | 237 |+| 13 | theguardian.com | 89.5 | 0.6% | 761 | 1105 | 289 |+| 14 | tripadvisor.com | 89.2 | 0.6% | 714 | 968 | 365 |+| 15 | nhs.uk | 85.6 | 0.5% | 397 | 805 | 342 |+| 16 | netflix.com | 82.3 | 0.5% | 473 | 862 | 348 |+| 17 | x.com | 78.7 | 0.5% | 860 | 1231 | 195 |+| 18 | espn.com | 77.3 | 0.5% | 553 | 893 | 288 |+| 19 | merriam-webster.com | 73.9 | 0.5% | 404 | 547 | 317 |+| 20 | skysports.com | 71.9 | 0.4% | 419 | 746 | 295 |+| 21 | mayoclinic.org | 67.1 | 0.4% | 255 | 429 | 268 |+| 22 | cambridge.org | 66.7 | 0.4% | 389 | 512 | 252 |+| 23 | spotify.com | 58.5 | 0.4% | 463 | 732 | 187 |+| 24 | fandom.com | 58.2 | 0.4% | 447 | 579 | 205 |+| 25 | britannica.com | 58.0 | 0.4% | 499 | 679 | 241 |++✅ = added this pass. After removing already-have (Wikipedia, row 1) and unaddressable+login-walled/social (instagram, facebook, x, and further down tiktok/linkedin/pinterest+≈ 6.5%) and google-self-links (row 7, 1.5%), **~15–18% of gold mass sits on domains with+real, scrapeable search** (reddit, bbc, gov.uk, rottentomatoes, guardian, the+dictionaries, nhs/mayoclinic, …). Many, however, are **IP-blocked (403)** from a+datacenter — see Source recall below.++## What was added++Two sources — the biggest *accessible* missing domains:++- **`www_gov_uk`** — recipe YAML over the GOV.UK search API.+- **`imdb`** — hand-written adapter over IMDb's autosuggest API (query goes in the+ URL path, so it can't be a declarative recipe).++Supporting infra:++- Recipe engine gained a JSON **`base_url`** join (`recipe.py`): a JSON API that+ returns a relative path (gov.uk's `/contact-hmrc`) is joined to the canonical+ absolute URL. Needed because the URL-template helper %-quotes slashes and so+ can't path-join.+- **`SUPER_SEARCH_FORCE_INCLUDE`** setting + pinning in `select_sources` (minimal+ selection wiring; the bandit stays dormant). Defaults to `[]` — **off**.+- `scripts/super_search_coverage.py recall --source X` — per-source exact-URL recall.+- `scripts/super_search_new_sources_eval.py` — NDCG over the in-coverage subset.+- `evaluate_super_search._collect_docs` now takes a `selection_key` so the doc-pool+ cache never mixes source configurations; `compare_search_modes` is 3-way + `--clear-cache`.++## Source recall (does the source return the *exact* gold URL?)++The NDCG harness matches URLs by exact string, so this is the load-bearing metric.++| source | exact-URL recall | near-match (host+path) |+|---|---|---|+| gov.uk | **58%** | 58% (URLs already canonical) |+| imdb | **42%** | **67%** |++imdb's 25-pt exact/near gap is entirely `m.imdb.com` (34% of imdb gold) vs our+`www.imdb.com` (66%) — we emit the majority form; one string can't match both.++Many other high-value domains are **IP-blocked (HTTP 403)** from a datacenter:+reddit (also needs OAuth now), merriam-webster, britannica, mayoclinic. Cambridge+and Cleveland Clinic are reachable but were not added in this pass.++## End-to-end NDCG (in-coverage test subset, gov.uk+imdb force-included)++`scripts/super_search_new_sources_eval.py` — only the test queries whose gold+results include a URL on a new source's domain (1,313 such queries), where+selection can actually change the ranking.++| arm | NDCG (n=50) | NDCG (n=150) |+|---|---|---|+| standard search | 0.516 | 0.515 |+| Super Search baseline | 0.463 | 0.485 |+| **Super Search + new sources** | **0.477** | **0.488** |+| Δ (new − baseline) | +0.014 | **+0.003** |+| queries better / worse | 7 / 6 | **16 / 31** |++## Conclusion++**Adding good sources nets ≈ 0 on NDCG, and Super Search still trails plain+standard search (0.488 vs 0.515) even on the queries where the new domains are+relevant.**++The mechanism works in isolation — the new sources produce large, real individual+wins (gov.uk takes `inheritance tax threshold` and `login universal credit` to+NDCG 1.0; imdb lifts `stealing paradise` +0.63), proving the chain+source → fetch exact gold URL → survive LTR → top-10. But at n=150 those wins are+**outnumbered ~2:1 by regressions** (16 vs 31).++Critically, the 31 regressions are on queries where the new domain *is* relevant —+so they are **not** caused by off-topic sources. They are the **LTR re-ranker+mis-ranking the enlarged document pool**: it promotes a new-source doc that isn't+the gold answer above a previously-better result.++So the bottleneck is **the re-ranker over the heterogeneous Super Search pool**+(external results + crawled pages + link-followed pages) — not source availability+and not source selection. That re-ranker is also why Super Search (0.49) trails+standard search (0.52) overall.++## Recommendations++1. **Do not ship `SUPER_SEARCH_FORCE_INCLUDE`** (force-including is net-harmful).+ It defaults to `[]`, so production behaviour is unchanged. The gov.uk/imdb+ adapters are sound and remain available for when the ranker improves.+2. **Next lever: the LTR re-ranker.** Retrain / filter it on the heterogeneous+ Super Search document pool against gold, where the 0.49-vs-0.52 gap lives.+ Adding sources without fixing the ranker does not pay off.++## Reproducing the results++**Prerequisites**+- Gold dataset present at `devdata/rankeval-2026-04/remote-datasets/rankings-{train,test}.csv`+ (rebuild with `uv run python -m mwmbl.rankeval.dataset.extension_dataset` if missing).+- Local mwmbl index at `devdata/index-v2.tinysearch` (the standard-search arm uses it).+- Network access — the sources are live APIs — and Redis (the cosine selection path).+- Every command is prefixed with the env both scripts/harnesses expect:+ `DATABASE_URL="postgres://daoud@" DJANGO_SETTINGS_MODULE=mwmbl.settings_dev`.++Let `E=DATABASE_URL="postgres://daoud@" DJANGO_SETTINGS_MODULE=mwmbl.settings_dev` below.++**1. Gold-coverage gate (the ~0.36% mass ceiling that killed source selection)**+```+$E uv run python scripts/super_search_coverage.py # report (default)+```++**2. Missing-domain ranking (the addressable upside that motivated adding sources)**+```+$E uv run python scripts/super_search_coverage.py missing --top 45+```+NB: the "Where the gold relevance lives" figures (top-10 = 26.6%, current sources ≈ 1%)+were measured *before* gov.uk/imdb were added. Re-running now drops those two from the+list and raises the already-a-source share to ~4.4% (top-10 → ~24%). To get the exact+pre-addition numbers, run this against the parent commit (`git stash` / checkout `HEAD~1`).++**3. Per-source exact-URL recall against gold (the load-bearing match metric)**+```+$E uv run python scripts/super_search_coverage.py recall --source www_gov_uk --max-queries 60+$E uv run python scripts/super_search_coverage.py recall --source imdb --max-queries 60+```++**4. End-to-end NDCG on the in-coverage subset (the headline table) — the result to reproduce**+```+$E uv run python scripts/super_search_new_sources_eval.py --max-queries 50 # faster read+$E uv run python scripts/super_search_new_sources_eval.py --max-queries 150 # ~25-40 min+```+Each invocation force-includes `www_gov_uk`+`imdb` internally and prints a `mean NDCG`+block for the three arms (`standard`, `ss-baseline`, `ss+new`) plus the per-query+better/worse breakdown. The headline table is those two runs side by side — the+`--max-queries 50` run is the n=50 column, `--max-queries 150` the n=150 column:++| arm | NDCG (n=50) | NDCG (n=150) |+|---|---|---|+| standard search | 0.516 | 0.515 |+| Super Search baseline | 0.463 | 0.485 |+| **Super Search + new sources** | **0.477** | **0.488** |+| Δ (new − baseline) | +0.014 | +0.003 |+| queries better / worse | 7 / 6 | 16 / 31 |++Slow because it runs the full Super Search pipeline (live source fan-out + crawl ++link-follow) per query. Absolute numbers drift run-to-run (live APIs, crawl variability);+the query *sample* is seeded (`default_rng(0)`) so the same queries are scored each time,+and the signal to trust is the paired `ss+new − ss-baseline` delta and the better/worse count.++**5. Full-sample 3-way comparison (slower, and too diluted to show the effect — for context)**+```+$E uv run python -m mwmbl.rankeval.evaluation.compare_search_modes --fraction 0.03 --clear-cache+```++**Unit tests for the new code**+```+$E uv run pytest test/test_super_search_sources.py test/test_super_search_recipes.py \+ test/test_super_search_select.py -q+```++**Caveats** — absolute NDCG and recall drift run-to-run (live APIs, crawl variability,+Wikipedia availability); trust the *paired* deltas, not absolute values. The recall+sampler and the in-coverage eval subset are both seeded (`Random(0)` / `default_rng(0)`),+so the *query selection* is reproducible; the fetched results are not. The `--clear-cache`+flag in step 5 matters: the doc-pool cache is keyed by query + selection set, so stale+pools must be cleared when source adapters or the force-include set change.diff --git a/mwmbl/rankeval/SUPER_SEARCH_EVAL_FINDINGS.md b/mwmbl/rankeval/SUPER_SEARCH_EVAL_FINDINGS.mdnew file mode 100644index 0000000..5ff9241--- /dev/null+++ b/mwmbl/rankeval/SUPER_SEARCH_EVAL_FINDINGS.md@@ -0,0 +1,78 @@+# Super Search v2 evaluation — findings & handoff++## Goal+Evaluate Super Search v2 vs standard search on a current dataset, starting with the+cosine baseline. This grew into: rebuilding the eval dataset, fixing eval infra,+retraining the LTR model, and a deep investigation of why cosine source selection+underperforms.++Branch: `super-search-2` (all work below committed & pushed).++## Headline findings+1. **Standard search vs Super Search v2 (cosine), 298 test queries, same index:**+ NDCG **0.319 vs 0.293** — Super Search does *not* beat standard search and is+ ~11× slower. (Both use the same local mwmbl index + retrained LTR + MMR + wiki;+ the comparison isolates what Super Search's extra sources/crawl add.)+2. **Why: cosine source selection ≈ random.** Offline source-selection eval (500+ queries × 132 sources): coverage@10 — random 0.44, **cosine 0.45**, popularity+ 0.58, **XGBoost (learned) 0.64**, oracle 1.0. Online captured reward — cosine+ 0.43, **Thompson-sampling bandit (nu=0.25) 0.80**, oracle 0.99.+3. **A learned/coverage-based policy wins big over cosine** (≈+86% captured reward).+ `popularity` is the dominant feature; cosine features are useless-to-harmful.+4. **But the bandit is contextual-in-form, ~static-in-practice:** a fixed "best-10+ sources every query" list already captures 0.769 vs the bandit's 0.802 — context+ adds only +0.03, because the only predictive features are source-static. Reward is+ concentrated (top-10 generalist sources = 77.6% of all reward).+5. **Three query×source "topical match" features all fail** (corr ≈ 0, too sparse):+ cosine, query↔domain-name overlap (fires 0.1% of cells), mwmbl-index domain hits+ (local & remote, <1%). Source contribution is coverage-driven, not topical. The+ high-reward generalists never lexically match the query. (Feature B is precise when+ it fires — 4× reward on 13 hits — so it could be a cheap *rule*: query contains a+ source's domain token ⇒ force-include that source.)+6. **Wikipedia in eval was silently failing** (HTTP 429 under burst) — fixed with a+ retry adapter; ~36% of queries had been dropping their wiki results.+7. **LTR retrain on the new dataset beats the old model** end-to-end: test NDCG+ 0.206 → 0.253 (~+23%). New model committed as production `model.xgb`.++## Commits this session (origin/main..HEAD on `super-search-2`)+- `7eb13db` — Backblaze dataset puller in `extension_dataset.py` (+`--no-download`),+ removed dead Bing pipeline, added `mwmbl/rankeval/README.md`; regenerated gold CSVs+ from full extension-scrape history (2025-07-15→2026-06-24, 7297 train/5969 test q).+- `1b11fbe` — `evaluate_super_search.py`: Super Search pipeline as a `RankingModel`.+- `f51dc41` — cache the Super Search doc-pool (joblib, `devdata/super-search-eval-cache`)+ so ranking iterations re-run free; + `compare_ltr_models.py`.+- `c358ac2` — retrained Rust XGB model + regenerated `learning-to-rank.csv.gz`+ (previous model backed up at `devdata/rankeval-2026-04/model-current.xgb`).+- `397797f` — Wikipedia search API retry on 429 (`rank.py`, `WIKI_RETRY`).+- `8c1b351` — `compare_search_modes.py` (standard vs Super Search).++## Harnesses / how to re-run+All under `mwmbl/rankeval/evaluation/`, run with:+`DATABASE_URL="postgres://daoud@" DJANGO_SETTINGS_MODULE=mwmbl.settings_dev uv run python -m mwmbl.rankeval.evaluation.<name> ...`+- `compare_search_modes --fraction 0.05` — standard vs Super Search.+- `compare_ltr_models --model a=PATH --model b=PATH --fraction 0.1` — two LTR models.+- `evaluate_super_search --fraction 0.05` — Super Search alone (cached doc-pool).+- `scripts/super_search_eval.py build-matrix|select|simulate` — source-selection eval+ (reward-matrix tooling; `super_search_select/evaluation.py` has `coverage_at_k`,+ `simulate_baselines`, `sweep_explore_scale`).+- Dataset refresh: `python -m mwmbl.rankeval.dataset.extension_dataset` (needs+ `MWMBL_KEY_ID`/`MWMBL_APPLICATION_KEY` in `.env`).+- The 500-query reward matrix used above is saved (untracked) at+ `devdata/ss_eval_matrix.{npz,json}` — load with+ `RewardMatrix.load("devdata/ss_eval_matrix")` (from+ `super_search_select/evaluation.py`). To rebuild from scratch: `build-matrix`+ (~20 min; ArXiv 429s are harmless).++## Open decision for next session+Pick the direction for Super Search source selection:+- **(a) Ship the coverage-based win now** — flip the bandit on+ (`SUPER_SEARCH_USE_BANDIT=True`, `SUPER_SEARCH_TS_EXPLORE_SCALE=0.25` in+ `settings_common.py`), or replace it with a simpler non-contextual "rank sources by+ learned contribution" (captures ~96% of the bandit, far less machinery). Optionally+ add the high-precision domain-token force-include rule.+- **(b) Invest in real contextual features** (higher effort) — query-intent →+ per-source `field` affinity, or historical per-source contribution by query class.+ The three obvious topical-match features are confirmed dead ends.++Caveat on (a): the online bandit cold-starts and learns over live traffic; it won't+jump to 0.80 instantly, but will quickly leave the near-random cosine baseline behind.diff --git a/mwmbl/rankeval/evaluation/compare_search_modes.py b/mwmbl/rankeval/evaluation/compare_search_modes.pyindex b422b6f..914c2e3 100644--- a/mwmbl/rankeval/evaluation/compare_search_modes.py+++ b/mwmbl/rankeval/evaluation/compare_search_modes.py@@ -26,12 +26,19 @@ import numpy as npos.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")django.setup()+from django.conf import settings # noqa: E402+import mwmbl.rankeval.evaluation.evaluate as evaluate_module # noqa: E402+import mwmbl.rankeval.evaluation.evaluate_super_search as ss_module # noqa: E402from mwmbl.rankeval.evaluation.evaluate import evaluate # noqa: E402from mwmbl.rankeval.evaluation.evaluate_ranker import MwmblRankingModel # noqa: E402from mwmbl.rankeval.evaluation.evaluate_super_search import SuperSearchRankingModel # noqa: E402from mwmbl.search_setup import ranker # noqa: E402 (local mwmbl index + LTR + MMR + wiki)+# High-value sources added from the gold-mass analysis; force-included so the+# content-blind selector actually queries them (see SUPER_SEARCH_FORCE_INCLUDE).+NEW_SOURCES = ["www_gov_uk", "imdb"]+def run():parser = ArgumentParser()@@ -39,17 +46,31 @@ def run():help="Fraction of gold test queries to sample.")parser.add_argument("--train", action="store_true",help="Evaluate on the train split instead of test.")+ parser.add_argument("--clear-cache", action="store_true",+ help="Clear the Super Search doc-pool cache before evaluating.")args = parser.parse_args()+ if args.clear_cache:+ ss_module.memory.clear(warn=False)++ # Each Super Search arm sets the force-include list and a matching cache key so+ # the doc-pool cache (keyed by query + selection_key) never mixes source sets.+ def ss_arm(force):+ settings.SUPER_SEARCH_FORCE_INCLUDE = force+ return SuperSearchRankingModel(selection_key="+".join(force))+models = [- ("standard search (local index + wiki)", MwmblRankingModel(ranker)),- ("super search v2 (cosine baseline)", SuperSearchRankingModel()),+ ("standard search (local index + wiki)", lambda: MwmblRankingModel(ranker)),+ ("super search v2 (cosine baseline, no new sources)", lambda: ss_arm([])),+ ("super search + new sources (gov.uk, imdb)", lambda: ss_arm(NEW_SOURCES)),]- for label, model in models:+ for label, make_model in models:print(f"\n{'=' * 70}\nEvaluating {label}\n{'=' * 70}")- # Reseed so both modes are scored on the same sampled query subset.+ model = make_model() # sets force-include for this arm before evaluating+ # Reseed so every mode is scored on the same sampled query subset.evaluate_module.random = np.random.default_rng(42)evaluate(model, fraction=args.fraction, use_test=not args.train)+ settings.SUPER_SEARCH_FORCE_INCLUDE = []if __name__ == "__main__":diff --git a/mwmbl/rankeval/evaluation/evaluate_super_search.py b/mwmbl/rankeval/evaluation/evaluate_super_search.pyindex 4222a0a..bd6d400 100644--- a/mwmbl/rankeval/evaluation/evaluate_super_search.py+++ b/mwmbl/rankeval/evaluation/evaluate_super_search.py@@ -81,8 +81,14 @@ async def _collect(query: str) -> list[Document]:@memory.cache-def _collect_docs(query: str) -> list[dict]:- """Cached: the collected document pool for a query, as plain dicts."""+def _collect_docs(query: str, selection_key: str = "") -> list[dict]:+ """Cached: the collected document pool for a query, as plain dicts.++ ``selection_key`` is part of the cache key only: the collected pool depends on+ which sources are queried (source selection is read from settings at call+ time), so callers that change selection — e.g. force-including extra sources —+ must pass a distinct key to avoid colliding with another config's cached pool.+ """return [_doc_to_dict(d) for d in asyncio.run(_collect(query))]@@ -95,8 +101,13 @@ async def _rank(query: str, docs: list[Document]) -> list[str]:class SuperSearchRankingModel(RankingModel):+ def __init__(self, selection_key: str = ""):+ # Distinguishes cached doc pools when source selection differs between runs+ # (e.g. force-including extra sources). Set settings to match before use.+ self.selection_key = selection_key+def predict(self, query: str) -> list[str]:- docs = [_dict_to_doc(d) for d in _collect_docs(query)]+ docs = [_dict_to_doc(d) for d in _collect_docs(query, self.selection_key)]return asyncio.run(_rank(query, docs))diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex ecebe7d..208334f 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -297,3 +297,4 @@ SUPER_SEARCH_TS_PRIOR_PRECISION = 1.0 # ridge prior precision (lambda); A0 = laSUPER_SEARCH_TS_NOISE_VARIANCE = 0.25 # reward noise variance (sigma^2); reward in [0,1]SUPER_SEARCH_QVEC_CACHE_TTL = 3600 # seconds to cache a query's projected vectorsSUPER_SEARCH_USE_BANDIT = False # False = cosine-top-10 baseline; True = Thompson sampling+SUPER_SEARCH_FORCE_INCLUDE = [] # source names always queried (high-value sources), like always_ondiff --git a/mwmbl/tinysearchengine/super_search_select/policy.py b/mwmbl/tinysearchengine/super_search_select/policy.pyindex 83f99cf..9a42923 100644--- a/mwmbl/tinysearchengine/super_search_select/policy.py+++ b/mwmbl/tinysearchengine/super_search_select/policy.py@@ -49,11 +49,16 @@ def select_sources(_record_features(ctx, query, source_names)return list(source_names)- always_on = [n for n in source_names if get_meta(n).always_on]- selectable = [n for n in source_names if n not in set(always_on)]- budget = max(k - len(always_on), 0)+ # Pinned sources are always queried: the global always-on sources plus any+ # high-value sources named in SUPER_SEARCH_FORCE_INCLUDE (the offline-chosen+ # sources that carry real gold relevance but a content-blind policy would skip).+ force_include = getattr(settings, "SUPER_SEARCH_FORCE_INCLUDE", []) or []+ pinned = [n for n in source_names if get_meta(n).always_on]+ pinned += [n for n in source_names if n in force_include and n not in pinned]+ selectable = [n for n in source_names if n not in set(pinned)]+ budget = max(k - len(pinned), 0)if budget == 0:- chosen = always_on[:k]+ chosen = pinned[:k]if ctx is not None:_record_features(ctx, query, chosen)return chosen@@ -69,16 +74,16 @@ def select_sources(chosen = _select_cosine(qctx, selectable, profs, budget)if ctx is not None:- for name in always_on + chosen:+ for name in pinned + chosen:if name in feats:ctx.features[name] = feats[name].tolist()elif name not in ctx.features:- # always-on sources weren't scored; compute their features too.+ # pinned sources weren't scored; compute their features too.ctx.features[name] = feature_vector(qctx, get_meta(name), profs.get(name, (None, None))).tolist()- return always_on + chosen+ return pinned + chosendef _select_cosine(qctx, selectable, profs, budget) -> list[str]:diff --git a/mwmbl/tinysearchengine/super_search_select/registry.py b/mwmbl/tinysearchengine/super_search_select/registry.pyindex c3320a4..31983c2 100644--- a/mwmbl/tinysearchengine/super_search_select/registry.py+++ b/mwmbl/tinysearchengine/super_search_select/registry.py@@ -47,6 +47,7 @@ _STATIC_META: dict[str, SiteMeta] = {"stackexchange": SiteMeta("stackexchange", "stackoverflow.com", "programming", 1.0, 1.0),"arxiv": SiteMeta("arxiv", "arxiv.org", "academia", 1.0, 1.0),"pypi": SiteMeta("pypi", "pypi.org", "programming", 0.6, 0.6),+ "imdb": SiteMeta("imdb", "www.imdb.com", "media", 1.0, 1.0),}diff --git a/mwmbl/tinysearchengine/super_search_sources/__init__.py b/mwmbl/tinysearchengine/super_search_sources/__init__.pyindex 763019d..eb877e4 100644--- a/mwmbl/tinysearchengine/super_search_sources/__init__.py+++ b/mwmbl/tinysearchengine/super_search_sources/__init__.py@@ -8,6 +8,7 @@ orchestrator.from mwmbl.tinysearchengine.super_search_sources.arxiv import search as search_arxivfrom mwmbl.tinysearchengine.super_search_sources.github import search as search_githubfrom mwmbl.tinysearchengine.super_search_sources.hn import search as search_hn+from mwmbl.tinysearchengine.super_search_sources.imdb import search as search_imdbfrom mwmbl.tinysearchengine.super_search_sources.mwmbl_index import search as search_mwmblfrom mwmbl.tinysearchengine.super_search_sources.pypi import search as search_pypifrom mwmbl.tinysearchengine.super_search_sources.recipe import load_recipes, make_recipe_source@@ -20,6 +21,7 @@ SOURCES = {"stackexchange": search_stackexchange,"arxiv": search_arxiv,"pypi": search_pypi,+ "imdb": search_imdb,}# Declarative YAML recipes (recipes/*.yaml) are loaded at import time and addeddiff --git a/mwmbl/tinysearchengine/super_search_sources/imdb.py b/mwmbl/tinysearchengine/super_search_sources/imdb.pynew file mode 100644index 0000000..186aeaa--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/imdb.py@@ -0,0 +1,55 @@+"""IMDb title/name lookup via the public autosuggest API.++IMDb has no open full-text search API, but the autosuggest endpoint that powers+the site's search box returns titles and people ranked by relevance, each with a+stable id (``tt…`` for titles, ``nm…`` for names) that maps to the canonical+``/title/`` or ``/name/`` page. We emit the ``www.imdb.com`` form with a trailing+slash, which is how the gold dataset records the majority of IMDb URLs.++The query goes in the URL path (not a query-string param), so this can't be a+declarative recipe; the path is bucketed by the query's first alphanumeric char,+as the endpoint expects.+"""+import logging+from urllib.parse import quote++import httpx++from mwmbl.tinysearchengine.indexer import Document++logger = logging.getLogger(__name__)++SUGGEST_URL = "https://v3.sg.media-imdb.com/suggestion/{bucket}/{query}.json"+++def _url_for(item_id: str) -> str:+ if item_id.startswith("tt"):+ return f"https://www.imdb.com/title/{item_id}/"+ if item_id.startswith("nm"):+ return f"https://www.imdb.com/name/{item_id}/"+ return ""+++async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Document]:+ q = query.strip()+ if not q:+ return []+ bucket = next((c for c in q.lower() if c.isalnum()), "x")+ url = SUGGEST_URL.format(bucket=bucket, query=quote(q, safe=""))+ try:+ response = await client.get(url)+ response.raise_for_status()+ payload = response.json()+ except (httpx.HTTPError, ValueError) as e:+ logger.info("IMDb source failed: %s", e)+ return []++ docs: list[Document] = []+ for item in payload.get("d", [])[:limit]:+ target = _url_for(item.get("id", ""))+ if not target:+ continue+ # 'l' is the title/name; 's' the cast/role blurb; 'q' the kind (feature, TV series…).+ extract = item.get("s") or item.get("q") or ""+ docs.append(Document(title=item.get("l", ""), url=target, extract=extract))+ return docsdiff --git a/mwmbl/tinysearchengine/super_search_sources/recipe.py b/mwmbl/tinysearchengine/super_search_sources/recipe.pyindex 4ae53bb..8b43cc3 100644--- a/mwmbl/tinysearchengine/super_search_sources/recipe.py+++ b/mwmbl/tinysearchengine/super_search_sources/recipe.py@@ -197,6 +197,7 @@ def _parse_json(payload, spec: dict) -> list[Document]:items = _walk(payload, spec.get("results", "")) or []fields = spec["fields"]strip = set(spec.get("strip_html", []))+ base_url = spec.get("base_url", "")docs: list[Document] = []for item in items:if not isinstance(item, dict):@@ -206,20 +207,24 @@ def _parse_json(payload, spec: dict) -> list[Document]:for name, field_spec in fields.items()if name != "url" and isinstance(field_spec, str)}- doc = _make_doc(values, _resolve_url_json(fields.get("url"), item, values))+ doc = _make_doc(values, _resolve_url_json(fields.get("url"), item, values, base_url))if doc is not None:docs.append(doc)return docs-def _resolve_url_json(url_spec, item: dict, values: dict) -> str:+def _resolve_url_json(url_spec, item: dict, values: dict, base_url: str = "") -> str:+ # A JSON API often returns a relative path (e.g. gov.uk's "/contact-hmrc"); join+ # it onto ``base_url`` to produce the canonical absolute URL, mirroring HTML.if url_spec is None:return ""if isinstance(url_spec, str):- return _coerce_str(_walk(item, url_spec))- if isinstance(url_spec, dict) and "template" in url_spec:- return _fill_template(url_spec["template"], {**item, **values})- return ""+ url = _coerce_str(_walk(item, url_spec))+ elif isinstance(url_spec, dict) and "template" in url_spec:+ url = _fill_template(url_spec["template"], {**item, **values})+ else:+ return ""+ return urljoin(base_url, url) if (url and base_url) else url# ---------------------------------------------------------------------------diff --git a/mwmbl/tinysearchengine/super_search_sources/recipes/www_gov_uk.yaml b/mwmbl/tinysearchengine/super_search_sources/recipes/www_gov_uk.yamlnew file mode 100644index 0000000..6263f0f--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/recipes/www_gov_uk.yaml@@ -0,0 +1,22 @@+# GOV.UK via its public search API. Results carry a site-relative ``link``+# (e.g. "/contact-hmrc"); base_url joins it to the canonical absolute URL that+# the gold dataset records (https://www.gov.uk/contact-hmrc).+name: www_gov_uk+domain: www.gov.uk+field: law-government+request:+ url: https://www.gov.uk/api/search.json+ params:+ q: "{query}"+ count: "{limit}"+response:+ format: json+ base_url: https://www.gov.uk+ results: results+ fields:+ title: title+ extract: description+ url: link+smoke:+ query: vat rates+ expect_title_contains: VATdiff --git a/scripts/super_search_coverage.py b/scripts/super_search_coverage.pynew file mode 100644index 0000000..733e12e--- /dev/null+++ b/scripts/super_search_coverage.py@@ -0,0 +1,384 @@+#!/usr/bin/env python3+"""Phase 1 feasibility gate for offline gold-grounded Super Search source selection.++Measures how much the rankeval *gold* dataset overlaps our Super Search source+domains. Source selection can only move NDCG on queries where a gold URL lives on+one of our source domains, so this script quantifies that ceiling before we build+the gold-grounded reward matrix / selector.++For every gold URL we match its host against the ~130 registered source domains+under two normalizations:++ * exact host - the host string equals a source domain. This is the only kind+ of match that can actually score in the NDCG harness, which+ compares URLs by exact string (evaluate.py: ``scores.get(url)``).+ * registrable - strip ``www.``/``m.`` and compare registrable domains. An upper+ bound on recoverable coverage if we fixed URL normalization+ (over-counts sibling subdomains, e.g. support. vs developer.).++Run:+ DATABASE_URL="postgres://daoud@" DJANGO_SETTINGS_MODULE=mwmbl.settings_dev \+ uv run python scripts/super_search_coverage.py+"""+import argparse+import os+import sys+from collections import Counter, defaultdict+from pathlib import Path+from urllib.parse import urlparse++import django+import pandas as pd++REPO_ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO_ROOT))+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")+django.setup()++from mwmbl.rankeval.evaluation.evaluate import CLICK_PROPORTIONS, NUM_RESULTS_FOR_EVAL # noqa: E402+from mwmbl.rankeval.paths import ( # noqa: E402+ RANKINGS_DATASET_TEST_PATH,+ RANKINGS_DATASET_TRAIN_PATH,+)+from mwmbl.tinysearchengine.super_search_select.features import ( # noqa: E402+ INTENT_NAMES,+ classify_intent,+)+from mwmbl.tinysearchengine.super_search_select.registry import get_registry # noqa: E402++# Common multi-label public suffixes so registrable-domain folding doesn't collapse+# e.g. bbc.co.uk -> co.uk. Not exhaustive (no full public-suffix list), but covers+# the suffixes that actually appear in the gold set / source shortlist.+_MULTI_SUFFIXES = {+ "co.uk", "org.uk", "ac.uk", "gov.uk", "me.uk", "ltd.uk", "plc.uk",+ "com.au", "net.au", "org.au", "edu.au", "gov.au",+ "co.nz", "co.za", "co.in", "co.jp", "co.kr", "com.br", "com.mx",+ "com.cn", "com.tr", "com.sg", "com.hk", "or.jp", "ne.jp",+}+++def host_of(url: str) -> str:+ """Lowercase host of a URL, sans userinfo and port. ``""`` if unparseable."""+ try:+ netloc = urlparse(str(url)).netloc.lower()+ except ValueError:+ return ""+ return netloc.split("@")[-1].split(":")[0]+++def _strip_www(host: str) -> str:+ for prefix in ("www.", "m."):+ if host.startswith(prefix):+ return host[len(prefix):]+ return host+++def registrable(host: str) -> str:+ """Registrable domain: strip ``www.``/``m.`` then take the last 2 labels (3 for+ known multi-label suffixes like ``co.uk``)."""+ host = _strip_www(host)+ labels = host.split(".")+ if len(labels) <= 2:+ return host+ if ".".join(labels[-2:]) in _MULTI_SUFFIXES:+ return ".".join(labels[-3:])+ return ".".join(labels[-2:])+++def load_gold() -> pd.DataFrame:+ frames = []+ for split, path in (("train", RANKINGS_DATASET_TRAIN_PATH),+ ("test", RANKINGS_DATASET_TEST_PATH)):+ df = pd.read_csv(path)+ df["split"] = split+ frames.append(df)+ return pd.concat(frames, ignore_index=True)+++def click_weight(rank) -> float:+ """Gold relevance mass of a row by its 1-based rank (0 beyond the top-10)."""+ try:+ r = int(rank)+ except (TypeError, ValueError):+ return 0.0+ return CLICK_PROPORTIONS[r - 1] if 1 <= r <= NUM_RESULTS_FOR_EVAL else 0.0+++def cmd_report():+ registry = get_registry()+ # source domain (lowercased) -> source names; same keyed by registrable domain.+ exact_map: dict[str, list[str]] = defaultdict(list)+ reg_map: dict[str, list[str]] = defaultdict(list)+ field_of: dict[str, str] = {}+ for name, meta in registry.items():+ domain = meta.domain.lower()+ exact_map[domain].append(name)+ reg_map[registrable(domain)].append(name)+ field_of[name] = meta.field++ gold = load_gold()+ n_rows = len(gold)+ queries = gold["query"].unique()+ n_queries = len(queries)++ # Per-query matched source-name sets, under each normalization.+ q_exact: dict[str, set[str]] = defaultdict(set)+ q_reg: dict[str, set[str]] = defaultdict(set)+ exact_rows = reg_rows = 0+ exact_mass = total_mass = 0.0+ rank_hist_exact: Counter = Counter() # rank -> hit count (exact)+ source_queries_exact: dict[str, set[str]] = defaultdict(set)+ source_queries_reg: dict[str, set[str]] = defaultdict(set)++ for query, url, rank in zip(gold["query"], gold["url"], gold["rank"]):+ w = click_weight(rank)+ total_mass += w+ host = host_of(url)+ if not host:+ continue+ ex = exact_map.get(host)+ rg = reg_map.get(registrable(host))+ if ex:+ exact_rows += 1+ exact_mass += w+ try:+ rank_hist_exact[int(rank)] += 1+ except (TypeError, ValueError):+ pass+ for name in ex:+ q_exact[query].add(name)+ source_queries_exact[name].add(query)+ if rg:+ reg_rows += 1+ for name in rg:+ q_reg[query].add(name)+ source_queries_reg[name].add(query)++ n_q_exact = len(q_exact)+ n_q_reg = len(q_reg)++ def pct(num, den):+ return f"{100.0 * num / den:.2f}%" if den else "n/a"++ print("=" * 72)+ print("Super Search gold-coverage feasibility gate")+ print("=" * 72)+ print(f"Sources registered: {len(registry)}")+ print(f"Distinct source domains: {len(exact_map)} exact / {len(reg_map)} registrable")+ print(f"Gold rows (train+test): {n_rows}")+ print(f"Gold queries: {n_queries}")+ print()+ print("Row-level overlap (a gold URL on a source domain):")+ print(f" exact host: {exact_rows:>6} rows ({pct(exact_rows, n_rows)})")+ print(f" registrable: {reg_rows:>6} rows ({pct(reg_rows, n_rows)})")+ print()+ print("Query-level coverage (>=1 gold URL on a source domain) <-- the ceiling:")+ print(f" exact host: {n_q_exact:>6} queries ({pct(n_q_exact, n_queries)})")+ print(f" registrable: {n_q_reg:>6} queries ({pct(n_q_reg, n_queries)})")+ print()+ print("Gold relevance mass (click-weighted, top-10 only) on source domains:")+ print(f" exact host: {exact_mass:.1f} / {total_mass:.1f} ({pct(exact_mass, total_mass)})")+ print()++ print("-" * 72)+ print("Per-source covered queries (exact host; registrable in parens):")+ print("-" * 72)+ ranked = sorted(source_queries_exact.items(), key=lambda kv: -len(kv[1]))+ # include reg-only sources (matched under registrable but never exact) at the tail+ reg_only = [n for n in source_queries_reg if n not in source_queries_exact]+ for name in reg_only:+ ranked.append((name, set()))+ for name, qs in ranked:+ reg_n = len(source_queries_reg.get(name, set()))+ domain = registry[name].domain if name in registry else name+ print(f" {name:24} {domain:28} {len(qs):>4} ({reg_n:>4})")+ print()++ print("-" * 72)+ print("Gold-rank distribution of exact-host hits (where the source URL ranks):")+ print("-" * 72)+ buckets = {"rank 1-3": 0, "rank 4-10": 0, "rank 11+": 0}+ for rank, count in rank_hist_exact.items():+ if 1 <= rank <= 3:+ buckets["rank 1-3"] += count+ elif 4 <= rank <= 10:+ buckets["rank 4-10"] += count+ else:+ buckets["rank 11+"] += count+ for label, count in buckets.items():+ print(f" {label:12} {count:>6} ({pct(count, exact_rows)})")+ print()++ print("-" * 72)+ print("Stratification by source field (exact-host covered query-field pairs):")+ print("-" * 72)+ field_cov: Counter = Counter()+ for query, names in q_exact.items():+ for field in {field_of.get(n, "other") for n in names}:+ field_cov[field] += 1+ for field, count in field_cov.most_common():+ print(f" {field:24} {count:>5} queries")+ print()++ print("-" * 72)+ print("Stratification by query intent (coverage rate among queries of that intent):")+ print("-" * 72)+ intent_total: Counter = Counter()+ intent_covered: Counter = Counter()+ covered_queries = set(q_exact)+ for query in queries:+ intents = classify_intent(query)+ for name, flag in zip(INTENT_NAMES, intents):+ if flag:+ intent_total[name] += 1+ if query in covered_queries:+ intent_covered[name] += 1+ for name in INTENT_NAMES:+ tot = intent_total[name]+ cov = intent_covered[name]+ print(f" {name:12} {cov:>5}/{tot:<6} covered ({pct(cov, tot)})")+ print()+ print("=" * 72)+ print("GATE: query-level coverage is the hard ceiling on how many queries source")+ print("selection can affect. If even the registrable number stays in low single")+ print("digits, prefer a static best-sources list over a learned per-query model.")+ print("=" * 72)+++def _norm(url: str) -> tuple[str, str]:+ """Registrable-host + path (trailing slash / query stripped) for near-match."""+ return registrable(host_of(url)), urlparse(str(url)).path.rstrip("/")+++def cmd_recall(source: str, per_source_limit: int, max_queries: int):+ """For one source, measure how many of the gold URLs on its domain it actually+ returns. exact-URL recall is what scores in NDCG (evaluate.py exact match);+ near-match recall (host+path, ignoring www/m/trailing-slash/query) shows whether+ a URL-format fix would recover the rest."""+ import asyncio++ import httpx+ from django.conf import settings++ from mwmbl.tinysearchengine.super_search_select.registry import get_meta+ from mwmbl.tinysearchengine.super_search_sources import SOURCES++ if source not in SOURCES:+ print(f"unknown source {source!r}. Known (sample): {sorted(SOURCES)[:8]}...")+ return+ dom = registrable(get_meta(source).domain.lower())+ gold = load_gold()+ targets: dict[str, set[str]] = defaultdict(set)+ for query, url in zip(gold["query"], gold["url"]):+ if registrable(host_of(str(url))) == dom:+ targets[query].add(str(url))+ qs = list(targets)+ print(f"source {source!r} (registrable domain {dom}): {len(qs)} gold queries touch it")+ if max_queries and len(qs) > max_queries:+ import random as _random+ _random.Random(0).shuffle(qs)+ qs = qs[:max_queries]+ print(f"sampling {len(qs)} of them")++ fn = SOURCES[source]+ timeout = max(float(settings.SUPER_SEARCH_PER_SOURCE_TIMEOUT), 10.0)++ async def run() -> dict[str, list[str]]:+ async with httpx.AsyncClient(follow_redirects=True, timeout=timeout,+ headers={"User-Agent": "mwmbl-super-search-eval/0.1"}) as client:+ out: dict[str, list[str]] = {}+ for q in qs:+ try:+ docs = await fn(client, q, per_source_limit)+ except Exception:+ docs = []+ out[q] = [d.url for d in docs if d.url]+ return out++ returned = asyncio.run(run())+ exact = near = empty = 0+ misses = []+ for q in qs:+ tgt = targets[q]+ ret = returned.get(q, [])+ if not ret:+ empty += 1+ rset, rnorm = set(ret), {_norm(u) for u in ret}+ ex = any(t in rset for t in tgt)+ nr = any(_norm(t) in rnorm for t in tgt)+ exact += ex+ near += nr+ if not ex and len(misses) < 10:+ misses.append((q, sorted(tgt)[0], ret[:2]))+ n = len(qs) or 1+ print(f"\nexact-URL recall: {exact}/{len(qs)} ({100*exact/n:.1f}%)")+ print(f"near-match recall (host+path): {near}/{len(qs)} ({100*near/n:.1f}%)")+ print(f"queries where source returned nothing: {empty}/{len(qs)}")+ print("\nmisses (gold target vs our top returns):")+ for q, t, ret in misses:+ print(f" q={q!r}\n gold: {t}\n ours: {ret}")+++def cmd_missing(top: int):+ """Rank gold domains we do NOT have as a source by click-weighted gold mass —+ i.e. the addressable upside from adding new sources."""+ ours = {registrable(m.domain.lower()) for m in get_registry().values()}+ gold = load_gold()+ mass: dict[str, float] = defaultdict(float)+ queries: dict[str, set] = defaultdict(set)+ rows: Counter = Counter()+ top3: Counter = Counter()+ total = 0.0+ for query, url, rank in zip(gold["query"], gold["url"], gold["rank"]):+ w = click_weight(rank)+ total += w+ host = host_of(url)+ if not host:+ continue+ dom = registrable(host)+ mass[dom] += w+ queries[dom].add(query)+ rows[dom] += 1+ try:+ if 1 <= int(rank) <= 3:+ top3[dom] += 1+ except (TypeError, ValueError):+ pass++ miss = [(d, m, len(queries[d]), rows[d], top3[d]) for d, m in mass.items() if d not in ours]+ miss.sort(key=lambda x: -x[1])+ ours_mass = sum(m for d, m in mass.items() if d in ours)+ print(f"total gold mass {total:.0f} | distinct domains {len(mass)} | missing {len(miss)}")+ print(f"domains already a source (registrable match) = {100*ours_mass/total:.2f}% of gold mass\n")+ print(f"{'#':>3} {'domain':32} {'mass':>7} {'%mass':>6} {'queries':>8} {'rows':>6} {'rank1-3':>7}")+ for i, (d, m, nq, nr, t3) in enumerate(miss[:top]):+ print(f"{i+1:>3} {d:32} {m:7.1f} {100*m/total:5.1f}% {nq:8} {nr:6} {t3:7}")+ print()+ for n in (10, 20, 40):+ share = 100 * sum(x[1] for x in miss[:n]) / total+ print(f"top-{n} missing domains = {share:.1f}% of gold mass")+++def main():+ parser = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = parser.add_subparsers(dest="command")+ sub.add_parser("report", help="gold-coverage feasibility report (default)")+ sub.add_parser("missing", help="rank gold domains we lack by gold mass")+ p_missing = sub.choices["missing"]+ p_missing.add_argument("--top", type=int, default=45)+ p_recall = sub.add_parser("recall", help="per-source exact-URL recall of gold")+ p_recall.add_argument("--source", required=True, help="source name in SOURCES")+ p_recall.add_argument("--limit", type=int, default=10)+ p_recall.add_argument("--max-queries", type=int, default=80)+ args = parser.parse_args()+ if args.command == "recall":+ cmd_recall(args.source, args.limit, args.max_queries)+ elif args.command == "missing":+ cmd_missing(args.top)+ else:+ cmd_report()+++if __name__ == "__main__":+ main()diff --git a/scripts/super_search_new_sources_eval.py b/scripts/super_search_new_sources_eval.pynew file mode 100644index 0000000..71fdd93--- /dev/null+++ b/scripts/super_search_new_sources_eval.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""Targeted NDCG comparison for the newly-added Super Search sources.++The full-sample compare_search_modes dilutes the effect of a few high-value+sources across thousands of unrelated queries. This script instead evaluates only+the *in-coverage* test queries — those whose gold results include a URL on a new+source's domain — where source selection can actually change the ranking. For each+such query it scores three arms (standard / SS baseline / SS + new sources) with+the same gold→NDCG method as rankeval.evaluation.evaluate.++Run:+ DATABASE_URL="postgres://daoud@" DJANGO_SETTINGS_MODULE=mwmbl.settings_dev \+ uv run python scripts/super_search_new_sources_eval.py --max-queries 80+"""+import argparse+import os+import sys+from pathlib import Path+from urllib.parse import urlparse++import django+import numpy as np+import pandas as pd++REPO_ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO_ROOT))+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")+django.setup()++from django.conf import settings # noqa: E402+from sklearn.metrics import ndcg_score # noqa: E402++from mwmbl.rankeval.evaluation.evaluate import CLICK_PROPORTIONS, NUM_RESULTS_FOR_EVAL # noqa: E402+from mwmbl.rankeval.evaluation.evaluate_ranker import MwmblRankingModel # noqa: E402+from mwmbl.rankeval.evaluation.evaluate_super_search import SuperSearchRankingModel # noqa: E402+from mwmbl.rankeval.paths import RANKINGS_DATASET_TEST_PATH # noqa: E402+from mwmbl.search_setup import ranker # noqa: E402+from mwmbl.tinysearchengine.super_search_select.registry import get_meta # noqa: E402++NEW_SOURCES = ["www_gov_uk", "imdb"]+++def _registrable(host: str) -> str:+ for prefix in ("www.", "m."):+ if host.startswith(prefix):+ host = host[len(prefix):]+ labels = host.split(".")+ return ".".join(labels[-2:]) if len(labels) > 2 else host+++def _host(url: str) -> str:+ try:+ return urlparse(str(url)).netloc.lower().split("@")[-1].split(":")[0]+ except ValueError:+ return ""+++def _ndcg(predicted_urls: list[str], gold_scores: dict[str, float]) -> float:+ top = predicted_urls[:NUM_RESULTS_FOR_EVAL]+ y_true = [gold_scores.get(u, 0.0) for u in top] + [0.0] * (NUM_RESULTS_FOR_EVAL - len(top))+ y_pred = list(range(NUM_RESULTS_FOR_EVAL, 0, -1))+ return ndcg_score([y_true], [y_pred])+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--max-queries", type=int, default=80)+ args = parser.parse_args()++ df = pd.read_csv(RANKINGS_DATASET_TEST_PATH)+ new_domains = {_registrable(get_meta(n).domain.lower()) for n in NEW_SOURCES}++ # In-coverage queries: a gold URL of theirs sits on one of the new domains.+ covered = {q for q, u in zip(df["query"], df["url"])+ if _registrable(_host(u)) in new_domains}+ queries = sorted(covered)+ rng = np.random.default_rng(0)+ rng.shuffle(queries)+ queries = queries[:args.max_queries]+ print(f"{len(covered)} in-coverage test queries; evaluating {len(queries)}")++ # Gold score dicts per query (same construction as evaluate.py).+ gold = {}+ for q in queries:+ rows = df[df["query"] == q][["url"]].iloc[:NUM_RESULTS_FOR_EVAL].copy()+ rows["score"] = CLICK_PROPORTIONS[:len(rows)]+ gold[q] = rows.set_index("url")["score"].to_dict()++ arms = [+ ("standard", lambda: MwmblRankingModel(ranker), None),+ ("ss-baseline", lambda: SuperSearchRankingModel(selection_key=""), []),+ ("ss+new", lambda: SuperSearchRankingModel(selection_key="+".join(NEW_SOURCES)), NEW_SOURCES),+ ]+ per_query = {name: {} for name, _, _ in arms}+ for name, make_model, force in arms:+ if force is not None:+ settings.SUPER_SEARCH_FORCE_INCLUDE = force+ model = make_model()+ print(f"\n--- arm {name} ---")+ for i, q in enumerate(queries):+ preds = model.predict(q)+ per_query[name][q] = _ndcg(preds, gold[q])+ if (i + 1) % 20 == 0:+ print(f" {i + 1}/{len(queries)}")+ settings.SUPER_SEARCH_FORCE_INCLUDE = []++ print("\n" + "=" * 60)+ print(f"{'arm':14} {'mean NDCG':>10}")+ for name, _, _ in arms:+ vals = list(per_query[name].values())+ print(f"{name:14} {np.mean(vals):>10.4f}")++ base = per_query["ss-baseline"]+ new = per_query["ss+new"]+ wins = sum(new[q] > base[q] + 1e-9 for q in queries)+ losses = sum(new[q] < base[q] - 1e-9 for q in queries)+ delta = np.mean([new[q] - base[q] for q in queries])+ print(f"\nss+new vs ss-baseline: mean Δ {delta:+.4f} | better {wins}, worse {losses}, "+ f"same {len(queries) - wins - losses}")+ movers = sorted(queries, key=lambda q: new[q] - base[q], reverse=True)+ print("\ntop NDCG gains (ss+new over baseline):")+ for q in movers[:8]:+ if new[q] - base[q] > 1e-9:+ print(f" {new[q] - base[q]:+.3f} {q!r}")+++if __name__ == "__main__":+ main()diff --git a/test/test_super_search_recipes.py b/test/test_super_search_recipes.pyindex ec8c40d..66c3fc4 100644--- a/test/test_super_search_recipes.py+++ b/test/test_super_search_recipes.py@@ -125,6 +125,26 @@ async def test_archive_org_nested_results_and_template(httpx_mock):assert docs[0].extract == "Moon landing"+async def test_json_base_url_joins_relative_path(httpx_mock):+ """A JSON API returning a site-relative url (e.g. gov.uk's "/contact-hmrc") is+ joined onto base_url to the canonical absolute URL, without %-quoting slashes."""+ recipe = Recipe(+ name="govuk", domain="www.gov.uk", field="law-government",+ request={"url": "https://www.gov.uk/api/search.json", "params": {"q": "{query}"}},+ response={"format": "json", "base_url": "https://www.gov.uk", "results": "results",+ "fields": {"title": "title", "url": "link"}},+ smoke={"query": "vat", "expect_title_contains": "VAT"},+ )+ httpx_mock.add_response(+ url=re.compile(r"https://www\.gov\.uk/api/search\.json.*"),+ json={"results": [{"title": "Contact HMRC", "link": "/find-hmrc-contacts/income-tax"}]},+ )+ async with httpx.AsyncClient() as client:+ docs = await search_with_recipe(client, recipe, "hmrc", 5)+ assert len(docs) == 1+ assert docs[0].url == "https://www.gov.uk/find-hmrc-contacts/income-tax"++# ---------------------------------------------------------------------------# HTML: Project Gutenberg — CSS selectors + relative href resolution# ---------------------------------------------------------------------------diff --git a/test/test_super_search_sources.py b/test/test_super_search_sources.pyindex 9c31622..c0cc5e0 100644--- a/test/test_super_search_sources.py+++ b/test/test_super_search_sources.py@@ -13,6 +13,7 @@ import pytestfrom mwmbl.tinysearchengine.super_search_sources.arxiv import search as search_arxivfrom mwmbl.tinysearchengine.super_search_sources.github import search as search_githubfrom mwmbl.tinysearchengine.super_search_sources.hn import search as search_hn+from mwmbl.tinysearchengine.super_search_sources.imdb import search as search_imdbfrom mwmbl.tinysearchengine.super_search_sources.pypi import search as search_pypifrom mwmbl.tinysearchengine.super_search_sources.stackexchange import search as search_stackexchange@@ -149,3 +150,32 @@ async def test_pypi_rejects_invalid_name():# Spaces / punctuation -> not a valid package namedocs = await search_pypi(client, "this is a phrase!", 5)assert docs == []+++# ---------------------------------------------------------------------------+# IMDb (autosuggest)+# ---------------------------------------------------------------------------++async def test_imdb_maps_ids_to_canonical_urls(httpx_mock):+ httpx_mock.add_response(+ url=re.compile(r"https://v3\.sg\.media-imdb\.com/suggestion/.*"),+ json={"d": [+ {"id": "tt0468569", "l": "The Dark Knight", "q": "feature", "s": "Christian Bale"},+ {"id": "nm0000288", "l": "Christian Bale", "s": "Actor"},+ {"id": "ls123", "l": "a user list"}, # not a title/name -> skipped+ ]},+ )+ async with httpx.AsyncClient() as client:+ docs = await search_imdb(client, "the dark knight", 5)+ assert [d.url for d in docs] == [+ "https://www.imdb.com/title/tt0468569/",+ "https://www.imdb.com/name/nm0000288/",+ ]+ assert docs[0].title == "The Dark Knight"+++async def test_imdb_swallows_http_errors(httpx_mock):+ httpx_mock.add_response(status_code=500)+ async with httpx.AsyncClient() as client:+ docs = await search_imdb(client, "inception", 5)+ assert docs == []