An open source, non-profit web search engine
Remove query text from SuperSearchImpression and SourceProvenance
Daoud Clarke15dfc9f395d9
diff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.pyindex 9181cec..8ea2c35 100644--- a/mwmbl/indexer/update_urls.py+++ b/mwmbl/indexer/update_urls.py@@ -171,7 +171,7 @@ def _propagate_source_provenance(crawled_page_links: dict[str, list[str]]):for link_url in link_urls:rows.append(SourceProvenance(url=link_url, source=source, parent_url=page_url[:500],- depth=depth + 1, query=None,+ depth=depth + 1,))if rows:SourceProvenance.objects.bulk_create(rows, ignore_conflicts=True)diff --git a/mwmbl/migrations/0027_remove_sourceprovenance_query_and_more.py b/mwmbl/migrations/0027_remove_sourceprovenance_query_and_more.pynew file mode 100644index 0000000..d9d5847--- /dev/null+++ b/mwmbl/migrations/0027_remove_sourceprovenance_query_and_more.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.13 on 2026-07-05 21:52++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ('mwmbl', '0026_sourceprovenance'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='sourceprovenance',+ name='query',+ ),+ migrations.RemoveField(+ model_name='supersearchimpression',+ name='query',+ ),+ ]diff --git a/mwmbl/models.py b/mwmbl/models.pyindex 33d2c98..ee60188 100644--- a/mwmbl/models.py+++ b/mwmbl/models.py@@ -233,9 +233,9 @@ class SuperSearchImpression(models.Model):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.+ durable training data for the contextual bandit. Deliberately does not+ store the query text, to avoid persisting user search history."""- query = models.CharField(max_length=512)candidates = models.JSONField(default=list) # all selectable source names (action space)selected = models.JSONField(default=list) # sources actually queriedfeatures = models.JSONField(default=dict) # {source: [feature vector]} for selected sources@@ -267,11 +267,11 @@ class SourceProvenance(models.Model):Written for each URL a source returns, and propagated onto links found onpages later crawled from those URLs, so source usefulness can be judged- offline including for descendant pages.+ offline including for descendant pages. Deliberately does not store the+ query text, to avoid persisting user search history."""url = models.URLField(max_length=500, unique=True) # first source wins, matches source_by_url semanticssource = models.CharField(max_length=128) # super-search source name (e.g. "gov.uk")- query = models.CharField(max_length=512, null=True, blank=True) # query for direct results; null when propagatedparent_url = models.URLField(max_length=500, null=True, blank=True) # page this URL was found on (null = direct result)depth = models.IntegerField(default=0) # 0 = direct super-search result; +1 per crawl hoptimestamp = models.DateTimeField(auto_now_add=True)diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.pyindex 4ef8cb5..57e5540 100644--- a/mwmbl/tinysearchengine/super_search.py+++ b/mwmbl/tinysearchengine/super_search.py@@ -534,7 +534,7 @@ def _enqueue_discovered_urls(ctx: SelectionContext) -> None:_add_found_urls_to_db_and_queue(found_urls, queued_batches)-async def _record_rewards(query: str, ctx: SelectionContext, last_results_key: list) -> None:+async def _record_rewards(ctx: SelectionContext, last_results_key: list) -> None:"""Compute per-source rewards and log the impression.Preferred reward: mean relevance-judge score of each source's final-pool@@ -549,11 +549,11 @@ async def _record_rewards(query: str, ctx: SelectionContext, last_results_key: ltop_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)+ await asyncio.to_thread(log_impression, ctx, rewards)except Exception:logger.exception("super-search failed to record rewards")try:- await asyncio.to_thread(record_source_provenance, query, ctx)+ await asyncio.to_thread(record_source_provenance, ctx)except Exception:logger.exception("super-search failed to record source provenance")try:@@ -697,7 +697,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 _record_rewards(selection_ctx, last_results_key)await queue.put(_SENTINEL)task = asyncio.create_task(producer())diff --git a/mwmbl/tinysearchengine/super_search_select/rewards.py b/mwmbl/tinysearchengine/super_search_select/rewards.pyindex 5c53cc2..ebe0110 100644--- a/mwmbl/tinysearchengine/super_search_select/rewards.py+++ b/mwmbl/tinysearchengine/super_search_select/rewards.py@@ -75,7 +75,7 @@ def compute_judge_rewards(ctx: SelectionContext) -> dict[str, float] | None:for name, (total, count) in totals.items()}-def log_impression(query: str, ctx: SelectionContext, rewards: dict[str, float]) -> None:+def log_impression(ctx: SelectionContext, rewards: dict[str, float]) -> None:"""Persist a SuperSearchImpression row (no-op without a database)."""if not getattr(settings, "HAS_DATABASE", False):return@@ -83,7 +83,6 @@ def log_impression(query: str, ctx: SelectionContext, rewards: dict[str, float])from mwmbl.models import SuperSearchImpressionSuperSearchImpression.objects.create(- query=query[:512],candidates=ctx.candidates,selected=ctx.selected,features=ctx.features,@@ -93,7 +92,7 @@ def log_impression(query: str, ctx: SelectionContext, rewards: dict[str, float])logger.exception("failed to log super-search impression")-def record_source_provenance(query: str, ctx: SelectionContext) -> None:+def record_source_provenance(ctx: SelectionContext) -> None:"""Persist a SourceProvenance row per (url, source) Super Search returned.Records the durable url -> source mapping (depth 0) so source usefulness can@@ -109,7 +108,7 @@ def record_source_provenance(query: str, ctx: SelectionContext) -> None:from mwmbl.models import SourceProvenancerows = [- SourceProvenance(url=url, source=source, query=query[:512], depth=0)+ SourceProvenance(url=url, source=source, depth=0)for url, source in ctx.source_by_url.items()]SourceProvenance.objects.bulk_create(rows, ignore_conflicts=True)diff --git a/test/test_super_search_select.py b/test/test_super_search_select.pyindex b8fbca0..fd0f1c5 100644--- a/test/test_super_search_select.py+++ b/test/test_super_search_select.py@@ -195,7 +195,7 @@ def test_compute_judge_rewards_none_without_scores():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})+ rewards.log_impression(SelectionContext(selected=["a"]), {"a": 0.5})def test_record_source_provenance_noop_without_database(monkeypatch):@@ -203,7 +203,7 @@ def test_record_source_provenance_noop_without_database(monkeypatch):ctx = SelectionContext(selected=["a"])ctx.record_results("a", ["https://x/u1"])# Should not raise even though provenance is gated off.- rewards.record_source_provenance("q", ctx)+ rewards.record_source_provenance(ctx)@pytest.mark.django_db@@ -215,15 +215,14 @@ def test_record_source_provenance_writes_direct_rows(monkeypatch):ctx.record_results("a", ["https://x/u1", "https://x/u2"])ctx.record_results("b", ["https://x/u3"])- rewards.record_source_provenance("my query", ctx)+ rewards.record_source_provenance(ctx)assert SourceProvenance.objects.count() == 3row = SourceProvenance.objects.get(url="https://x/u1")assert row.source == "a"assert row.depth == 0- assert row.query == "my query"assert row.parent_url is None# Idempotent: a second call must not raise or duplicate (unique url + ignore_conflicts).- rewards.record_source_provenance("my query", ctx)+ rewards.record_source_provenance(ctx)assert SourceProvenance.objects.count() == 3diff --git a/test/test_update_urls.py b/test/test_update_urls.pyindex e143355..5f17171 100644--- a/test/test_update_urls.py+++ b/test/test_update_urls.py@@ -77,7 +77,7 @@ def test_propagate_source_provenance_noop_without_database(monkeypatch):@pytest.mark.django_dbdef test_propagate_source_provenance_carries_source_to_links(monkeypatch):monkeypatch.setattr("django.conf.settings.HAS_DATABASE", True)- SourceProvenance.objects.create(url=PAGE, source="gov.uk", query="benefits", depth=0)+ SourceProvenance.objects.create(url=PAGE, source="gov.uk", depth=0)_propagate_source_provenance({PAGE: [CHILD_1, CHILD_2]})@@ -86,7 +86,6 @@ def test_propagate_source_provenance_carries_source_to_links(monkeypatch):assert row.source == "gov.uk"assert row.parent_url == PAGEassert row.depth == 1- assert row.query is None@pytest.mark.django_db