diff --git a/service/src/main/inse/orgminer/logic.py b/service/src/main/inse/orgminer/logic.py index 503d9675..a2bc045e 100644 --- a/service/src/main/inse/orgminer/logic.py +++ b/service/src/main/inse/orgminer/logic.py @@ -2,11 +2,14 @@ from collections import defaultdict import asyncio -from typing import Any, Callable, Optional +from typing import Any, Awaitable, Callable, Optional from inse.integrations.elasticsearch import search from inse.utils import normalize_name from inse.model import ESCluster, ESIndex -from inse.authors.v2.service import _build_collaboration_graph +from inse.authors.v2.service import ( + _build_collaboration_graph, + _build_collaboration_graph_query, +) from inse.auth.model import Account, Organization from inse import config from .model import ( @@ -134,6 +137,180 @@ async def get_person_collaborator_weights( return weights +async def get_collaborator_weights_for_targets( + author_id: str, + institution_id: str, + target_ids: set[str] | frozenset[str] | list[str], +) -> dict[str, float]: + """Return ``{collaborator_id: shared_work_weight}`` only for ``target_ids``. + + The collaboration-graph builder expands every pair of authors on every work, + which explodes for works with hundreds or thousands of authors. Verification + only needs the weights towards the other staff candidates in the same + organization, so this asks Elasticsearch for those counts directly. + """ + targets = sorted(set(target_ids) - {author_id}) + if not targets: + return {} + + query = _build_collaboration_graph_query( + raw_oa_author_id=author_id, + institution_ids=[institution_id], + ) + body = { + "size": 0, + "query": query, + "aggs": { + "collaborators": { + "nested": {"path": "authorships"}, + "aggs": { + "targets": { + "terms": { + "field": "authorships.author.id", + "include": targets, + "size": len(targets), + } + } + }, + } + }, + } + + results = await search( + body=body, + index=ESIndex.OPENALEX_WORKS_WILDCARD, + cluster=ESCluster.NES, + ) + buckets = ( + results.get("aggregations", {}) + .get("collaborators", {}) + .get("targets", {}) + .get("buckets", []) + ) + return { + bucket["key"]: float(bucket["doc_count"]) + for bucket in buckets + if bucket.get("key") + } + + +async def get_verified_staff_with_collab_graph( + staff_list: list[dict[str, Any]], + institution_id: str = DEFAULT_INSTITUTION_ID, + max_concurrent_queries: int | None = None, +) -> list[dict[str, Any]]: + """Return verified staff entries with the OpenAlex IDs and edges proving verification. + + A staff entry is verified when at least one of its OpenAlex author candidates + has a collaboration edge to a candidate belonging to a different staff entry + in the same organization. + + Only collaborator weights towards the organization's other staff candidates + are fetched, so verification memory does not grow with the size of an + author's full co-author network. + + ``max_concurrent_queries`` bounds the OpenAlex candidate and graph searches. + It is useful for batch jobs processing organizations with large staff lists. + """ + if max_concurrent_queries is not None and max_concurrent_queries < 1: + raise ValueError("max_concurrent_queries must be at least 1.") + + query_semaphore = ( + asyncio.Semaphore(max_concurrent_queries) + if max_concurrent_queries is not None + else None + ) + + async def _run_query(operation: Callable[[], Awaitable[Any]]) -> Any: + if query_semaphore is None: + return await operation() + async with query_semaphore: + return await operation() + + async def _resolve_staff(staff: dict[str, Any]) -> set[str]: + name = staff.get("name") + if not name: + return set() + + candidate_ids = await _run_query( + lambda: resolve_author_candidates( + normalize_name(name), + institution_id, + ) + ) + return set(candidate_ids) + + async def _get_neighbor_weights( + author_id: str, target_ids: set[str] + ) -> dict[str, float]: + return await _run_query( + lambda: get_collaborator_weights_for_targets( + author_id, + institution_id, + target_ids, + ) + ) + + candidate_sets = await asyncio.gather( + *(_resolve_staff(staff) for staff in staff_list) + ) + + async def _verify_staff( + staff_index: int, own_ids: set[str] + ) -> dict[str, Any] | None: + if not own_ids: + return None + + other_ids = ( + set().union( + *( + candidate_ids + for index, candidate_ids in enumerate(candidate_sets) + if index != staff_index + ) + ) + - own_ids + ) + if not other_ids: + return None + + # ``other_ids`` only contains OpenAlex candidates of the other staff + # entries in this organization, and every candidate set was resolved + # against ``institution_id``. Collaborator weights are therefore + # restricted to same-university colleagues; no external co-author can + # contribute evidence. + author_ids = sorted(own_ids) + neighbor_weights = await asyncio.gather( + *(_get_neighbor_weights(author_id, other_ids) for author_id in author_ids) + ) + evidence = [ + { + "openalex_id": author_id, + "collaborator_openalex_id": collaborator_id, + "shared_work_weight": weights[collaborator_id], + } + for author_id, weights in zip(author_ids, neighbor_weights) + for collaborator_id in sorted(weights.keys() & other_ids) + ] + if not evidence: + return None + + return { + "staff_index": staff_index, + "staff": staff_list[staff_index], + "openalex_ids": sorted({item["openalex_id"] for item in evidence}), + "collaboration_evidence": evidence, + } + + checked_entries = await asyncio.gather( + *( + _verify_staff(staff_index, candidate_ids) + for staff_index, candidate_ids in enumerate(candidate_sets) + ) + ) + return [entry for entry in checked_entries if entry is not None] + + async def find_org_for_person( name: str, institution_id: str = None, @@ -567,62 +744,14 @@ async def get_orgminer_content_verified_by_collab_graph( orgminer_content = hits[0]["_source"] staff_list = orgminer_content.get("staff") or [] - async def _resolve_staff(staff: dict) -> set[str]: - name = staff.get("name") - if not name: - return set() - - candidate_ids = await resolve_author_candidates( - normalize_name(name), - institution_id, - ) - return set(candidate_ids) - - async def _get_neighbor_ids(author_id: str) -> set[str]: - collaborator_weights = await get_person_collaborator_weights( - author_id, - institution_id, - ) - return set(collaborator_weights.keys()) - - candidate_sets = await asyncio.gather( - *(_resolve_staff(staff) for staff in staff_list) - ) - - async def _is_verified(staff_index: int) -> bool: - own_ids = candidate_sets[staff_index] - if not own_ids: - return False - - # Candidates belonging to other staff members only. - other_ids = ( - set().union( - *( - candidate_ids - for index, candidate_ids in enumerate(candidate_sets) - if index != staff_index - ) - ) - - own_ids - ) - - if not other_ids: - return False - - neighbor_sets = await asyncio.gather( - *(_get_neighbor_ids(author_id) for author_id in own_ids) - ) - - return any(neighbor_ids & other_ids for neighbor_ids in neighbor_sets) - - verified_flags = await asyncio.gather( - *(_is_verified(index) for index in range(len(staff_list))) + verified_entries = await get_verified_staff_with_collab_graph( + staff_list, + institution_id, ) orgminer_content["verified_staff"] = [ - staff - for staff, is_verified in zip(staff_list, verified_flags) - if is_verified + entry["staff"] + for entry in verified_entries ] return OrgminerContent.from_elastic_hit(orgminer_content) @@ -704,4 +833,4 @@ async def get_classified_pages(org_url: str,institution_id: str = DEFAULT_INSTIT return ClassifiedPageResponse( total=response["hits"]["total"]["value"], pages=classified_pages - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/orgminer/test_logic.py b/service/src/main/inse/orgminer/test_logic.py index 644ecbec..15470475 100644 --- a/service/src/main/inse/orgminer/test_logic.py +++ b/service/src/main/inse/orgminer/test_logic.py @@ -1,8 +1,170 @@ +import asyncio import json from inse.orgminer import logic +def test_get_verified_staff_with_collab_graph_returns_matching_ids_and_edges( + monkeypatch, +): + staff = [ + {"name": "Person One", "email": "one@example.org"}, + {"name": "Person Two"}, + ] + resolved = { + "person one": ["https://openalex.org/A1", "https://openalex.org/A2"], + "person two": ["https://openalex.org/B1"], + } + neighbors = { + "https://openalex.org/A1": {"https://openalex.org/B1": 2.5}, + "https://openalex.org/A2": {}, + "https://openalex.org/B1": {}, + } + + async def resolve_author_candidates(name, institution_id): + return resolved[name] + + async def get_collaborator_weights_for_targets( + author_id, institution_id, target_ids + ): + return { + collaborator_id: weight + for collaborator_id, weight in neighbors[author_id].items() + if collaborator_id in target_ids + } + + monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates) + monkeypatch.setattr( + logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets + ) + + result = asyncio.run( + logic.get_verified_staff_with_collab_graph(staff, "I123") + ) + + assert result == [ + { + "staff_index": 0, + "staff": staff[0], + "openalex_ids": ["https://openalex.org/A1"], + "collaboration_evidence": [ + { + "openalex_id": "https://openalex.org/A1", + "collaborator_openalex_id": "https://openalex.org/B1", + "shared_work_weight": 2.5, + } + ], + } + ] + + +def test_get_verified_staff_with_collab_graph_respects_query_concurrency( + monkeypatch, +): + staff = [{"name": "Person One"}, {"name": "Person Two"}] + active_queries = 0 + peak_queries = 0 + + async def tracked(result): + nonlocal active_queries, peak_queries + active_queries += 1 + peak_queries = max(peak_queries, active_queries) + try: + await asyncio.sleep(0.001) + return result + finally: + active_queries -= 1 + + async def resolve_author_candidates(name, institution_id): + author_id = "https://openalex.org/A1" if name == "person one" else "https://openalex.org/A2" + return await tracked([author_id]) + + async def get_collaborator_weights_for_targets( + author_id, institution_id, target_ids + ): + neighbor_id = ( + "https://openalex.org/A2" + if author_id == "https://openalex.org/A1" + else "https://openalex.org/A1" + ) + return await tracked( + {neighbor_id: 1.0} if neighbor_id in target_ids else {} + ) + + monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates) + monkeypatch.setattr( + logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets + ) + + result = asyncio.run( + logic.get_verified_staff_with_collab_graph( + staff, + "I123", + max_concurrent_queries=1, + ) + ) + + assert len(result) == 2 + assert peak_queries == 1 + + +def test_get_collaborator_weights_for_targets_uses_bounded_aggregation( + monkeypatch, +): + captured = {} + + async def fake_search(**kwargs): + captured.update(kwargs) + return { + "aggregations": { + "collaborators": { + "targets": { + "buckets": [ + {"key": "https://openalex.org/B1", "doc_count": 7}, + ] + } + } + } + } + + monkeypatch.setattr(logic, "search", fake_search) + + result = asyncio.run( + logic.get_collaborator_weights_for_targets( + "https://openalex.org/A1", + "I123", + {"https://openalex.org/B1", "https://openalex.org/A1"}, + ) + ) + + assert result == {"https://openalex.org/B1": 7.0} + body = captured["body"] + assert body["size"] == 0 + nested = body["aggs"]["collaborators"] + assert nested["nested"] == {"path": "authorships"} + assert nested["aggs"]["targets"]["terms"]["include"] == [ + "https://openalex.org/B1" + ] + assert "query" in body + + +def test_get_collaborator_weights_for_targets_without_targets_skips_request( + monkeypatch, +): + async def fail_search(**kwargs): + raise AssertionError("search must not be called") + + monkeypatch.setattr(logic, "search", fail_search) + + result = asyncio.run( + logic.get_collaborator_weights_for_targets( + "https://openalex.org/A1", "I123", set() + ) + ) + + assert result == {} + + def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch): monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path)