fix eu
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-08-11 11:37:30 +02:00
parent a3eebedb02
commit e1b3318e68
2 changed files with 115 additions and 24 deletions
@@ -1,3 +1,4 @@
import asyncio
from datetime import datetime
import hashlib
from unittest.mock import AsyncMock, patch
@@ -21,6 +22,7 @@ from inse.dashboard.common import (
)
from inse.dashboard.bund_topics_service import get_dashboard_bund_topics
from inse.dashboard.eu_topics_service import get_dashboard_eu_topics
from inse.dashboard.model import TopAuthor
from inse.dashboard.project_status_service import reconcile_status_counts
from inse.dashboard.project_ids_service import (
_get_dfg_project_ids_from_projects_service,
@@ -31,10 +33,12 @@ from inse.dashboard.project_statistics_service import (
get_dashboard_eu_projects,
)
from inse.dashboard.top_authors_service import (
_count_eu_projects_for_candidates,
_openalex_work_authors_by_eu_projects,
_top_news_authors,
get_top_authors,
)
from inse.exceptions import ElasticsearchException
from inse.model import ESIndex
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
@@ -53,6 +57,54 @@ from inse.works.v2 import service as works_v2_service
ORG_INSTITUTION_ID = "https://openalex.org/I123"
@pytest.mark.anyio
async def test_eu_project_counts_are_bounded_retried_and_isolated():
attempts: dict[str, int] = {}
active_requests = 0
maximum_active_requests = 0
async def count_projects(author_id: str, **kwargs) -> int:
nonlocal active_requests, maximum_active_requests
attempts[author_id] = attempts.get(author_id, 0) + 1
active_requests += 1
maximum_active_requests = max(maximum_active_requests, active_requests)
await asyncio.sleep(0.001)
active_requests -= 1
if author_id == "A0" and attempts[author_id] < 3:
raise ElasticsearchException("temporary")
if author_id == "A1":
raise ElasticsearchException("unavailable")
return int(author_id.removeprefix("A"))
candidates = [
TopAuthor(id=f"A{index}", name=f"Author {index}", count=0) for index in range(8)
]
with (
patch(
"inse.dashboard.top_authors_service._person_eu_project_count",
new=count_projects,
),
patch(
"inse.dashboard.top_authors_service.EU_PROJECT_COUNT_RETRY_DELAY_SECONDS",
0,
),
):
result = await _count_eu_projects_for_candidates(candidates)
assert maximum_active_requests <= 5
assert attempts["A0"] == 3
assert attempts["A1"] == 3
assert [author.id for author in result] == [
"A0",
"A2",
"A3",
"A4",
"A5",
"A6",
"A7",
]
@pytest.fixture
def anyio_backend():
return "asyncio"
@@ -1078,9 +1130,9 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
async def eu_projects(**kwargs):
assert kwargs["funding_start_years"] is None
assert kwargs["funding_end_years"] is None
assert kwargs["active_from_year"] == 2020
assert kwargs["active_to_year"] == 2022
if kwargs.get("raw_oa_institution_id"):
assert kwargs["active_from_year"] is None
assert kwargs["active_to_year"] is None
return EuCordisProjectSearchPage(
elements=[
EuCordisProjectSummary(
@@ -1094,9 +1146,11 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
page=0,
size=1000,
)
assert kwargs["active_from_year"] == 2020
assert kwargs["active_to_year"] == 2022
return EuCordisProjectSearchPage(
elements=[],
total={"A1": 4, "A2": 1}[kwargs["author_id"]],
total={"A1": 4, "A2": 0}[kwargs["author_id"]],
page=0,
size=1,
)
@@ -1128,7 +1182,6 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
assert [author.model_dump() for author in result.eu_projects] == [
{"id": "A1", "name": "Ada Example", "count": 4},
{"id": "A2", "name": "Grace Example", "count": 1},
]
@@ -5,7 +5,10 @@ from collections import defaultdict
from datetime import datetime
from typing import Any, Literal
from fastapi import HTTPException
from inse import config
from inse.exceptions import ElasticsearchException, UpstreamAPIException
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
@@ -27,9 +30,12 @@ from .model import TopAuthor, TopAuthorAnalysis, TopAuthorStatistics
from .project_ids_service import _get_eu_project_ids_from_projects_service
TOP_AUTHOR_LIMIT = 10
EU_PROJECT_COUNT_CONCURRENCY = 5
EU_PROJECT_COUNT_MAX_ATTEMPTS = 3
EU_PROJECT_COUNT_RETRY_DELAY_SECONDS = 0.5
logger = logging.getLogger(__name__)
ACADEMIC_TITLE_RE = re.compile(
r"^(?:(?:professor(?:in)?|prof|dr)(?:\\.-[a-z]+)?\\.?|rer\\.|nat\\.|med\\.|ing\\.)\\s+",
r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+",
re.IGNORECASE,
)
@@ -831,11 +837,11 @@ async def _top_eu_project_publication_authors(
if not institution_author_ids:
return []
project_ids = await _get_eu_project_ids_from_projects_service(
institution_id,
from_year=from_year,
to_year=to_year,
)
# Candidate discovery is deliberately all-time. The selected period is
# applied to each person's authoritative project count below. Otherwise a
# person can disappear merely because their recent projects have no linked
# CORDIS publication/DOI, despite having projects in the selected period.
project_ids = await _get_eu_project_ids_from_projects_service(institution_id)
if not project_ids:
return []
@@ -886,25 +892,57 @@ async def _top_eu_project_publication_authors(
institution_author_ids,
limit=None,
)
counts = await asyncio.gather(
*(
_person_eu_project_count(
candidate.id,
from_year=from_year,
to_year=to_year,
)
for candidate in candidates
if candidate.id
)
ranked = await _count_eu_projects_for_candidates(
candidates,
from_year=from_year,
to_year=to_year,
)
ranked = [
TopAuthor(id=candidate.id, name=candidate.name, count=count)
for candidate, count in zip(candidates, counts, strict=True)
]
ranked = [author for author in ranked if author.count > 0]
ranked.sort(key=lambda author: (-author.count, author.name, author.id or ""))
return ranked[:TOP_AUTHOR_LIMIT]
async def _count_eu_projects_for_candidates(
candidates: list[TopAuthor],
from_year: int | None = None,
to_year: int | None = None,
) -> list[TopAuthor]:
semaphore = asyncio.Semaphore(EU_PROJECT_COUNT_CONCURRENCY)
async def load(candidate: TopAuthor) -> TopAuthor | None:
if not candidate.id:
return None
for attempt in range(1, EU_PROJECT_COUNT_MAX_ATTEMPTS + 1):
try:
async with semaphore:
count = await _person_eu_project_count(
candidate.id,
from_year=from_year,
to_year=to_year,
)
return TopAuthor(id=candidate.id, name=candidate.name, count=count)
except (ElasticsearchException, UpstreamAPIException, HTTPException) as exc:
is_retryable = (
not isinstance(exc, (HTTPException, UpstreamAPIException))
or exc.status_code >= 500
)
if not is_retryable or attempt == EU_PROJECT_COUNT_MAX_ATTEMPTS:
logger.warning(
"Could not load EU project count for author %s after %s attempt(s).",
candidate.id,
attempt,
exc_info=True,
)
return None
await asyncio.sleep(EU_PROJECT_COUNT_RETRY_DELAY_SECONDS * attempt)
return None
results = await asyncio.gather(*(load(candidate) for candidate in candidates))
return [result for result in results if result is not None]
def _cordis_publication_doi_project_ids(
response: dict[str, Any],
allowed_project_ids: set[str],