perf(patents): batch OpenAlex topic lookups into a single request per page, cutting endpoint latency from ~4-8s to ~0.6-1.1s #206

Merged
khalti merged 1 commits from ts-136-patent-to-researchers-v2 into dev 2026-07-11 21:53:23 +02:00
4 changed files with 166 additions and 48 deletions
+28 -12
View File
@@ -8,7 +8,10 @@ from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.ipc_lookup import extract_ipc_symbol
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.patents_openalex_keywords.client import PatentsOpenAlexKeywordsClient
from inse.patents.patents_openalex_keywords.client import (
PatentsOpenAlexKeywordsClient,
candidate_doc_ids,
)
logger = logging.getLogger(__name__)
@@ -196,8 +199,11 @@ async def enrich_patents_openalex_topics(
) -> None:
"""Attaches OpenAlex topic labels matched to each patent's ipc/cpc codes.
Looks up each unique symbol once (in parallel) against
patents_openalex_keywords, then fans the results back out per patent.
Resolves every unique symbol across all patents in a single _search
request against patents_openalex_keywords, then fans the results back
out per patent. Doing this per-symbol (even in parallel) instead of as
one batch added seconds of latency to endpoints enriching many patents
at once, like get_all_patents.
"""
symbols = list(dict.fromkeys(
extract_ipc_symbol(raw)
@@ -208,12 +214,25 @@ async def enrich_patents_openalex_topics(
if not symbols:
return
docs = await asyncio.gather(
*(keywords_client.lookup_symbol(symbol) for symbol in symbols),
return_exceptions=True,
)
topics_by_symbol: dict[str, list[model.OpenAlexTopicTag]] = {
symbol: [
candidate_ids_by_symbol = {symbol: candidate_doc_ids(symbol) for symbol in symbols}
all_doc_ids = list(dict.fromkeys(
doc_id
for candidate_ids in candidate_ids_by_symbol.values()
for doc_id in candidate_ids
))
try:
docs_by_id = await keywords_client.lookup_ids(all_doc_ids)
except Exception:
logger.warning("patents_openalex_keywords batch lookup failed", exc_info=True)
return
topics_by_symbol: dict[str, list[model.OpenAlexTopicTag]] = {}
for symbol, candidate_ids in candidate_ids_by_symbol.items():
doc = next((docs_by_id[doc_id] for doc_id in candidate_ids if doc_id in docs_by_id), None)
if not doc:
continue
topics_by_symbol[symbol] = [
model.OpenAlexTopicTag(
topic_id=match.get("topic_id"),
topic_display_name=match["topic_display_name"],
@@ -223,9 +242,6 @@ async def enrich_patents_openalex_topics(
for match in doc.get("topic_matches") or []
if match.get("topic_display_name")
]
for symbol, doc in zip(symbols, docs)
if doc and not isinstance(doc, BaseException)
}
for patent in patents:
seen: set[str] = set()
@@ -5,13 +5,17 @@ from inse.patents.common.parsing import enrich_patents_openalex_topics
class _FakeKeywordsClient:
def __init__(self, docs: dict[str, dict]):
self.docs = docs
self.lookup_calls: list[str] = []
def __init__(self, docs_by_id: dict[str, dict]):
self.docs_by_id = docs_by_id
self.lookup_ids_calls: list[list[str]] = []
async def lookup_symbol(self, symbol: str):
self.lookup_calls.append(symbol)
return self.docs.get(symbol)
async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict]:
self.lookup_ids_calls.append(doc_ids)
return {
doc_id: self.docs_by_id[doc_id]
for doc_id in doc_ids
if doc_id in self.docs_by_id
}
def _patent(patent_id: str, ipc: list[str], cpc: list[str] | None = None) -> PatentEntry:
@@ -21,7 +25,7 @@ def _patent(patent_id: str, ipc: list[str], cpc: list[str] | None = None) -> Pat
def test_enrich_patents_openalex_topics_attaches_field_and_domain() -> None:
client = _FakeKeywordsClient(
{
"C07K 11/02": {
"subgroup:C07K11/02": {
"topic_matches": [
{
"topic_id": "https://openalex.org/T1",
@@ -31,7 +35,7 @@ def test_enrich_patents_openalex_topics_attaches_field_and_domain() -> None:
},
]
},
"A61K 38/00": {
"subgroup:A61K38/00": {
"topic_matches": [
{
"topic_id": "https://openalex.org/T3",
@@ -58,7 +62,7 @@ def test_enrich_patents_openalex_topics_attaches_field_and_domain() -> None:
def test_enrich_patents_openalex_topics_dedupes_by_topic_id() -> None:
client = _FakeKeywordsClient(
{
"C07K 11/02": {
"subgroup:C07K11/02": {
"topic_matches": [
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
@@ -82,10 +86,13 @@ def test_enrich_patents_openalex_topics_skips_unmatched_symbols() -> None:
assert patent.openalex_topics == []
def test_enrich_patents_openalex_topics_looks_up_each_symbol_once() -> None:
def test_enrich_patents_openalex_topics_resolves_all_patents_in_one_batch_call() -> None:
"""A single lookup_ids() call must cover every unique symbol across all
patents — per-symbol requests (even in parallel) previously added
seconds of latency on endpoints enriching many patents at once."""
client = _FakeKeywordsClient(
{
"C07K 11/02": {
"subgroup:C07K11/02": {
"topic_matches": [
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Peptide Chemistry"},
]
@@ -99,6 +106,28 @@ def test_enrich_patents_openalex_topics_looks_up_each_symbol_once() -> None:
asyncio.run(enrich_patents_openalex_topics(patents, client))
assert client.lookup_calls == ["C07K 11/02"]
assert len(client.lookup_ids_calls) == 1
assert patents[0].openalex_topics[0].topic_display_name == "Peptide Chemistry"
assert patents[1].openalex_topics[0].topic_display_name == "Peptide Chemistry"
def test_enrich_patents_openalex_topics_prefers_more_specific_level() -> None:
client = _FakeKeywordsClient(
{
"subgroup:C07K11/02": {
"topic_matches": [
{"topic_id": "https://openalex.org/T1", "topic_display_name": "Specific Match"},
]
},
"class:C07": {
"topic_matches": [
{"topic_id": "https://openalex.org/T2", "topic_display_name": "Broad Match"},
]
},
}
)
patent = _patent("EP1", ipc=["C07K 11/02 20060101AFI"])
asyncio.run(enrich_patents_openalex_topics([patent], client))
assert patent.openalex_topics[0].topic_display_name == "Specific Match"
@@ -19,6 +19,31 @@ logger = logging.getLogger(__name__)
_LEVEL_LOOKUP_ORDER = ("subgroup", "group", "subclass", "class", "section")
def candidate_doc_ids(symbol: str) -> list[str]:
"""Builds the ordered (most to least specific) doc ids to try for a symbol."""
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass
normalized = symbol.strip().upper().replace(" ", "")
candidates: list[tuple[str, str]] = [(level, normalized) for level in _LEVEL_LOOKUP_ORDER]
subclass = infer_subclass(normalized)
if subclass:
candidates.append(("subclass", subclass))
if len(normalized) >= 3:
candidates.append(("class", normalized[:3]))
if normalized:
candidates.append(("section", normalized[:1]))
seen: set[tuple[str, str]] = set()
ordered_ids: list[str] = []
for level, candidate in candidates:
key = (level, candidate)
if key in seen:
continue
seen.add(key)
ordered_ids.append(f"{level}:{candidate}")
return ordered_ids
class PatentsOpenAlexKeywordsClient:
def __init__(
self,
@@ -153,26 +178,39 @@ class PatentsOpenAlexKeywordsClient:
hits = response.json().get("hits", {}).get("hits", [])
return hits[0].get("_source") if hits else None
async def lookup_ids(self, doc_ids: list[str]) -> dict[str, dict[str, Any]]:
"""Resolves multiple doc ids in a single _search request (id -> _source)."""
unique_ids = list(dict.fromkeys(doc_ids))
if not unique_ids:
return {}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{PATENTS_OPENALEX_KEYWORDS_INDEX}/_search",
headers=self._headers(),
json={"size": len(unique_ids), "query": {"ids": {"values": unique_ids}}},
)
if response.status_code == 404:
return {}
response.raise_for_status()
hits = response.json().get("hits", {}).get("hits", [])
return {hit["_id"]: hit.get("_source", {}) for hit in hits}
async def lookup_symbol(self, symbol: str) -> dict[str, Any] | None:
from inse.patents.patents_openalex_keywords.ipc_entries import infer_subclass
ordered_ids = candidate_doc_ids(symbol)
if not ordered_ids:
return None
normalized = symbol.strip().upper().replace(" ", "")
candidates: list[tuple[str, str]] = [(level, normalized) for level in _LEVEL_LOOKUP_ORDER]
subclass = infer_subclass(normalized)
if subclass:
candidates.append(("subclass", subclass))
if len(normalized) >= 3:
candidates.append(("class", normalized[:3]))
if normalized:
candidates.append(("section", normalized[:1]))
seen: set[tuple[str, str]] = set()
for level, candidate in candidates:
key = (level, candidate)
if key in seen:
continue
seen.add(key)
doc = await self.lookup(level, candidate)
if doc is not None:
return doc
# One _search covering every candidate level instead of up to 5
# sequential requests per symbol — this matters a lot when enriching
# many patents at once (see get_all_patents), where a sequential
# per-symbol lookup chain added multiple seconds of latency.
docs_by_id = await self.lookup_ids(ordered_ids)
for doc_id in ordered_ids:
if doc_id in docs_by_id:
return docs_by_id[doc_id]
return None
@@ -63,14 +63,27 @@ async def test_lookup_returns_none_when_no_hits():
@pytest.mark.anyio
async def test_lookup_symbol_stops_at_first_matching_level():
async def test_lookup_symbol_resolves_via_a_single_batched_request():
"""lookup_symbol must send exactly one _search covering every candidate
level (subgroup/group/subclass/class/section), not one request per level
— sequential per-level requests previously added multiple seconds of
latency when enriching many patents at once."""
captured: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
captured.append(request)
body = json.loads(request.content)
requested_id = body["query"]["ids"]["values"][0]
if requested_id == "group:C07K11/02":
values = body["query"]["ids"]["values"]
if "group:C07K11/02" in values:
return httpx.Response(
200,
json={"hits": {"hits": [{"_id": requested_id, "_source": {"ipc_label": "match"}}]}},
json={
"hits": {
"hits": [
{"_id": "group:C07K11/02", "_source": {"ipc_label": "match"}}
]
}
},
)
return httpx.Response(200, json={"hits": {"hits": []}})
@@ -80,4 +93,26 @@ async def test_lookup_symbol_stops_at_first_matching_level():
)
doc = await client.lookup_symbol("C07K 11/02")
assert len(captured) == 1
assert doc == {"ipc_label": "match"}
@pytest.mark.anyio
async def test_lookup_symbol_prefers_more_specific_level_when_multiple_match():
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
values = body["query"]["ids"]["values"]
hits = []
if "subgroup:C07K11/02" in values:
hits.append({"_id": "subgroup:C07K11/02", "_source": {"ipc_label": "subgroup-match"}})
if "class:C07" in values:
hits.append({"_id": "class:C07", "_source": {"ipc_label": "class-match"}})
return httpx.Response(200, json={"hits": {"hits": hits}})
client = PatentsOpenAlexKeywordsClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
doc = await client.lookup_symbol("C07K 11/02")
assert doc == {"ipc_label": "subgroup-match"}