diff --git a/service/src/main/inse/patents/authors/logic.py b/service/src/main/inse/patents/authors/logic.py index 8b2df53a..32a6f8bc 100644 --- a/service/src/main/inse/patents/authors/logic.py +++ b/service/src/main/inse/patents/authors/logic.py @@ -1,5 +1,4 @@ """Business logic for patent lookup by inventor.""" -import asyncio import logging import httpx @@ -10,16 +9,14 @@ from starlette.status import HTTP_503_SERVICE_UNAVAILABLE from inse.patents.authors.identity import is_ambiguous_name from inse.patents.authors.name_matching import filter_patents_by_author_name from inse.patents.authors.name_variants import parse_person_name +from inse.patents.authors.search_pagination import search_author_patents_adaptive from inse.patents.authors.topic_filter import filter_patents_by_ipc_topic_mapping from inse.patents.patents_openalex_keywords.resolver import PatentOpenAlexMappingResolver from inse.patents.common import model from inse.patents.common.elastic_search_client import MissingApiKeyError from inse.patents.common.parsing import ( - deduplicate_patents, enrich_patents_classifications, expand_matched_epo_application_families, - parse_epo_hits, - parse_uspto_hits, ) from inse.patents.ipc_search_client import IpcSearchClient from inse.patents.search_client import PatentSearchClient @@ -55,7 +52,9 @@ async def get_patents_by_author_id( ) try: - epo_data, uspto_data = await _search_both_indices(search_client, author_name) + search_result = await search_author_patents_adaptive( + search_client, author_name + ) except MissingApiKeyError as exc: raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, @@ -67,9 +66,26 @@ async def get_patents_by_author_id( detail="Patent search request failed.", ) from exc - all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data) - all_patents = deduplicate_patents(all_patents) + all_patents = search_result.patents patent_hit_count = len(all_patents) + if search_result.completeness.value == "truncated_inconclusive": + # Unread ES hits remain; zero UI patents must not be treated as proof + # that the author has no patents in the index. + logger.warning( + "search_completeness=%s for author %s (%s): epo_scanned=%d/%d " + "uspto_scanned=%d/%d stop=%s/%s strong_matches=%d/%d", + search_result.completeness.value, + author_id, + author_name, + search_result.epo.hits_scanned, + search_result.epo.total_hits, + search_result.uspto.hits_scanned, + search_result.uspto.total_hits, + search_result.epo.stop_reason, + search_result.uspto.stop_reason, + search_result.epo.strong_name_match_count, + search_result.uspto.strong_name_match_count, + ) matched_patents = filter_patents_by_author_name(all_patents, author_name) try: matched_patents = await expand_matched_epo_application_families( @@ -138,13 +154,6 @@ async def get_patents_by_author_id( patents=[item.patent for item in filtered], ) -async def _search_both_indices(client, display_name: str): - return await asyncio.gather( - client.search_epo(client.epo_query_by_inventor(display_name)), - client.search_uspto(client.uspto_query_by_inventor(display_name)), - ) - - async def _get_author(author_id: str) -> Author | None: short_id = author_id.replace("https://openalex.org/", "") result = await person_logic.search_persons(author_id=short_id) diff --git a/service/src/main/inse/patents/authors/search_pagination.py b/service/src/main/inse/patents/authors/search_pagination.py new file mode 100644 index 00000000..b4af7bed --- /dev/null +++ b/service/src/main/inse/patents/authors/search_pagination.py @@ -0,0 +1,315 @@ +"""Adaptive inventor-search pagination for author → patent lookup. + +Fetches ES hits in pages and stops early once enough *strong, unique* local +name matches are found, or when scan / page / time budgets are exhausted. +Does not change the inventor query itself — only how many scored hits are +examined and how completeness is interpreted. +""" +from __future__ import annotations + +import asyncio +import logging +import time +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Awaitable, Callable + +from inse.patents.authors.identity import best_name_match_kind +from inse.patents.authors.name_matching import filter_patents_by_author_name +from inse.patents.common import model +from inse.patents.common.parsing import ( + deduplicate_patents, + parse_epo_hits, + parse_search_total, + parse_uspto_hits, +) + +logger = logging.getLogger(__name__) + +AUTHOR_PATENT_PAGE_SIZE = 100 +AUTHOR_PATENT_MAX_SCANNED_PER_SOURCE = 1000 +AUTHOR_PATENT_TARGET_NAME_MATCHES = 30 +AUTHOR_PATENT_MAX_PAGES_PER_SOURCE = 10 +AUTHOR_PATENT_MAX_SECONDS_PER_SOURCE = 20.0 + +# Partial matches (e.g. "George Smith" for "George Davey Smith") may pass the +# name filter but must not drive the early-stop budget. +_STRONG_NAME_MATCH_KINDS = frozenset({"full", "initial"}) + + +class SearchCompleteness(str, Enum): + """How complete the inventor hit scan is for UI interpretation. + + COMPLETE + The ES result set for the source (or both sources) was fully read. + TRUNCATED_INCONCLUSIVE + Scanning stopped while unread hits remain. A zero UI result does **not** + prove the author has no patents in the index. + EXTRA_FINAL_RESULTS_FOUND + Diagnostic only: finals appear only when scanning beyond the first page. + """ + + COMPLETE = "complete" + TRUNCATED_INCONCLUSIVE = "truncated_inconclusive" + EXTRA_FINAL_RESULTS_FOUND = "extra_final_results_found" + + +def is_strong_name_match(patent: model.PatentEntry, display_name: str) -> bool: + """True when the patent is a unique-worthy strong personal name hit. + + Requires the existing name filter to accept the patent, and the best + inventor given-name kind to be ``full`` or ``initial`` (not ``partial``). + """ + if not filter_patents_by_author_name([patent], display_name): + return False + return best_name_match_kind(patent, display_name) in _STRONG_NAME_MATCH_KINDS + + +def count_unique_name_matches( + patents: list[model.PatentEntry], + display_name: str, + *, + strong_only: bool = False, +) -> int: + """Count distinct patent IDs that pass the name filter (optionally strong).""" + seen: set[str] = set() + for patent in patents: + pid = patent.patent_id + if not pid or pid in seen: + continue + if strong_only: + if is_strong_name_match(patent, display_name): + seen.add(pid) + elif filter_patents_by_author_name([patent], display_name): + seen.add(pid) + return len(seen) + + +@dataclass +class SourcePaginationResult: + source: str + patents: list[model.PatentEntry] = field(default_factory=list) + total_hits: int = 0 + hits_scanned: int = 0 + pages_fetched: int = 0 + name_match_count: int = 0 + strong_name_match_count: int = 0 + truncated: bool = False + completeness: SearchCompleteness = SearchCompleteness.COMPLETE + stop_reason: str = "" + elapsed_seconds: float = 0.0 + page_timings_ms: list[float] = field(default_factory=list) + error: str | None = None + + +@dataclass +class AuthorPatentSearchResult: + patents: list[model.PatentEntry] + epo: SourcePaginationResult + uspto: SourcePaginationResult + + @property + def truncated(self) -> bool: + return self.epo.truncated or self.uspto.truncated + + @property + def completeness(self) -> SearchCompleteness: + if ( + self.epo.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + or self.uspto.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ): + return SearchCompleteness.TRUNCATED_INCONCLUSIVE + return SearchCompleteness.COMPLETE + + +def classify_search_completeness( + *, + hits_scanned: int, + total_hits: int, + stop_reason: str, +) -> SearchCompleteness: + """Map pagination stop state to a completeness verdict.""" + if stop_reason == "error": + return SearchCompleteness.TRUNCATED_INCONCLUSIVE + if hits_scanned >= total_hits: + return SearchCompleteness.COMPLETE + # Unread hits remain — including early stop on strong-name target. + return SearchCompleteness.TRUNCATED_INCONCLUSIVE + + +async def search_author_patents_adaptive( + client: Any, + display_name: str, + *, + page_size: int = AUTHOR_PATENT_PAGE_SIZE, + max_scanned_per_source: int = AUTHOR_PATENT_MAX_SCANNED_PER_SOURCE, + target_name_matches: int = AUTHOR_PATENT_TARGET_NAME_MATCHES, + max_pages_per_source: int = AUTHOR_PATENT_MAX_PAGES_PER_SOURCE, + max_seconds_per_source: float = AUTHOR_PATENT_MAX_SECONDS_PER_SOURCE, +) -> AuthorPatentSearchResult: + """Search EPO and USPTO with independent adaptive pagination.""" + epo, uspto = await asyncio.gather( + paginate_inventor_source( + source="EPO", + display_name=display_name, + build_payload=lambda size, search_after: client.epo_query_by_inventor( + display_name, size=size, search_after=search_after + ), + search=client.search_epo, + parse_hits=parse_epo_hits, + page_size=page_size, + max_scanned=max_scanned_per_source, + target_name_matches=target_name_matches, + max_pages=max_pages_per_source, + max_seconds=max_seconds_per_source, + ), + paginate_inventor_source( + source="USPTO", + display_name=display_name, + build_payload=lambda size, search_after: client.uspto_query_by_inventor( + display_name, size=size, search_after=search_after + ), + search=client.search_uspto, + parse_hits=parse_uspto_hits, + page_size=page_size, + max_scanned=max_scanned_per_source, + target_name_matches=target_name_matches, + max_pages=max_pages_per_source, + max_seconds=max_seconds_per_source, + ), + ) + combined = deduplicate_patents(epo.patents + uspto.patents) + result = AuthorPatentSearchResult(patents=combined, epo=epo, uspto=uspto) + if result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE: + logger.info( + "Author patent search completeness=%s for %r: epo=%s uspto=%s " + "(scanned epo=%d/%d uspto=%d/%d, strong_matches epo=%d uspto=%d)", + result.completeness.value, + display_name, + epo.stop_reason, + uspto.stop_reason, + epo.hits_scanned, + epo.total_hits, + uspto.hits_scanned, + uspto.total_hits, + epo.strong_name_match_count, + uspto.strong_name_match_count, + ) + return result + + +async def paginate_inventor_source( + *, + source: str, + display_name: str, + build_payload: Callable[[int, list[Any] | None], dict[str, Any]], + search: Callable[[dict[str, Any]], Awaitable[dict[str, Any]]], + parse_hits: Callable[[dict[str, Any]], list[model.PatentEntry]], + page_size: int, + max_scanned: int, + target_name_matches: int, + max_pages: int, + max_seconds: float, +) -> SourcePaginationResult: + """Fetch inventor hits page-by-page until strong name-match or safety limits. + + Pagination uses ``search_after`` (stable cursor) after the first page. + The early-stop target counts **unique** patents with a strong name match + (``full`` / ``initial``), not raw or partial filter hits. + """ + started = time.perf_counter() + result = SourcePaginationResult(source=source) + accumulated: list[model.PatentEntry] = [] + search_after: list[Any] | None = None + + try: + while True: + elapsed = time.perf_counter() - started + if elapsed >= max_seconds: + result.stop_reason = "time_budget" + break + if result.pages_fetched >= max_pages: + result.stop_reason = "max_pages" + break + if result.hits_scanned >= max_scanned: + result.stop_reason = "max_scanned" + break + if ( + result.pages_fetched > 0 + and result.strong_name_match_count >= target_name_matches + ): + result.stop_reason = "target_strong_name_matches" + break + if result.pages_fetched > 0 and result.hits_scanned >= result.total_hits: + result.stop_reason = "exhausted" + break + + remaining_budget = max_scanned - result.hits_scanned + size = min(page_size, remaining_budget) + if size <= 0: + result.stop_reason = "max_scanned" + break + + payload = build_payload(size, search_after) + page_started = time.perf_counter() + data = await search(payload) + page_ms = (time.perf_counter() - page_started) * 1000.0 + result.page_timings_ms.append(round(page_ms, 1)) + + if result.pages_fetched == 0: + result.total_hits = parse_search_total(data) + + raw_hits = data.get("hits", {}).get("hits", []) or [] + page_patents = parse_hits(data) + if not page_patents: + result.stop_reason = "exhausted" + break + + accumulated.extend(page_patents) + result.hits_scanned += len(page_patents) + result.pages_fetched += 1 + result.name_match_count = count_unique_name_matches( + accumulated, display_name, strong_only=False + ) + result.strong_name_match_count = count_unique_name_matches( + accumulated, display_name, strong_only=True + ) + + last_sort = raw_hits[-1].get("sort") if raw_hits else None + search_after = last_sort if last_sort is not None else search_after + + if result.hits_scanned >= result.total_hits: + result.stop_reason = "exhausted" + break + if result.strong_name_match_count >= target_name_matches: + result.stop_reason = "target_strong_name_matches" + break + if result.hits_scanned >= max_scanned: + result.stop_reason = "max_scanned" + break + if result.pages_fetched >= max_pages: + result.stop_reason = "max_pages" + break + if time.perf_counter() - started >= max_seconds: + result.stop_reason = "time_budget" + break + + except Exception as exc: + result.error = f"{type(exc).__name__}: {exc}" + result.stop_reason = "error" + logger.exception("%s inventor pagination failed for %r", source, display_name) + + result.patents = accumulated + result.elapsed_seconds = round(time.perf_counter() - started, 3) + if not result.stop_reason: + result.stop_reason = "exhausted" + + result.completeness = classify_search_completeness( + hits_scanned=result.hits_scanned, + total_hits=result.total_hits, + stop_reason=result.stop_reason, + ) + result.truncated = ( + result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ) + return result diff --git a/service/src/main/inse/patents/authors/search_queries.py b/service/src/main/inse/patents/authors/search_queries.py index e87c6583..436169b2 100644 --- a/service/src/main/inse/patents/authors/search_queries.py +++ b/service/src/main/inse/patents/authors/search_queries.py @@ -150,6 +150,8 @@ class InventorSearchQueries: display_name: str, first_name: str | None = None, size: int = DEFAULT_SEARCH_SIZE, + from_: int = 0, + search_after: list | None = None, ) -> dict[str, Any]: if first_name and display_name and " " not in display_name.strip(): display_name = f"{first_name} {display_name}".strip() @@ -164,7 +166,7 @@ class InventorSearchQueries: } } - return { + payload: dict[str, Any] = { "size": size, "track_total_hits": True, "sort": [ @@ -190,6 +192,11 @@ class InventorSearchQueries: ], "query": query, } + if search_after: + payload["search_after"] = search_after + else: + payload["from"] = max(0, int(from_)) + return payload def epo_query_by_application_number( self, @@ -238,6 +245,8 @@ class InventorSearchQueries: display_name: str, first_name: str | None = None, size: int = DEFAULT_SEARCH_SIZE, + from_: int = 0, + search_after: list | None = None, ) -> dict[str, Any]: if first_name and display_name and " " not in display_name.strip(): display_name = f"{first_name} {display_name}".strip() @@ -249,7 +258,7 @@ class InventorSearchQueries: } } - return { + payload: dict[str, Any] = { "size": size, "track_total_hits": True, "sort": [ @@ -276,6 +285,11 @@ class InventorSearchQueries: ], "query": query, } + if search_after: + payload["search_after"] = search_after + else: + payload["from"] = max(0, int(from_)) + return payload def _application_number_variants(application_number: str) -> list[str]: diff --git a/service/src/main/inse/patents/authors/test_search_pagination.py b/service/src/main/inse/patents/authors/test_search_pagination.py new file mode 100644 index 00000000..4c902b16 --- /dev/null +++ b/service/src/main/inse/patents/authors/test_search_pagination.py @@ -0,0 +1,232 @@ +"""Unit tests for adaptive inventor-search pagination.""" +from __future__ import annotations + +import pytest + +from inse.patents.authors.search_pagination import ( + SearchCompleteness, + classify_search_completeness, + count_unique_name_matches, + is_strong_name_match, + paginate_inventor_source, +) +from inse.patents.common import model +from inse.patents.common.parsing import parse_epo_hits + + +def _hit(patent_id: str, inventors: list[str], *, sort: list | None = None) -> dict: + doc = { + "_id": patent_id[2:], + "_source": { + "doc_number": patent_id[2:], + "inventors_name": inventors, + "applicants_name": [], + "title_en": f"Title {patent_id}", + }, + } + if sort is not None: + doc["sort"] = sort + return doc + + +def _response(total: int, hits: list[dict]) -> dict: + return {"hits": {"total": {"value": total, "relation": "eq"}, "hits": hits}} + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@pytest.mark.anyio +async def test_pagination_stops_on_unique_strong_name_matches() -> None: + pages: list[dict] = [] + + async def search(payload: dict) -> dict: + pages.append(payload) + if "search_after" not in payload: + hits = [ + _hit(f"EP{i:07d}", ["Other, Person"], sort=[1.0, "2020", i]) + for i in range(100) + ] + else: + hits = [ + _hit( + f"EP{100 + i:07d}", + ["Stein, Dan J."], + sort=[2.0, "2019", 100 + i], + ) + for i in range(30) + ] + return _response(5000, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="Dan J. Stein", + build_payload=lambda size, search_after: ( + {"size": size, "search_after": search_after} + if search_after + else {"size": size, "from": 0} + ), + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=1000, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.pages_fetched == 2 + assert result.strong_name_match_count >= 30 + assert result.stop_reason == "target_strong_name_matches" + assert result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + assert result.truncated is True + assert "search_after" in pages[1] + + +@pytest.mark.anyio +async def test_partial_matches_do_not_count_toward_stop_target() -> None: + """George Smith is partial for George Davey Smith — keep scanning.""" + + async def search(payload: dict) -> dict: + # Always return partial-style matches; never reach strong target. + offset = 0 if "search_after" not in payload else 100 + hits = [ + _hit( + f"EP{offset + i:07d}", + ["Smith, George"], + sort=[1.0, "2020", offset + i], + ) + for i in range(100) + ] + return _response(5000, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="George Davey Smith", + build_payload=lambda size, search_after: ( + {"size": size, "search_after": search_after} + if search_after + else {"size": size} + ), + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=300, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.strong_name_match_count == 0 + assert result.name_match_count > 0 + assert result.stop_reason == "max_scanned" + assert result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + + +@pytest.mark.anyio +async def test_duplicate_patent_ids_count_once() -> None: + patents = [ + model.PatentEntry( + patent_id="EP1", + source="EPO", + inventors=["Stein, Dan J."], + assignees=[], + ), + model.PatentEntry( + patent_id="EP1", + source="EPO", + inventors=["Stein, Dan J."], + assignees=[], + ), + model.PatentEntry( + patent_id="EP2", + source="EPO", + inventors=["Stein, Dan J."], + assignees=[], + ), + ] + assert count_unique_name_matches(patents, "Dan J. Stein", strong_only=True) == 2 + + +@pytest.mark.anyio +async def test_pagination_marks_truncated_inconclusive_at_max_scanned() -> None: + async def search(payload: dict) -> dict: + cursor = payload.get("search_after") + base = int(cursor[-1]) + 1 if cursor else 0 + hits = [ + _hit(f"EP{base + i:07d}", ["Other, Person"], sort=[1.0, "2020", base + i]) + for i in range(payload["size"]) + ] + return _response(200_000, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="Dan J. Stein", + build_payload=lambda size, search_after: ( + {"size": size, "search_after": search_after} + if search_after + else {"size": size} + ), + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=300, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.hits_scanned == 300 + assert result.completeness == SearchCompleteness.TRUNCATED_INCONCLUSIVE + assert result.truncated is True + assert result.strong_name_match_count == 0 + + +@pytest.mark.anyio +async def test_pagination_complete_when_exhausted() -> None: + async def search(payload: dict) -> dict: + hits = [_hit("EP0000001", ["Stein, Dan J."], sort=[1.0, "2020", 1])] + return _response(1, hits) + + result = await paginate_inventor_source( + source="EPO", + display_name="Dan J. Stein", + build_payload=lambda size, search_after: {"size": size}, + search=search, + parse_hits=parse_epo_hits, + page_size=100, + max_scanned=1000, + target_name_matches=30, + max_pages=10, + max_seconds=60.0, + ) + + assert result.completeness == SearchCompleteness.COMPLETE + assert result.truncated is False + assert result.stop_reason == "exhausted" + assert is_strong_name_match(result.patents[0], "Dan J. Stein") + + +def test_classify_search_completeness() -> None: + assert ( + classify_search_completeness( + hits_scanned=8, total_hits=8, stop_reason="exhausted" + ) + == SearchCompleteness.COMPLETE + ) + assert ( + classify_search_completeness( + hits_scanned=1000, total_hits=200000, stop_reason="max_scanned" + ) + == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ) + assert ( + classify_search_completeness( + hits_scanned=200, + total_hits=5000, + stop_reason="target_strong_name_matches", + ) + == SearchCompleteness.TRUNCATED_INCONCLUSIVE + ) diff --git a/service/src/main/inse/patents/test_elastic_search_client.py b/service/src/main/inse/patents/test_elastic_search_client.py index 9bbfaa47..6403362c 100644 --- a/service/src/main/inse/patents/test_elastic_search_client.py +++ b/service/src/main/inse/patents/test_elastic_search_client.py @@ -26,6 +26,7 @@ def test_epo_query_uses_nested_search_and_name_variants(): payload = client.epo_query_by_inventor("Pedro José Marrón") assert payload["size"] == DEFAULT_SEARCH_SIZE + assert payload["from"] == 0 assert payload["sort"][0] == {"_score": {"order": "desc"}} nested = payload["query"]["nested"] assert nested["path"] == "inventors_name_nested" @@ -36,6 +37,30 @@ def test_epo_query_uses_nested_search_and_name_variants(): assert "should" in inventor_query["bool"] +def test_epo_and_uspto_inventor_queries_support_from_offset(): + client = PatentSearchClient(api_key="test-key") + epo = client.epo_query_by_inventor("Dan J. Stein", size=100, from_=200) + uspto = client.uspto_query_by_inventor("Dan J. Stein", size=50, from_=100) + assert epo["from"] == 200 + assert epo["size"] == 100 + assert "search_after" not in epo + assert uspto["from"] == 100 + assert uspto["size"] == 50 + + +def test_inventor_queries_use_search_after_instead_of_from(): + client = PatentSearchClient(api_key="test-key") + cursor = [12.5, "20200101", 42] + epo = client.epo_query_by_inventor("Dan J. Stein", size=100, search_after=cursor) + uspto = client.uspto_query_by_inventor( + "Dan J. Stein", size=100, search_after=cursor + ) + assert epo["search_after"] == cursor + assert "from" not in epo + assert uspto["search_after"] == cursor + assert "from" not in uspto + + def test_epo_query_never_searches_standalone_initial_without_last_name(): client = PatentSearchClient(api_key="test-key") payload = client.epo_query_by_inventor("Dan J. Stein")