An open source, non-profit web search engine
Rank Combined Search with Jev composite + Staan rank
Claude9c7d9c684f97
diff --git a/mwmbl/search_setup.py b/mwmbl/search_setup.pyindex 510cfbc..1c19ef5 100644--- a/mwmbl/search_setup.py+++ b/mwmbl/search_setup.py@@ -5,6 +5,7 @@ from django.conf import settingsfrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklistfrom mwmbl.tinysearchengine.completer import Completerfrom mwmbl.tinysearchengine.indexer import Document, TinyIndex+from mwmbl.tinysearchengine.jev_rank import JevRankerfrom mwmbl.tinysearchengine.ltr import RustXGBPipelinefrom mwmbl.tinysearchengine.ltr_rank import CombinedLTRRanker, LTRRankerfrom mwmbl.tinysearchengine.mmr_rank import MMRRanker@@ -28,6 +29,7 @@ ranker = MMRRanker(LTRRanker(tiny_index, completer, ltr_model, include_wiki=True# Combined Search gets its own model and its own ranker, so retraining on the pooled# Mwmbl + Staan candidate set never moves standard search's ranking. The model uses-# Staan's ranking as features, which only CombinedLTRRanker supplies.+# Staan's ranking as features, which only CombinedLTRRanker supplies. Jev orders the final+# list from the model's unwrapped output; MMR only applies when Jev is unavailable.combined_ltr_model = RustXGBPipeline.from_model_path(str(settings.COMBINED_MODEL_PATH))-combined_ranker = MMRRanker(CombinedLTRRanker(tiny_index, completer, combined_ltr_model))+combined_ranker = JevRanker(CombinedLTRRanker(tiny_index, completer, combined_ltr_model))diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 9752484..0c26156 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -300,6 +300,16 @@ STAAN_SEARCH_URL = os.environ.get("STAAN_SEARCH_URL", "https://api.staan.ai/v2/sSTAAN_MARKET = os.environ.get("STAAN_MARKET", "en-us")STAAN_TIMEOUT_SECONDS = 5+# Jev (TypeSafe), which orders Combined Search's results - see mwmbl.tinysearchengine.jev_rank.+# Without a key, or when a request fails or times out, Combined Search serves the LTR + MMR+# ordering instead.+JEV_API_KEY = os.environ.get("JEV_API_KEY", "")+JEV_URL = "https://api.typesafe.ai/v1/systemone"+# The model version the composite weights were tuned on: a new version means re-tuning them.+JEV_MODEL = "jev-1.13.0"+# Jev takes about 0.6s at p50 and runs after Staan, so a slow call has to give up quickly.+JEV_TIMEOUT_SECONDS = 1.5+# Super SearchSUPER_SEARCH_MONTHLY_LIMIT = 100SUPER_SEARCH_TOP_K = 10 # promote sources in top-K seen so far for crawlingdiff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.pyindex 98d7879..0698571 100644--- a/mwmbl/tinysearchengine/combined_search.py+++ b/mwmbl/tinysearchengine/combined_search.py@@ -11,7 +11,8 @@ is what a client actually wants.The ranking core is three calls. Ranker.retrieve looks the query up in the index whileStaan is fetched, so the two overlap. Ranker.search_retrieved then pools the index pages-with Staan's results as additional_results, blacklist-filters the lot and ranks it.+with Staan's results as additional_results, blacklist-filters the lot and ranks it, and+JevRanker orders the top of that with one Jev request (see jev_rank.py).There is no separate Wikipedia fetch: Staan already returns Wikipedia pages when they arerelevant, and evaluation found the extra fetch roughly neutral on quality (see@@ -48,10 +49,10 @@ router = Router(tags=["Combined Search"])DESCRIPTION = ("Search the Mwmbl index and EUSP (European Search Perspective) in one request and ""return the ranked union.\n\n"- "Every candidate - crawled by Mwmbl or returned by EUSP - is scored by one "- "learning-to-rank model trained on the pooled candidate set, then "- "diversified so a single domain cannot take the whole page. The response is the same "- "SearXNG-compatible shape as `/api/v2/search/`.\n\n"+ "A learning-to-rank model trained on the pooled candidate set picks the best of the "+ "index's results. Those and EUSP's are then judged for relevance and quality by an "+ "LLM-based model, and ordered by that judgment and EUSP's own ranking. The top ten are "+ "returned, in the same SearXNG-compatible shape as `/api/v2/search/`.\n\n""The `engine` field names the provider a result came from:\n""- `mwmbl` - organically crawled by the Mwmbl crawler\n""- `eusp` - returned by the European Search Perspective (EUSP) web-search API\n"diff --git a/mwmbl/tinysearchengine/jev_rank.py b/mwmbl/tinysearchengine/jev_rank.pynew file mode 100644index 0000000..9c390a1--- /dev/null+++ b/mwmbl/tinysearchengine/jev_rank.py@@ -0,0 +1,192 @@+"""Combined Search's final ordering: Jev composite + Staan rank.++Jev (TypeSafe's structured-judgment model) answers two Score questions about every+candidate in one request per query: how relevant it is, on the Haiku judge's UK-relevance+rubric (0-3), and whether it is a substantive page or thin, spam or junk (0-2). The pool -+Staan's results plus the LTR's top 30, without MMR - is then sorted by++ relevance + 0.5 x quality - 0.1 x Staan's position (10 if Staan didn't return it)+ - 0.5 if Staan didn't return it++and the top ten are served. Every weight was tuned on the 849 training queries' serving pool+(pass-3 NDCG@10), never on the en-gb evaluation queries. Judged holistically it beats+Staan-first, the previous best ordering, by a wide margin. The experiments and their write-up+are on the archived branch of mwmbl/mwmbl#462 (scripts/combined_ltr_labels/jev_composite.py,+mwmbl/rankeval/combined-holistic-eval.md).++Leaning on Staan's order is deliberate: every learned ordering that overrode Staan's top+results lost to it holistically, even where it gained on per-page NDCG. MMR is not applied,+since judged holistically it made no difference and it demotes Staan's same-site results.++If Jev is unconfigured, fails or is slow, the request falls back to the LTR + MMR ordering+served before this, so Jev being down costs quality, never results.+"""++import time+from logging import getLogger++import numpy as np+import requests+from django.conf import settings++from mwmbl.tinysearchengine.indexer import Document, DocumentSource+from mwmbl.tinysearchengine.mmr_rank import mmr_rerank+from mwmbl.tinysearchengine.rank import Ranker, Retrieval, find_blacklisted_urls+from mwmbl.tinysearchengine.staan import STAAN_TOP_SCORE++logger = getLogger(__name__)++NUM_RESULTS = 10+# How many of the LTR's results join Staan's in the pool Jev scores.+NUM_LTR_CANDIDATES = 30+# The Staan position given to a candidate Staan didn't return: one past its last result.+NOT_IN_STAAN = 10++RELEVANCE_WEIGHT = 1.0+QUALITY_WEIGHT = 0.5+STAAN_POSITION_WEIGHT = 0.1+INDEX_PENALTY = 0.5++SEARCHER = "a web searcher in the United Kingdom"++# The wording is the experiment's exactly: the weights were tuned on Jev's answers to these+# questions, so changing a word means re-tuning them.+RELEVANCE_QUESTION = "How well does the search result `result` satisfy `query`, for `searcher`?"+RELEVANCE_CRITERIA = [+ "Irrelevant: off-topic, wrong entity, spam, or broken.",+ "Marginal: on-topic-ish but thin or tangential, the wrong sense of an ambiguous query, an SEO or "+ "doorway page, or a page for another country where the answer depends on the country.",+ "Good: relevant and useful, but partial, secondary, or less authoritative.",+ "Excellent: directly satisfies what the searcher most likely wants - the official site for a "+ "navigational query, a thorough direct answer to a question, an authoritative page on exactly "+ "that entity, the right local or transactional page, a current report for a news query.",+]+QUALITY_QUESTION = "Is the search result `result` a substantive page, judging by its title, URL and snippet?"+QUALITY_CRITERIA = [+ "Junk: spam, a content farm, a doorway or SEO page, a scraped or auto-generated page, a page "+ "selling something unrelated, or a broken, empty, login or error page.",+ "Thin: little real content - a stub, a bare listing or directory page, a tag or search page, "+ "or a page that only repeats the query's words.",+ "Substantive: a real page with real content, or the real site or service it names.",+]+QUESTIONS = {+ "r": (RELEVANCE_QUESTION, RELEVANCE_CRITERIA),+ "q": (QUALITY_QUESTION, QUALITY_CRITERIA),+}++# One session for the process, so its pooled connections are reused: Jev is on Combined+# Search's critical path, after Staan.+session = requests.Session()+++def jev_request(query: str, documents: list[Document]) -> dict:+ questions = {+ f"{prefix}{i}": {+ "type": "score",+ "instructions": {+ "result": {"title": document.title, "url": document.url, "snippet": document.extract or ""},+ "question": question,+ },+ "criteria": criteria,+ }+ for i, document in enumerate(documents)+ for prefix, (question, criteria) in QUESTIONS.items()+ }+ return {"model": settings.JEV_MODEL, "state": {"query": query, "searcher": SEARCHER}, "questions": questions}+++def get_jev_scores(query: str, documents: list[Document]) -> np.ndarray:+ """Jev's (relevance, quality) for each document, one row each. Raises on any failure."""+ response = session.post(+ settings.JEV_URL,+ json=jev_request(query, documents),+ headers={"Authorization": f"Bearer {settings.JEV_API_KEY}"},+ 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))])+++def staan_position(document: Document) -> int:+ # A Staan result's score encodes the rank Staan gave it (see staan_score), which counts+ # Staan's results before the blacklist filter, exactly as the experiment did.+ if document.source == DocumentSource.STAAN:+ return round(STAAN_TOP_SCORE - document.score)+ return NOT_IN_STAAN+++def composite_order(pool: list[Document], jev_scores: np.ndarray) -> list[Document]:+ positions = np.array([staan_position(document) for document in pool], dtype=float)+ from_index = positions == NOT_IN_STAAN+ composite = (+ RELEVANCE_WEIGHT * jev_scores[:, 0]+ + QUALITY_WEIGHT * jev_scores[:, 1]+ - STAAN_POSITION_WEIGHT * positions+ - INDEX_PENALTY * from_index+ )+ # Stable, so ties keep the pool's order: Staan's results first, in Staan's order.+ order = np.argsort(-composite, kind="stable")+ return [pool[i] for i in order]+++def candidate_pool(staan_results: list[Document], ranked: list[Document]) -> list[Document]:+ """Staan's results, then the LTR's top results, each URL once.++ Staan's come from Staan's own list rather than the LTR's output, so a Staan result the+ model scored below zero still gets judged, as in the experiment. They still go through+ the blacklist, which the LTR's output already has.+ """+ blacklisted_urls = find_blacklisted_urls(staan_results) if settings.BLACKLIST_FILTER_AT_RETRIEVAL else set()+ staan_kept = [document for document in staan_results if document.url not in blacklisted_urls]+ by_url = {document.url: document for document in staan_kept + ranked[:NUM_LTR_CANDIDATES]}+ return list(by_url.values())+++class JevRanker:+ """Decorator that orders a CombinedLTRRanker's pool with Jev composite + Staan rank.++ The wrapped ranker must not be wrapped in MMRRanker: Jev scores the LTR's own order, and+ MMR is only applied on the fallback path.+ """++ def __init__(self, ranker: Ranker):+ self.ranker = ranker++ def search(self, s: str, additional_results: list[Document], use_external_search: bool = True) -> list[Document]:+ ranked = self.ranker.search(s, additional_results, use_external_search)+ return self.rerank(s, additional_results, ranked)++ def retrieve(self, q: str) -> Retrieval:+ return self.ranker.retrieve(q)++ def search_retrieved(self, retrieval: Retrieval, additional_results: list[Document]) -> list[Document]:+ ranked = self.ranker.search_retrieved(retrieval, additional_results)+ return self.rerank(retrieval.query, additional_results, ranked)++ def complete(self, q: str):+ return self.ranker.complete(q)++ def get_raw_results(self, query: str):+ return self.ranker.get_raw_results(query)++ def rerank(self, query: str, additional_results: list[Document], ranked: list[Document]) -> list[Document]:+ staan_results = [document for document in additional_results if document.source == DocumentSource.STAAN]+ pool = candidate_pool(staan_results, ranked)+ if not pool:+ return []++ if not settings.JEV_API_KEY:+ logger.warning("JEV_API_KEY is not configured")+ return mmr_rerank(ranked)++ start = time.monotonic()+ try:+ jev_scores = get_jev_scores(query, pool)+ except Exception as e:+ # Only the type, never the message or body: both can embed the user's query.+ logger.warning("Jev failed, serving the LTR + MMR ordering: %s", type(e).__name__)+ return mmr_rerank(ranked)+ logger.info("Jev scored %d candidates in %.2fs", len(pool), time.monotonic() - start)++ return composite_order(pool, jev_scores)[:NUM_RESULTS]diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.pyindex 8bbcf89..d1fd7cf 100644--- a/mwmbl/tinysearchengine/rank.py+++ b/mwmbl/tinysearchengine/rank.py@@ -301,6 +301,7 @@ def remove_curate_state(state: DocumentState):class Retrieval:"""What Ranker.retrieve found in the index for a query, ready to be ranked."""+ query: strterms: list[str]completions: list[str]is_complete: bool@@ -417,7 +418,7 @@ class Ranker:if items is not None:pages += items- return Retrieval(terms, completions, is_complete, curated_items, pages)+ return Retrieval(q, terms, completions, is_complete, curated_items, pages)def _rank(self, retrieval: Retrieval, additional_results: list[Document], external_search_items: list[Document]diff --git a/test/test_jev_rank.py b/test/test_jev_rank.pynew file mode 100644index 0000000..0b963d3--- /dev/null+++ b/test/test_jev_rank.py@@ -0,0 +1,191 @@+"""JevRanker: Combined Search's final ordering, Jev composite + Staan rank."""++from unittest.mock import MagicMock++import pytest+import requests++import mwmbl.tinysearchengine.jev_rank as jev_rank+from mwmbl.tinysearchengine.indexer import Document, DocumentSource+from mwmbl.tinysearchengine.jev_rank import (+ NUM_LTR_CANDIDATES,+ NUM_RESULTS,+ QUALITY_QUESTION,+ RELEVANCE_QUESTION,+ JevRanker,+ candidate_pool,+ composite_order,+ jev_request,+)+from mwmbl.tinysearchengine.mmr_rank import mmr_rerank+from mwmbl.tinysearchengine.rank import Ranker+from mwmbl.tinysearchengine.staan import staan_score++QUERY = "bankside hotel"+++def staan_result(url: str, rank: int) -> Document:+ return Document(f"Staan {rank}", url, "", staan_score(rank), source=DocumentSource.STAAN)+++def index_result(url: str) -> Document:+ return Document(f"Index {url}", url, "", 1.0)+++class FakeRanker(Ranker):+ """Returns a fixed LTR ordering, whatever it is asked."""++ def __init__(self, ranked: list[Document]):+ super().__init__(None, None)+ self.ranked = ranked++ def search(self, s, additional_results, use_external_search=True):+ return self.ranked+++def jev_answers(scores: list[tuple[float, float]]) -> dict:+ answers = {}+ for i, (relevance, quality) in enumerate(scores):+ answers[f"r{i}"] = {"score": relevance}+ answers[f"q{i}"] = {"score": quality}+ return {"answers": answers}++[email protected](autouse=True)+def no_blacklist(monkeypatch):+ monkeypatch.setattr(jev_rank, "find_blacklisted_urls", lambda documents: set())+++def jev(monkeypatch, settings):+ """Stub the Jev endpoint, recording each request body."""+ settings.JEV_API_KEY = "test-key"+ requests_made = []++ def configure(scores_for):+ def fake_post(url, json, headers, timeout):+ requests_made.append(json)+ num_candidates = len(json["questions"]) // 2+ response = MagicMock()+ response.json.return_value = jev_answers(scores_for(num_candidates))+ return response++ monkeypatch.setattr(jev_rank.session, "post", fake_post)+ return requests_made++ return configure+++def test_the_request_asks_relevance_and_quality_for_every_candidate(settings):+ documents = [staan_result("https://a.com/", 0), index_result("https://b.com/")]++ body = jev_request(QUERY, documents)++ assert body["model"] == settings.JEV_MODEL+ assert body["state"] == {"query": QUERY, "searcher": "a web searcher in the United Kingdom"}+ assert set(body["questions"]) == {"r0", "q0", "r1", "q1"}+ assert body["questions"]["r1"]["instructions"]["question"] == RELEVANCE_QUESTION+ assert body["questions"]["q1"]["instructions"]["question"] == QUALITY_QUESTION+ assert body["questions"]["r1"]["instructions"]["result"] == {+ "title": "Index https://b.com/",+ "url": "https://b.com/",+ "snippet": "",+ }+ assert len(body["questions"]["r0"]["criteria"]) == 4+ assert len(body["questions"]["q0"]["criteria"]) == 3+++def test_composite_weights_relevance_quality_staan_position_and_the_index_penalty():+ staan_top = staan_result("https://staan-top.com/", 0)+ staan_fifth = staan_result("https://staan-fifth.com/", 5)+ index_page = index_result("https://index.com/")+ pool = [staan_top, staan_fifth, index_page]+ # staan_top: 2.0 + 0.5 x 1 - 0.1 x 0 = 2.5+ # staan_fifth: 2.6 + 0.5 x 2 - 0.1 x 5 = 3.1+ # index_page: 2.8 + 0.5 x 2 - 0.1 x 10 - 0.5 = 2.3+ scores = jev_rank.np.array([[2.0, 1.0], [2.6, 2.0], [2.8, 2.0]])++ assert composite_order(pool, scores) == [staan_fifth, staan_top, index_page]+++def test_ties_keep_staans_order():+ pool = [staan_result("https://a.com/", 0), staan_result("https://b.com/", 5)]+ # b's extra relevance exactly offsets its lower Staan position.+ scores = jev_rank.np.array([[2.0, 2.0], [2.5, 2.0]])++ assert composite_order(pool, scores) == pool+++def test_the_pool_is_staan_then_the_ltrs_top_results_each_url_once():+ staan = [staan_result("https://a.com/", 0), staan_result("https://b.com/", 1)]+ ranked = [index_result("https://b.com/")] + [index_result(f"https://{i}.com/") for i in range(40)]++ pool = candidate_pool(staan, ranked)++ assert [document.url for document in pool[:2]] == ["https://a.com/", "https://b.com/"]+ assert len(pool) == 1 + NUM_LTR_CANDIDATES+ assert pool[-1].url == f"https://{NUM_LTR_CANDIDATES - 2}.com/"+++def test_blacklisted_staan_results_stay_out_of_the_pool(monkeypatch):+ monkeypatch.setattr(jev_rank, "find_blacklisted_urls", lambda documents: {"https://spam.com/"})+ staan = [staan_result("https://spam.com/", 0), staan_result("https://a.com/", 1)]++ assert [document.url for document in candidate_pool(staan, [])] == ["https://a.com/"]+++def test_search_serves_the_composite_top_ten(jev):+ staan = [staan_result(f"https://staan{i}.com/", i) for i in range(10)]+ ranked = [index_result(f"https://index{i}.com/") for i in range(30)]+ # Every candidate equally good: Staan's position and the index penalty decide.+ requests_made = jev(lambda n: [(2.0, 2.0)] * n)++ results = JevRanker(FakeRanker(ranked)).search(QUERY, staan, False)++ assert len(requests_made) == 1+ assert len(requests_made[0]["questions"]) == 2 * 40+ assert results == staan[:NUM_RESULTS]+++def test_a_strong_index_result_outranks_a_weak_staan_result(jev):+ staan = [staan_result("https://staan.com/", 0)]+ ranked = [index_result("https://index.com/")]+ jev(lambda n: [(1.0, 1.0), (3.0, 2.0)])++ results = JevRanker(FakeRanker(ranked)).search(QUERY, staan, False)++ assert [document.url for document in results] == ["https://index.com/", "https://staan.com/"]++[email protected]("error", [requests.Timeout(), requests.HTTPError(), KeyError("answers")])+def test_a_failed_jev_call_falls_back_to_the_ltr_and_mmr_ordering(monkeypatch, settings, error):+ settings.JEV_API_KEY = "test-key"++ def failing_post(*args, **kwargs):+ raise error++ monkeypatch.setattr(jev_rank.session, "post", failing_post)+ ranked = [index_result(f"https://example.com/{i}") for i in range(3)] + [index_result("https://other.com/")]++ results = JevRanker(FakeRanker(ranked)).search(QUERY, [], False)++ assert results == mmr_rerank(ranked)+++def test_without_a_key_jev_is_not_called(monkeypatch, settings):+ settings.JEV_API_KEY = ""+ post = MagicMock()+ monkeypatch.setattr(jev_rank.session, "post", post)+ ranked = [index_result("https://a.com/")]++ results = JevRanker(FakeRanker(ranked)).search(QUERY, [], False)++ post.assert_not_called()+ assert results == ranked+++def test_an_empty_pool_is_not_sent_to_jev(jev):+ requests_made = jev(lambda n: [])++ assert JevRanker(FakeRanker([])).search(QUERY, [], False) == []+ assert requests_made == []