Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Un-wire Super Search v2 selection/judge pipeline from the live request path

Daoud Clarke76baabd8e767
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index 46d1971..e5f1b07 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -67,7 +67,7 @@ class MwmblConfig(AppConfig):
try:
from background_task.models import Task
- from mwmbl.background import retrain_super_search_xgb, sync_search_counts
+ from mwmbl.background import sync_search_counts
SYNC_TASK = "mwmbl.background.sync_search_counts"
@@ -75,21 +75,6 @@ class MwmblConfig(AppConfig):
if not Task.objects.filter(task_name=SYNC_TASK).exists():
sync_search_counts(repeat=3600, repeat_until=None)
- # Retrain the Super Search xgb source model daily from the
- # impression log (skips until enough pairs have accumulated).
- XGB_TASK = "mwmbl.background.retrain_super_search_xgb"
- if not Task.objects.filter(task_name=XGB_TASK).exists():
- retrain_super_search_xgb(repeat=86400, repeat_until=None)
-
except Exception:
# Don't prevent startup if background task scheduling fails
log.exception("Failed to schedule background tasks")
-
- try:
- # SETNX-seed Redis content profiles + reward EMAs from the bundled
- # xgb artifact so serving features match training from the first
- # request (and a Redis wipe self-heals on next startup).
- from mwmbl.tinysearchengine.super_search_select import xgb_model
- xgb_model.seed_online_state()
- except Exception:
- log.exception("Failed to seed super-search online state")
diff --git a/mwmbl/background.py b/mwmbl/background.py
index f756ec8..50cca81 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -88,27 +88,6 @@ def copy_indexes_continuously():
# Periodic quota maintenance tasks (Django Background Tasks)
# ---------------------------------------------------------------------------
-@background(schedule=0)
-def retrain_super_search_xgb():
- """Daily batch retrain of the Super Search xgb source model.
-
- The impression log is the contextual bandit's memory: this folds the last
- training window of logged (features, judge-reward) pairs into a fresh
- XGBoost artifact, which serving processes hot-reload via its mtime. Skips
- (with a log line) when too few pairs have accumulated; training/IO errors
- propagate so failures are visible.
- """
- from mwmbl.tinysearchengine.super_search_select import xgb_model
-
- metrics = xgb_model.train_and_save_from_impressions(
- window_days=settings.SUPER_SEARCH_XGB_TRAIN_WINDOW_DAYS,
- min_rows=settings.SUPER_SEARCH_XGB_MIN_TRAIN_ROWS,
- out_dir=settings.SUPER_SEARCH_XGB_MODEL_DIR,
- )
- if metrics is not None:
- logger.info("super-search xgb retrained: %s", metrics)
-
-
@background(schedule=0)
def sync_search_counts():
"""
diff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.py
index 8ea2c35..bdd2125 100644
--- a/mwmbl/indexer/update_urls.py
+++ b/mwmbl/indexer/update_urls.py
@@ -50,7 +50,6 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Re
url_timestamps = {}
url_statuses = defaultdict(lambda: URLStatus.NEW)
domain_links = defaultdict(set)
- crawled_page_links: dict[str, list[str]] = {}
for batch in batches:
for item in batch.items:
timestamp = get_datetime_from_timestamp(item.timestamp / 1000.0)
@@ -67,7 +66,7 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Re
continue
for link in item.content.all_links:
process_link(batch.user_id_hash, crawled_page_domain, link, timestamp, url_timestamps, url_users,
- blacklist_provider, domain_links, item.url, crawled_page_links)
+ blacklist_provider, domain_links)
found_urls = [FoundURL(url, url_users[url], url_statuses[url], url_timestamps[url])
for url in url_statuses.keys() | url_users.keys()]
@@ -80,8 +79,6 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Re
for source_domain, target_domains in domain_links.items():
domain_link_db.update_domain_links(source_domain, target_domains)
- _propagate_source_provenance(crawled_page_links)
-
end = datetime.utcnow()
logger.info(f"Recorded URLs in database in {end - start}")
@@ -111,7 +108,7 @@ def add_hn_links(new_item_queue: RedisURLQueue):
def process_link(user_id_hash: str, crawled_page_domain: str, link: Link, timestamp: datetime,
url_timestamps: dict[str, datetime], url_users: dict[str, str], blacklist_provider,
- domain_links: dict[str, set[str]], page_url: str, crawled_page_links: dict[str, list[str]]):
+ domain_links: dict[str, set[str]]):
try:
parsed_link = parse_url(link.url)
except ValueError:
@@ -132,52 +129,6 @@ def process_link(user_id_hash: str, crawled_page_domain: str, link: Link, timest
url_users[root_url] = user_id_hash
url_timestamps[root_url] = timestamp
domain_links[crawled_page_domain].add(parsed_link.netloc)
- # Remember which links came off which crawled page, for source-provenance
- # propagation (only used when the page itself has a known Super Search source).
- if len(link.url) <= 500:
- crawled_page_links.setdefault(page_url, []).append(link.url)
-
-
-def _propagate_source_provenance(crawled_page_links: dict[str, list[str]]):
- """Carry a crawled page's Super Search source onto the links found on it.
-
- Only pages already recorded in SourceProvenance propagate, so the common case
- (no provenance) costs a single batched query. Propagation is bounded by
- SOURCE_PROVENANCE_MAX_DEPTH to limit transitive spread. No-op without a
- database; never raises into URL recording.
- """
- if not getattr(settings, "HAS_DATABASE", False):
- return
- if not crawled_page_links:
- return
- try:
- from mwmbl.models import SourceProvenance
-
- max_depth = getattr(settings, "SOURCE_PROVENANCE_MAX_DEPTH", 3)
- known = {
- url: (source, depth)
- for url, source, depth in SourceProvenance.objects.filter(
- url__in=list(crawled_page_links.keys())
- ).values_list("url", "source", "depth")
- }
- rows = []
- for page_url, link_urls in crawled_page_links.items():
- entry = known.get(page_url)
- if entry is None:
- continue
- source, depth = entry
- if depth >= max_depth:
- continue
- for link_url in link_urls:
- rows.append(SourceProvenance(
- url=link_url, source=source, parent_url=page_url[:500],
- depth=depth + 1,
- ))
- if rows:
- SourceProvenance.objects.bulk_create(rows, ignore_conflicts=True)
- logger.info(f"Propagated source provenance to {len(rows)} links")
- except Exception:
- logger.exception("failed to propagate source provenance")
def get_datetime_from_timestamp(timestamp: float) -> datetime:
diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.py
index d2b7751..558546c 100644
--- a/mwmbl/tinysearchengine/super_search.py
+++ b/mwmbl/tinysearchengine/super_search.py
@@ -15,7 +15,6 @@ import asyncio
import copy
import heapq
from concurrent.futures import ThreadPoolExecutor
-from datetime import datetime
import json
import logging
import re
@@ -33,32 +32,19 @@ from ninja.errors import HttpError
from pydantic import BaseModel, Field
from mwmbl.crawler.retrieve import crawl_url
-from mwmbl.crawler.urls import FoundURL, URLStatus
from mwmbl.indexer.index_batches import index_results_against_query
-from mwmbl.indexer.update_urls import _add_found_urls_to_db_and_queue
from mwmbl.quota import (
check_rate_limit,
decrement_monthly_super_search,
increment_monthly_super_search,
)
from mwmbl.search_auth import authenticate_user
-from mwmbl.search_setup import index_path, ltr_model, queued_batches
+from mwmbl.search_setup import index_path, ltr_model
from mwmbl.tinysearchengine.indexer import Document
from mwmbl.tinysearchengine.ltr_rank import score_documents
from mwmbl.tinysearchengine.mmr_rank import mmr_rerank
from mwmbl.tinysearchengine.rank import score_result_whole
from mwmbl.tinysearchengine.super_search_sources import SOURCES
-from mwmbl.tinysearchengine.super_search_select import rstats as ss_rstats
-from mwmbl.tinysearchengine.super_search_select import judge as ss_judge
-from mwmbl.tinysearchengine.super_search_select import profiles as ss_profiles
-from mwmbl.tinysearchengine.super_search_select.policy import select_sources
-from mwmbl.tinysearchengine.super_search_select.rewards import (
- SelectionContext,
- compute_judge_rewards,
- compute_rewards,
- log_impression,
- record_source_provenance,
-)
from mwmbl.tokenizer import tokenize
logger = logging.getLogger(__name__)
@@ -98,14 +84,6 @@ async def _crawl(url: str):
return await loop.run_in_executor(_CRAWL_EXECUTOR, crawl_url, url, _get_redis())
-async def _update_profile(name: str, docs: list[Document]) -> None:
- """Fold a source's results into its content profile (off-thread, best-effort)."""
- try:
- await asyncio.to_thread(ss_profiles.update_profile, name, docs)
- except Exception:
- logger.exception("super-search profile update failed for %s", name)
-
-
# ---------------------------------------------------------------------------
# Event payload schemas
#
@@ -134,10 +112,9 @@ class ResultItem(Schema):
examples=[1.8423])
source: str = Field(
description=(
- "Originating Super Search source for this result (e.g. `github`) — "
- "the source that first produced the URL, for both `result_promoted` "
- "and final `results` items. Empty string when the source is unknown "
- "(e.g. an inline-followed link whose parent had no recorded source)."
+ "Originating source for `result_promoted` (one of the Super Search "
+ "sources, e.g. `github`); empty string for items in the final "
+ "`results` ranking, which merges all sources."
),
examples=["github", ""],
)
@@ -370,14 +347,10 @@ async def _call_source(name: str, fn, client: httpx.AsyncClient, query: str, lim
async def _follow_links(
parent: Document, query: str, emit, all_docs: list[Document],
- last_results_key: list, lock: asyncio.Lock, ctx: SelectionContext,
- judge_worker: "_JudgeWorker | None" = None,
+ last_results_key: list, lock: asyncio.Lock,
) -> None:
"""Crawl the parent URL, score its outbound links, and collect the best for final ranking."""
max_links = settings.SUPER_SEARCH_MAX_LINKS_PER_PAGE
- # Inline-followed pages are surfaced by Super Search itself, so attribute
- # them (and the parent) to the source that produced the parent result.
- parent_source = ctx.source_by_url.get(parent.url)
try:
result = await _crawl(parent.url)
@@ -399,8 +372,7 @@ async def _follow_links(
all_docs.append(Document(title=parent_title, url=parent.url, extract=parent_extract))
if not raw_links:
- await _emit_final_results(query, all_docs, emit, last_results_key, lock, ctx,
- judge_worker=judge_worker)
+ await _emit_final_results(query, all_docs, emit, last_results_key, lock)
return
terms = tokenize(query)
@@ -433,109 +405,12 @@ async def _follow_links(
url=proxy_doc.url,
extract=c.get("extract") or "",
))
- if parent_source:
- ctx.record_results(parent_source, [proxy_doc.url])
-
- await _emit_final_results(query, all_docs, emit, last_results_key, lock, ctx,
- judge_worker=judge_worker)
-
-
-def _judge_score_docs(query: str, docs: list[Document]) -> list[float] | None:
- """Score docs with the fine-tuned relevance judge; None if it is unavailable."""
- judge = ss_judge.get_judge()
- if judge is None:
- return None
- return judge.score(query, [ss_judge.doc_text(d.title, d.extract) for d in docs])
-
-
-class _JudgeWorker:
- """Judge-scores docs incrementally as sources return them.
-
- A single consumer task micro-batches queued docs into `_judge_score_docs`
- calls off the event loop, accumulating url→score into ctx.judge_scores.
- Progressive frames can then rank already-judged docs with the judge instead
- of the LTR model, and the final frame only has to score stragglers rather
- than the whole pool in one end-of-pipeline lump. One task means at most one
- ONNX inference at a time, so no extra locking is needed around the judge.
- """
-
- def __init__(self, query: str, ctx: SelectionContext):
- self._query = query
- self._ctx = ctx
- self._queue: asyncio.Queue[Document] = asyncio.Queue()
- self._enqueued: set[str] = set()
- self.unavailable = False
- self._task = asyncio.create_task(self._run())
-
- def submit(self, docs: list[Document]) -> None:
- """Queue docs for scoring; already-submitted URLs are skipped."""
- if self.unavailable or self._task.done():
- return
- for doc in docs:
- if doc.url and doc.url not in self._enqueued:
- self._enqueued.add(doc.url)
- self._queue.put_nowait(doc)
- async def _run(self) -> None:
- while True:
- batch = [await self._queue.get()]
- while len(batch) < ss_judge.BATCH_SIZE:
- try:
- batch.append(self._queue.get_nowait())
- except asyncio.QueueEmpty:
- break
- scores = await asyncio.to_thread(_judge_score_docs, self._query, batch)
- if scores is None:
- self.unavailable = True
- return
- self._ctx.judge_scores.update(zip((d.url for d in batch), scores))
-
- async def aclose(self) -> None:
- """Stop the worker; idempotent. Unscored docs become final-frame stragglers."""
- if not self._task.done():
- self._task.cancel()
- try:
- await self._task
- except asyncio.CancelledError:
- pass
- except Exception:
- logger.exception("super-search judge worker failed")
-
-
-async def _hybrid_scores(query: str, unique: list[Document], ctx: SelectionContext) -> list[float]:
- """Judge scores where available, LTR for the not-yet-judged remainder.
-
- Both are [0, 1] probabilities but calibrated differently, so judged and
- unjudged docs can interleave imperfectly for a frame or two; each frame
- converges toward the fully judged ranking.
- """
- judged = ctx.judge_scores
- unjudged = [d for d in unique if d.url not in judged]
- ltr_by_url: dict[str, float] = {}
- if unjudged:
- ltr_scores = await asyncio.to_thread(score_documents, ltr_model, query, unjudged)
- ltr_by_url = dict(zip((d.url for d in unjudged), ltr_scores))
- return [judged.get(d.url, ltr_by_url.get(d.url, 0.0)) for d in unique]
-
-
-async def _final_judge_scores(
- query: str, unique: list[Document], ctx: SelectionContext, judge_worker: "_JudgeWorker",
-) -> list[float] | None:
- """Close the worker and judge only the docs it hasn't already scored."""
- await judge_worker.aclose()
- stragglers = [d for d in unique if d.url not in ctx.judge_scores]
- if stragglers:
- scores = await asyncio.to_thread(_judge_score_docs, query, stragglers)
- if scores is not None:
- ctx.judge_scores.update(zip((d.url for d in stragglers), scores))
- elif not ctx.judge_scores:
- return None # judge unavailable end-to-end: caller falls back to LTR
- return [ctx.judge_scores.get(d.url, 0.0) for d in unique]
+ await _emit_final_results(query, all_docs, emit, last_results_key, lock)
async def _emit_final_results(
- query: str, all_docs: list[Document], emit, last_results_key: list, lock: asyncio.Lock,
- ctx: SelectionContext, use_judge: bool = False, judge_worker: "_JudgeWorker | None" = None,
+ query: str, all_docs: list[Document], emit, last_results_key: list, lock: asyncio.Lock
) -> None:
terms = tokenize(query)
final_limit = getattr(settings, "SUPER_SEARCH_FINAL_RESULTS_LIMIT", 100)
@@ -558,25 +433,7 @@ async def _emit_final_results(
if not unique:
return
- # The end-of-search frame is re-ranked by the fine-tuned relevance
- # judge when available (the LTR model anti-correlates with human
- # curation — see devdata/judge_train/RESULTS.md); the per-URL judge
- # scores double as the bandit's per-source reward signal.
- final_scores = None
- if use_judge:
- if judge_worker is not None:
- final_scores = await _final_judge_scores(query, unique, ctx, judge_worker)
- else:
- final_scores = await asyncio.to_thread(_judge_score_docs, query, unique)
- if final_scores is not None:
- ctx.judge_scores = dict(zip((doc.url for doc in unique), final_scores))
- elif judge_worker is not None and not judge_worker.unavailable:
- # Progressive frame: feed the incremental judge and rank with
- # whatever it has scored so far, LTR for the rest.
- judge_worker.submit(unique)
- final_scores = await _hybrid_scores(query, unique, ctx)
- if final_scores is None:
- final_scores = await asyncio.to_thread(score_documents, ltr_model, query, unique)
+ final_scores = await asyncio.to_thread(score_documents, ltr_model, query, unique)
ranked = sorted(zip(unique, final_scores), key=lambda x: -x[1])[:final_limit]
# Diversify with MMR (demotes, never drops, same-domain / near-duplicate
# results) to match standard search — see MMRRanker in search_setup.py.
@@ -588,10 +445,7 @@ async def _emit_final_results(
return
last_results_key[0] = key
await emit("results", ResultsEvent(
- results=[
- _result_payload(doc, score, ctx.source_by_url.get(doc.url, ""), "final")
- for doc, score in ranked
- ],
+ results=[_result_payload(doc, score, "", "final") for doc, score in ranked],
count=len(ranked),
))
@@ -613,65 +467,10 @@ async def _index_results(query: str, docs: list[Document]) -> int:
return 0
-def _enqueue_discovered_urls(ctx: SelectionContext) -> None:
- """Queue every URL Super Search discovered for organic crawling.
-
- Tags each FoundURL with its originating source name in the user_id_hash slot
- (consistent with the 'hn' seed precedent), so descendant pages crawled later
- can inherit the source via SourceProvenance. Blocking (Redis + Postgres);
- run off the event loop. Never raises into the caller.
- """
- now = datetime.utcnow()
- found_urls = [
- FoundURL(url, source, URLStatus.NEW, now, last_crawled=None)
- for url, source in ctx.source_by_url.items()
- ]
- if found_urls:
- _add_found_urls_to_db_and_queue(found_urls, queued_batches)
-
-
-async def _record_rewards(ctx: SelectionContext, last_results_key: list) -> None:
- """Compute per-source rewards and log the impression.
-
- Preferred reward: mean relevance-judge score of each source's final-pool
- documents (recorded by the judged final re-rank). Fallback when the judge
- is unavailable: fraction of a source's results surviving the final top-K.
- """
- if not ctx.selected:
- return
- rewards = compute_judge_rewards(ctx)
- if rewards is None:
- final_urls = list(last_results_key[0] or ())
- top_k = getattr(settings, "SUPER_SEARCH_TOP_K", 10)
- rewards = compute_rewards(ctx, final_urls[:top_k])
- try:
- await asyncio.to_thread(log_impression, ctx, rewards)
- except Exception:
- logger.exception("super-search failed to record rewards")
- try:
- # Per-source reward EMA: the online stat behind the contribution_ema
- # feature (aggregate per source, nothing query-derived). Together with
- # the impression log this is the policy's whole update — the xgb model
- # itself retrains in batch.
- await asyncio.to_thread(ss_rstats.update, rewards)
- except Exception:
- logger.exception("super-search failed to update reward stats")
- try:
- await asyncio.to_thread(record_source_provenance, ctx)
- except Exception:
- logger.exception("super-search failed to record source provenance")
- try:
- await asyncio.to_thread(_enqueue_discovered_urls, ctx)
- except Exception:
- logger.exception("super-search failed to enqueue discovered urls")
-
-
async def _run_pipeline(
- query: str, emit, all_docs: list[Document], last_results_key: list, lock: asyncio.Lock,
- ctx: SelectionContext, judge_worker: "_JudgeWorker | None" = None,
+ query: str, emit, all_docs: list[Document], last_results_key: list, lock: asyncio.Lock
) -> None:
per_source_limit = settings.SUPER_SEARCH_RESULTS_PER_SOURCE
- ctx.per_source_limit = per_source_limit
top_k = getattr(settings, "SUPER_SEARCH_TOP_K", 10)
limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)
timeout = httpx.Timeout(settings.SUPER_SEARCH_PER_SOURCE_TIMEOUT)
@@ -703,20 +502,11 @@ async def _run_pipeline(
follow_redirects=True,
headers={"User-Agent": HTTP_USER_AGENT},
) as client:
- # Select a subset of sources to query (xgb contextual-bandit policy)
- # rather than fanning out to every registered source.
- sources_to_query = getattr(settings, "SUPER_SEARCH_SOURCES_TO_QUERY", len(SOURCES))
- ctx.candidates = list(SOURCES.keys())
- selected = await asyncio.to_thread(
- select_sources, query, ctx.candidates, sources_to_query, ctx
- )
- ctx.selected = selected
-
source_tasks = []
- for name in selected:
+ for name, fn in SOURCES.items():
await emit("source_started", SourceStartedEvent(source=name))
source_tasks.append(
- asyncio.create_task(_call_source(name, SOURCES[name], client, query, per_source_limit))
+ asyncio.create_task(_call_source(name, fn, client, query, per_source_limit))
)
secondary: list[asyncio.Task] = []
@@ -730,12 +520,6 @@ async def _run_pipeline(
if not docs:
continue
- # Fold this source's results into its decaying-mean content profile
- # (best-effort; tracked in `secondary` so failures are logged at gather).
- secondary.append(asyncio.create_task(_update_profile(name, docs)))
- # Remember which source produced each URL, for reward attribution.
- ctx.record_results(name, [d.url for d in docs if d.url])
-
scores = await asyncio.to_thread(_heuristic_score_docs, query, docs)
for doc, score in zip(docs, scores):
if doc.url and doc.title:
@@ -743,11 +527,10 @@ async def _run_pipeline(
if _maybe_promote(doc, score):
await emit("result_promoted", _result_payload(doc, score, name, "direct"))
secondary.append(
- asyncio.create_task(_follow_links(doc, query, emit, all_docs, last_results_key, lock, ctx, judge_worker))
+ asyncio.create_task(_follow_links(doc, query, emit, all_docs, last_results_key, lock))
)
if all_docs:
- await _emit_final_results(query, all_docs, emit, last_results_key, lock, ctx,
- judge_worker=judge_worker)
+ await _emit_final_results(query, all_docs, emit, last_results_key, lock)
if secondary:
results = await asyncio.gather(*secondary, return_exceptions=True)
@@ -768,11 +551,6 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):
all_docs: list[Document] = []
last_results_key: list = [None]
results_lock = asyncio.Lock()
- selection_ctx = SelectionContext()
- # Created here rather than in _run_pipeline so the deadline's wait_for
- # cannot cancel it: on timeout the accumulated scores survive and the
- # judged final frame only has stragglers left to score.
- judge_worker = _JudgeWorker(query, selection_ctx)
async def emit(event_type: str, data: Any) -> None:
await queue.put((event_type, data))
@@ -781,8 +559,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):
nonlocal reason, pages_indexed
try:
await asyncio.wait_for(
- _run_pipeline(query, emit, all_docs, last_results_key, results_lock, selection_ctx,
- judge_worker),
+ _run_pipeline(query, emit, all_docs, last_results_key, results_lock),
timeout=settings.SUPER_SEARCH_DEADLINE_SECONDS,
)
except asyncio.TimeoutError:
@@ -795,19 +572,13 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):
reason = "error"
await queue.put(("error", ErrorEvent(message=str(e))))
finally:
- try:
- if reason in ("complete", "timed_out"):
- try:
- await _emit_final_results(query, all_docs, emit, last_results_key,
- results_lock, selection_ctx, use_judge=True,
- judge_worker=judge_worker)
- except Exception:
- logger.exception("super-search failed to emit final results")
- pages_indexed = await _index_results(query, all_docs)
- await _record_rewards(selection_ctx, last_results_key)
- finally:
- await judge_worker.aclose()
- await queue.put(_SENTINEL)
+ if reason in ("complete", "timed_out"):
+ try:
+ await _emit_final_results(query, all_docs, emit, last_results_key, results_lock)
+ except Exception:
+ logger.exception("super-search failed to emit final results")
+ pages_indexed = await _index_results(query, all_docs)
+ await queue.put(_SENTINEL)
task = asyncio.create_task(producer())
@@ -837,7 +608,6 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):
await task
except (asyncio.CancelledError, Exception):
pass
- await judge_worker.aclose()
# ---------------------------------------------------------------------------
@@ -872,7 +642,7 @@ def init_router() -> None:
"| `result_promoted` | result item (`origin=\"direct\"`) | A result entered the live top-K and will have its outbound links followed. |\n"
"| `page_fetched` | `{url, links}` | A promoted page was crawled; `links` is the number of outbound links found. |\n"
"| `link_followed` | `{url, from}` | An outbound link from a crawled page was fetched and added to the candidate pool. |\n"
- "| `results` | `{results[], count}` | The current authoritative ranking (items have `origin=\"final\"`). Emitted progressively after each source and once more at the end; the end-of-search frame is re-ranked by the fine-tuned relevance judge when available — **replace** your displayed list on each. |\n"
+ "| `results` | `{results[], count}` | The current authoritative ranking (items have `origin=\"final\"`). Emitted progressively after each source and once more at the end — **replace** your displayed list on each. |\n"
"| `error` | `{message}` | The pipeline crashed; the stream ends. |\n"
"| `done` | `{reason, elapsed_seconds, monthly_usage, monthly_limit, pages_indexed}` | Terminal event. `reason` is `complete`, `timed_out`, `cancelled` or `error`; `pages_indexed` is the number of new pages added to the Mwmbl index by this search. |\n\n"
"The exact JSON shape of every payload is given by the `oneOf` schema "
diff --git a/mwmbl/tinysearchengine/super_search_sources/__init__.py b/mwmbl/tinysearchengine/super_search_sources/__init__.py
index 7f1aa24..763019d 100644
--- a/mwmbl/tinysearchengine/super_search_sources/__init__.py
+++ b/mwmbl/tinysearchengine/super_search_sources/__init__.py
@@ -7,16 +7,11 @@ orchestrator.
"""
from mwmbl.tinysearchengine.super_search_sources.arxiv import search as search_arxiv
from mwmbl.tinysearchengine.super_search_sources.github import search as search_github
-from mwmbl.tinysearchengine.super_search_sources.guardian import search as search_guardian
from mwmbl.tinysearchengine.super_search_sources.hn import search as search_hn
-from mwmbl.tinysearchengine.super_search_sources.homepage import search as search_homepage
-from mwmbl.tinysearchengine.super_search_sources.imdb import search as search_imdb
from mwmbl.tinysearchengine.super_search_sources.mwmbl_index import search as search_mwmbl
-from mwmbl.tinysearchengine.super_search_sources.nhs import search as search_nhs
from mwmbl.tinysearchengine.super_search_sources.pypi import search as search_pypi
from mwmbl.tinysearchengine.super_search_sources.recipe import load_recipes, make_recipe_source
from mwmbl.tinysearchengine.super_search_sources.stackexchange import search as search_stackexchange
-from mwmbl.tinysearchengine.super_search_sources.wikidata import search as search_wikidata
SOURCES = {
"mwmbl": search_mwmbl,
@@ -25,11 +20,6 @@ SOURCES = {
"stackexchange": search_stackexchange,
"arxiv": search_arxiv,
"pypi": search_pypi,
- "imdb": search_imdb,
- "nhs": search_nhs, # UK consumer-health (conditions, medicines)
- "wikidata_official": search_wikidata, # official website of an entity (P856)
- "homepage": search_homepage, # heuristic brand-homepage guesser
- "guardian": search_guardian, # UK/world news (Content API, needs key)
}
# Declarative YAML recipes (recipes/*.yaml) are loaded at import time and added
diff --git a/test/test_super_search.py b/test/test_super_search.py
index 39681a4..24de687 100644
--- a/test/test_super_search.py
+++ b/test/test_super_search.py
@@ -303,35 +303,6 @@ def test_final_results_event_emitted(client, api_key, monkeypatch):
assert event_types.index("results") < event_types.index("done")
-def test_final_results_carry_originating_source(client, api_key, monkeypatch):
- """Final 'results' items report the source that produced their URL (not '')."""
- cache.delete(_super_search_monthly_key(api_key.user.id))
- _stub_sources(monkeypatch, {
- "github": [Document(title="Python repo", url="https://gh.example/", extract="python code")],
- "hn": [Document(title="Python thread", url="https://hn.example/", extract="python talk")],
- })
- _stub_scoring(monkeypatch, [0.9, 0.8] + [0.0] * 20)
-
- def fake_crawl(url, redis):
- return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}
-
- monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)
-
- response = client.get(
- "/api/v2/super-search/?q=python",
- HTTP_X_API_KEY=api_key.raw_key,
- )
- assert response.status_code == 200
- events = _parse_sse(_read_stream(response))
- final = [d for t, d in events if t == "results"][-1]["results"]
- source_by_url = {item["url"]: item["source"] for item in final}
- assert source_by_url["https://gh.example/"] == "github"
- assert source_by_url["https://hn.example/"] == "hn"
- # Every final item is tagged origin=final.
- assert all(item["origin"] == "final" for item in final)
-
-
@pytest.mark.django_db
def test_final_results_are_mmr_diversified(client, api_key, monkeypatch):
"""The final ranking applies MMR diversity (as standard search does): a second
diff --git a/test/test_update_urls.py b/test/test_update_urls.py
index 5f17171..47894c6 100644
--- a/test/test_update_urls.py
+++ b/test/test_update_urls.py
@@ -1,18 +1,15 @@
from collections import defaultdict
-import pytest
-
from mwmbl.crawler.batch import Link
-from mwmbl.indexer.update_urls import process_link, _propagate_source_provenance
+from mwmbl.indexer.update_urls import process_link
from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
-from mwmbl.models import SourceProvenance
def test_process_link_normal():
+ url_scores = {"https://somesite.com/something.html": 0.0, "https://somesite.com/": 0.0}
url_timestamps = {}
url_users = {}
domain_links = defaultdict(set)
- crawled_page_links = {}
blacklist_provider = StaticBlacklistProvider(set())
process_link(
@@ -24,22 +21,16 @@ def test_process_link_normal():
url_users=url_users,
blacklist_provider=blacklist_provider,
domain_links=domain_links,
- page_url="https://somewhere.com/page.html",
- crawled_page_links=crawled_page_links,
)
assert domain_links == {"somewhere.com": {"somesite.com"}}
- # The accepted link is remembered against the page it was found on.
- assert crawled_page_links == {
- "https://somewhere.com/page.html": ["https://somesite.com/something.html"]
- }
def test_process_link_excludes_porn():
+ url_scores = {}
url_timestamps = {}
url_users = {}
domain_links = {}
- crawled_page_links = {}
# Create a blacklist provider that blocks porn sites
blacklist_provider = StaticBlacklistProvider({"somepornsite.com"})
@@ -52,56 +43,9 @@ def test_process_link_excludes_porn():
url_users=url_users,
blacklist_provider=blacklist_provider,
domain_links=domain_links,
- page_url="https://somewhere.com/page.html",
- crawled_page_links=crawled_page_links,
)
+ assert url_scores == {}
assert url_timestamps == {}
assert url_users == {}
assert domain_links == {}
- # Blacklisted links are not recorded for provenance propagation either.
- assert crawled_page_links == {}
-
-
-PAGE = "https://gov.uk/guidance"
-CHILD_1 = "https://gov.uk/guidance/details"
-CHILD_2 = "https://example.com/referenced"
-
-
-def test_propagate_source_provenance_noop_without_database(monkeypatch):
- monkeypatch.setattr("django.conf.settings.HAS_DATABASE", False)
- # Should not raise even though provenance is gated off.
- _propagate_source_provenance({PAGE: [CHILD_1]})
-
-
-def test_propagate_source_provenance_carries_source_to_links(monkeypatch):
- monkeypatch.setattr("django.conf.settings.HAS_DATABASE", True)
- SourceProvenance.objects.create(url=PAGE, source="gov.uk", depth=0)
-
- _propagate_source_provenance({PAGE: [CHILD_1, CHILD_2]})
-
- for child in (CHILD_1, CHILD_2):
- row = SourceProvenance.objects.get(url=child)
- assert row.source == "gov.uk"
- assert row.parent_url == PAGE
- assert row.depth == 1
-
-
-def test_propagate_source_provenance_skips_unknown_pages(monkeypatch):
- monkeypatch.setattr("django.conf.settings.HAS_DATABASE", True)
- # PAGE has no provenance row, so nothing should be written for its links.
- _propagate_source_provenance({PAGE: [CHILD_1, CHILD_2]})
- assert SourceProvenance.objects.count() == 0
-
-
-def test_propagate_source_provenance_respects_depth_cap(monkeypatch):
- monkeypatch.setattr("django.conf.settings.HAS_DATABASE", True)
- monkeypatch.setattr("django.conf.settings.SOURCE_PROVENANCE_MAX_DEPTH", 2)
- SourceProvenance.objects.create(url=PAGE, source="gov.uk", depth=2)
-
- _propagate_source_provenance({PAGE: [CHILD_1]})
-
- assert not SourceProvenance.objects.filter(url=CHILD_1).exists()