An open source, non-profit web search engine
Add Super Search streaming endpoint
Daoud Clarke4a49ba87255d
diff --git a/mwmbl/api.py b/mwmbl/api.pyindex f4ca633..06c4c46 100644--- a/mwmbl/api.py+++ b/mwmbl/api.py@@ -113,6 +113,7 @@ v2_api = NinjaExtraAPI(openapi_extra={"tags": [{"name": "Search"},+ {"name": "Super Search"},]},)@@ -137,12 +138,14 @@ def register_routers(ranker, batch_cache, queued_batches):dependencies (ranker, batch_cache, queued_batches) are available."""import mwmbl.tinysearchengine.search as search_module+ import mwmbl.tinysearchengine.super_search as super_search_moduleimport mwmbl.crawler.app as crawler_modulefrom mwmbl.platform.api import router as platform_router# Initialise routers that depend on runtime objectssearch_module.init_router(ranker)search_module.init_v2_router(ranker)+ super_search_module.init_router()crawler_module.init_router(batch_cache, queued_batches)api.add_router("/search/", search_module.router, tags=["Search"])@@ -150,3 +153,4 @@ def register_routers(ranker, batch_cache, queued_batches):api.add_router("/platform/", platform_router, tags=["Platform"])v2_api.add_router("/search/", search_module.v2_router, tags=["Search"])+ v2_api.add_router("/super-search/", super_search_module.router, tags=["Super Search"])diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex ee16ae0..e5f1b07 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -50,6 +50,21 @@ class MwmblConfig(AppConfig):Schedule periodic background tasks if they are not already queued.Uses django-background-tasks; requires `manage.py process_tasks` to be running."""+ import asyncio+ import logging+ log = logging.getLogger(__name__)++ # Under bare `uvicorn` (as opposed to gunicorn+uvicorn-workers), apps.ready()+ # runs with an active event loop, so the sync ORM call below raises+ # SynchronousOnlyOperation. The scheduling is idempotent and the production+ # `process_tasks` worker creates the entry too, so skip with a quiet note.+ try:+ asyncio.get_running_loop()+ log.info("Skipping background task scheduling: running in async context.")+ return+ except RuntimeError:+ pass+try:from background_task.models import Taskfrom mwmbl.background import sync_search_counts@@ -62,7 +77,4 @@ class MwmblConfig(AppConfig):except Exception:# Don't prevent startup if background task scheduling fails- import logging- logging.getLogger(__name__).exception(- "Failed to schedule background tasks"- )+ log.exception("Failed to schedule background tasks")diff --git a/mwmbl/quota.py b/mwmbl/quota.pyindex cf9506f..04799e2 100644--- a/mwmbl/quota.py+++ b/mwmbl/quota.py@@ -25,6 +25,13 @@ def _monthly_key(user_id: int, year: int | None = None, month: int | None = Nonereturn f"search:monthly:{user_id}:{y}:{m:02d}"+def _super_search_monthly_key(user_id: int, year: int | None = None, month: int | None = None) -> str:+ now = datetime.now(timezone.utc)+ y = year if year is not None else now.year+ m = month if month is not None else now.month+ return f"super_search:monthly:{user_id}:{y}:{m:02d}"++def _rate_key(user_id: int) -> str:return f"search:rate:{user_id}"@@ -71,6 +78,19 @@ def increment_monthly(user_id: int) -> int:return cache.incr(key)+def get_monthly_super_search_count(user_id: int) -> int:+ """Return the current monthly super-search request count for a user (0 if not set)."""+ return cache.get(_super_search_monthly_key(user_id), default=0)+++def increment_monthly_super_search(user_id: int) -> int:+ """Increment the monthly super-search counter and return the new value."""+ key = _super_search_monthly_key(user_id)+ if cache.add(key, 1, timeout=MONTHLY_TTL):+ return 1+ return cache.incr(key)++# ---------------------------------------------------------------------------# Key scanning (used by background jobs only — requires django-redis)# ---------------------------------------------------------------------------diff --git a/mwmbl/search_auth.py b/mwmbl/search_auth.pyindex 60abe71..0258ea8 100644--- a/mwmbl/search_auth.py+++ b/mwmbl/search_auth.py@@ -30,7 +30,9 @@ def invalidate_user_api_key_cache(user_id: int) -> None:class SearchApiKeyAuth(APIKeyHeader):param_name = "X-API-Key"- def authenticate(self, request, key: str):+ def authenticate(self, request, key: str | None):+ if not key:+ return Nonekey_hash = hashlib.sha256(key.encode()).hexdigest()cache_key = _cache_key(key_hash)diff --git a/mwmbl/search_setup.py b/mwmbl/search_setup.pyindex b75e0a4..9fb2922 100644--- a/mwmbl/search_setup.py+++ b/mwmbl/search_setup.py@@ -33,7 +33,7 @@ index_path = Path(settings.DATA_PATH) / settings.INDEX_NAMEtiny_index = TinyIndex(item_factory=Document, index_path=index_path)tiny_index.__enter__()-_model = RustXGBPipeline.from_model_path(str(settings.RUST_MODEL_PATH))-ranker = DomainLimitingRanker(LTRRanker(tiny_index, completer, _model, include_wiki=True, num_wiki_results=3))+ltr_model = RustXGBPipeline.from_model_path(str(settings.RUST_MODEL_PATH))+ranker = DomainLimitingRanker(LTRRanker(tiny_index, completer, ltr_model, include_wiki=True, num_wiki_results=3))batch_cache = BatchCache(Path(settings.DATA_PATH) / settings.BATCH_DIR_NAME)diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 7767d7a..47a538a 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -275,3 +275,13 @@ CURRENT_AGREEMENT_VERSIONS = {"TERMS_OF_SERVICE_GUI": "v2026-04-A","TERMS_OF_SERVICE_API": "v2026-04-A",}++# Super Search+SUPER_SEARCH_MONTHLY_LIMIT = 10+SUPER_SEARCH_TOP_K = 10 # promote sources in top-K seen so far for crawling+SUPER_SEARCH_DEADLINE_SECONDS = 10.0+SUPER_SEARCH_PER_SOURCE_TIMEOUT = 2.0+SUPER_SEARCH_MAX_CONCURRENT_PER_HOST = 4+SUPER_SEARCH_MAX_LINKS_PER_PAGE = 3+SUPER_SEARCH_RESULTS_PER_SOURCE = 10+SUPER_SEARCH_FINAL_RESULTS_LIMIT = 100diff --git a/mwmbl/tinysearchengine/ltr_rank.py b/mwmbl/tinysearchengine/ltr_rank.pyindex 95e0daa..16dd1ab 100644--- a/mwmbl/tinysearchengine/ltr_rank.py+++ b/mwmbl/tinysearchengine/ltr_rank.py@@ -80,3 +80,21 @@ class LTRRanker(Ranker):if self.include_wiki:return get_wiki_results(query, self.num_wiki_results)return []+++def score_documents(model, query: str, documents: list[Document]) -> list[float]:+ """Run the LTR model over the given documents and return raw per-doc scores.++ Sync — call from a thread when used inside an async context.+ """+ if not documents:+ return []+ data = [{+ 'query': query,+ 'url': page.url,+ 'title': page.title if page.title is not None else "",+ 'extract': page.extract if page.extract is not None else "",+ 'score': page.score if page.score is not None else 0.0,+ } for page in documents]+ predictions = model.predict(data)+ return [float(p) for p in predictions]diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.pynew file mode 100644index 0000000..b21c78f--- /dev/null+++ b/mwmbl/tinysearchengine/super_search.py@@ -0,0 +1,385 @@+"""Super Search — multi-source streaming search endpoint.++Fans out a query to several external search APIs, re-ranks the union with the+existing LTR model, and for any result above the threshold fetches the page,+picks promising outbound links, and re-ranks those too. Progress and results+are streamed to the client over Server-Sent Events.++See plan: /api/v2/super-search/+"""+import asyncio+import heapq+import json+import logging+import re+import time+from typing import Any+from urllib.parse import unquote, urlparse++import httpx+from asgiref.sync import sync_to_async+from django.conf import settings+from django.http import StreamingHttpResponse+from ninja import Router+from ninja.errors import HttpError++from mwmbl.crawler.retrieve import crawl_url+from mwmbl.models import MwmblUser+from mwmbl.quota import (+ check_rate_limit,+ get_monthly_super_search_count,+ increment_monthly_super_search,+)+from mwmbl.search_auth import SearchApiKeyAuth+from mwmbl.search_setup import ltr_model+from mwmbl.tinysearchengine.indexer import Document+from mwmbl.tinysearchengine.ltr_rank import score_documents+from mwmbl.tinysearchengine.super_search_sources import SOURCES++logger = logging.getLogger(__name__)++router = Router(tags=["Super Search"])++KEEPALIVE_INTERVAL = 5.0 # seconds between idle keepalive comments+HTTP_USER_AGENT = "mwmbl-super-search/0.1 (+https://mwmbl.org)"+_SENTINEL: object = object()+_URL_EXT_RE = re.compile(r"\.\w{1,5}$")+_URL_TOKEN_RE = re.compile(r"[-_+]+")+++# ---------------------------------------------------------------------------+# SSE helpers+# ---------------------------------------------------------------------------++def _sse_frame(event_type: str, data: Any) -> bytes:+ payload = json.dumps(data, default=str, ensure_ascii=False)+ return f"event: {event_type}\ndata: {payload}\n\n".encode("utf-8")+++def _result_payload(doc: Document, score: float, source: str, origin: str) -> dict:+ return {+ "url": doc.url,+ "title": doc.title,+ "extract": doc.extract,+ "score": round(score, 4),+ "source": source,+ "origin": origin,+ }+++def _title_from_url(url: str) -> str:+ """Cheap human-readable proxy used to score outbound links with the LTR model."""+ try:+ parsed = urlparse(url)+ except ValueError:+ return url+ segments = [s for s in parsed.path.split("/") if s]+ if not segments:+ return parsed.netloc+ last = unquote(segments[-1])+ last = _URL_EXT_RE.sub("", last)+ return _URL_TOKEN_RE.sub(" ", last).strip() or parsed.netloc+++async def _authenticate(request) -> MwmblUser:+ """Resolve the requesting user from either an X-API-Key header or a JWT.++ Returns the user on success; raises HttpError(401) otherwise.+ Database lookups are off-loaded via ``sync_to_async`` because the view+ that calls this is async.+ """+ raw_key = request.headers.get("X-API-Key")+ if raw_key:+ api_key = await sync_to_async(SearchApiKeyAuth().authenticate)(request, raw_key)+ if api_key is None:+ raise HttpError(401, "Invalid API key.")+ return await sync_to_async(lambda: api_key.user)()++ auth_header = request.headers.get("Authorization", "")+ if auth_header.startswith("Bearer "):+ token = auth_header[len("Bearer "):]+ try:+ from ninja_jwt.tokens import AccessToken+ access = AccessToken(token)+ user_id = access["user_id"]+ except Exception:+ raise HttpError(401, "Invalid token.")+ try:+ return await sync_to_async(MwmblUser.objects.get)(id=user_id)+ except MwmblUser.DoesNotExist:+ raise HttpError(401, "Unknown user.")++ raise HttpError(401, "Authentication required: X-API-Key or Bearer token.")+++# ---------------------------------------------------------------------------+# Pipeline+# ---------------------------------------------------------------------------++async def _call_source(name: str, fn, client: httpx.AsyncClient, query: str, limit: int):+ try:+ docs = await asyncio.wait_for(+ fn(client, query, limit),+ timeout=settings.SUPER_SEARCH_PER_SOURCE_TIMEOUT,+ )+ return name, docs, None+ except asyncio.TimeoutError:+ return name, [], "timeout"+ except Exception as e: # noqa: BLE001 — adapters shouldn't raise but be defensive+ logger.info("super-search source %s raised: %s", name, e)+ return name, [], str(e)+++async def _follow_links(+ parent: Document, parent_source: str, query: str, emit, all_docs: list[Document]+) -> None:+ """Crawl the parent URL, score its outbound links, and collect the best for final ranking."""+ max_links = settings.SUPER_SEARCH_MAX_LINKS_PER_PAGE++ try:+ result = await asyncio.to_thread(crawl_url, parent.url)+ except Exception as e: # noqa: BLE001+ logger.info("crawl_url failed for %s: %s", parent.url, e)+ return++ content = result.get("content") if isinstance(result, dict) else None+ if not content:+ return++ raw_links = list(content.get("links") or []) + list(content.get("extra_links") or [])+ raw_links = raw_links[:50]+ await emit("page_fetched", {"url": parent.url, "links": len(raw_links)})+ if not raw_links:+ return++ proxy_docs = [Document(title=_title_from_url(u), url=u, extract="") for u in raw_links]+ proxy_scores = await asyncio.to_thread(score_documents, ltr_model, query, proxy_docs)++ ranked = sorted(zip(proxy_docs, proxy_scores), key=lambda x: -x[1])[:max_links]+ if not ranked:+ return++ fetches = await asyncio.gather(+ *[asyncio.to_thread(crawl_url, d.url) for d, _ in ranked],+ return_exceptions=True,+ )++ for (proxy_doc, _), fetched in zip(ranked, fetches):+ if isinstance(fetched, Exception):+ continue+ c = fetched.get("content") if isinstance(fetched, dict) else None+ if not c:+ continue+ await emit("link_followed", {"url": proxy_doc.url, "from": parent.url})+ doc = Document(+ title=c.get("title") or _title_from_url(proxy_doc.url),+ url=proxy_doc.url,+ extract=c.get("extract") or "",+ )+ if doc.url and doc.title and doc.extract:+ all_docs.append(doc)+++async def _run_pipeline(query: str, emit) -> None:+ per_source_limit = settings.SUPER_SEARCH_RESULTS_PER_SOURCE+ top_k = getattr(settings, "SUPER_SEARCH_TOP_K", 10)+ final_limit = getattr(settings, "SUPER_SEARCH_FINAL_RESULTS_LIMIT", 100)+ limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)+ timeout = httpx.Timeout(settings.SUPER_SEARCH_PER_SOURCE_TIMEOUT)++ all_docs: list[Document] = []++ # Min-heap tracking top-K seen so far: (score, counter, doc).+ # A doc enters the top-K when the heap has < k entries or its score beats+ # the current minimum; once promoted it is never un-promoted.+ _heap: list[tuple[float, int, Document]] = []+ _promoted_urls: set[str] = set()+ _ctr = 0++ def _maybe_promote(doc: Document, score: float) -> bool:+ nonlocal _ctr+ if doc.url in _promoted_urls:+ return False+ if len(_heap) < top_k:+ heapq.heappush(_heap, (score, _ctr, doc))+ elif score > _heap[0][0]:+ heapq.heapreplace(_heap, (score, _ctr, doc))+ else:+ return False+ _ctr += 1+ _promoted_urls.add(doc.url)+ return True++ async with httpx.AsyncClient(+ limits=limits,+ timeout=timeout,+ follow_redirects=True,+ headers={"User-Agent": HTTP_USER_AGENT},+ ) as client:+ source_tasks = []+ for name, fn in SOURCES.items():+ await emit("source_started", {"source": name})+ source_tasks.append(+ asyncio.create_task(_call_source(name, fn, client, query, per_source_limit))+ )++ secondary: list[asyncio.Task] = []++ for completed in asyncio.as_completed(source_tasks):+ name, docs, error = await completed+ if error is not None:+ await emit("source_failed", {"source": name, "error": error})+ continue+ await emit("source_returned", {"source": name, "count": len(docs)})+ if not docs:+ continue++ scores = await asyncio.to_thread(score_documents, ltr_model, query, docs)+ for doc, score in zip(docs, scores):+ if doc.url and doc.title and doc.extract:+ all_docs.append(doc)+ if _maybe_promote(doc, score):+ await emit("result_promoted", _result_payload(doc, score, name, "direct"))+ secondary.append(+ asyncio.create_task(_follow_links(doc, name, query, emit, all_docs))+ )++ if secondary:+ await asyncio.gather(*secondary, return_exceptions=True)++ # Deduplicate and produce final ranked list.+ seen: set[str] = set()+ unique: list[Document] = []+ for doc in all_docs:+ if doc.url and doc.title and doc.extract and doc.url not in seen:+ seen.add(doc.url)+ unique.append(doc)++ if unique:+ final_scores = await asyncio.to_thread(score_documents, ltr_model, query, unique)+ ranked = sorted(zip(unique, final_scores), key=lambda x: -x[1])[:final_limit]+ await emit("results", {+ "results": [_result_payload(doc, score, "", "final") for doc, score in ranked],+ "count": len(ranked),+ })+++# ---------------------------------------------------------------------------+# SSE generator+# ---------------------------------------------------------------------------++async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):+ queue: asyncio.Queue = asyncio.Queue()+ started = time.monotonic()+ reason = "complete"++ async def emit(event_type: str, data: Any) -> None:+ await queue.put((event_type, data))++ async def producer():+ nonlocal reason+ try:+ await asyncio.wait_for(+ _run_pipeline(query, emit),+ timeout=settings.SUPER_SEARCH_DEADLINE_SECONDS,+ )+ except asyncio.TimeoutError:+ reason = "timed_out"+ except asyncio.CancelledError:+ reason = "cancelled"+ raise+ except Exception as e: # noqa: BLE001+ logger.exception("super-search pipeline crashed")+ reason = "error"+ await queue.put(("error", {"message": str(e)}))+ finally:+ await queue.put(_SENTINEL)++ task = asyncio.create_task(producer())++ try:+ while True:+ try:+ item = await asyncio.wait_for(queue.get(), timeout=KEEPALIVE_INTERVAL)+ except asyncio.TimeoutError:+ yield b": keepalive\n\n"+ continue+ if item is _SENTINEL:+ break+ event_type, data = item+ yield _sse_frame(event_type, data)++ yield _sse_frame("done", {+ "reason": reason,+ "elapsed_seconds": round(time.monotonic() - started, 3),+ "monthly_usage": monthly_usage,+ "monthly_limit": monthly_limit,+ })+ finally:+ if not task.done():+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception):+ pass+++# ---------------------------------------------------------------------------+# Route registration+# ---------------------------------------------------------------------------++def init_router() -> None:+ @router.get(+ "",+ auth=None, # handled manually in the view to support both API key and JWT under an async view+ summary="Super Search (streaming, SSE)",+ description=(+ "Multi-source streaming search. Fans out to Hacker News, GitHub, "+ "Stack Exchange, ArXiv and PyPI, re-ranks all results with the "+ "Mwmbl LTR model, and for items above the relevance threshold "+ "crawls the page and follows the most promising outbound links.\n\n"+ "Authentication is required (search-scoped API key in `X-API-Key` "+ "or JWT bearer token). Quota is 10 requests per user per month.\n\n"+ "Returns `text/event-stream`. Event types: `source_started`, "+ "`source_returned`, `source_failed`, `result_promoted`, "+ "`page_fetched`, `link_followed`, `error`, `done`."+ ),+ openapi_extra={+ "parameters": [{+ "name": "q",+ "in": "query",+ "required": True,+ "schema": {"type": "string", "example": "rust async runtimes"},+ }],+ "responses": {+ "200": {+ "description": "An SSE stream of search events.",+ "content": {"text/event-stream": {"schema": {"type": "string"}}},+ },+ },+ },+ )+ async def super_search(request, q: str):+ user = await _authenticate(request)++ if not await sync_to_async(check_rate_limit)(user.id):+ raise HttpError(429, "Rate limit exceeded: maximum 5 requests per second.")++ monthly_limit = settings.SUPER_SEARCH_MONTHLY_LIMIT+ current = await sync_to_async(get_monthly_super_search_count)(user.id)+ if current >= monthly_limit:+ raise HttpError(+ 429,+ f"Super Search monthly quota exceeded: {monthly_limit} requests per month "+ f"and you have used {current}.",+ )+ monthly_usage = await sync_to_async(increment_monthly_super_search)(user.id)++ return StreamingHttpResponse(+ _sse_stream(q, monthly_usage, monthly_limit),+ content_type="text/event-stream",+ headers={+ "X-Accel-Buffering": "no",+ "Cache-Control": "no-cache",+ },+ )diff --git a/mwmbl/tinysearchengine/super_search_sources/__init__.py b/mwmbl/tinysearchengine/super_search_sources/__init__.pynew file mode 100644index 0000000..4cf5cd9--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/__init__.py@@ -0,0 +1,20 @@+"""External-search adapters used by Super Search.++Each adapter exposes ``async def search(client, query, limit) -> list[Document]``+and is responsible for one external API. Adapters never raise on HTTP/parse+errors — they log and return an empty list so one slow source can't sink the+orchestrator.+"""+from mwmbl.tinysearchengine.super_search_sources.arxiv import search as search_arxiv+from mwmbl.tinysearchengine.super_search_sources.github import search as search_github+from mwmbl.tinysearchengine.super_search_sources.hn import search as search_hn+from mwmbl.tinysearchengine.super_search_sources.pypi import search as search_pypi+from mwmbl.tinysearchengine.super_search_sources.stackexchange import search as search_stackexchange++SOURCES = {+ "hn": search_hn,+ "github": search_github,+ "stackexchange": search_stackexchange,+ "arxiv": search_arxiv,+ "pypi": search_pypi,+}diff --git a/mwmbl/tinysearchengine/super_search_sources/arxiv.py b/mwmbl/tinysearchengine/super_search_sources/arxiv.pynew file mode 100644index 0000000..7fb64cd--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/arxiv.py@@ -0,0 +1,44 @@+"""ArXiv search via the public Atom API."""+import logging+from xml.etree import ElementTree as ET++import httpx++from mwmbl.tinysearchengine.indexer import Document++logger = logging.getLogger(__name__)++ENDPOINT = "https://export.arxiv.org/api/query"+NS = {+ "atom": "http://www.w3.org/2005/Atom",+}+++async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Document]:+ try:+ response = await client.get(+ ENDPOINT,+ params={+ "search_query": f"all:{query}",+ "start": 0,+ "max_results": limit,+ },+ )+ response.raise_for_status()+ root = ET.fromstring(response.text)+ except (httpx.HTTPError, ET.ParseError) as e:+ logger.info("ArXiv source failed: %s", e)+ return []++ docs: list[Document] = []+ for entry in root.findall("atom:entry", NS):+ url_el = entry.find("atom:id", NS)+ title_el = entry.find("atom:title", NS)+ summary_el = entry.find("atom:summary", NS)+ if url_el is None or url_el.text is None:+ continue+ url = url_el.text.strip()+ title = (title_el.text or "").strip() if title_el is not None else ""+ extract = (summary_el.text or "").strip() if summary_el is not None else ""+ docs.append(Document(title=title, url=url, extract=extract))+ return docsdiff --git a/mwmbl/tinysearchengine/super_search_sources/github.py b/mwmbl/tinysearchengine/super_search_sources/github.pynew file mode 100644index 0000000..b31d52d--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/github.py@@ -0,0 +1,39 @@+"""GitHub repository search via the unauthenticated REST API.++Unauthenticated calls are limited to 10 requests/minute for the search endpoint,+which is acceptable for the initial Super Search release. Add a token later+to lift the cap.+"""+import logging++import httpx++from mwmbl.tinysearchengine.indexer import Document++logger = logging.getLogger(__name__)++ENDPOINT = "https://api.github.com/search/repositories"+++async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Document]:+ try:+ response = await client.get(+ ENDPOINT,+ params={"q": query, "per_page": limit},+ headers={"Accept": "application/vnd.github+json"},+ )+ response.raise_for_status()+ payload = response.json()+ except (httpx.HTTPError, ValueError) as e:+ logger.info("GitHub source failed: %s", e)+ return []++ docs: list[Document] = []+ for item in payload.get("items", []):+ url = item.get("html_url")+ if not url:+ continue+ title = item.get("full_name") or item.get("name") or ""+ extract = item.get("description") or ""+ docs.append(Document(title=title, url=url, extract=extract))+ return docsdiff --git a/mwmbl/tinysearchengine/super_search_sources/hn.py b/mwmbl/tinysearchengine/super_search_sources/hn.pynew file mode 100644index 0000000..5e78df4--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/hn.py@@ -0,0 +1,33 @@+"""Hacker News via the Algolia search API (no auth required)."""+import logging++import httpx++from mwmbl.tinysearchengine.indexer import Document++logger = logging.getLogger(__name__)++ENDPOINT = "https://hn.algolia.com/api/v1/search"+++async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Document]:+ try:+ response = await client.get(+ ENDPOINT,+ params={"query": query, "hitsPerPage": limit, "tags": "story"},+ )+ response.raise_for_status()+ payload = response.json()+ except (httpx.HTTPError, ValueError) as e:+ logger.info("HN source failed: %s", e)+ return []++ docs: list[Document] = []+ for hit in payload.get("hits", []):+ url = hit.get("url") or f"https://news.ycombinator.com/item?id={hit.get('objectID')}"+ title = hit.get("title") or hit.get("story_title") or ""+ extract = hit.get("story_text") or hit.get("comment_text") or ""+ if not title and not extract:+ continue+ docs.append(Document(title=title, url=url, extract=extract))+ return docsdiff --git a/mwmbl/tinysearchengine/super_search_sources/pypi.py b/mwmbl/tinysearchengine/super_search_sources/pypi.pynew file mode 100644index 0000000..8f7c1bf--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/pypi.py@@ -0,0 +1,38 @@+"""PyPI lookup via the JSON API.++PyPI has no public full-text search endpoint, so we treat the query as a+package name and look it up directly. Returns at most one Document.+"""+import logging+import re++import httpx++from mwmbl.tinysearchengine.indexer import Document++logger = logging.getLogger(__name__)++ENDPOINT = "https://pypi.org/pypi/{name}/json"+NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")+++async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Document]:+ name = query.strip().split()[0] if query.strip() else ""+ if not name or not NAME_RE.match(name):+ return []++ try:+ response = await client.get(ENDPOINT.format(name=name))+ if response.status_code == 404:+ return []+ response.raise_for_status()+ payload = response.json()+ except (httpx.HTTPError, ValueError) as e:+ logger.info("PyPI source failed: %s", e)+ return []++ info = payload.get("info") or {}+ url = info.get("package_url") or f"https://pypi.org/project/{name}/"+ title = info.get("name") or name+ extract = info.get("summary") or ""+ return [Document(title=title, url=url, extract=extract)]diff --git a/mwmbl/tinysearchengine/super_search_sources/stackexchange.py b/mwmbl/tinysearchengine/super_search_sources/stackexchange.pynew file mode 100644index 0000000..95704a5--- /dev/null+++ b/mwmbl/tinysearchengine/super_search_sources/stackexchange.py@@ -0,0 +1,51 @@+"""Stack Exchange (Stack Overflow site) search via the public API.++Unauthenticated requests are subject to a 300/day quota per IP. The adapter+silently returns [] on quota or transport errors.+"""+import html+import logging++import httpx++from mwmbl.tinysearchengine.indexer import Document++logger = logging.getLogger(__name__)++ENDPOINT = "https://api.stackexchange.com/2.3/search/advanced"+++async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Document]:+ try:+ response = await client.get(+ ENDPOINT,+ params={+ "q": query,+ "site": "stackoverflow",+ "order": "desc",+ "sort": "relevance",+ "pagesize": limit,+ },+ )+ response.raise_for_status()+ payload = response.json()+ except (httpx.HTTPError, ValueError) as e:+ logger.info("Stack Exchange source failed: %s", e)+ return []++ docs: list[Document] = []+ for item in payload.get("items", []):+ url = item.get("link")+ if not url:+ continue+ title = html.unescape(item.get("title") or "")+ tags = " ".join(item.get("tags", []))+ score = item.get("score")+ bits = []+ if tags:+ bits.append(f"Tags: {tags}.")+ if score is not None:+ bits.append(f"Score: {score}.")+ extract = " ".join(bits)+ docs.append(Document(title=title, url=url, extract=extract))+ return docsdiff --git a/pyproject.toml b/pyproject.tomlindex b1ae307..f759e4b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -46,6 +46,7 @@ dependencies = ["django-background-tasks>=1.2.8","django-redis>=5.4.0","polar-sdk>=0.10.0",+ "httpx>=0.27.0",][project.optional-dependencies]@@ -69,6 +70,9 @@ dev = ["pytest>=7.0.1","pytest-mock>=3.10.0","pytest-django>=4.5.2",+ "pytest-asyncio>=0.23.0",+ "pytest-httpx>=0.30.0",+ "blockbuster>=1.5.0","fakeredis>=2.30.1","maturin>=1.5,<2.0","patchelf>=0.17.2.4",@@ -88,3 +92,4 @@ log_cli_level = "INFO"DJANGO_SETTINGS_MODULE = "mwmbl.settings_test"python_files = ["tests.py", "test_*.py", "*_tests.py"]addopts = "--reuse-db"+asyncio_mode = "auto"diff --git a/test/conftest.py b/test/conftest.pynew file mode 100644index 0000000..b0da0ed--- /dev/null+++ b/test/conftest.py@@ -0,0 +1,35 @@+"""Pytest configuration shared across the test suite.++The `blockbuster` fixture installs BlockBuster, which monkey-patches the+stdlib blocking primitives (`socket`, `time.sleep`, file I/O…) and raises+when they are called from a running event loop. Use it in async tests that+exercise code which must not block — particularly Super Search.++We also enable asyncio debug mode and lower `slow_callback_duration` so any+callback that runs longer than 100 ms triggers a warning. Combined with+`-W error::RuntimeWarning` (set per test if desired), this catches most+accidental sync calls leaking into async paths.+"""+import asyncio+import sys++import pytest+++def blockbuster():+ """Detect blocking calls made from inside the event loop during the test."""+ try:+ from blockbuster import blockbuster_ctx+ except ImportError: # pragma: no cover+ pytest.skip("blockbuster not installed")+ with blockbuster_ctx() as bb:+ yield bb+++def async_debug_loop(event_loop):+ """Enable asyncio debug mode and a strict slow-callback threshold."""+ event_loop.set_debug(True)+ event_loop.slow_callback_duration = 0.1+ yield event_loopdiff --git a/test/test_super_search.py b/test/test_super_search.pynew file mode 100644index 0000000..e8cfa5f--- /dev/null+++ b/test/test_super_search.py@@ -0,0 +1,262 @@+"""Integration tests for the Super Search streaming endpoint.++These tests:+- Mock external sources and `crawl_url` so no network is touched.+- Stub the LTR scoring helper so promotion is deterministic.+- Verify quota, auth, event ordering, and forbidden-symbol presence in+ the orchestrator (architecture guard).+"""+import json+from pathlib import Path+from unittest.mock import patch++import pytest+from allauth.account.models import EmailAddress+from asgiref.sync import async_to_sync+from django.contrib.auth import get_user_model+from django.core.cache import cache+from django.test import Client, override_settings+from ninja_jwt.tokens import RefreshToken++from mwmbl.models import ApiKey, generate_api_key+from mwmbl.quota import _super_search_monthly_key+from mwmbl.tinysearchengine.indexer import Document++User = get_user_model()+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------++def user(db):+ u = User.objects.create_user(username="ssuser", email="[email protected]", password="x")+ EmailAddress.objects.create(user=u, email="[email protected]", verified=True, primary=True)+ return u+++def access_token(user):+ return str(RefreshToken.for_user(user).access_token)+++def api_key(user):+ raw, h = generate_api_key()+ obj = ApiKey.objects.create(user=user, key=h, name="ss", scopes=[ApiKey.Scope.SEARCH])+ obj.raw_key = raw+ return obj+++def client(db):+ return Client()+++def _parse_sse(body: bytes) -> list[tuple[str, dict]]:+ events: list[tuple[str, dict]] = []+ for chunk in body.split(b"\n\n"):+ chunk = chunk.strip()+ if not chunk or chunk.startswith(b":"):+ continue+ event_type = None+ data = None+ for line in chunk.split(b"\n"):+ if line.startswith(b"event: "):+ event_type = line[len(b"event: "):].decode()+ elif line.startswith(b"data: "):+ data = json.loads(line[len(b"data: "):].decode())+ if event_type is not None:+ events.append((event_type, data))+ return events+++def _read_stream(response) -> bytes:+ content = response.streaming_content+ if hasattr(content, "__aiter__"):+ async def _collect():+ return b"".join([chunk async for chunk in content])+ return async_to_sync(_collect)()+ return b"".join(content)+++def _stub_sources(monkeypatch, by_source: dict[str, list[Document]]):+ """Replace the live source adapters with deterministic stubs."""+ import mwmbl.tinysearchengine.super_search as ss++ new_sources = {}+ for name, docs in by_source.items():+ async def fake_search(client, query, limit, _docs=docs):+ return _docs+ new_sources[name] = fake_search+ monkeypatch.setattr(ss, "SOURCES", new_sources)+++def _stub_scoring(monkeypatch, scores: list[float]):+ """Make score_documents return the supplied list (one score per doc)."""+ import mwmbl.tinysearchengine.super_search as ss++ iterator = iter(scores)++ def fake_score(model, query, docs):+ return [next(iterator, 0.0) for _ in docs]++ monkeypatch.setattr(ss, "score_documents", fake_score)+++# ---------------------------------------------------------------------------+# Auth & quota+# ---------------------------------------------------------------------------++def test_super_search_requires_auth(client):+ response = client.get("/api/v2/super-search/?q=python")+ assert response.status_code == 401+++def test_super_search_with_api_key(client, api_key, monkeypatch):+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {"hn": []})+ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ assert response.status_code == 200+ events = _parse_sse(_read_stream(response))+ assert any(t == "done" for t, _ in events)+++def test_super_search_with_jwt(client, access_token, user, monkeypatch):+ cache.delete(_super_search_monthly_key(user.id))+ _stub_sources(monkeypatch, {"hn": []})+ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_AUTHORIZATION=f"Bearer {access_token}",+ )+ assert response.status_code == 200+ _read_stream(response)+++def test_super_search_quota_enforced(client, api_key, monkeypatch):+ cache.set(_super_search_monthly_key(api_key.user.id), 10, timeout=3600)+ _stub_sources(monkeypatch, {"hn": []})+ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ assert response.status_code == 429+ cache.delete(_super_search_monthly_key(api_key.user.id))+++# ---------------------------------------------------------------------------+# Event-stream behaviour+# ---------------------------------------------------------------------------++@override_settings(SUPER_SEARCH_TOP_K=2)+def test_promoted_results_use_top_k(client, api_key, monkeypatch):+ """Exactly top-K docs are promoted for crawling; surplus docs are excluded."""+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [+ Document(title="Best", url="https://best.example/", extract="x"),+ Document(title="Second", url="https://second.example/", extract="x"),+ Document(title="Third", url="https://third.example/", extract="x"),+ ],+ })+ # Scores in descending order — only the top-2 should be promoted.+ _stub_scoring(monkeypatch, [0.9, 0.5, 0.1] + [0.0] * 20)++ def fake_crawl(url):+ return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}++ monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ assert response.status_code == 200+ events = _parse_sse(_read_stream(response))+ event_types = [t for t, _ in events]++ assert "source_started" in event_types+ assert "source_returned" in event_types+ promoted = [d for t, d in events if t == "result_promoted"]+ promoted_urls = {p["url"] for p in promoted}+ assert len(promoted) == 2+ assert "https://best.example/" in promoted_urls+ assert "https://second.example/" in promoted_urls+ assert "https://third.example/" not in promoted_urls+ assert event_types[-1] == "done"+++def test_final_results_event_emitted(client, api_key, monkeypatch):+ """A 'results' event with the full ranked list is emitted before 'done'."""+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [Document(title="Python intro", url="https://py.example/", extract="A guide")],+ })+ _stub_scoring(monkeypatch, [0.5] + [0.0] * 20)++ def fake_crawl(url):+ return {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None}++ monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ assert response.status_code == 200+ events = _parse_sse(_read_stream(response))+ event_types = [t for t, _ in events]++ assert "results" in event_types+ results_events = [d for t, d in events if t == "results"]+ assert len(results_events) == 1+ results = results_events[0]["results"]+ assert len(results) >= 1+ assert results[0]["url"] == "https://py.example/"+ # 'results' must appear before 'done'+ assert event_types.index("results") < event_types.index("done")+++def test_source_failure_emits_source_failed(client, api_key, monkeypatch):+ cache.delete(_super_search_monthly_key(api_key.user.id))++ import mwmbl.tinysearchengine.super_search as ss++ async def bad_source(client, query, limit):+ raise RuntimeError("boom")++ monkeypatch.setattr(ss, "SOURCES", {"hn": bad_source})++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ events = _parse_sse(_read_stream(response))+ types = [t for t, _ in events]+ assert "source_failed" in types+ assert types[-1] == "done"+++# ---------------------------------------------------------------------------+# Architecture guard: no forbidden sync symbols in the orchestrator+# ---------------------------------------------------------------------------++def test_super_search_module_has_no_blocking_imports():+ """A failsafe against accidentally importing the sync `requests` lib+ or using `time.sleep` at module scope in the async orchestrator.+ """+ path = Path(__file__).resolve().parent.parent / "mwmbl" / "tinysearchengine" / "super_search.py"+ source = path.read_text()+ assert "\nimport requests" not in source and "\nfrom requests " not in source+ assert "time.sleep" not in sourcediff --git a/test/test_super_search_sources.py b/test/test_super_search_sources.pynew file mode 100644index 0000000..927df44--- /dev/null+++ b/test/test_super_search_sources.py@@ -0,0 +1,151 @@+"""Per-source adapter tests for Super Search.++Each adapter is exercised against a mocked httpx transport so we can verify+result coercion without hitting the network. We also assert that an HTTP+error returns an empty list rather than propagating — orchestrator robustness+depends on this.+"""+import re++import httpx+import pytest++from mwmbl.tinysearchengine.super_search_sources.arxiv import search as search_arxiv+from mwmbl.tinysearchengine.super_search_sources.github import search as search_github+from mwmbl.tinysearchengine.super_search_sources.hn import search as search_hn+from mwmbl.tinysearchengine.super_search_sources.pypi import search as search_pypi+from mwmbl.tinysearchengine.super_search_sources.stackexchange import search as search_stackexchange+++async def _client():+ return httpx.AsyncClient()+++# ---------------------------------------------------------------------------+# Hacker News (Algolia)+# ---------------------------------------------------------------------------++async def test_hn_returns_documents(httpx_mock):+ httpx_mock.add_response(+ url="https://hn.algolia.com/api/v1/search?query=python&hitsPerPage=5&tags=story",+ json={"hits": [+ {"title": "Why Python", "url": "https://example.com/why", "objectID": "1"},+ {"title": "Ask HN", "story_text": "Some text", "objectID": "2"}, # no url+ ]},+ )+ async with httpx.AsyncClient() as client:+ docs = await search_hn(client, "python", 5)+ assert len(docs) == 2+ assert docs[0].url == "https://example.com/why"+ assert docs[1].url.startswith("https://news.ycombinator.com/item?id=")+++async def test_hn_swallows_http_errors(httpx_mock):+ httpx_mock.add_response(status_code=500)+ async with httpx.AsyncClient() as client:+ docs = await search_hn(client, "python", 5)+ assert docs == []+++# ---------------------------------------------------------------------------+# GitHub+# ---------------------------------------------------------------------------++async def test_github_returns_documents(httpx_mock):+ httpx_mock.add_response(+ url=re.compile(r"https://api\.github\.com/search/repositories.*"),+ json={"items": [+ {"full_name": "psf/requests", "html_url": "https://github.com/psf/requests",+ "description": "HTTP for humans"},+ {"name": "noop", "html_url": ""}, # missing url -> skipped+ ]},+ )+ async with httpx.AsyncClient() as client:+ docs = await search_github(client, "requests", 5)+ assert len(docs) == 1+ assert docs[0].title == "psf/requests"+++async def test_github_swallows_errors(httpx_mock):+ httpx_mock.add_response(status_code=403)+ async with httpx.AsyncClient() as client:+ docs = await search_github(client, "anything", 5)+ assert docs == []+++# ---------------------------------------------------------------------------+# Stack Exchange+# ---------------------------------------------------------------------------++async def test_stackexchange_returns_documents(httpx_mock):+ httpx_mock.add_response(+ url=re.compile(r"https://api\.stackexchange\.com/.*"),+ json={"items": [+ {"title": "How do I & X?", "link": "https://stackoverflow.com/q/1",+ "tags": ["python", "async"], "score": 12},+ ]},+ )+ async with httpx.AsyncClient() as client:+ docs = await search_stackexchange(client, "async python", 5)+ assert len(docs) == 1+ # HTML entities are unescaped+ assert "&" in docs[0].title and "amp" not in docs[0].title+ assert "python" in docs[0].extract+ assert "12" in docs[0].extract+++# ---------------------------------------------------------------------------+# ArXiv+# ---------------------------------------------------------------------------++ARXIV_ATOM = """<?xml version="1.0" encoding="UTF-8"?>+<feed xmlns="http://www.w3.org/2005/Atom">+ <entry>+ <id>http://arxiv.org/abs/2401.00001v1</id>+ <title>Attention Is All You Need</title>+ <summary>We propose...</summary>+ </entry>+</feed>+"""++async def test_arxiv_returns_documents(httpx_mock):+ httpx_mock.add_response(+ url=re.compile(r"https://export\.arxiv\.org/.*"),+ text=ARXIV_ATOM,+ )+ async with httpx.AsyncClient() as client:+ docs = await search_arxiv(client, "attention", 5)+ assert len(docs) == 1+ assert docs[0].url == "http://arxiv.org/abs/2401.00001v1"+ assert "Attention" in docs[0].title+++# ---------------------------------------------------------------------------+# PyPI+# ---------------------------------------------------------------------------++async def test_pypi_returns_document(httpx_mock):+ httpx_mock.add_response(+ url="https://pypi.org/pypi/requests/json",+ json={"info": {"name": "requests", "summary": "HTTP for humans",+ "package_url": "https://pypi.org/project/requests/"}},+ )+ async with httpx.AsyncClient() as client:+ docs = await search_pypi(client, "requests", 5)+ assert len(docs) == 1+ assert docs[0].title == "requests"+ assert "HTTP" in docs[0].extract+++async def test_pypi_404_returns_empty(httpx_mock):+ httpx_mock.add_response(status_code=404)+ async with httpx.AsyncClient() as client:+ docs = await search_pypi(client, "nonsense", 5)+ assert docs == []+++async def test_pypi_rejects_invalid_name():+ async with httpx.AsyncClient() as client:+ # Spaces / punctuation -> not a valid package name+ docs = await search_pypi(client, "this is a phrase!", 5)+ assert docs == []diff --git a/uv.lock b/uv.lockindex f09dada..421f19e 100644--- a/uv.lock+++ b/uv.lock@@ -63,6 +63,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/69/bf/f0f194d3379d3f3347478bd267f754fc68c11cbf2fe302a6ab69447b1417/beautifulsoup4-4.10.0-py3-none-any.whl", hash = "sha256:9a315ce70049920ea4572a4055bc4bd700c940521d36fc858205ad4fcde149bf", size = 97398, upload-time = "2021-09-08T00:16:06.464Z" },]+[[package]]+name = "blockbuster"+version = "1.5.26"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "forbiddenfruit", marker = "implementation_name == 'cpython'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/55/e0/dcbab602790a576b0b94108c07e2c048e5897df7cc83722a89582d733987/blockbuster-1.5.26.tar.gz", hash = "sha256:cc3ce8c70fa852a97ee3411155f31e4ad2665cd1c6c7d2f8bb1851dab61dc629", size = 36085, upload-time = "2025-12-05T10:43:47.735Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/95/c1/84fc6811122f54b20de2e5afb312ee07a3a47a328755587d1e505475239b/blockbuster-1.5.26-py3-none-any.whl", hash = "sha256:f8e53fb2dd4b6c6ec2f04907ddbd063ca7cd1ef587d24448ef4e50e81e3a79bb", size = 13226, upload-time = "2025-12-05T10:43:48.778Z" },+]+[[package]]name = "boto3"version = "1.35.99"@@ -437,6 +449,12 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/6f/27/b8b057a23f7777177e92d3a602fd866751b6b45014964548997e92e048fd/fakeredis-2.35.1-py3-none-any.whl", hash = "sha256:67d97e11f562b7870e11e5c30cf182270bfb2dd37f6707dba47cc6d91628d1b9", size = 129678, upload-time = "2026-04-12T17:05:56.86Z" },]+[[package]]+name = "forbiddenfruit"+version = "0.1.4"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/e6/79/d4f20e91327c98096d605646bdc6a5ffedae820f38d378d3515c42ec5e60/forbiddenfruit-0.1.4.tar.gz", hash = "sha256:e3f7e66561a29ae129aac139a85d610dbf3dd896128187ed5454b6421f624253", size = 43756, upload-time = "2021-01-16T21:03:35.401Z" }+[[package]]name = "gunicorn"version = "25.3.0"@@ -703,6 +721,7 @@ dependencies = [{ name = "django-vite" },{ name = "dotenv" },{ name = "gunicorn" },+ { name = "httpx" },{ name = "lxml" },{ name = "lxml-html-clean" },{ name = "mmh3" },@@ -743,11 +762,14 @@ indexer = [[package.dev-dependencies]dev = [+ { name = "blockbuster" },{ name = "fakeredis" },{ name = "maturin" },{ name = "patchelf" },{ name = "pytest" },+ { name = "pytest-asyncio" },{ name = "pytest-django" },+ { name = "pytest-httpx" },{ name = "pytest-mock" },]@@ -767,6 +789,7 @@ requires-dist = [{ name = "django-vite", specifier = ">=2.1.3" },{ name = "dotenv", specifier = ">=0.9.9" },{ name = "gunicorn", specifier = ">=21.0.0" },+ { name = "httpx", specifier = ">=0.27.0" },{ name = "idna", marker = "extra == 'indexer'", specifier = "==3.3" },{ name = "langdetect", marker = "extra == 'indexer'", specifier = "==1.0.9" },{ name = "levenshtein", marker = "extra == 'indexer'", specifier = "==0.16.0" },@@ -803,11 +826,14 @@ provides-extras = ["indexer"][package.metadata.requires-dev]dev = [+ { name = "blockbuster", specifier = ">=1.5.0" },{ name = "fakeredis", specifier = ">=2.30.1" },{ name = "maturin", specifier = ">=1.5,<2.0" },{ name = "patchelf", specifier = ">=0.17.2.4" },{ name = "pytest", specifier = ">=7.0.1" },+ { name = "pytest-asyncio", specifier = ">=0.23.0" },{ name = "pytest-django", specifier = ">=4.5.2" },+ { name = "pytest-httpx", specifier = ">=0.30.0" },{ name = "pytest-mock", specifier = ">=3.10.0" },]@@ -1142,6 +1168,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },]+[[package]]+name = "pytest-asyncio"+version = "1.4.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "pytest" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514, upload-time = "2026-05-26T09:56:04.083Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" },+]+[[package]]name = "pytest-django"version = "4.12.0"@@ -1154,6 +1193,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/83/a5/41d091f697c09609e7ef1d5d61925494e0454ebf51de7de05f0f0a728f1d/pytest_django-4.12.0-py3-none-any.whl", hash = "sha256:3ff300c49f8350ba2953b90297d23bf5f589db69545f56f1ec5f8cff5da83e85", size = 26123, upload-time = "2026-02-14T18:40:47.381Z" },]+[[package]]+name = "pytest-httpx"+version = "0.36.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "httpx" },+ { name = "pytest" },+]+sdist = { url = "https://files.pythonhosted.org/packages/4e/42/f53c58570e80d503ade9dd42ce57f2915d14bcbe25f6308138143950d1d6/pytest_httpx-0.36.2.tar.gz", hash = "sha256:05a56527484f7f4e8c856419ea379b8dc359c36801c4992fdb330f294c690356", size = 57683, upload-time = "2026-04-09T13:57:19.837Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/1e/55/1fa65f8e4fceb19dd6daa867c162ad845d547f6058cd92b4b02384a44777/pytest_httpx-0.36.2-py3-none-any.whl", hash = "sha256:d42ebd5679442dc7bfb0c48e0767b6562e9bc4534d805127b0084171886a5e22", size = 20315, upload-time = "2026-04-09T13:57:18.587Z" },+]+[[package]]name = "pytest-mock"version = "3.15.1"