Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Serve every result, Jev's order first, and default Staan to en-gb

Claudeadc74f9e88a9
diff --git a/mwmbl/search_setup.py b/mwmbl/search_setup.py
index 1c19ef5..4636d54 100644
--- a/mwmbl/search_setup.py
+++ b/mwmbl/search_setup.py
@@ -30,6 +30,6 @@ 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. Jev orders the final
-# list from the model's unwrapped output; MMR only applies when Jev is unavailable.
+# list from the model's output, without MMR.
combined_ltr_model = RustXGBPipeline.from_model_path(str(settings.COMBINED_MODEL_PATH))
combined_ranker = JevRanker(CombinedLTRRanker(tiny_index, completer, combined_ltr_model))
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 0c26156..4a8e41b 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -297,12 +297,13 @@ COMBINED_MODEL_PATH = Path(__file__).parent / "resources" / "model-combined.xgb"
# the external results index - see mwmbl.tinysearchengine.staan.
STAAN_SEARCH_API_KEY = os.environ.get("STAAN_SEARCH_API_KEY", "")
STAAN_SEARCH_URL = os.environ.get("STAAN_SEARCH_URL", "https://api.staan.ai/v2/search/web")
-STAAN_MARKET = os.environ.get("STAAN_MARKET", "en-us")
+# en-gb because Combined Search's ordering was tuned on en-gb results, for a UK searcher.
+STAAN_MARKET = os.environ.get("STAAN_MARKET", "en-gb")
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.
+# Without a key, or when a request fails or times out, Combined Search serves the LTR's
+# order 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.
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.py
index 0698571..b528333 100644
--- a/mwmbl/tinysearchengine/combined_search.py
+++ b/mwmbl/tinysearchengine/combined_search.py
@@ -12,7 +12,7 @@ is what a client actually wants.
The ranking core is three calls. Ranker.retrieve looks the query up in the index while
Staan 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, and
-JevRanker orders the top of that with one Jev request (see jev_rank.py).
+JevRanker re-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 are
relevant, and evaluation found the extra fetch roughly neutral on quality (see
@@ -49,10 +49,11 @@ 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"
- "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"
+ "A learning-to-rank model trained on the pooled candidate set ranks every candidate. "
+ "EUSP's results and the model's top results are then judged for relevance and quality "
+ "by an LLM-based model, and ordered by that judgment and EUSP's own ranking; the rest "
+ "follow in the model's order. The response is 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.py
index 9c390a1..e913e14 100644
--- a/mwmbl/tinysearchengine/jev_rank.py
+++ b/mwmbl/tinysearchengine/jev_rank.py
@@ -8,7 +8,7 @@ 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
+and the rest of the LTR's results follow in the LTR's order. 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,
@@ -18,8 +18,8 @@ Leaning on Staan's order is deliberate: every learned ordering that overrode Sta
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.
+If Jev is unconfigured, fails or is slow, the request falls back to the LTR's order, so Jev
+being down costs quality, never results.
"""
import time
@@ -30,13 +30,11 @@ 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.
@@ -146,8 +144,7 @@ def candidate_pool(staan_results: list[Document], ranked: list[Document]) -> lis
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.
+ The wrapped ranker must not be wrapped in MMRRanker: Jev scores the LTR's own order.
"""
def __init__(self, ranker: Ranker):
@@ -178,15 +175,17 @@ class JevRanker:
if not settings.JEV_API_KEY:
logger.warning("JEV_API_KEY is not configured")
- return mmr_rerank(ranked)
+ return 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.warning("Jev failed, serving the LTR's order: %s", type(e).__name__)
+ return ranked
logger.info("Jev scored %d candidates in %.2fs", len(pool), time.monotonic() - start)
- return composite_order(pool, jev_scores)[:NUM_RESULTS]
+ pool_urls = {document.url for document in pool}
+ rest = [document for document in ranked if document.url not in pool_urls]
+ return composite_order(pool, jev_scores) + rest
diff --git a/test/test_jev_rank.py b/test/test_jev_rank.py
index 0b963d3..339816b 100644
--- a/test/test_jev_rank.py
+++ b/test/test_jev_rank.py
@@ -9,7 +9,6 @@ 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,
@@ -17,7 +16,6 @@ from mwmbl.tinysearchengine.jev_rank import (
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
@@ -134,17 +132,17 @@ def test_blacklisted_staan_results_stay_out_of_the_pool(monkeypatch):
assert [document.url for document in candidate_pool(staan, [])] == ["https://a.com/"]
-def test_search_serves_the_composite_top_ten(jev):
+def test_jev_orders_the_pool_and_the_rest_follow_in_the_ltrs_order(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)
+ ranked = [index_result(f"https://index{i}.com/") for i in range(50)]
+ # The index results Jev sees rate best of all, so only the pool's order can be Jev's.
+ requests_made = jev(lambda n: [(1.0, 1.0)] * 10 + [(3.0, 2.0)] * (n - 10))
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]
+ assert results == ranked[:NUM_LTR_CANDIDATES] + staan + ranked[NUM_LTR_CANDIDATES:]
def test_a_strong_index_result_outranks_a_weak_staan_result(jev):
@@ -158,7 +156,7 @@ def test_a_strong_index_result_outranks_a_weak_staan_result(jev):
@pytest.mark.parametrize("error", [requests.Timeout(), requests.HTTPError(), KeyError("answers")])
-def test_a_failed_jev_call_falls_back_to_the_ltr_and_mmr_ordering(monkeypatch, settings, error):
+def test_a_failed_jev_call_falls_back_to_the_ltrs_order(monkeypatch, settings, error):
settings.JEV_API_KEY = "test-key"
def failing_post(*args, **kwargs):
@@ -169,7 +167,7 @@ def test_a_failed_jev_call_falls_back_to_the_ltr_and_mmr_ordering(monkeypatch, s
results = JevRanker(FakeRanker(ranked)).search(QUERY, [], False)
- assert results == mmr_rerank(ranked)
+ assert results == ranked
def test_without_a_key_jev_is_not_called(monkeypatch, settings):
diff --git a/test/test_staan.py b/test/test_staan.py
index a6fb7d3..41ab5ca 100644
--- a/test/test_staan.py
+++ b/test/test_staan.py
@@ -84,7 +84,7 @@ def test_results_come_back_as_documents_attributed_to_staan(cache_index):
assert [document.url for document in results] == ["https://tokio.rs/", "https://docs.rs/tokio"]
assert [document.title for document in results] == ["Tokio", "tokio - Rust"]
assert {document.source for document in results} == {DocumentSource.STAAN}
- assert requested.call_args.kwargs["params"] == {"q": "rust async", "market": "en-us"}
+ assert requested.call_args.kwargs["params"] == {"q": "rust async", "market": "en-gb"}
assert requested.call_args.kwargs["headers"] == {"Authorization": "Bearer test-key"}