Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Super Search v2: contextual-bandit source selection skeleton

Daoud Clarkee72994d61380
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index e5f1b07..ca5c60e 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 sync_search_counts
+ from mwmbl.background import sync_search_counts, sync_super_search_bandit
SYNC_TASK = "mwmbl.background.sync_search_counts"
@@ -75,6 +75,11 @@ class MwmblConfig(AppConfig):
if not Task.objects.filter(task_name=SYNC_TASK).exists():
sync_search_counts(repeat=3600, repeat_until=None)
+ # Persist Super Search bandit state Redis <-> Postgres once per hour.
+ BANDIT_TASK = "mwmbl.background.sync_super_search_bandit"
+ if not Task.objects.filter(task_name=BANDIT_TASK).exists():
+ sync_super_search_bandit(repeat=3600, repeat_until=None)
+
except Exception:
# Don't prevent startup if background task scheduling fails
log.exception("Failed to schedule background tasks")
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 50cca81..4439c64 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -88,6 +88,42 @@ def copy_indexes_continuously():
# Periodic quota maintenance tasks (Django Background Tasks)
# ---------------------------------------------------------------------------
+@background(schedule=0)
+def sync_super_search_bandit():
+ """Bidirectional sync of Super Search bandit state between Redis and Postgres.
+
+ Step 1 (Postgres → Redis): seed any arms missing from Redis (restores live
+ state after a Redis restart without clobbering newer in-memory updates).
+ Step 2 (Redis → Postgres): persist live arm state as a durable backup.
+ """
+ import numpy as np
+
+ from mwmbl.models import SuperSearchBanditState
+ from mwmbl.tinysearchengine.super_search_select import bandit
+
+ # Step 1: restore missing arms from Postgres.
+ pg_states = {}
+ for row in SuperSearchBanditState.objects.all():
+ d = row.dim
+ pg_states[row.site] = bandit.ArmState(
+ A=np.frombuffer(bytes(row.a), dtype=np.float64).reshape(d, d).copy(),
+ b=np.frombuffer(bytes(row.b), dtype=np.float64).copy(),
+ )
+ if pg_states:
+ bandit.seed_states(pg_states, overwrite=False)
+
+ # Step 2: persist live Redis state back to Postgres.
+ for site, state in bandit.export_all().items():
+ SuperSearchBanditState.objects.update_or_create(
+ site=site,
+ defaults={
+ "dim": int(state.b.shape[0]),
+ "a": state.A.astype(np.float64).tobytes(),
+ "b": state.b.astype(np.float64).tobytes(),
+ },
+ )
+
+
@background(schedule=0)
def sync_search_counts():
"""
diff --git a/mwmbl/migrations/0024_supersearchimpression.py b/mwmbl/migrations/0024_supersearchimpression.py
new file mode 100644
index 0000000..8532f0f
--- /dev/null
+++ b/mwmbl/migrations/0024_supersearchimpression.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.13 on 2026-06-21 22:20
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0023_userbilling_cancel_at_period_end'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='SuperSearchImpression',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('query', models.CharField(max_length=512)),
+ ('candidates', models.JSONField(default=list)),
+ ('selected', models.JSONField(default=list)),
+ ('features', models.JSONField(default=dict)),
+ ('rewards', models.JSONField(default=dict)),
+ ('timestamp', models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ 'indexes': [models.Index(fields=['timestamp'], name='mwmbl_super_timesta_bbb2f8_idx')],
+ },
+ ),
+ ]
diff --git a/mwmbl/migrations/0025_supersearchbanditstate.py b/mwmbl/migrations/0025_supersearchbanditstate.py
new file mode 100644
index 0000000..f8972bd
--- /dev/null
+++ b/mwmbl/migrations/0025_supersearchbanditstate.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.13 on 2026-06-21 22:25
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0024_supersearchimpression'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='SuperSearchBanditState',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('site', models.CharField(max_length=128, unique=True)),
+ ('dim', models.IntegerField()),
+ ('a', models.BinaryField()),
+ ('b', models.BinaryField()),
+ ('updated_at', models.DateTimeField(auto_now=True)),
+ ],
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 32e38a1..bc5b395 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -226,3 +226,37 @@ class SearchResultVote(models.Model):
models.Index(fields=['url', 'query']),
models.Index(fields=['timestamp']),
]
+
+
+class SuperSearchImpression(models.Model):
+ """One Super Search request: which sources were available, which were queried,
+ the features they were selected on, and the implicit reward each earned.
+
+ Feeds the offline feature-selection / policy-tuning harness and provides
+ durable training data for the contextual bandit.
+ """
+ query = models.CharField(max_length=512)
+ candidates = models.JSONField(default=list) # all selectable source names (action space)
+ selected = models.JSONField(default=list) # sources actually queried
+ features = models.JSONField(default=dict) # {source: [feature vector]} for selected sources
+ rewards = models.JSONField(default=dict) # {source: reward in [0, 1]}
+ timestamp = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=['timestamp']),
+ ]
+
+
+class SuperSearchBanditState(models.Model):
+ """Durable backup of a source's Thompson-sampling sufficient statistics.
+
+ The live state lives in Redis; this table is synced periodically so the
+ bandit survives a Redis restart. ``a`` / ``b`` are raw float64 bytes
+ (``A`` is ``dim*dim``, ``b`` is ``dim``).
+ """
+ site = models.CharField(max_length=128, unique=True)
+ dim = models.IntegerField()
+ a = models.BinaryField()
+ b = models.BinaryField()
+ updated_at = models.DateTimeField(auto_now=True)
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 10d3d45..ecebe7d 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -286,3 +286,14 @@ SUPER_SEARCH_MAX_LINKS_PER_PAGE = 3
SUPER_SEARCH_RESULTS_PER_SOURCE = 10
SUPER_SEARCH_FINAL_RESULTS_LIMIT = 100
SUPER_SEARCH_CRAWL_WORKERS = 8 # threads in the dedicated crawl pool
+
+# Super Search source selection (bandit / cosine profiles)
+SUPER_SEARCH_SOURCES_TO_QUERY = 10 # max sources queried per search
+SUPER_SEARCH_PROJECTION_DIM = 64 # feature-hashing / random-projection dimension
+SUPER_SEARCH_PROFILE_DECAY = 0.1 # decaying-mean weight for per-site content profiles
+SUPER_SEARCH_EXPLORE_FLOOR = 2 # guaranteed exploration slots per search
+SUPER_SEARCH_TS_EXPLORE_SCALE = 1.0 # Thompson-sampling posterior-covariance multiplier (nu)
+SUPER_SEARCH_TS_PRIOR_PRECISION = 1.0 # ridge prior precision (lambda); A0 = lambda*I
+SUPER_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 vectors
+SUPER_SEARCH_USE_BANDIT = False # False = cosine-top-10 baseline; True = Thompson sampling
diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.py
index 558546c..3d9db7d 100644
--- a/mwmbl/tinysearchengine/super_search.py
+++ b/mwmbl/tinysearchengine/super_search.py
@@ -45,6 +45,14 @@ 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 bandit as ss_bandit
+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_rewards,
+ log_impression,
+)
from mwmbl.tokenizer import tokenize
logger = logging.getLogger(__name__)
@@ -84,6 +92,14 @@ 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
#
@@ -467,10 +483,30 @@ async def _index_results(query: str, docs: list[Document]) -> int:
return 0
+async def _record_rewards(query: str, ctx: SelectionContext, last_results_key: list) -> None:
+ """Compute implicit per-source rewards from the final top-K and log the impression."""
+ if not ctx.selected:
+ return
+ 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, query, ctx, rewards)
+ except Exception:
+ logger.exception("super-search failed to record rewards")
+ if getattr(settings, "SUPER_SEARCH_USE_BANDIT", False):
+ try:
+ await asyncio.to_thread(ss_bandit.update, ctx.features, rewards)
+ except Exception:
+ logger.exception("super-search failed to update bandit")
+
+
async def _run_pipeline(
- query: str, emit, all_docs: list[Document], last_results_key: list, lock: asyncio.Lock
+ query: str, emit, all_docs: list[Document], last_results_key: list, lock: asyncio.Lock,
+ ctx: SelectionContext,
) -> 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)
@@ -502,11 +538,20 @@ async def _run_pipeline(
follow_redirects=True,
headers={"User-Agent": HTTP_USER_AGENT},
) as client:
+ # Select a subset of sources to query (cosine/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, fn in SOURCES.items():
+ for name in selected:
await emit("source_started", SourceStartedEvent(source=name))
source_tasks.append(
- asyncio.create_task(_call_source(name, fn, client, query, per_source_limit))
+ asyncio.create_task(_call_source(name, SOURCES[name], client, query, per_source_limit))
)
secondary: list[asyncio.Task] = []
@@ -520,6 +565,12 @@ 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:
@@ -551,6 +602,7 @@ 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()
async def emit(event_type: str, data: Any) -> None:
await queue.put((event_type, data))
@@ -559,7 +611,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),
+ _run_pipeline(query, emit, all_docs, last_results_key, results_lock, selection_ctx),
timeout=settings.SUPER_SEARCH_DEADLINE_SECONDS,
)
except asyncio.TimeoutError:
@@ -578,6 +630,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):
except Exception:
logger.exception("super-search failed to emit final results")
pages_indexed = await _index_results(query, all_docs)
+ await _record_rewards(query, selection_ctx, last_results_key)
await queue.put(_SENTINEL)
task = asyncio.create_task(producer())
diff --git a/mwmbl/tinysearchengine/super_search_select/__init__.py b/mwmbl/tinysearchengine/super_search_select/__init__.py
new file mode 100644
index 0000000..c633e3f
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/__init__.py
@@ -0,0 +1,15 @@
+"""Source selection for Super Search.
+
+With ~100 registered sources, querying every one per search is too slow and
+expensive. This package selects a small subset (~10) to query, using a
+contextual bandit whose strongest features are the cosine similarity between the
+query and each site's accumulated content profile (bag-of-words and character
+n-grams, hashed/random-projected, cached in Redis).
+
+Modules:
+- ``vectors`` — feature-hashing projection, stop-words, char n-grams, cosine.
+- ``profiles`` — per-site content-profile read/update in Redis.
+- ``features`` — build the context feature vector for a (query, site) pair.
+- ``bandit`` — linear-Gaussian Thompson sampling policy (select / update).
+- ``registry`` — site metadata (field, popularity, domain) for features/priors.
+"""
diff --git a/mwmbl/tinysearchengine/super_search_select/bandit.py b/mwmbl/tinysearchengine/super_search_select/bandit.py
new file mode 100644
index 0000000..cbe64d0
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/bandit.py
@@ -0,0 +1,134 @@
+"""Per-arm linear-Gaussian Thompson sampling for source selection.
+
+Each source (arm) keeps Bayesian linear-regression sufficient statistics over
+the context features: ``A = lambda*I + sum(x x^T)`` and ``b = sum(r x)``. The
+posterior over the weight vector is ``N(A^-1 b, sigma^2 A^-1)``; Thompson
+sampling draws ``theta ~ N(A^-1 b, nu^2 sigma^2 A^-1)`` and scores a candidate by
+``theta . x``. An unseen arm has ``A = lambda*I`` (high posterior variance), so
+it is explored automatically — no separate cold-start logic needed.
+
+State lives in Redis as raw float32 blobs (binary-safe connection), updated at
+request completion and (separately) persisted to Postgres for durability.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+import redis
+from django.conf import settings
+
+from mwmbl.tinysearchengine.super_search_select.features import NUM_FEATURES
+
+_KEY_A = "ss:bandit:A:{site}"
+_KEY_B = "ss:bandit:b:{site}"
+_A_PREFIX = "ss:bandit:A:"
+
+_redis: redis.Redis | None = None
+
+
+def _get_redis() -> redis.Redis:
+ global _redis
+ if _redis is None:
+ _redis = redis.from_url(settings.REDIS_URL)
+ return _redis
+
+
+@dataclass
+class ArmState:
+ A: np.ndarray # (d, d) precision matrix
+ b: np.ndarray # (d,) weighted-response vector
+
+
+def prior_state(d: int = NUM_FEATURES) -> ArmState:
+ """Ridge prior: A = lambda*I, b = 0 (posterior mean 0, wide covariance)."""
+ lam = settings.SUPER_SEARCH_TS_PRIOR_PRECISION
+ return ArmState(A=lam * np.eye(d, dtype=np.float64), b=np.zeros(d, dtype=np.float64))
+
+
+def _decode_state(raw_a: bytes | None, raw_b: bytes | None, d: int) -> ArmState:
+ if not raw_a or not raw_b:
+ return prior_state(d)
+ A = np.frombuffer(raw_a, dtype=np.float64).reshape(d, d).copy()
+ b = np.frombuffer(raw_b, dtype=np.float64).copy()
+ return ArmState(A=A, b=b)
+
+
+def get_states(sites: list[str], d: int = NUM_FEATURES) -> dict[str, ArmState]:
+ """Batch-load arm states for many sites (prior for any unseen arm)."""
+ if not sites:
+ return {}
+ r = _get_redis()
+ keys = [_KEY_A.format(site=s) for s in sites] + [_KEY_B.format(site=s) for s in sites]
+ raw = r.mget(keys)
+ n = len(sites)
+ return {site: _decode_state(raw[i], raw[n + i], d) for i, site in enumerate(sites)}
+
+
+def save_states(states: dict[str, ArmState]) -> None:
+ pipe = _get_redis().pipeline()
+ for site, state in states.items():
+ pipe.set(_KEY_A.format(site=site), state.A.astype(np.float64).tobytes())
+ pipe.set(_KEY_B.format(site=site), state.b.astype(np.float64).tobytes())
+ pipe.execute()
+
+
+def sample_score(state: ArmState, x: np.ndarray, rng: np.random.Generator) -> float:
+ """Thompson sample: draw theta from the posterior and score ``theta . x``."""
+ A_inv = np.linalg.inv(state.A)
+ mean = A_inv @ state.b
+ nu = settings.SUPER_SEARCH_TS_EXPLORE_SCALE
+ sigma2 = settings.SUPER_SEARCH_TS_NOISE_VARIANCE
+ cov = (nu * nu * sigma2) * A_inv
+ # Symmetrise to guard against tiny asymmetries from the inverse.
+ cov = 0.5 * (cov + cov.T)
+ theta = rng.multivariate_normal(mean, cov)
+ return float(theta @ x)
+
+
+def update_arm(state: ArmState, x: np.ndarray, reward: float) -> ArmState:
+ """Rank-1 Bayesian update: A += x x^T, b += reward * x."""
+ state.A += np.outer(x, x)
+ state.b += reward * x
+ return state
+
+
+def all_sites() -> list[str]:
+ """Names of every arm with state in Redis (used by the persistence task)."""
+ r = _get_redis()
+ sites = []
+ for key in r.scan_iter(match=_A_PREFIX + "*"):
+ k = key.decode() if isinstance(key, (bytes, bytearray)) else key
+ sites.append(k[len(_A_PREFIX):])
+ return sites
+
+
+def export_all() -> dict[str, ArmState]:
+ """Load every arm's state (for Redis -> Postgres persistence)."""
+ return get_states(all_sites())
+
+
+def seed_states(states: dict[str, ArmState], overwrite: bool = False) -> None:
+ """Write states to Redis. With ``overwrite=False`` only fills missing keys
+ (used to restore from Postgres without clobbering newer live state)."""
+ pipe = _get_redis().pipeline()
+ for site, state in states.items():
+ pipe.set(_KEY_A.format(site=site), state.A.astype(np.float64).tobytes(), nx=not overwrite)
+ pipe.set(_KEY_B.format(site=site), state.b.astype(np.float64).tobytes(), nx=not overwrite)
+ pipe.execute()
+
+
+def update(features: dict[str, list[float]], rewards: dict[str, float]) -> None:
+ """Apply observed rewards to the selected arms and persist the new states.
+
+ ``features`` are the feature vectors used at selection time (so the update is
+ consistent with the action), keyed by source.
+ """
+ sites = [s for s in rewards if s in features]
+ if not sites:
+ return
+ states = get_states(sites)
+ for site in sites:
+ x = np.asarray(features[site], dtype=np.float64)
+ update_arm(states[site], x, rewards[site])
+ save_states(states)
diff --git a/mwmbl/tinysearchengine/super_search_select/evaluation.py b/mwmbl/tinysearchengine/super_search_select/evaluation.py
new file mode 100644
index 0000000..3f8a6c1
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/evaluation.py
@@ -0,0 +1,214 @@
+"""Offline evaluation for source selection: feature selection + policy simulation.
+
+Everything is driven by a dense reward matrix (queries x sources): the feature
+vector ``X[q, s]`` each (query, source) pair was/​would be scored on, the implicit
+reward ``R[q, s]`` (fraction of that source's results surviving into the final
+top-K), and a ``mask`` of which sources actually returned anything.
+
+With every cell filled we can, without any online traffic:
+ * select features — fit an XGBoost reward model (grouped CV by query) and
+ rank/ablate features by held-out recall@k;
+ * simulate the policy — replay linear-Gaussian Thompson sampling over the
+ matrix, sweep the exploration scale ``nu``, and compare against baselines
+ (random / popularity / cosine / oracle).
+
+This module is pure (numpy/sklearn/xgboost only); building the matrix from live
+sources lives in ``scripts/super_search_eval.py``.
+"""
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+
+import numpy as np
+
+from mwmbl.tinysearchengine.super_search_select.features import FEATURE_NAMES
+
+
+@dataclass
+class RewardMatrix:
+ queries: list[str]
+ sources: list[str]
+ feature_names: list[str]
+ X: np.ndarray # (Q, S, F) features
+ R: np.ndarray # (Q, S) reward in [0, 1]
+ mask: np.ndarray # (Q, S) bool: source returned results for the query
+
+ def save(self, path: str | Path) -> None:
+ path = Path(path)
+ np.savez_compressed(path.with_suffix(".npz"), X=self.X, R=self.R, mask=self.mask)
+ path.with_suffix(".json").write_text(json.dumps({
+ "queries": self.queries,
+ "sources": self.sources,
+ "feature_names": self.feature_names,
+ }))
+
+ @classmethod
+ def load(cls, path: str | Path) -> "RewardMatrix":
+ path = Path(path)
+ arrs = np.load(path.with_suffix(".npz"))
+ meta = json.loads(path.with_suffix(".json").read_text())
+ return cls(
+ queries=meta["queries"], sources=meta["sources"],
+ feature_names=meta["feature_names"],
+ X=arrs["X"], R=arrs["R"], mask=arrs["mask"],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Metrics
+# ---------------------------------------------------------------------------
+
+def coverage_at_k(scores: np.ndarray, R: np.ndarray, mask: np.ndarray, k: int) -> float:
+ """Mean (over queries) reward captured by the top-k scored sources, relative
+ to the oracle top-k. 1.0 = picked the best possible k every time."""
+ Q = R.shape[0]
+ total = 0.0
+ n = 0
+ for q in range(Q):
+ avail = np.where(mask[q])[0]
+ if avail.size == 0:
+ continue
+ oracle = np.sort(R[q, avail])[::-1][:k].sum()
+ if oracle <= 0:
+ continue
+ order = avail[np.argsort(scores[q, avail])[::-1][:k]]
+ total += R[q, order].sum() / oracle
+ n += 1
+ return total / n if n else 0.0
+
+
+# ---------------------------------------------------------------------------
+# Feature selection (XGBoost, grouped CV by query)
+# ---------------------------------------------------------------------------
+
+def _flatten(matrix: RewardMatrix, feature_idx: list[int]):
+ """Flatten masked (query, source) cells into (X, y, groups) for sklearn."""
+ Q, S, _ = matrix.X.shape
+ rows, ys, groups = [], [], []
+ for q in range(Q):
+ for s in range(S):
+ if matrix.mask[q, s]:
+ rows.append(matrix.X[q, s, feature_idx])
+ ys.append(matrix.R[q, s])
+ groups.append(q)
+ return np.array(rows), np.array(ys), np.array(groups)
+
+
+def _cell_index(matrix: RewardMatrix) -> list[tuple[int, int]]:
+ """The (query, source) cell behind each flattened masked row, in order."""
+ return [(q, s)
+ for q in range(matrix.X.shape[0])
+ for s in range(matrix.X.shape[1])
+ if matrix.mask[q, s]]
+
+
+def evaluate_feature_set(matrix: RewardMatrix, feature_idx: list[int], k: int = 10,
+ n_splits: int = 5, seed: int = 0) -> dict:
+ """Grouped CV (by query): train XGBoost on the chosen features, scatter the
+ out-of-fold predictions to the (query, source) grid, and report held-out
+ coverage@k and RMSE."""
+ from sklearn.model_selection import GroupKFold
+ from xgboost import XGBRegressor
+
+ X, y, groups = _flatten(matrix, feature_idx)
+ cells = _cell_index(matrix)
+ pred = np.full(matrix.R.shape, -np.inf) # unmasked cells stay unselectable
+ rmses = []
+ gkf = GroupKFold(n_splits=min(n_splits, len(set(groups))))
+ for train, test in gkf.split(X, y, groups):
+ model = XGBRegressor(n_estimators=200, max_depth=4, learning_rate=0.1,
+ subsample=0.8, random_state=seed)
+ model.fit(X[train], y[train])
+ p = model.predict(X[test])
+ rmses.append(float(np.sqrt(np.mean((p - y[test]) ** 2))))
+ for j, i in enumerate(test):
+ q, s = cells[i]
+ pred[q, s] = p[j]
+ return {
+ "coverage_at_k": coverage_at_k(pred, matrix.R, matrix.mask, k),
+ "rmse": float(np.mean(rmses)),
+ }
+
+
+def select_features(matrix: RewardMatrix, k: int = 10, seed: int = 0) -> dict:
+ """Backward ablation: full-set coverage@k plus each feature's drop when removed
+ (positive drop => the feature helps held-out selection)."""
+ all_idx = list(range(len(matrix.feature_names)))
+ base = evaluate_feature_set(matrix, all_idx, k, seed=seed)["coverage_at_k"]
+ ablation = {}
+ for i, name in enumerate(matrix.feature_names):
+ reduced = [j for j in all_idx if j != i]
+ if not reduced:
+ continue
+ cov = evaluate_feature_set(matrix, reduced, k, seed=seed)["coverage_at_k"]
+ ablation[name] = base - cov
+ return {"baseline_coverage": base, "ablation_drop": ablation}
+
+
+# ---------------------------------------------------------------------------
+# Policy simulation
+# ---------------------------------------------------------------------------
+
+def simulate_ts(matrix: RewardMatrix, k: int, nu: float, sigma2: float = 0.25,
+ lam: float = 1.0, seed: int = 0) -> float:
+ """Replay linear-Gaussian Thompson sampling; return mean per-query captured reward."""
+ rng = np.random.default_rng(seed)
+ Q, S, F = matrix.X.shape
+ A = np.stack([lam * np.eye(F) for _ in range(S)])
+ b = np.zeros((S, F))
+ captured = 0.0
+ for q in range(Q):
+ avail = np.where(matrix.mask[q])[0]
+ if avail.size == 0:
+ continue
+ scores = np.full(S, -np.inf)
+ for s in avail:
+ A_inv = np.linalg.inv(A[s])
+ mean = A_inv @ b[s]
+ cov = (nu * nu * sigma2) * A_inv
+ theta = rng.multivariate_normal(mean, 0.5 * (cov + cov.T))
+ scores[s] = theta @ matrix.X[q, s]
+ chosen = avail[np.argsort(scores[avail])[::-1][:k]]
+ for s in chosen:
+ x = matrix.X[q, s]
+ A[s] += np.outer(x, x)
+ b[s] += matrix.R[q, s] * x
+ captured += matrix.R[q, s]
+ return captured / Q
+
+
+def simulate_baselines(matrix: RewardMatrix, k: int, seed: int = 0) -> dict:
+ """Mean per-query captured reward for static baselines and the oracle."""
+ rng = np.random.default_rng(seed)
+ Q = matrix.X.shape[0]
+ names = matrix.feature_names
+ cos_i = names.index("cos_bow") if "cos_bow" in names else None
+ pop_i = names.index("popularity") if "popularity" in names else None
+
+ def run(score_fn) -> float:
+ total = 0.0
+ for q in range(Q):
+ avail = np.where(matrix.mask[q])[0]
+ if avail.size == 0:
+ continue
+ chosen = score_fn(q, avail)[:k]
+ total += matrix.R[q, chosen].sum()
+ return total / Q
+
+ out = {
+ "oracle": run(lambda q, a: a[np.argsort(matrix.R[q, a])[::-1]]),
+ "random": run(lambda q, a: rng.permutation(a)),
+ }
+ if cos_i is not None:
+ out["cosine"] = run(lambda q, a: a[np.argsort(matrix.X[q, a, cos_i])[::-1]])
+ if pop_i is not None:
+ out["popularity"] = run(lambda q, a: a[np.argsort(matrix.X[q, a, pop_i])[::-1]])
+ return out
+
+
+def sweep_explore_scale(matrix: RewardMatrix, k: int, nus: list[float],
+ sigma2: float = 0.25, lam: float = 1.0, seed: int = 0) -> dict[float, float]:
+ """Mean captured reward for each candidate exploration scale ``nu``."""
+ return {nu: simulate_ts(matrix, k, nu, sigma2, lam, seed) for nu in nus}
diff --git a/mwmbl/tinysearchengine/super_search_select/features.py b/mwmbl/tinysearchengine/super_search_select/features.py
new file mode 100644
index 0000000..995dbc3
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/features.py
@@ -0,0 +1,100 @@
+"""Context features for the (query, site) source-selection decision.
+
+``feature_vector`` returns a fixed-length numpy array whose ordering matches
+``FEATURE_NAMES``; the same vector feeds both the greedy cosine baseline
+(Phase 2) and the contextual bandit (Phase 4). The headline features are the
+query-vs-site-profile cosines (``cos_bow`` / ``cos_cng``); the rest are site
+priors, online per-site stats, and cheap query-shape signals. Which features
+actually earn their keep is decided by the offline evaluation (Phase 5).
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+import numpy as np
+from django.conf import settings
+
+from mwmbl.tinysearchengine.super_search_select import vectors
+from mwmbl.tinysearchengine.super_search_select.registry import SiteMeta
+
+# Stable feature order. ``bias`` is the per-arm intercept (lets the bandit learn
+# a site's base success rate even with all-zero context).
+FEATURE_NAMES = [
+ "bias",
+ "cos_bow",
+ "cos_cng",
+ "popularity",
+ "estimated_pages",
+ "contribution_ema",
+ "latency_penalty",
+ "failure_rate",
+ "query_len",
+ "has_code_token",
+]
+NUM_FEATURES = len(FEATURE_NAMES)
+
+# Tokens that look like code / identifiers — a cheap signal that programming
+# sources are more likely relevant. Checked against the raw (un-lowercased) query.
+_CODE_RE = re.compile(r"[_/{}();]|::|->|[a-z][A-Z]|\.\w")
+
+
+@dataclass
+class QueryContext:
+ """Per-query, site-independent context, computed once per search."""
+ bow: np.ndarray
+ cng: np.ndarray
+ n_tokens: int
+ has_code_token: bool
+
+ @classmethod
+ def build(cls, query: str, bow: np.ndarray, cng: np.ndarray) -> "QueryContext":
+ return cls(
+ bow=bow,
+ cng=cng,
+ n_tokens=len(query.split()),
+ has_code_token=bool(_CODE_RE.search(query)),
+ )
+
+
+@dataclass
+class SiteStats:
+ """Online per-site stats used as features (read from Redis; defaults for cold sites)."""
+ contribution_ema: float = 0.0 # mean fraction of results surviving into top-K
+ latency_ema: float = 0.0 # mean response time, seconds
+ failure_rate: float = 0.0 # fraction of recent queries that errored/timed out
+
+
+def feature_vector(
+ qctx: QueryContext,
+ meta: SiteMeta,
+ profile: tuple[np.ndarray | None, np.ndarray | None],
+ stats: SiteStats | None = None,
+) -> np.ndarray:
+ """Build the context feature vector for one (query, site) pair."""
+ stats = stats or SiteStats()
+ bow_profile, cng_profile = profile
+ timeout = settings.SUPER_SEARCH_PER_SOURCE_TIMEOUT or 1.0
+ x = np.array([
+ 1.0, # bias
+ vectors.cosine(qctx.bow, bow_profile), # cos_bow
+ vectors.cosine(qctx.cng, cng_profile), # cos_cng
+ meta.popularity, # popularity
+ meta.estimated_pages, # estimated_pages
+ stats.contribution_ema, # contribution_ema
+ min(stats.latency_ema / timeout, 1.0), # latency_penalty (0..1)
+ stats.failure_rate, # failure_rate
+ min(qctx.n_tokens, 10) / 10.0, # query_len (normalised)
+ 1.0 if qctx.has_code_token else 0.0, # has_code_token
+ ], dtype=np.float64)
+ return x
+
+
+def cosine_relevance(qctx: QueryContext, profile: tuple[np.ndarray | None, np.ndarray | None]) -> float:
+ """Greedy relevance score for the Phase-2 baseline: blended query-vs-profile cosine.
+
+ Char n-grams are weighted lower; they mainly help on morphology / rare tokens
+ where whole-word BoW misses. A site with no profile yet scores 0 (cold).
+ """
+ bow_profile, cng_profile = profile
+ return 0.7 * vectors.cosine(qctx.bow, bow_profile) + 0.3 * vectors.cosine(qctx.cng, cng_profile)
diff --git a/mwmbl/tinysearchengine/super_search_select/policy.py b/mwmbl/tinysearchengine/super_search_select/policy.py
new file mode 100644
index 0000000..83f99cf
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/policy.py
@@ -0,0 +1,117 @@
+"""Source-selection policy: pick which ~10 of ~100 sources to query.
+
+Two interchangeable scorings over the same context features:
+
+- **cosine baseline** (default): greedy query-vs-profile cosine, with a few
+ reserved slots for cold sites so new sources are discovered.
+- **Thompson sampling** (``SUPER_SEARCH_USE_BANDIT``): per-arm linear-Gaussian
+ posterior sampling, which explores cold arms automatically via their wide
+ posterior.
+
+Either way the always-on global sources (own index, HN) are included for free,
+and the feature vectors used for the decision are stashed on the
+``SelectionContext`` so the bandit update at request completion is consistent
+with the action taken.
+"""
+from __future__ import annotations
+
+import random
+
+import numpy as np
+from django.conf import settings
+
+from mwmbl.tinysearchengine.super_search_select import bandit, profiles
+from mwmbl.tinysearchengine.super_search_select.features import (
+ QueryContext,
+ SiteStats,
+ cosine_relevance,
+ feature_vector,
+)
+from mwmbl.tinysearchengine.super_search_select.registry import get_meta
+from mwmbl.tinysearchengine.super_search_select.rewards import SelectionContext
+
+
+def select_sources(
+ query: str,
+ source_names: list[str],
+ k: int | None = None,
+ ctx: SelectionContext | None = None,
+) -> list[str]:
+ """Return up to ``k`` source names to query for ``query``.
+
+ If ``ctx`` is given, the feature vector each selected source was scored on is
+ recorded in ``ctx.features`` for a consistent bandit update later.
+ """
+ if k is None:
+ k = settings.SUPER_SEARCH_SOURCES_TO_QUERY
+ if len(source_names) <= k:
+ if ctx is not None:
+ _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)
+ if budget == 0:
+ chosen = always_on[:k]
+ if ctx is not None:
+ _record_features(ctx, query, chosen)
+ return chosen
+
+ bow, cng = profiles.get_query_vectors(query)
+ qctx = QueryContext.build(query, bow, cng)
+ profs = profiles.get_profiles(selectable)
+ feats = {n: feature_vector(qctx, get_meta(n), profs[n]) for n in selectable}
+
+ if settings.SUPER_SEARCH_USE_BANDIT:
+ chosen = _select_bandit(selectable, feats, budget)
+ else:
+ chosen = _select_cosine(qctx, selectable, profs, budget)
+
+ if ctx is not None:
+ for name in always_on + 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.
+ ctx.features[name] = feature_vector(
+ qctx, get_meta(name), profs.get(name, (None, None))
+ ).tolist()
+
+ return always_on + chosen
+
+
+def _select_cosine(qctx, selectable, profs, budget) -> list[str]:
+ warm = [n for n in selectable if profs[n][0] is not None]
+ cold = [n for n in selectable if profs[n][0] is None]
+ explore_n = min(getattr(settings, "SUPER_SEARCH_EXPLORE_FLOOR", 0), len(cold), budget)
+ exploit_n = budget - explore_n
+ warm.sort(key=lambda n: cosine_relevance(qctx, profs[n]), reverse=True)
+ chosen = warm[:exploit_n]
+ chosen += random.sample(cold, explore_n) if explore_n else []
+ if len(chosen) < budget:
+ remaining = [n for n in warm[exploit_n:] + cold if n not in set(chosen)]
+ chosen += remaining[: budget - len(chosen)]
+ return chosen
+
+
+def _select_bandit(selectable, feats, budget) -> list[str]:
+ rng = np.random.default_rng()
+ states = bandit.get_states(selectable)
+ scored = sorted(
+ selectable,
+ key=lambda n: bandit.sample_score(states[n], np.asarray(feats[n]), rng),
+ reverse=True,
+ )
+ return scored[:budget]
+
+
+def _record_features(ctx: SelectionContext, query: str, names: list[str]) -> None:
+ """Compute and stash feature vectors for ``names`` (small-fanout / all-selected case)."""
+ bow, cng = profiles.get_query_vectors(query)
+ qctx = QueryContext.build(query, bow, cng)
+ profs = profiles.get_profiles(names)
+ for name in names:
+ ctx.features[name] = feature_vector(
+ qctx, get_meta(name), profs.get(name, (None, None)), SiteStats()
+ ).tolist()
diff --git a/mwmbl/tinysearchengine/super_search_select/profiles.py b/mwmbl/tinysearchengine/super_search_select/profiles.py
new file mode 100644
index 0000000..d168050
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/profiles.py
@@ -0,0 +1,105 @@
+"""Per-site content profiles and query-vector caching in Redis.
+
+A *content profile* is a decaying mean of the projected vectors of the results a
+site returns; it summarises "what this site tends to surface" and is the
+site-side half of the query-vs-site cosine feature. It is updated every time the
+site is queried (``update_profile``), so it sharpens as the site is used more.
+
+Vectors are stored as raw float32 bytes, so this module uses its own
+binary-safe Redis connection (the shared client in ``search_setup`` /
+``super_search`` uses ``decode_responses=True``, which would corrupt bytes).
+"""
+from __future__ import annotations
+
+import numpy as np
+import redis
+from django.conf import settings
+
+from mwmbl.tinysearchengine.indexer import Document
+from mwmbl.tinysearchengine.super_search_select import vectors
+
+_PROFILE_BOW = "ss:profile:bow:{site}"
+_PROFILE_CNG = "ss:profile:cng:{site}"
+_QVEC_BOW = "ss:qvec:bow:{key}"
+_QVEC_CNG = "ss:qvec:cng:{key}"
+
+_redis: redis.Redis | None = None
+
+
+def _get_redis() -> redis.Redis:
+ """Binary-safe Redis connection (decode_responses defaults to False)."""
+ global _redis
+ if _redis is None:
+ _redis = redis.from_url(settings.REDIS_URL)
+ return _redis
+
+
+def _dim() -> int:
+ return settings.SUPER_SEARCH_PROJECTION_DIM
+
+
+def sample_text(docs: list[Document]) -> str:
+ """Concatenate titles + extracts of a result sample into one text blob."""
+ return " ".join(f"{d.title or ''} {d.extract or ''}" for d in docs)
+
+
+def _blend(old: np.ndarray | None, sample: np.ndarray, decay: float) -> np.ndarray:
+ if old is None:
+ return sample
+ return vectors._l2_normalise((1.0 - decay) * old + decay * sample)
+
+
+def get_profile(site: str) -> tuple[np.ndarray | None, np.ndarray | None]:
+ """Return ``(bow_profile, cng_profile)`` for a site, or ``(None, None)`` if unseen."""
+ r = _get_redis()
+ bow = vectors.from_bytes(r.get(_PROFILE_BOW.format(site=site)))
+ cng = vectors.from_bytes(r.get(_PROFILE_CNG.format(site=site)))
+ return bow, cng
+
+
+def get_profiles(sites: list[str]) -> dict[str, tuple[np.ndarray | None, np.ndarray | None]]:
+ """Batch fetch ``(bow, cng)`` profiles for many sites in a single round-trip."""
+ if not sites:
+ return {}
+ r = _get_redis()
+ keys = [_PROFILE_BOW.format(site=s) for s in sites] + [_PROFILE_CNG.format(site=s) for s in sites]
+ raw = r.mget(keys)
+ n = len(sites)
+ return {
+ site: (vectors.from_bytes(raw[i]), vectors.from_bytes(raw[n + i]))
+ for i, site in enumerate(sites)
+ }
+
+
+def update_profile(site: str, docs: list[Document]) -> None:
+ """Fold a result sample into the site's decaying-mean content profile."""
+ if not docs:
+ return
+ text = sample_text(docs)
+ dim, decay = _dim(), settings.SUPER_SEARCH_PROFILE_DECAY
+ bow_old, cng_old = get_profile(site)
+ bow_new = _blend(bow_old, vectors.project_bow(text, dim), decay)
+ cng_new = _blend(cng_old, vectors.project_char_ngrams(text, dim), decay)
+ pipe = _get_redis().pipeline()
+ pipe.set(_PROFILE_BOW.format(site=site), vectors.to_bytes(bow_new))
+ pipe.set(_PROFILE_CNG.format(site=site), vectors.to_bytes(cng_new))
+ pipe.execute()
+
+
+def get_query_vectors(query: str) -> tuple[np.ndarray, np.ndarray]:
+ """Projected ``(bow, cng)`` vectors for a query, cached in Redis with a TTL."""
+ key = vectors.query_cache_key(query)
+ dim = _dim()
+ r = _get_redis()
+ bow = vectors.from_bytes(r.get(_QVEC_BOW.format(key=key)))
+ cng = vectors.from_bytes(r.get(_QVEC_CNG.format(key=key)))
+ if bow is not None and cng is not None:
+ return bow, cng
+ bow = vectors.project_bow(query, dim)
+ cng = vectors.project_char_ngrams(query, dim)
+ ttl = settings.SUPER_SEARCH_QVEC_CACHE_TTL
+ pipe = r.pipeline()
+ pipe.set(_QVEC_BOW.format(key=key), vectors.to_bytes(bow), ex=ttl)
+ pipe.set(_QVEC_CNG.format(key=key), vectors.to_bytes(cng), ex=ttl)
+ pipe.execute()
+ return bow, cng
diff --git a/mwmbl/tinysearchengine/super_search_select/registry.py b/mwmbl/tinysearchengine/super_search_select/registry.py
new file mode 100644
index 0000000..c3320a4
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/registry.py
@@ -0,0 +1,100 @@
+"""Per-site metadata for Super Search source selection.
+
+Joins each registered source with metadata used as bandit features and
+cold-start priors: its ``field`` (category), ``domain``, and a numeric
+popularity / estimated-pages prior taken from the curated shortlist
+(``devdata/super-search-shortlist.json``).
+
+Recipe sources carry ``domain``/``field`` directly (parsed by ``recipe.py``);
+the handful of hand-written Python adapters have static metadata here. The
+shortlist supplies popularity / page-count priors by domain.
+"""
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+
+from django.conf import settings
+
+logger = logging.getLogger(__name__)
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+_DEFAULT_SHORTLIST = _REPO_ROOT / "devdata" / "super-search-shortlist.json"
+
+# Map the shortlist's ordinal levels to a numeric prior in [0, 1].
+LEVEL_SCORE = {"high": 1.0, "medium": 0.6, "low": 0.3}
+_DEFAULT_SCORE = 0.6
+
+
+@dataclass(frozen=True)
+class SiteMeta:
+ name: str # source key in SOURCES
+ domain: str
+ field: str = "other"
+ popularity: float = _DEFAULT_SCORE
+ estimated_pages: float = _DEFAULT_SCORE
+ always_on: bool = False # global sources always included in selection
+
+
+# Hand-written adapters: not in the shortlist (or special/global), so metadata is static.
+_STATIC_META: dict[str, SiteMeta] = {
+ "mwmbl": SiteMeta("mwmbl", "mwmbl.org", "other", 1.0, 1.0, always_on=True),
+ "hn": SiteMeta("hn", "news.ycombinator.com", "tech", 1.0, 0.6, always_on=True),
+ "github": SiteMeta("github", "github.com", "programming", 1.0, 1.0),
+ "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),
+}
+
+
+def _shortlist_path() -> Path:
+ return Path(getattr(settings, "SUPER_SEARCH_SHORTLIST_PATH", _DEFAULT_SHORTLIST))
+
+
+@lru_cache(maxsize=1)
+def _load_shortlist() -> dict[str, dict]:
+ """Map domain -> shortlist entry. Missing file -> empty (defaults are used)."""
+ path = _shortlist_path()
+ try:
+ data = json.loads(path.read_text())
+ except (OSError, ValueError) as e:
+ logger.warning("Could not load Super Search shortlist %s: %s", path, e)
+ return {}
+ return {entry["name"]: entry for entry in data.get("domains", [])}
+
+
+@lru_cache(maxsize=1)
+def get_registry() -> dict[str, SiteMeta]:
+ """Build metadata for every registered source, keyed by source name.
+
+ Imported lazily to avoid a circular import with ``super_search_sources``.
+ """
+ from mwmbl.tinysearchengine.super_search_sources.recipe import load_recipes
+
+ registry: dict[str, SiteMeta] = dict(_STATIC_META)
+ shortlist = _load_shortlist()
+ for name, recipe in load_recipes().items():
+ if name in registry:
+ continue
+ entry = shortlist.get(recipe.domain, {})
+ registry[name] = SiteMeta(
+ name=name,
+ domain=recipe.domain,
+ field=recipe.field or "other",
+ popularity=LEVEL_SCORE.get(entry.get("popularity"), _DEFAULT_SCORE),
+ estimated_pages=LEVEL_SCORE.get(entry.get("estimated_pages"), _DEFAULT_SCORE),
+ )
+ return registry
+
+
+def get_meta(name: str) -> SiteMeta:
+ """Metadata for ``name``, with a safe default for unknown sources."""
+ return get_registry().get(name, SiteMeta(name=name, domain=name))
+
+
+def all_fields() -> list[str]:
+ """Sorted unique field labels across the registry (for one-hot/field features)."""
+ return sorted({m.field for m in get_registry().values()})
diff --git a/mwmbl/tinysearchengine/super_search_select/rewards.py b/mwmbl/tinysearchengine/super_search_select/rewards.py
new file mode 100644
index 0000000..c7b0270
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/rewards.py
@@ -0,0 +1,66 @@
+"""Implicit reward and impression logging for source selection.
+
+The reward for a queried source is the fraction of its results that survive into
+the final LTR-ranked top-K — a self-contained "did this source contribute"
+signal needing no click logging. ``SelectionContext`` carries the per-request
+state (which sources were selected, and which URL came from which source) from
+the pipeline to the completion hook, where ``compute_rewards`` and
+``log_impression`` run.
+"""
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+
+from django.conf import settings
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class SelectionContext:
+ """Per-request selection state, populated as the pipeline runs."""
+ candidates: list[str] = field(default_factory=list) # full action space
+ selected: list[str] = field(default_factory=list) # sources actually queried
+ source_by_url: dict[str, str] = field(default_factory=dict) # url -> originating source
+ features: dict[str, list[float]] = field(default_factory=dict) # source -> feature vector
+ per_source_limit: int = 0
+
+ def record_results(self, source: str, urls: list[str]) -> None:
+ """Note the URLs a source returned (first source to produce a URL wins)."""
+ for url in urls:
+ self.source_by_url.setdefault(url, source)
+
+
+def compute_rewards(ctx: SelectionContext, final_top_k_urls: list[str]) -> dict[str, float]:
+ """Reward per selected source = fraction of its results in the final top-K.
+
+ Normalised by ``per_source_limit`` so a source returning many top-K results
+ scores near 1.0 and one returning none scores 0.0. Every selected source gets
+ an entry (0.0 if it contributed nothing) — the bandit needs the zeros too.
+ """
+ limit = max(ctx.per_source_limit, 1)
+ rewards = {name: 0.0 for name in ctx.selected}
+ for url in final_top_k_urls:
+ source = ctx.source_by_url.get(url)
+ if source in rewards:
+ rewards[source] += 1.0 / limit
+ return {name: min(r, 1.0) for name, r in rewards.items()}
+
+
+def log_impression(query: str, ctx: SelectionContext, rewards: dict[str, float]) -> None:
+ """Persist a SuperSearchImpression row (no-op without a database)."""
+ if not getattr(settings, "HAS_DATABASE", False):
+ return
+ try:
+ from mwmbl.models import SuperSearchImpression
+
+ SuperSearchImpression.objects.create(
+ query=query[:512],
+ candidates=ctx.candidates,
+ selected=ctx.selected,
+ features=ctx.features,
+ rewards=rewards,
+ )
+ except Exception:
+ logger.exception("failed to log super-search impression")
diff --git a/mwmbl/tinysearchengine/super_search_select/vectors.py b/mwmbl/tinysearchengine/super_search_select/vectors.py
new file mode 100644
index 0000000..be4557e
--- /dev/null
+++ b/mwmbl/tinysearchengine/super_search_select/vectors.py
@@ -0,0 +1,116 @@
+"""Fixed-dimension text vectors for Super Search source selection.
+
+Bag-of-words and character n-gram vectors are compressed to a fixed dimension
+via *feature hashing* (the signed hashing trick). Feature hashing is itself a
+random projection, so we never store or load a projection matrix — the
+projection is defined entirely by the hash function (``mmh3``, already a project
+dependency), which makes it deterministic and reproducible across processes.
+
+Vectors are dense ``numpy`` float32 arrays, L2-normalised so cosine similarity
+is a plain dot product. ``to_bytes`` / ``from_bytes`` give a compact Redis
+representation.
+"""
+from __future__ import annotations
+
+import hashlib
+
+import mmh3
+import numpy as np
+
+from mwmbl.tokenizer import tokenize
+
+# A compact English stop-word list. Removing these stops common function words
+# from dominating the projected bag-of-words. (No stop-word list existed in the
+# repo; this is intentionally small and self-contained.)
+STOP_WORDS = frozenset({
+ "a", "about", "above", "after", "again", "all", "am", "an", "and", "any",
+ "are", "as", "at", "be", "because", "been", "before", "being", "below",
+ "between", "both", "but", "by", "can", "did", "do", "does", "doing", "down",
+ "during", "each", "few", "for", "from", "further", "had", "has", "have",
+ "having", "he", "her", "here", "hers", "herself", "him", "himself", "his",
+ "how", "i", "if", "in", "into", "is", "it", "its", "itself", "just", "me",
+ "more", "most", "my", "myself", "no", "nor", "not", "now", "of", "off",
+ "on", "once", "only", "or", "other", "our", "ours", "ourselves", "out",
+ "over", "own", "s", "same", "she", "should", "so", "some", "such", "t",
+ "than", "that", "the", "their", "theirs", "them", "themselves", "then",
+ "there", "these", "they", "this", "those", "through", "to", "too", "under",
+ "until", "up", "very", "was", "we", "were", "what", "when", "where",
+ "which", "while", "who", "whom", "why", "will", "with", "you", "your",
+ "yours", "yourself", "yourselves",
+})
+
+# Seeds for the two independent hashes used by the hashing trick: one picks the
+# bucket, the other picks the sign. Independent seeds keep index and sign
+# uncorrelated (a single hash split into index/sign couples the two).
+_INDEX_SEED = 0
+_SIGN_SEED = 1
+
+
+def _hash_token(token: str, dim: int) -> tuple[int, float]:
+ index = mmh3.hash(token, _INDEX_SEED, signed=False) % dim
+ sign = 1.0 if (mmh3.hash(token, _SIGN_SEED, signed=False) & 1) else -1.0
+ return index, sign
+
+
+def _l2_normalise(vec: np.ndarray) -> np.ndarray:
+ norm = float(np.linalg.norm(vec))
+ if norm > 0.0:
+ vec /= norm
+ return vec
+
+
+def _content_tokens(text: str, remove_stop_words: bool) -> list[str]:
+ tokens = tokenize(text or "")
+ if remove_stop_words:
+ tokens = [t for t in tokens if t not in STOP_WORDS]
+ return tokens
+
+
+def project_bow(text: str, dim: int, *, remove_stop_words: bool = True) -> np.ndarray:
+ """Project a bag-of-words of ``text`` into ``dim`` dimensions, L2-normalised."""
+ vec = np.zeros(dim, dtype=np.float32)
+ for token in _content_tokens(text, remove_stop_words):
+ index, sign = _hash_token(token, dim)
+ vec[index] += sign
+ return _l2_normalise(vec)
+
+
+def project_char_ngrams(
+ text: str, dim: int, *, n_min: int = 3, n_max: int = 5, remove_stop_words: bool = True
+) -> np.ndarray:
+ """Project character ``n_min``..``n_max``-grams of ``text`` into ``dim`` dimensions.
+
+ Each token is padded with spaces so word-boundary n-grams are captured
+ (mirrors scikit-learn's ``char_wb`` analyzer). Robust to morphology, code
+ identifiers and non-English text where whole-word BoW is brittle.
+ """
+ vec = np.zeros(dim, dtype=np.float32)
+ for token in _content_tokens(text, remove_stop_words):
+ padded = f" {token} "
+ for n in range(n_min, n_max + 1):
+ for i in range(len(padded) - n + 1):
+ index, sign = _hash_token(padded[i:i + n], dim)
+ vec[index] += sign
+ return _l2_normalise(vec)
+
+
+def cosine(a: np.ndarray | None, b: np.ndarray | None) -> float:
+ """Cosine similarity of two L2-normalised vectors (a plain dot product)."""
+ if a is None or b is None:
+ return 0.0
+ return float(np.dot(a, b))
+
+
+def to_bytes(vec: np.ndarray) -> bytes:
+ return np.asarray(vec, dtype=np.float32).tobytes()
+
+
+def from_bytes(raw: bytes | None) -> np.ndarray | None:
+ if not raw:
+ return None
+ return np.frombuffer(raw, dtype=np.float32).copy()
+
+
+def query_cache_key(query: str) -> str:
+ """Stable short key for caching a query's projected vectors in Redis."""
+ return hashlib.sha1(query.encode("utf-8", errors="ignore")).hexdigest()[:16]
diff --git a/mwmbl/tinysearchengine/super_search_sources/recipe.py b/mwmbl/tinysearchengine/super_search_sources/recipe.py
index 351599e..4ae53bb 100644
--- a/mwmbl/tinysearchengine/super_search_sources/recipe.py
+++ b/mwmbl/tinysearchengine/super_search_sources/recipe.py
@@ -99,8 +99,12 @@ async def search_with_recipe(
req = recipe.request
method = req.get("method", "GET").upper()
params = _build_params(req.get("params"), query, limit)
+ headers = _substitute(req.get("headers"), query, limit) if req.get("headers") else None
+ json_body = _substitute(req.get("json"), query, limit) if req.get("json") is not None else None
try:
- response = await client.request(method, req["url"], params=params)
+ response = await client.request(
+ method, req["url"], params=params, headers=headers, json=json_body
+ )
response.raise_for_status()
fmt = recipe.response_format
if fmt == "json":
@@ -125,6 +129,8 @@ def _substitute(value, query: str, limit: int):
return value.format(query=query, limit=limit)
if isinstance(value, list):
return [_substitute(v, query, limit) for v in value]
+ if isinstance(value, dict):
+ return {k: _substitute(v, query, limit) for k, v in value.items()}
return value
@@ -165,13 +171,23 @@ def _make_doc(values: dict, url: str) -> Document | None:
# ---------------------------------------------------------------------------
def _walk(data, path: str):
- """Walk a dotted path (``a.b.c``) through nested dicts; None if absent."""
+ """Walk a dotted path through nested dicts/lists; None if absent.
+
+ A path segment that is an integer (e.g. ``data.0.items``) indexes a list,
+ so APIs that wrap results in a single-element list or a fixed slot can be
+ expressed without Python.
+ """
if not path:
return data
current = data
for part in path.split("."):
if isinstance(current, dict) and part in current:
current = current[part]
+ elif isinstance(current, list) and part.lstrip("-").isdigit():
+ try:
+ current = current[int(part)]
+ except IndexError:
+ return None
else:
return None
return current
@@ -259,30 +275,33 @@ def _resolve_url_html(url_spec, el, base_url: str) -> str:
def _parse_xml(xml_text: str, spec: dict) -> list[Document]:
root = fromstring(xml_text)
results_path = spec.get("results", "")
- items = root.findall(results_path) if results_path else [root]
+ # Optional XML namespace prefix map, e.g. {atom: "http://www.w3.org/2005/Atom"},
+ # so namespaced feeds (Atom/arXiv-style) can be expressed as pure recipes.
+ namespaces = spec.get("namespaces") or None
+ items = root.findall(results_path, namespaces) if results_path else [root]
fields = spec["fields"]
strip = set(spec.get("strip_html", []))
docs: list[Document] = []
for item in items:
values = {
- name: _select_xml(item, field_spec, name in strip)
+ name: _select_xml(item, field_spec, name in strip, namespaces)
for name, field_spec in fields.items()
if name != "url"
}
- doc = _make_doc(values, _resolve_url_xml(fields.get("url"), item, values))
+ doc = _make_doc(values, _resolve_url_xml(fields.get("url"), item, values, namespaces))
if doc is not None:
docs.append(doc)
return docs
-def _select_xml(item: Element, spec, strip_html: bool = False) -> str:
+def _select_xml(item: Element, spec, strip_html: bool = False, namespaces: dict | None = None) -> str:
value = ""
if isinstance(spec, str):
- child = item.find(spec)
+ child = item.find(spec, namespaces)
value = (child.text or "") if child is not None else ""
elif isinstance(spec, dict):
attr, selector = spec.get("attr"), spec.get("selector")
- target = item.find(selector) if selector else item
+ target = item.find(selector, namespaces) if selector else item
if target is not None:
value = target.get(attr, "") if attr else (target.text or "")
if strip_html and value:
@@ -290,9 +309,9 @@ def _select_xml(item: Element, spec, strip_html: bool = False) -> str:
return value.strip()
-def _resolve_url_xml(url_spec, item: Element, values: dict) -> str:
+def _resolve_url_xml(url_spec, item: Element, values: dict, namespaces: dict | None = None) -> str:
if url_spec is None:
return ""
if isinstance(url_spec, dict) and "template" in url_spec:
return _fill_template(url_spec["template"], {**item.attrib, **values})
- return _select_xml(item, url_spec)
+ return _select_xml(item, url_spec, namespaces=namespaces)
diff --git a/pyproject.toml b/pyproject.toml
index 2340b09..6f46ce5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -94,8 +94,9 @@ log_cli = true
log_cli_level = "INFO"
DJANGO_SETTINGS_MODULE = "mwmbl.settings_test"
python_files = ["tests.py", "test_*.py", "*_tests.py"]
-addopts = "--reuse-db -m 'not live'"
+addopts = "--reuse-db -m 'not live and not slow'"
asyncio_mode = "auto"
markers = [
"live: hits real external endpoints; excluded from the default run. Run with -m live (used by the weekly Super Search smoke workflow).",
+ "slow: heavy CPU (e.g. XGBoost feature selection); excluded from the default run. Run with -m slow.",
]
diff --git a/scripts/build_super_search_candidates.py b/scripts/build_super_search_candidates.py
index 91e6e33..917e6f1 100644
--- a/scripts/build_super_search_candidates.py
+++ b/scripts/build_super_search_candidates.py
@@ -11,6 +11,13 @@ Two-phase helper for the Super Search v2 candidate analysis:
schema/taxonomy, merge in original order, and write
super-search-candidates.json. Prints distribution stats.
+ shortlist - filter candidates to recommended + has_search + non-obscure.
+
+ select_targets - pick ~140 shortlist sites that still need a recipe (excluding
+ those already served by an adapter/recipe), maximising field
+ diversity, and split them into small batches under
+ recipe_chunks/input_NNN.json for the recipe sub-agent fan-out.
+
Run from the repo root (the directory containing curated-domains.json).
"""
import argparse
@@ -25,8 +32,25 @@ CURATED = REPO_ROOT / "curated-domains.json"
CHUNK_DIR = REPO_ROOT / "candidate_chunks"
OUTPUT = REPO_ROOT / "super-search-candidates.json"
SHORTLIST = REPO_ROOT / "super-search-shortlist.json"
+DEVDATA_SHORTLIST = REPO_ROOT / "devdata" / "super-search-shortlist.json"
+RECIPES_DIR = REPO_ROOT / "mwmbl" / "tinysearchengine" / "super_search_sources" / "recipes"
+TARGETS = REPO_ROOT / "super-search-targets.json"
+RECIPE_CHUNK_DIR = REPO_ROOT / "recipe_chunks"
CHUNK_SIZE = 150
+# Over-select so ~20-30% dropped (API key / no clean endpoint / un-passable smoke)
+# still leaves ~100 landed recipes.
+TARGET_COUNT = 140
+RECIPE_BATCH_SIZE = 5
+
+# Domains already served by a hand-written adapter (recipe domains are detected
+# from the YAML files). The Stack Exchange adapter covers the whole SE network.
+ADAPTER_DOMAINS = {
+ "mwmbl.org", "news.ycombinator.com", "github.com", "pypi.org",
+ "arxiv.org", "info.arxiv.org",
+ "stackoverflow.com", "stackexchange.com", "superuser.com",
+ "mathoverflow.net", "serverfault.com", "askubuntu.com",
+}
# Fixed taxonomy / enums (keep in sync with the subagent prompt).
FIELDS = {
@@ -228,15 +252,83 @@ def cmd_shortlist():
return 0
+def _covered_domains():
+ """Domains already served: hand-written adapters + existing recipe YAML files."""
+ import yaml
+ covered = set(ADAPTER_DOMAINS)
+ for path in RECIPES_DIR.glob("*.yaml"):
+ try:
+ covered.add(yaml.safe_load(path.read_text())["domain"])
+ except (KeyError, yaml.YAMLError, OSError):
+ continue
+ return covered
+
+
+def _select_diverse(entries, count):
+ """Round-robin across fields (popularity-first within a field) to maximise diversity."""
+ pop_rank = {"high": 0, "medium": 1, "low": 2}
+ by_field = {}
+ for e in entries:
+ by_field.setdefault(e["field"], []).append(e)
+ for field_entries in by_field.values():
+ field_entries.sort(key=lambda e: (pop_rank[e["popularity"]], e["name"]))
+ selected, fields = [], sorted(by_field)
+ while len(selected) < count and any(by_field.values()):
+ for field in fields:
+ if by_field[field]:
+ selected.append(by_field[field].pop(0))
+ if len(selected) >= count:
+ break
+ return selected
+
+
+def cmd_select_targets():
+ """Pick ~TARGET_COUNT shortlist sites needing a recipe, batched for sub-agents."""
+ path = DEVDATA_SHORTLIST if DEVDATA_SHORTLIST.exists() else SHORTLIST
+ if not path.exists():
+ print("No shortlist found; run `shortlist` first.", file=sys.stderr)
+ return 1
+ entries = json.loads(path.read_text())["domains"]
+ covered = _covered_domains()
+ candidates = [e for e in entries if e["name"] not in covered]
+ targets = _select_diverse(candidates, TARGET_COUNT)
+
+ TARGETS.write_text(json.dumps({"domains": targets}, indent=2, ensure_ascii=False) + "\n")
+
+ RECIPE_CHUNK_DIR.mkdir(exist_ok=True)
+ for old in RECIPE_CHUNK_DIR.glob("input_*.json"):
+ old.unlink()
+ n_batches = 0
+ for i in range(0, len(targets), RECIPE_BATCH_SIZE):
+ batch = targets[i:i + RECIPE_BATCH_SIZE]
+ (RECIPE_CHUNK_DIR / f"input_{i // RECIPE_BATCH_SIZE:03d}.json").write_text(
+ json.dumps(batch, indent=2, ensure_ascii=False)
+ )
+ n_batches += 1
+
+ print(f"Selected {len(targets)} targets from {len(candidates)} uncovered "
+ f"shortlist sites ({len(covered)} already covered).")
+ print(f"Wrote {TARGETS} and {n_batches} batches (size {RECIPE_BATCH_SIZE}) "
+ f"in {RECIPE_CHUNK_DIR} for the recipe sub-agent fan-out.")
+ print("\n-- field --")
+ for k, v in Counter(e["field"] for e in targets).most_common():
+ print(f" {k:20} {v}")
+ return 0
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("command", choices=["prepare", "merge", "shortlist"])
+ parser.add_argument(
+ "command", choices=["prepare", "merge", "shortlist", "select_targets"]
+ )
args = parser.parse_args()
if args.command == "prepare":
cmd_prepare()
return 0
if args.command == "shortlist":
return cmd_shortlist()
+ if args.command == "select_targets":
+ return cmd_select_targets()
return cmd_merge()
diff --git a/scripts/super_search_eval.py b/scripts/super_search_eval.py
new file mode 100644
index 0000000..d4c6790
--- /dev/null
+++ b/scripts/super_search_eval.py
@@ -0,0 +1,199 @@
+#!/usr/bin/env python3
+"""Offline evaluation harness for Super Search source selection.
+
+Subcommands:
+
+ build-matrix - query every source for each query in a query file, rank the
+ union with the LTR model, and write a dense (queries x sources)
+ reward + feature matrix. Requires network + Django.
+
+ select - fit the XGBoost reward model on the matrix (grouped CV by
+ query) and print each feature's ablation drop in coverage@k.
+
+ simulate - replay Thompson sampling over the matrix, sweep the
+ exploration scale nu, and print it against random / popularity
+ / cosine / oracle baselines.
+
+Usage:
+ DJANGO_SETTINGS_MODULE=mwmbl.settings_dev uv run python scripts/super_search_eval.py \
+ build-matrix --queries queries.txt --out eval_matrix
+ uv run python scripts/super_search_eval.py select --matrix eval_matrix
+ uv run python scripts/super_search_eval.py simulate --matrix eval_matrix
+"""
+import argparse
+import asyncio
+import os
+import sys
+from pathlib import Path
+
+import django
+import numpy as np
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO_ROOT))
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")
+
+
+def _bootstrap_django():
+ django.setup()
+
+
+# ---------------------------------------------------------------------------
+# build-matrix (network + Django)
+# ---------------------------------------------------------------------------
+
+async def _query_all_sources(query: str, limit: int):
+ import httpx
+ from django.conf import settings
+ from mwmbl.tinysearchengine.super_search_sources import SOURCES
+
+ timeout = settings.SUPER_SEARCH_PER_SOURCE_TIMEOUT
+ async with httpx.AsyncClient(follow_redirects=True, timeout=timeout,
+ headers={"User-Agent": "mwmbl-super-search-eval/0.1"}) as client:
+ async def one(name, fn):
+ try:
+ docs = await asyncio.wait_for(fn(client, query, limit), timeout=timeout)
+ return name, docs
+ except Exception:
+ return name, []
+ results = await asyncio.gather(*[one(n, f) for n, f in SOURCES.items()])
+ return dict(results)
+
+
+def build_matrix(queries: list[str], out: str):
+ from django.conf import settings
+ from mwmbl.search_setup import ltr_model
+ from mwmbl.tinysearchengine.ltr_rank import score_documents
+ from mwmbl.tinysearchengine.super_search_sources import SOURCES
+ from mwmbl.tinysearchengine.super_search_select import profiles, vectors
+ from mwmbl.tinysearchengine.super_search_select.features import (
+ FEATURE_NAMES, QueryContext, feature_vector,
+ )
+ from mwmbl.tinysearchengine.super_search_select.registry import get_meta
+ from mwmbl.tinysearchengine.super_search_select.evaluation import RewardMatrix
+
+ sources = list(SOURCES.keys())
+ s_index = {name: i for i, name in enumerate(sources)}
+ limit = settings.SUPER_SEARCH_RESULTS_PER_SOURCE
+ top_k = settings.SUPER_SEARCH_TOP_K
+ dim = settings.SUPER_SEARCH_PROJECTION_DIM
+ F = len(FEATURE_NAMES)
+
+ # Pass 1: query everything, recording per-query docs and accumulating each
+ # site's content profile (mean of its projected result samples).
+ per_query_docs = [] # list[dict[source -> list[Document]]]
+ prof_bow = {n: np.zeros(dim) for n in sources}
+ prof_cng = {n: np.zeros(dim) for n in sources}
+ for qi, query in enumerate(queries):
+ docs_by_source = asyncio.run(_query_all_sources(query, limit))
+ per_query_docs.append(docs_by_source)
+ for name, docs in docs_by_source.items():
+ if docs:
+ text = profiles.sample_text(docs)
+ prof_bow[name] += vectors.project_bow(text, dim)
+ prof_cng[name] += vectors.project_char_ngrams(text, dim)
+ print(f" [{qi + 1}/{len(queries)}] {query!r}: "
+ f"{sum(len(d) for d in docs_by_source.values())} docs")
+ profile = {n: (vectors._l2_normalise(prof_bow[n]), vectors._l2_normalise(prof_cng[n]))
+ for n in sources}
+
+ # Pass 2: features + implicit-contribution reward against the LTR top-K.
+ Q, S = len(queries), len(sources)
+ X = np.zeros((Q, S, F))
+ R = np.zeros((Q, S))
+ mask = np.zeros((Q, S), dtype=bool)
+ for qi, (query, docs_by_source) in enumerate(zip(queries, per_query_docs)):
+ bow = vectors.project_bow(query, dim)
+ cng = vectors.project_char_ngrams(query, dim)
+ qctx = QueryContext.build(query, bow, cng)
+
+ source_by_url, all_docs = {}, []
+ for name, docs in docs_by_source.items():
+ si = s_index[name]
+ X[qi, si] = feature_vector(qctx, get_meta(name), profile[name])
+ if docs:
+ mask[qi, si] = True
+ for d in docs:
+ if d.url and d.title:
+ source_by_url.setdefault(d.url, name)
+ all_docs.append(d)
+ if all_docs:
+ scores = score_documents(ltr_model, query, all_docs)
+ ranked = [d.url for d, _ in sorted(zip(all_docs, scores), key=lambda x: -x[1])][:top_k]
+ counts = {}
+ for url in ranked:
+ src = source_by_url.get(url)
+ if src:
+ counts[src] = counts.get(src, 0) + 1
+ for name, c in counts.items():
+ R[qi, s_index[name]] = min(c / max(limit, 1), 1.0)
+
+ matrix = RewardMatrix(queries=queries, sources=sources,
+ feature_names=list(FEATURE_NAMES), X=X, R=R, mask=mask)
+ matrix.save(out)
+ print(f"Wrote matrix {out}.npz/.json: {Q} queries x {S} sources, "
+ f"{int(mask.sum())} filled cells.")
+
+
+# ---------------------------------------------------------------------------
+# select / simulate (pure, no network)
+# ---------------------------------------------------------------------------
+
+def cmd_select(matrix_path: str, k: int):
+ from mwmbl.tinysearchengine.super_search_select.evaluation import RewardMatrix, select_features
+ m = RewardMatrix.load(matrix_path)
+ result = select_features(m, k=k)
+ print(f"baseline coverage@{k}: {result['baseline_coverage']:.4f}\n")
+ print("feature ablation (drop in coverage@k when removed; higher = more useful):")
+ for name, drop in sorted(result["ablation_drop"].items(), key=lambda kv: -kv[1]):
+ print(f" {name:18} {drop:+.4f}")
+
+
+def cmd_simulate(matrix_path: str, k: int):
+ from mwmbl.tinysearchengine.super_search_select.evaluation import (
+ RewardMatrix, simulate_baselines, sweep_explore_scale,
+ )
+ m = RewardMatrix.load(matrix_path)
+ base = simulate_baselines(m, k=k)
+ print("baselines (mean captured reward per query):")
+ for name, val in sorted(base.items(), key=lambda kv: -kv[1]):
+ print(f" {name:12} {val:.4f}")
+ print("\nThompson sampling by exploration scale nu:")
+ sweep = sweep_explore_scale(m, k=k, nus=[0.0, 0.25, 0.5, 1.0, 2.0, 4.0])
+ best = max(sweep, key=sweep.get)
+ for nu, val in sweep.items():
+ marker = " <- best" if nu == best else ""
+ print(f" nu={nu:<4} {val:.4f}{marker}")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ p_build = sub.add_parser("build-matrix")
+ p_build.add_argument("--queries", required=True, help="file with one query per line")
+ p_build.add_argument("--out", default="eval_matrix")
+
+ p_select = sub.add_parser("select")
+ p_select.add_argument("--matrix", default="eval_matrix")
+ p_select.add_argument("--k", type=int, default=10)
+
+ p_sim = sub.add_parser("simulate")
+ p_sim.add_argument("--matrix", default="eval_matrix")
+ p_sim.add_argument("--k", type=int, default=10)
+
+ args = parser.parse_args()
+ _bootstrap_django()
+
+ if args.command == "build-matrix":
+ queries = [ln.strip() for ln in Path(args.queries).read_text().splitlines() if ln.strip()]
+ build_matrix(queries, args.out)
+ elif args.command == "select":
+ cmd_select(args.matrix, args.k)
+ elif args.command == "simulate":
+ cmd_simulate(args.matrix, args.k)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/test_super_search_bandit.py b/test/test_super_search_bandit.py
new file mode 100644
index 0000000..951e5f9
--- /dev/null
+++ b/test/test_super_search_bandit.py
@@ -0,0 +1,123 @@
+"""Tests for the linear-Gaussian Thompson-sampling source-selection bandit."""
+import fakeredis
+import numpy as np
+import pytest
+
+from mwmbl.tinysearchengine.super_search_select import bandit, policy, profiles
+from mwmbl.tinysearchengine.super_search_select.features import NUM_FEATURES
+from mwmbl.tinysearchengine.super_search_select.rewards import SelectionContext
+
+
+def fake_bandit_redis(monkeypatch):
+ r = fakeredis.FakeRedis()
+ monkeypatch.setattr(bandit, "_redis", r)
+ return r
+
+
+def test_prior_state_shape():
+ s = bandit.prior_state()
+ assert s.A.shape == (NUM_FEATURES, NUM_FEATURES)
+ assert s.b.shape == (NUM_FEATURES,)
+ # Prior is lambda*I, b=0 -> posterior mean 0.
+ assert np.allclose(s.A, np.eye(NUM_FEATURES))
+ assert np.allclose(s.b, 0.0)
+
+
+def test_unseen_arm_returns_prior(fake_bandit_redis):
+ states = bandit.get_states(["never_seen"])
+ assert np.allclose(states["never_seen"].b, 0.0)
+
+
+def test_state_roundtrip(fake_bandit_redis):
+ s = bandit.prior_state()
+ x = np.arange(NUM_FEATURES, dtype=np.float64)
+ bandit.update_arm(s, x, 1.0)
+ bandit.save_states({"site": s})
+ loaded = bandit.get_states(["site"])["site"]
+ assert np.allclose(loaded.A, s.A)
+ assert np.allclose(loaded.b, s.b)
+
+
+def test_update_changes_posterior_mean(fake_bandit_redis):
+ # Repeatedly reward a feature direction; posterior mean should move that way.
+ s = bandit.prior_state()
+ x = np.zeros(NUM_FEATURES)
+ x[1] = 1.0 # the cos_bow slot
+ for _ in range(20):
+ bandit.update_arm(s, x, 1.0)
+ mean = np.linalg.inv(s.A) @ s.b
+ assert mean[1] > 0.5
+
+
+def test_update_via_features_and_rewards(fake_bandit_redis):
+ feats = {"a": [0.0] * NUM_FEATURES, "b": [0.0] * NUM_FEATURES}
+ feats["a"][1] = 1.0
+ feats["b"][1] = 1.0
+ bandit.update(feats, {"a": 1.0, "b": 0.0})
+ sa = bandit.get_states(["a"])["a"]
+ sb = bandit.get_states(["b"])["b"]
+ # 'a' got reward 1 in slot 1, 'b' got 0 -> a's b-vector larger there.
+ assert sa.b[1] == pytest.approx(1.0)
+ assert sb.b[1] == pytest.approx(0.0)
+
+
+def test_all_sites_and_export(fake_bandit_redis):
+ bandit.update({"a": [1.0] * NUM_FEATURES, "b": [1.0] * NUM_FEATURES},
+ {"a": 1.0, "b": 0.5})
+ assert set(bandit.all_sites()) == {"a", "b"}
+ exported = bandit.export_all()
+ assert set(exported) == {"a", "b"}
+
+
+def test_seed_states_does_not_clobber_live(fake_bandit_redis):
+ # Live arm trained; a stale Postgres prior should not overwrite it.
+ s = bandit.prior_state()
+ x = np.zeros(NUM_FEATURES); x[1] = 1.0
+ for _ in range(10):
+ bandit.update_arm(s, x, 1.0)
+ bandit.save_states({"site": s})
+
+ bandit.seed_states({"site": bandit.prior_state()}, overwrite=False)
+ loaded = bandit.get_states(["site"])["site"]
+ assert not np.allclose(loaded.b, 0.0) # live state preserved
+
+
+def test_thompson_prefers_learned_good_arm(fake_bandit_redis):
+ # Train arm "good" to like a context, "bad" to dislike it; sampling should
+ # pick "good" most of the time.
+ x = np.zeros(NUM_FEATURES)
+ x[0], x[1] = 1.0, 1.0 # bias + cos_bow
+ good = bandit.prior_state()
+ bad = bandit.prior_state()
+ for _ in range(50):
+ bandit.update_arm(good, x, 1.0)
+ bandit.update_arm(bad, x, 0.0)
+ bandit.save_states({"good": good, "bad": bad})
+
+ rng = np.random.default_rng(0)
+ states = bandit.get_states(["good", "bad"])
+ wins = 0
+ for _ in range(200):
+ sg = bandit.sample_score(states["good"], x, rng)
+ sb = bandit.sample_score(states["bad"], x, rng)
+ wins += sg > sb
+ assert wins > 150 # good clearly preferred
+
+
+def test_policy_bandit_branch_selects_and_records_features(monkeypatch):
+ """End-to-end: USE_BANDIT selection populates ctx.features and respects k."""
+ r = fakeredis.FakeRedis()
+ monkeypatch.setattr(bandit, "_redis", r)
+ monkeypatch.setattr(profiles, "_redis", r)
+ monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_USE_BANDIT", True)
+
+ names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
+ ctx = SelectionContext()
+ chosen = policy.select_sources("python testing tools", names, k=5, ctx=ctx)
+
+ assert len(chosen) == 5
+ assert "mwmbl" in chosen and "hn" in chosen # always-on included
+ # A feature vector was recorded for every chosen source.
+ assert set(chosen) <= set(ctx.features)
+ assert all(len(v) == NUM_FEATURES for v in ctx.features.values())
diff --git a/test/test_super_search_eval.py b/test/test_super_search_eval.py
new file mode 100644
index 0000000..3edbb42
--- /dev/null
+++ b/test/test_super_search_eval.py
@@ -0,0 +1,84 @@
+"""Tests for the offline evaluation harness on synthetic reward matrices."""
+import numpy as np
+import pytest
+
+from mwmbl.tinysearchengine.super_search_select import evaluation
+from mwmbl.tinysearchengine.super_search_select.evaluation import RewardMatrix
+from mwmbl.tinysearchengine.super_search_select.features import FEATURE_NAMES
+
+
+def _synthetic_matrix(Q=120, S=30, seed=0) -> RewardMatrix:
+ """Reward driven mostly by cos_bow (idx 1) and popularity (idx 3)."""
+ rng = np.random.default_rng(seed)
+ F = len(FEATURE_NAMES)
+ X = rng.random((Q, S, F)).astype(np.float64)
+ X[:, :, 0] = 1.0 # bias
+ cos_i = FEATURE_NAMES.index("cos_bow")
+ pop_i = FEATURE_NAMES.index("popularity")
+ R = np.clip(0.8 * X[:, :, cos_i] + 0.2 * X[:, :, pop_i]
+ + 0.02 * rng.standard_normal((Q, S)), 0.0, 1.0)
+ mask = np.ones((Q, S), dtype=bool)
+ return RewardMatrix(
+ queries=[f"q{i}" for i in range(Q)],
+ sources=[f"s{i}" for i in range(S)],
+ feature_names=list(FEATURE_NAMES), X=X, R=R, mask=mask,
+ )
+
+
+def test_coverage_bounds_and_oracle():
+ m = _synthetic_matrix()
+ # Oracle scoring (use true reward as the score) gives coverage 1.0.
+ cov = evaluation.coverage_at_k(m.R, m.R, m.mask, k=10)
+ assert cov == pytest.approx(1.0)
+ # Random scoring is below oracle.
+ rng = np.random.default_rng(1)
+ rand_cov = evaluation.coverage_at_k(rng.random(m.R.shape), m.R, m.mask, k=10)
+ assert 0.0 <= rand_cov < 1.0
+
+
+def test_baselines_ordering():
+ m = _synthetic_matrix()
+ out = evaluation.simulate_baselines(m, k=10)
+ assert out["oracle"] >= out["cosine"] >= out["random"]
+ assert out["cosine"] > out["random"] # cos_bow is the dominant signal
+
+
+def test_ts_tuning_beats_random_and_exploration_helps():
+ # The harness's job is to pick the exploration scale: a tuned TS should beat
+ # random, exploration (nu>0) should beat pure-greedy (nu=0), and nothing
+ # beats the oracle.
+ m = _synthetic_matrix()
+ base = evaluation.simulate_baselines(m, k=10)
+ sweep = evaluation.sweep_explore_scale(m, k=10, nus=[0.0, 0.25, 0.5, 1.0, 2.0])
+ best_nu = max(sweep, key=sweep.get)
+ best = sweep[best_nu]
+ assert best > base["random"]
+ assert best > sweep[0.0] # exploration helps vs greedy
+ assert best <= base["oracle"] + 1e-9
+
+
+def test_sweep_explore_scale_runs():
+ m = _synthetic_matrix(Q=60, S=20)
+ res = evaluation.sweep_explore_scale(m, k=8, nus=[0.0, 0.5, 1.0, 2.0])
+ assert set(res) == {0.0, 0.5, 1.0, 2.0}
+ assert all(v >= 0 for v in res.values())
+
+
+def test_save_load_roundtrip(tmp_path):
+ m = _synthetic_matrix(Q=10, S=5)
+ path = tmp_path / "matrix"
+ m.save(path)
+ loaded = RewardMatrix.load(path)
+ assert loaded.sources == m.sources
+ assert np.allclose(loaded.R, m.R)
+ assert loaded.feature_names == m.feature_names
+
+
+def test_feature_selection_flags_cos_bow(tmp_path):
+ pytest.importorskip("xgboost")
+ m = _synthetic_matrix(Q=80, S=20)
+ result = evaluation.select_features(m, k=8)
+ drops = result["ablation_drop"]
+ # cos_bow is the dominant driver, so removing it should hurt coverage most.
+ assert drops["cos_bow"] == max(drops.values())
diff --git a/test/test_super_search_recipes.py b/test/test_super_search_recipes.py
index 9c77a35..ec8c40d 100644
--- a/test/test_super_search_recipes.py
+++ b/test/test_super_search_recipes.py
@@ -202,3 +202,95 @@ async def test_http_error_returns_empty(httpx_mock):
def test_recipes_dir_exists():
assert Path(RECIPES_DIR).is_dir()
+
+
+# ---------------------------------------------------------------------------
+# v2 engine enhancements: headers, POST json body, XML namespaces, list index
+# ---------------------------------------------------------------------------
+
+async def test_request_headers_sent(httpx_mock):
+ recipe = Recipe(
+ name="hdr",
+ request={
+ "url": "https://example.com/api",
+ "headers": {"User-Agent": "custom-agent", "Accept": "application/json"},
+ "params": {"q": "{query}"},
+ },
+ response={"format": "json", "results": "results", "fields": {"title": "t", "url": "u"}},
+ )
+ httpx_mock.add_response(url=re.compile(r"https://example\.com/.*"), json={"results": []})
+ async with httpx.AsyncClient() as client:
+ await search_with_recipe(client, recipe, "x", 5)
+ request = httpx_mock.get_requests()[0]
+ assert request.headers["user-agent"] == "custom-agent"
+ assert request.headers["accept"] == "application/json"
+
+
+async def test_post_json_body_with_substitution(httpx_mock):
+ recipe = Recipe(
+ name="post",
+ request={
+ "url": "https://example.com/search",
+ "method": "POST",
+ "json": {"query": "{query}", "size": "{limit}"},
+ },
+ response={"format": "json", "results": "hits", "fields": {"title": "title", "url": "url"}},
+ )
+ httpx_mock.add_response(
+ url=re.compile(r"https://example\.com/.*"),
+ json={"hits": [{"title": "Hit", "url": "https://example.com/1"}]},
+ )
+ async with httpx.AsyncClient() as client:
+ docs = await search_with_recipe(client, recipe, "neutrino", 7)
+ request = httpx_mock.get_requests()[0]
+ assert request.method == "POST"
+ import json as _json
+ body = _json.loads(request.content)
+ assert body == {"query": "neutrino", "size": "7"}
+ assert docs[0].url == "https://example.com/1"
+
+
+async def test_json_list_index_path(httpx_mock):
+ recipe = Recipe(
+ name="listidx",
+ request={"url": "https://example.com/api", "params": {"q": "{query}"}},
+ response={"format": "json", "results": "data.0.items",
+ "fields": {"title": "name", "url": "link"}},
+ )
+ httpx_mock.add_response(
+ url=re.compile(r"https://example\.com/.*"),
+ json={"data": [{"items": [{"name": "First", "link": "https://example.com/a"}]}]},
+ )
+ async with httpx.AsyncClient() as client:
+ docs = await search_with_recipe(client, recipe, "x", 5)
+ assert len(docs) == 1 and docs[0].title == "First"
+
+
+ATOM_XML = """<?xml version="1.0" encoding="utf-8"?>
+<feed xmlns="http://www.w3.org/2005/Atom">
+ <entry>
+ <title>Deep Learning</title>
+ <summary>A survey</summary>
+ <id>http://arxiv.org/abs/1234.5678</id>
+ </entry>
+</feed>
+"""
+
+
+async def test_xml_namespaces(httpx_mock):
+ recipe = Recipe(
+ name="atom",
+ request={"url": "https://export.arxiv.org/api/query"},
+ response={
+ "format": "xml",
+ "namespaces": {"atom": "http://www.w3.org/2005/Atom"},
+ "results": ".//atom:entry",
+ "fields": {"title": "atom:title", "extract": "atom:summary", "url": "atom:id"},
+ },
+ )
+ httpx_mock.add_response(url=re.compile(r"https://export\.arxiv\.org/.*"), text=ATOM_XML)
+ async with httpx.AsyncClient() as client:
+ docs = await search_with_recipe(client, recipe, "deep learning", 5)
+ assert len(docs) == 1
+ assert docs[0].title == "Deep Learning"
+ assert docs[0].url == "http://arxiv.org/abs/1234.5678"
diff --git a/test/test_super_search_select.py b/test/test_super_search_select.py
new file mode 100644
index 0000000..5988ebd
--- /dev/null
+++ b/test/test_super_search_select.py
@@ -0,0 +1,175 @@
+"""Tests for Super Search source selection: profiles, features, policy."""
+import fakeredis
+import numpy as np
+import pytest
+
+from mwmbl.tinysearchengine.indexer import Document
+from mwmbl.tinysearchengine.super_search_select import features, policy, profiles, rewards, vectors
+from mwmbl.tinysearchengine.super_search_select.features import QueryContext, SiteStats
+from mwmbl.tinysearchengine.super_search_select.registry import SiteMeta
+from mwmbl.tinysearchengine.super_search_select.rewards import SelectionContext, compute_rewards
+
+DIM = 64
+
+
+def fake_profile_redis(monkeypatch):
+ """Binary-safe fake Redis wired into the profiles module."""
+ r = fakeredis.FakeRedis() # decode_responses=False (vectors are raw bytes)
+ monkeypatch.setattr(profiles, "_redis", r)
+ return r
+
+
+def _doc(title, extract=""):
+ return Document(title=title, url=f"https://x/{title}", extract=extract)
+
+
+# ---------------------------------------------------------------------------
+# Profiles
+# ---------------------------------------------------------------------------
+
+def test_unseen_profile_is_none(fake_profile_redis):
+ assert profiles.get_profile("nope") == (None, None)
+
+
+def test_update_then_get_profile(fake_profile_redis):
+ profiles.update_profile("site", [_doc("python web framework", "django flask")])
+ bow, cng = profiles.get_profile("site")
+ assert bow is not None and cng is not None
+ assert abs(float(np.linalg.norm(bow)) - 1.0) < 1e-5
+
+
+def test_profile_moves_towards_repeated_topic(fake_profile_redis):
+ # A site repeatedly returning ML content should profile closer to an ML query
+ # than to an unrelated one.
+ for _ in range(5):
+ profiles.update_profile("ml", [_doc("machine learning neural networks", "deep models")])
+ bow, _ = profiles.get_profile("ml")
+ ml_q = vectors.project_bow("neural network training", DIM)
+ other_q = vectors.project_bow("medieval french poetry", DIM)
+ assert vectors.cosine(ml_q, bow) > vectors.cosine(other_q, bow)
+
+
+def test_empty_docs_no_profile(fake_profile_redis):
+ profiles.update_profile("site", [])
+ assert profiles.get_profile("site") == (None, None)
+
+
+def test_query_vectors_cached(fake_profile_redis):
+ bow1, cng1 = profiles.get_query_vectors("hello world")
+ bow2, cng2 = profiles.get_query_vectors("hello world")
+ assert np.array_equal(bow1, bow2) and np.array_equal(cng1, cng2)
+ # Cached under the query key.
+ assert fake_profile_redis.exists(profiles._QVEC_BOW.format(key=vectors.query_cache_key("hello world")))
+
+
+def test_batch_profiles(fake_profile_redis):
+ profiles.update_profile("a", [_doc("alpha")])
+ got = profiles.get_profiles(["a", "b"])
+ assert got["a"][0] is not None
+ assert got["b"] == (None, None)
+
+
+# ---------------------------------------------------------------------------
+# Features
+# ---------------------------------------------------------------------------
+
+def _qctx(query):
+ bow = vectors.project_bow(query, DIM)
+ cng = vectors.project_char_ngrams(query, DIM)
+ return QueryContext.build(query, bow, cng)
+
+
+def test_feature_vector_shape_and_bias():
+ meta = SiteMeta("s", "s.com", "tech", popularity=0.6, estimated_pages=0.6)
+ x = features.feature_vector(_qctx("test query"), meta, (None, None))
+ assert x.shape == (features.NUM_FEATURES,)
+ assert x[0] == 1.0 # bias
+
+
+def test_code_token_detected():
+ assert _qctx("os.path.join example").has_code_token
+ assert not _qctx("history of rome").has_code_token
+
+
+def test_cosine_relevance_prefers_matching_profile():
+ qctx = _qctx("django database migration")
+ related = (vectors.project_bow("django orm migration schema", DIM),
+ vectors.project_char_ngrams("django orm migration schema", DIM))
+ unrelated = (vectors.project_bow("baroque opera composers", DIM),
+ vectors.project_char_ngrams("baroque opera composers", DIM))
+ assert features.cosine_relevance(qctx, related) > features.cosine_relevance(qctx, unrelated)
+ assert features.cosine_relevance(qctx, (None, None)) == 0.0
+
+
+def test_feature_vector_uses_stats():
+ meta = SiteMeta("s", "s.com", "tech")
+ stats = SiteStats(contribution_ema=0.5, latency_ema=10.0, failure_rate=0.25)
+ x = features.feature_vector(_qctx("q"), meta, (None, None), stats)
+ names = features.FEATURE_NAMES
+ assert x[names.index("contribution_ema")] == 0.5
+ assert x[names.index("latency_penalty")] == 1.0 # clamped (latency >> timeout)
+ assert x[names.index("failure_rate")] == 0.25
+
+
+# ---------------------------------------------------------------------------
+# Policy
+# ---------------------------------------------------------------------------
+
+def test_select_returns_all_when_fewer_than_k(fake_profile_redis):
+ names = ["a", "b", "c"]
+ assert set(policy.select_sources("q", names, k=10)) == set(names)
+
+
+def test_select_includes_always_on(fake_profile_redis, monkeypatch):
+ # mwmbl and hn are always-on in the static registry.
+ names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
+ chosen = policy.select_sources("python testing", names, k=5)
+ assert "mwmbl" in chosen and "hn" in chosen
+ assert len(chosen) == 5
+
+
+def test_select_prefers_relevant_warm_site(fake_profile_redis, monkeypatch):
+ monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_EXPLORE_FLOOR", 0)
+ # One warm site profiled on databases; others cold.
+ for _ in range(3):
+ profiles.update_profile("db_site", [_doc("postgres database sql indexing")])
+ names = ["db_site"] + [f"cold{i}" for i in range(20)]
+ chosen = policy.select_sources("sql database query", names, k=3)
+ assert "db_site" in chosen
+
+
+# ---------------------------------------------------------------------------
+# Rewards
+# ---------------------------------------------------------------------------
+
+def test_compute_rewards_fraction_in_top_k():
+ ctx = SelectionContext(selected=["a", "b", "c"], per_source_limit=10)
+ ctx.record_results("a", ["u1", "u2", "u3"])
+ ctx.record_results("b", ["u4"])
+ # c returned nothing useful
+ final_top_k = ["u1", "u2", "u4"] # a:2, b:1, c:0
+ r = compute_rewards(ctx, final_top_k)
+ assert r["a"] == pytest.approx(0.2)
+ assert r["b"] == pytest.approx(0.1)
+ assert r["c"] == 0.0
+
+
+def test_compute_rewards_clamped_and_covers_all_selected():
+ ctx = SelectionContext(selected=["a"], per_source_limit=2)
+ ctx.record_results("a", ["u1", "u2", "u3"])
+ r = compute_rewards(ctx, ["u1", "u2", "u3"]) # 3/2 -> clamp to 1.0
+ assert r == {"a": 1.0}
+
+
+def test_record_results_first_source_wins():
+ ctx = SelectionContext(selected=["a", "b"], per_source_limit=10)
+ ctx.record_results("a", ["shared"])
+ ctx.record_results("b", ["shared"])
+ assert ctx.source_by_url["shared"] == "a"
+
+
+def test_log_impression_noop_without_database(monkeypatch):
+ monkeypatch.setattr("django.conf.settings.HAS_DATABASE", False)
+ # Should not raise even though no DB is configured.
+ rewards.log_impression("q", SelectionContext(selected=["a"]), {"a": 0.5})
diff --git a/test/test_super_search_vectors.py b/test/test_super_search_vectors.py
new file mode 100644
index 0000000..777629c
--- /dev/null
+++ b/test/test_super_search_vectors.py
@@ -0,0 +1,70 @@
+"""Unit tests for Super Search vector utilities (no DB / Redis needed)."""
+import numpy as np
+
+from mwmbl.tinysearchengine.super_search_select import vectors
+
+
+DIM = 64
+
+
+def test_projection_is_l2_normalised():
+ vec = vectors.project_bow("the quick brown fox jumps", DIM)
+ assert vec.shape == (DIM,)
+ assert vec.dtype == np.float32
+ assert abs(float(np.linalg.norm(vec)) - 1.0) < 1e-5
+
+
+def test_projection_is_deterministic():
+ a = vectors.project_bow("python web framework", DIM)
+ b = vectors.project_bow("python web framework", DIM)
+ assert np.array_equal(a, b)
+
+
+def test_empty_text_gives_zero_vector():
+ vec = vectors.project_bow("", DIM)
+ assert float(np.linalg.norm(vec)) == 0.0
+ assert vectors.cosine(vec, vectors.project_bow("anything", DIM)) == 0.0
+
+
+def test_stop_words_removed():
+ # "the" / "of" are stop words, so these should project identically.
+ with_stops = vectors.project_bow("the history of rome", DIM)
+ without_stops = vectors.project_bow("history rome", DIM)
+ assert np.allclose(with_stops, without_stops)
+
+
+def test_cosine_self_is_one_and_bounds():
+ vec = vectors.project_bow("machine learning models", DIM)
+ assert abs(vectors.cosine(vec, vec) - 1.0) < 1e-5
+ other = vectors.project_bow("medieval french poetry", DIM)
+ sim = vectors.cosine(vec, other)
+ assert -1.0 - 1e-6 <= sim <= 1.0 + 1e-6
+
+
+def test_related_text_more_similar_than_unrelated():
+ query = vectors.project_bow("django database migration", DIM)
+ related = vectors.project_bow("django orm database schema migration", DIM)
+ unrelated = vectors.project_bow("baroque opera composers", DIM)
+ assert vectors.cosine(query, related) > vectors.cosine(query, unrelated)
+
+
+def test_char_ngrams_match_on_shared_substrings():
+ a = vectors.project_char_ngrams("tokenizer", DIM)
+ b = vectors.project_char_ngrams("tokenize", DIM)
+ c = vectors.project_char_ngrams("xylophone", DIM)
+ assert vectors.cosine(a, b) > vectors.cosine(a, c)
+
+
+def test_bytes_roundtrip():
+ vec = vectors.project_bow("roundtrip test vector", DIM)
+ restored = vectors.from_bytes(vectors.to_bytes(vec))
+ assert np.array_equal(vec, restored)
+ assert vectors.from_bytes(None) is None
+ assert vectors.from_bytes(b"") is None
+
+
+def test_query_cache_key_stable_and_short():
+ k1 = vectors.query_cache_key("hello world")
+ k2 = vectors.query_cache_key("hello world")
+ assert k1 == k2 and len(k1) == 16
+ assert vectors.query_cache_key("different") != k1