Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Remove cosine and Thompson-sampling selection: xgb is the only policy

Daoud Clarkebfde58de6629
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index cdf4dc0..54ec7ab 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -67,11 +67,7 @@ class MwmblConfig(AppConfig):
try:
from background_task.models import Task
- from mwmbl.background import (
- retrain_super_search_xgb,
- sync_search_counts,
- sync_super_search_bandit,
- )
+ from mwmbl.background import retrain_super_search_xgb, sync_search_counts
SYNC_TASK = "mwmbl.background.sync_search_counts"
@@ -79,14 +75,8 @@ 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)
-
# Retrain the Super Search xgb source model daily from the
- # impression log (skips unless the xgb mode is live and enough
- # pairs have accumulated).
+ # 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)
diff --git a/mwmbl/background.py b/mwmbl/background.py
index abdd698..f756ec8 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -88,42 +88,6 @@ 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 retrain_super_search_xgb():
"""Daily batch retrain of the Super Search xgb source model.
@@ -131,15 +95,11 @@ def retrain_super_search_xgb():
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 the mode isn't xgb or too few pairs have
- accumulated; training/IO errors propagate so failures are visible.
+ (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
- if settings.SUPER_SEARCH_SELECTION_MODE != "xgb":
- logger.info("super-search xgb retrain skipped: selection mode is %s",
- settings.SUPER_SEARCH_SELECTION_MODE)
- return
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,
diff --git a/mwmbl/migrations/0028_delete_supersearchbanditstate.py b/mwmbl/migrations/0028_delete_supersearchbanditstate.py
new file mode 100644
index 0000000..8fbae34
--- /dev/null
+++ b/mwmbl/migrations/0028_delete_supersearchbanditstate.py
@@ -0,0 +1,16 @@
+# Generated by Django 5.2.13 on 2026-07-07 20:22
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mwmbl', '0027_remove_sourceprovenance_query_and_more'),
+ ]
+
+ operations = [
+ migrations.DeleteModel(
+ name='SuperSearchBanditState',
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index ee60188..c0bd310 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -248,20 +248,6 @@ class SuperSearchImpression(models.Model):
]
-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)
-
-
class SourceProvenance(models.Model):
"""Which Super Search source a URL was (transitively) discovered from.
diff --git a/mwmbl/rankeval/SUPER_SEARCH_XGB_FINDINGS.md b/mwmbl/rankeval/SUPER_SEARCH_XGB_FINDINGS.md
index a7729c3..d30dc96 100644
--- a/mwmbl/rankeval/SUPER_SEARCH_XGB_FINDINGS.md
+++ b/mwmbl/rankeval/SUPER_SEARCH_XGB_FINDINGS.md
@@ -91,10 +91,12 @@ routing, is the objective.
one strength (home-source recall) does not convert into reward.
- **xgb ≥ LinTS on the judge objective** (holdout +0.036 coverage, replay
+0.004–0.039), **LinTS > xgb on the old survival matrix** (0.849 vs 0.785).
- Since the survival reward is the circular metric the judge pivot replaced,
- the judge results should carry the decision, but the old-eval gate as
- originally stated (beat LinTS on the old matrices too) is NOT met — flagged
- for an explicit call before deleting the LinTS strategy.
+ Decision (user call, 2026-07-07): the survival reward relies on an LTR
+ model trained on an unrepresentative dataset and is the circular metric the
+ judge pivot replaced, so the judge results carry it — **cosine and LinTS
+ removed; xgb is the only selection policy** (`SUPER_SEARCH_SELECTION_MODE`
+ gone, `bandit.py` / `SuperSearchBanditState` / TS settings deleted,
+ migration 0028).
- Exploration: eps=0 replays best, consistent with the earlier nu≈0.05
finding; keep a small eps (0.05–0.1) in production anyway to de-bias the
training log. `SUPER_SEARCH_XGB_EPSILON` defaults to 0.1.
diff --git a/mwmbl/rankeval/evaluation/evaluate_super_search.py b/mwmbl/rankeval/evaluation/evaluate_super_search.py
index d47781b..71a7fd2 100644
--- a/mwmbl/rankeval/evaluation/evaluate_super_search.py
+++ b/mwmbl/rankeval/evaluation/evaluate_super_search.py
@@ -1,8 +1,8 @@
"""
Evaluate the Super Search pipeline as a RankingModel against the gold dataset.
-Runs the real Super Search ranking core offline: select sources (cosine baseline
-by default — see ``SUPER_SEARCH_SELECTION_MODE``), fan out to them, re-rank the union
+Runs the real Super Search ranking core offline: select sources (xgb
+contextual-bandit policy), fan out to them, re-rank the union
with the LTR model, crawl promoted pages, follow outbound links, and MMR-diversify
into a final ranking. Only the SSE/auth/quota/indexing/reward machinery of the
HTTP endpoint is skipped; the ranking logic is exactly what production serves.
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 371fd8f..b13d15e 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -296,20 +296,11 @@ SUPER_SEARCH_JUDGE_MODEL_DIR = os.environ.get(
str(Path(__file__).parent.parent / "devdata" / "judge_train" / "models"
/ "minilm-both-v1" / "onnx"))
-# Super Search source selection (bandit / cosine profiles)
+# Super Search source selection (xgb contextual bandit over cosine-profile features)
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
-# Selection strategy: "cosine" (greedy top-10 baseline), "lints" (per-arm
-# Thompson sampling), or "xgb" (contextual bandit: XGBoost reward model with
-# epsilon-greedy exploration). Transitional — cosine/lints are removed once the
-# xgb policy passes the offline gate.
-SUPER_SEARCH_SELECTION_MODE = os.environ.get("SUPER_SEARCH_SELECTION_MODE", "cosine")
SUPER_SEARCH_FORCE_INCLUDE = [] # source names always queried (high-value sources), like always_on
# XGBoost contextual-bandit source model. The runtime dir receives online
diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.py
index 423f20d..6324566 100644
--- a/mwmbl/tinysearchengine/super_search.py
+++ b/mwmbl/tinysearchengine/super_search.py
@@ -48,7 +48,6 @@ 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 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
@@ -555,7 +554,9 @@ async def _record_rewards(ctx: SelectionContext, last_results_key: list) -> None
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).
+ # 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")
@@ -567,13 +568,6 @@ async def _record_rewards(ctx: SelectionContext, last_results_key: list) -> None
await asyncio.to_thread(_enqueue_discovered_urls, ctx)
except Exception:
logger.exception("super-search failed to enqueue discovered urls")
- # Only the per-arm LinTS bandit needs a per-request update; the xgb policy
- # learns from the impression log in batch.
- if getattr(settings, "SUPER_SEARCH_SELECTION_MODE", "cosine") == "lints":
- 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(
@@ -613,8 +607,8 @@ 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.
+ # 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(
diff --git a/mwmbl/tinysearchengine/super_search_select/__init__.py b/mwmbl/tinysearchengine/super_search_select/__init__.py
index c633e3f..52bc893 100644
--- a/mwmbl/tinysearchengine/super_search_select/__init__.py
+++ b/mwmbl/tinysearchengine/super_search_select/__init__.py
@@ -7,9 +7,11 @@ 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.
+- ``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.
+- ``rstats`` — per-source reward EMA in Redis (the contribution_ema feature).
+- ``xgb_model`` — the contextual-bandit reward model: training, artifact, serving.
+- ``policy`` — epsilon-greedy selection over the model's predicted rewards.
+- ``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
deleted file mode 100644
index cbe64d0..0000000
--- a/mwmbl/tinysearchengine/super_search_select/bandit.py
+++ /dev/null
@@ -1,134 +0,0 @@
-"""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/features.py b/mwmbl/tinysearchengine/super_search_select/features.py
index 95f3905..877c1f2 100644
--- a/mwmbl/tinysearchengine/super_search_select/features.py
+++ b/mwmbl/tinysearchengine/super_search_select/features.py
@@ -163,11 +163,3 @@ def feature_vector(
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
index 3a8973d..5403984 100644
--- a/mwmbl/tinysearchengine/super_search_select/policy.py
+++ b/mwmbl/tinysearchengine/super_search_select/policy.py
@@ -1,32 +1,27 @@
"""Source-selection policy: pick which ~10 of ~100 sources to query.
-Three interchangeable scorings over the same context features, chosen by
-``SUPER_SEARCH_SELECTION_MODE``:
-
-- **cosine** (default): greedy query-vs-profile cosine, with a few reserved
- slots for cold sites so new sources are discovered.
-- **lints**: per-arm linear-Gaussian Thompson sampling, which explores cold
- arms automatically via their wide posterior.
-- **xgb**: contextual bandit — an XGBoost model predicts each source's judge
- reward from the context features plus a source-identity one-hot, with
- epsilon-greedy exploration. Learns in batch from the impression log.
-
-Whichever runs, 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 reward attribution at request completion is
-consistent with the action taken.
+Contextual bandit: an XGBoost model (``xgb_model``) predicts each source's
+judge reward from the context features plus a source-identity one-hot, and
+selection is epsilon-greedy over those predictions — the explore slots keep
+cold sources discoverable and feed randomized pairs into the impression log,
+which is the model's batch training data. (The earlier greedy-cosine and
+per-arm Thompson-sampling policies were removed after the judge-reward evals;
+see mwmbl/rankeval/SUPER_SEARCH_XGB_FINDINGS.md.)
+
+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 reward attribution 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, rstats, xgb_model
+from mwmbl.tinysearchengine.super_search_select import profiles, rstats, xgb_model
from mwmbl.tinysearchengine.super_search_select.features import (
QueryContext,
- cosine_relevance,
feature_vector,
)
from mwmbl.tinysearchengine.super_search_select.registry import get_meta
@@ -42,7 +37,7 @@ def select_sources(
"""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.
+ recorded in ``ctx.features`` for consistent reward attribution later.
"""
if k is None:
k = settings.SUPER_SEARCH_SOURCES_TO_QUERY
@@ -71,15 +66,7 @@ def select_sources(
stats = rstats.get_stats(selectable)
feats = {n: feature_vector(qctx, get_meta(n), profs[n], stats[n]) for n in selectable}
- mode = settings.SUPER_SEARCH_SELECTION_MODE
- if mode == "xgb":
- chosen = _select_xgb(selectable, feats, budget)
- elif mode == "lints":
- chosen = _select_bandit(selectable, feats, budget)
- elif mode == "cosine":
- chosen = _select_cosine(qctx, selectable, profs, budget)
- else:
- raise ValueError(f"unknown SUPER_SEARCH_SELECTION_MODE {mode!r}")
+ chosen = _select_xgb(selectable, feats, budget)
if ctx is not None:
pinned_stats = rstats.get_stats([n for n in pinned if n not in feats])
@@ -96,28 +83,14 @@ def select_sources(
return pinned + 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_xgb(selectable, feats, budget) -> list[str]:
"""Epsilon-greedy over the XGBoost model's predicted rewards.
Each of the ``budget`` slots independently explores with probability
epsilon: the non-explore slots take the top-scored sources, the explore
slots are filled uniformly at random from the rest (cold sources included,
- so this subsumes the cosine path's explore floor and keeps randomized
- pairs flowing into the training log).
+ so exploration doubles as discovery and keeps randomized pairs flowing
+ into the training log).
"""
scores = xgb_model.get_model().score(feats)
ranked = sorted(selectable, key=lambda n: scores[n], reverse=True)
@@ -129,17 +102,6 @@ def _select_xgb(selectable, feats, budget) -> list[str]:
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)
diff --git a/test/test_super_search_bandit.py b/test/test_super_search_bandit.py
deleted file mode 100644
index dc59114..0000000
--- a/test/test_super_search_bandit.py
+++ /dev/null
@@ -1,124 +0,0 @@
-"""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, rstats
-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: lints selection populates ctx.features and respects k."""
- r = fakeredis.FakeRedis()
- monkeypatch.setattr(bandit, "_redis", r)
- monkeypatch.setattr(profiles, "_redis", r)
- monkeypatch.setattr(rstats, "_redis", r)
- monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "lints")
-
- 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_select.py b/test/test_super_search_select.py
index fd0f1c5..1d4aa94 100644
--- a/test/test_super_search_select.py
+++ b/test/test_super_search_select.py
@@ -4,7 +4,9 @@ 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 import (
+ features, policy, profiles, rewards, rstats, 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
@@ -14,9 +16,10 @@ DIM = 64
@pytest.fixture
def fake_profile_redis(monkeypatch):
- """Binary-safe fake Redis wired into the profiles module."""
+ """Binary-safe fake Redis wired into the profiles and rstats modules."""
r = fakeredis.FakeRedis() # decode_responses=False (vectors are raw bytes)
monkeypatch.setattr(profiles, "_redis", r)
+ monkeypatch.setattr(rstats, "_redis", r)
return r
@@ -92,16 +95,6 @@ def test_code_token_detected():
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)
@@ -129,14 +122,13 @@ def test_select_includes_always_on(fake_profile_redis, monkeypatch):
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")])
+def test_select_respects_budget_and_records_features(fake_profile_redis):
+ # Selection runs the xgb policy against the bundled warm-start artifact.
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
+ ctx = SelectionContext()
+ chosen = policy.select_sources("sql database query", names, k=3, ctx=ctx)
+ assert len(chosen) == 3
+ assert set(chosen) <= set(ctx.features)
# ---------------------------------------------------------------------------
diff --git a/test/test_super_search_xgb.py b/test/test_super_search_xgb.py
index b0ade4e..c12ad3a 100644
--- a/test/test_super_search_xgb.py
+++ b/test/test_super_search_xgb.py
@@ -209,11 +209,10 @@ def test_get_model_hot_reloads_after_retrain(tmp_path, monkeypatch):
@pytest.fixture
def xgb_policy_env(tmp_path, monkeypatch):
- """xgb selection mode with a toy artifact trained over the policy's sources."""
+ """Policy environment with a toy artifact trained over the policy's sources."""
r = fakeredis.FakeRedis()
monkeypatch.setattr(profiles, "_redis", r)
monkeypatch.setattr(rstats, "_redis", r)
- monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "xgb")
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_XGB_MODEL_DIR", str(tmp_path))
names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
_trained_model(tmp_path, sources=names)
@@ -253,7 +252,6 @@ def test_policy_xgb_missing_artifact_raises(monkeypatch, tmp_path):
r = fakeredis.FakeRedis()
monkeypatch.setattr(profiles, "_redis", r)
monkeypatch.setattr(rstats, "_redis", r)
- monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "xgb")
monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_XGB_MODEL_DIR",
str(tmp_path / "empty"))
monkeypatch.setattr(xgb_model, "BUNDLED_DIR", tmp_path / "no_bundle")
@@ -262,16 +260,6 @@ def test_policy_xgb_missing_artifact_raises(monkeypatch, tmp_path):
policy.select_sources("some query", names, k=5)
-def test_policy_unknown_mode_raises(monkeypatch):
- r = fakeredis.FakeRedis()
- monkeypatch.setattr(profiles, "_redis", r)
- monkeypatch.setattr(rstats, "_redis", r)
- monkeypatch.setattr("django.conf.settings.SUPER_SEARCH_SELECTION_MODE", "bogus")
- names = ["mwmbl", "hn"] + [f"site{i}" for i in range(20)]
- with pytest.raises(ValueError, match="SUPER_SEARCH_SELECTION_MODE"):
- policy.select_sources("some query", names, k=5)
-
-
# ---------------------------------------------------------------------------
# Online per-source reward EMA (rstats -> contribution_ema feature)
# ---------------------------------------------------------------------------