Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement the semantic scholar (allen institute for ai) import source (#111859)

Tom Owersd12620e644cb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semanticscholar.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semanticscholar.py
index ca82de9fc9d7..60d7d31caabf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semanticscholar.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semanticscholar.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SemanticScholarSourceConfig(config.Config):
- pass
+ api_key: str
+ query: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/canonical_descriptions.py
new file mode 100644
index 000000000000..e3c55471bc00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/canonical_descriptions.py
@@ -0,0 +1,50 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.settings import API_DOCS_URL
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "papers": {
+ "description": "Academic papers that match the configured search query.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "paperId": "The primary Semantic Scholar identifier for the paper.",
+ "corpusId": "The numeric identifier used in Semantic Scholar datasets.",
+ "externalIds": "Identifiers from other sources, such as DOI and arXiv.",
+ "title": "The title of the paper.",
+ "abstract": "The abstract, when available for distribution through the API.",
+ "url": "The page for the paper on Semantic Scholar.",
+ "year": "The year of publication.",
+ "publicationDate": "The date of publication, when known.",
+ "citationCount": "The number of papers that cite this paper.",
+ "referenceCount": "The number of papers cited by this paper.",
+ "authors": "Authors of the paper, with their Semantic Scholar identifiers.",
+ "venue": "The journal or conference that published the paper.",
+ "isOpenAccess": "Whether the paper has open access.",
+ },
+ },
+ "citations": {
+ "description": "Papers that cite papers in the configured search results. Unresolved paper links are excluded.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "paper_id": "The identifier of the paper in the search results.",
+ "related_paper_id": "The identifier of the paper that cites the search result.",
+ "citingPaper": "Metadata for the paper that contains the citation.",
+ "contexts": "Text around the citation in the citing paper.",
+ "intents": "The classified purposes of the citation.",
+ "isInfluential": "Whether Semantic Scholar classifies the citation as influential.",
+ },
+ },
+ "references": {
+ "description": "Papers cited by papers in the configured search results. Unresolved paper links are excluded.",
+ "docs_url": API_DOCS_URL,
+ "columns": {
+ "paper_id": "The identifier of the paper in the search results.",
+ "related_paper_id": "The identifier of the paper cited by the search result.",
+ "citedPaper": "Metadata for the paper in the bibliography.",
+ "contexts": "Text around the reference in the citing paper.",
+ "intents": "The classified purposes of the reference.",
+ "isInfluential": "Whether Semantic Scholar classifies the reference as influential.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/semantic_scholar.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/semantic_scholar.py
new file mode 100644
index 000000000000..8a3f0fe44abd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/semantic_scholar.py
@@ -0,0 +1,184 @@
+from typing import Any
+
+from requests import Response
+from requests.exceptions import HTTPError, RequestException
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTClient,
+ RESTClientRetryableError,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semanticscholar import (
+ SemanticScholarSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.settings import (
+ API_ROOT,
+ AUTH_ERROR,
+ EDGE_FIELDS,
+ ENDPOINTS,
+ LIMIT_ERROR,
+ MAX_PAPERS,
+ PAPER_FIELDS,
+ PRIMARY_KEYS,
+ QUERY_ERROR,
+ RELATED_PAPER_FIELDS,
+)
+
+
+@frozen
+class SemanticScholarResumeConfig:
+ paginator_state: dict[str, Any]
+
+
+def check_bulk_limit(response: Response, *args: object, **kwargs: object) -> None:
+ if response.status_code == 200 and response.url and "/paper/search/bulk" in response.url:
+ if int(response.json().get("total", 0)) > MAX_PAPERS:
+ raise ValueError(LIMIT_ERROR)
+
+
+def validate_credentials(config: SemanticScholarSourceConfig, api_version: str) -> tuple[bool, str | None]:
+ if not config.api_key.strip() or not config.api_key.isascii() or any(c.isspace() for c in config.api_key):
+ return False, "Enter an API key without spaces or unsupported characters."
+ if not config.query.strip():
+ return False, "Enter a search query for the papers you want to sync."
+ try:
+ client = RESTClient(
+ base_url=f"{API_ROOT}/{api_version}",
+ auth=APIKeyAuth(api_key=config.api_key, name="x-api-key"),
+ session=make_tracked_session(retry=Retry(total=0), redact_values=(config.api_key,)),
+ max_retry_attempts=1,
+ request_timeout=30,
+ allow_redirects=False,
+ allowed_hosts=[],
+ )
+ try:
+ next(
+ client.paginate(
+ path="paper/search/bulk",
+ params={"query": config.query, "fields": "paperId"},
+ paginator=SinglePagePaginator(),
+ data_selector="data",
+ data_selector_required=True,
+ )
+ )
+ finally:
+ client.session.close()
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status in (401, 403):
+ return False, AUTH_ERROR
+ if status == 400:
+ return False, QUERY_ERROR
+ return False, "Semantic Scholar could not validate the connection. Try again later."
+ except (RequestException, RESTClientRetryableError):
+ return False, "Semantic Scholar is unavailable or has limited requests. Try again later."
+ return True, None
+
+
+def semantic_scholar_source(
+ config: SemanticScholarSourceConfig,
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[SemanticScholarResumeConfig],
+ api_version: str,
+) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Semantic Scholar table: {inputs.schema_name}")
+ session = make_tracked_session(retry=Retry(total=0), redact_values=(config.api_key,))
+ session.hooks["response"].append(check_bulk_limit)
+ client: ClientConfig = {
+ "base_url": f"{API_ROOT}/{api_version}",
+ "auth": {"type": "api_key", "name": "x-api-key", "api_key": config.api_key, "location": "header"},
+ "session": session,
+ "request_timeout": 60,
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+ papers: EndpointResource = {
+ "name": "papers",
+ "endpoint": {
+ "path": "paper/search/bulk",
+ "params": {
+ "query": config.query,
+ "fields": PAPER_FIELDS if inputs.schema_name == "papers" else "paperId",
+ "sort": "paperId:asc",
+ },
+ "data_selector": "data",
+ "data_selector_required": True,
+ "paginator": {
+ "type": "cursor",
+ "cursor_path": "token",
+ "cursor_param": "token",
+ "raise_on_repeated_cursor": True,
+ },
+ },
+ }
+ resources: list[str | EndpointResource] = [papers]
+ if inputs.schema_name != "papers":
+ resources.append(
+ {
+ "name": inputs.schema_name,
+ "include_from_parent": ["paperId"],
+ "endpoint": {
+ "path": f"paper/{{paper_id}}/{inputs.schema_name}",
+ "params": {
+ "paper_id": {"type": "resolve", "resource": "papers", "field": "paperId"},
+ "limit": 1000,
+ "fields": EDGE_FIELDS,
+ },
+ "data_selector": "data",
+ "data_selector_required": True,
+ "paginator": {
+ "type": "cursor",
+ "cursor_path": "next",
+ "cursor_param": "offset",
+ "raise_on_repeated_cursor": True,
+ },
+ },
+ }
+ )
+ resume = manager.load_state() if manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ manager.save_state(SemanticScholarResumeConfig(paginator_state=state))
+
+ built = rest_api_resources(
+ {"client": client, "resource_defaults": {"write_disposition": "replace"}, "resources": resources},
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ resource = next(resource for resource in built if resource.name == inputs.schema_name)
+ if inputs.schema_name != "papers":
+ related_field = RELATED_PAPER_FIELDS[inputs.schema_name]
+
+ def normalize_edge(row: dict[str, Any]) -> dict[str, Any]:
+ row["paper_id"] = row.pop("_papers_paperId")
+ row["related_paper_id"] = row[related_field]["paperId"]
+ return row
+
+ resource.add_filter(lambda row: bool((row.get(related_field) or {}).get("paperId")))
+ resource.add_map(normalize_edge)
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS[inputs.schema_name],
+ sort_mode=None,
+ on_complete=session.close,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/settings.py
new file mode 100644
index 000000000000..b26cd0f6d763
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/settings.py
@@ -0,0 +1,19 @@
+API_ROOT = "https://api.semanticscholar.org/graph"
+API_DOCS_URL = "https://api.semanticscholar.org/api-docs/graph"
+MAX_PAPERS = 10_000_000
+ENDPOINTS = ("papers", "citations", "references")
+PAPER_FIELDS = (
+ "paperId,corpusId,externalIds,url,title,abstract,venue,year,publicationDate,"
+ "referenceCount,citationCount,influentialCitationCount,isOpenAccess,openAccessPdf,"
+ "fieldsOfStudy,s2FieldsOfStudy,publicationTypes,journal,authors"
+)
+EDGE_FIELDS = "paperId,title,year,publicationDate,authors,contexts,intents,isInfluential"
+RELATED_PAPER_FIELDS = {"citations": "citingPaper", "references": "citedPaper"}
+PRIMARY_KEYS = {
+ "papers": ["paperId"],
+ "citations": ["paper_id", "related_paper_id"],
+ "references": ["paper_id", "related_paper_id"],
+}
+AUTH_ERROR = "Semantic Scholar rejected the API key. Check your key and its API access."
+QUERY_ERROR = "Semantic Scholar rejected the search query. Check the query syntax."
+LIMIT_ERROR = "The search exceeds the Semantic Scholar bulk limit. Use a more specific search query."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/source.py
index 8e93bba01ae1..6135c1e56915 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/source.py
@@ -1,16 +1,48 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semanticscholar import (
SemanticScholarSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.semantic_scholar import (
+ SemanticScholarResumeConfig,
+ semantic_scholar_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.settings import (
+ API_DOCS_URL,
+ AUTH_ERROR,
+ ENDPOINTS,
+ LIMIT_ERROR,
+ QUERY_ERROR,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SemanticScholarSource(SimpleSource[SemanticScholarSourceConfig]):
+class SemanticScholarSource(ResumableSource[SemanticScholarSourceConfig, SemanticScholarResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v1",)
+ default_version = "v1"
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SEMANTICSCHOLAR
@@ -22,6 +54,84 @@ class SemanticScholarSource(SimpleSource[SemanticScholarSourceConfig]):
category=DataWarehouseSourceCategory.ANALYTICS,
label="Semantic Scholar (Allen Institute for AI)",
iconPath="/static/services/semantic_scholar.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Request an API key from the [Semantic Scholar API page]"
+ "(https://www.semanticscholar.org/product/api#api-key-form). "
+ "Enter a specific query to select papers. Citations and references make additional requests for each matching paper. "
+ "Each sync refreshes all results. Links without a related paper ID are excluded."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ secret=True,
+ placeholder="",
+ ),
+ SourceFieldInputConfig(
+ name="query",
+ label="Paper search query",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ secret=False,
+ placeholder='"graph neural networks"',
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: SemanticScholarSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # Publication dates cannot identify metadata updates or papers added after their publication date.
+ return [
+ SourceSchema(
+ name=name, supports_incremental=False, supports_append=False, should_sync_default=name == "papers"
+ )
+ for name in ENDPOINTS
+ if names is None or name in names
+ ]
+
+ def validate_credentials(
+ self,
+ config: SemanticScholarSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, self.resolve_api_version(api_version))
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": AUTH_ERROR,
+ "400 Client Error": QUERY_ERROR,
+ "Invalid API Key": AUTH_ERROR,
+ LIMIT_ERROR: LIMIT_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SemanticScholarResumeConfig]:
+ return ResumableSourceManager(inputs, SemanticScholarResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SemanticScholarSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SemanticScholarResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return semantic_scholar_source(
+ config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/tests/test_semantic_scholar.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/tests/test_semantic_scholar.py
new file mode 100644
index 000000000000..a16332ab584a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semantic_scholar/tests/test_semantic_scholar.py
@@ -0,0 +1,202 @@
+from collections.abc import Iterable
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock
+
+import responses
+from requests.exceptions import HTTPError, Timeout
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semanticscholar import (
+ SemanticScholarSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.semantic_scholar import (
+ SemanticScholarResumeConfig,
+ semantic_scholar_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.settings import (
+ AUTH_ERROR,
+ LIMIT_ERROR,
+ QUERY_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semantic_scholar.source import (
+ SemanticScholarSource,
+)
+
+BASE_URL = "https://api.semanticscholar.org/graph/v1"
+CONFIG = SemanticScholarSourceConfig(api_key="test-api-key", query='"test paper" | graphs')
+
+
+def make_inputs(endpoint: str, incremental: bool = False) -> SourceInputs:
+ return SourceInputs(
+ schema_name=endpoint,
+ schema_id="schema",
+ source_id="source",
+ team_id=1,
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value="2025-01-01",
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="test-job",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+def make_manager(state: dict[str, Any] | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = state is not None
+ manager.load_state.return_value = SemanticScholarResumeConfig(paginator_state=state) if state is not None else None
+ return manager
+
+
+def items(response: SourceResponse) -> Iterable[Any]:
+ return cast(Iterable[Any], response.items())
+
+
[email protected]("incremental", [False, True])
[email protected]("resume_token", [None, "saved-token"])
+def test_bulk_pagination_auth_and_full_refresh(incremental: bool, resume_token: str | None) -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"total": 2, "token": "next-token", "data": [{"paperId": "a"}]})
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"total": 2, "data": [{"paperId": "b"}]})
+ manager = make_manager({"cursor": resume_token} if resume_token else None)
+ result = SemanticScholarSource().source_for_pipeline(CONFIG, manager, make_inputs("papers", incremental))
+ assert list(items(result)) == [[{"paperId": "a"}], [{"paperId": "b"}]]
+ requests = [call.request for call in responses.calls]
+ params = [parse_qs(urlsplit(request.url).query) for request in requests]
+ assert [param.get("token") for param in params] == [[resume_token] if resume_token else None, ["next-token"]]
+ for request, param in zip(requests, params):
+ assert request.headers["x-api-key"] == "test-api-key"
+ assert "test-api-key" not in request.url
+ assert param["query"] == [CONFIG.query]
+ assert param["sort"] == ["paperId:asc"]
+ assert "publicationDateOrYear" not in param
+ assert "limit" not in param
+ assert "citationCount" in param["fields"][0]
+ manager.save_state.assert_called_once_with(SemanticScholarResumeConfig(paginator_state={"cursor": "next-token"}))
+
+
[email protected](("endpoint", "related_field"), [("citations", "citingPaper"), ("references", "citedPaper")])
+def test_edges_paginate_each_parent_and_keep_distinct_keys(endpoint: str, related_field: str) -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"data": [{"paperId": "a"}, {"paperId": "b"}]})
+ responses.get(f"{BASE_URL}/paper/a/{endpoint}", json={"next": 1, "data": [{related_field: {"paperId": "shared"}}]})
+ responses.get(
+ f"{BASE_URL}/paper/a/{endpoint}", json={"data": [{related_field: None}, {related_field: {"paperId": None}}]}
+ )
+ responses.get(f"{BASE_URL}/paper/b/{endpoint}", json={"data": [{related_field: {"paperId": "shared"}}]})
+ manager = make_manager()
+ result = semantic_scholar_source(CONFIG, make_inputs(endpoint), manager, "v1")
+ rows = [row for page in items(result) for row in page]
+ assert [(row["paper_id"], row["related_paper_id"]) for row in rows] == [("a", "shared"), ("b", "shared")]
+ assert all("_papers_paperId" not in row for row in rows)
+ params = [parse_qs(urlsplit(call.request.url).query) for call in responses.calls]
+ assert [param.get("offset") for param in params] == [None, None, ["1"], None]
+ assert params[0]["fields"] == ["paperId"]
+ for param in params[1:]:
+ assert param["limit"] == ["1000"]
+ assert "paper_id" not in param
+ assert "query" not in param
+ assert manager.save_state.call_args.args[0].paginator_state["completed"] == [
+ f"paper/a/{endpoint}",
+ f"paper/b/{endpoint}",
+ ]
+
+
[email protected]("endpoint", ["citations", "references"])
+def test_resume_skips_completed_parents_and_restores_child_offset(endpoint: str) -> None:
+ related_field = "citingPaper" if endpoint == "citations" else "citedPaper"
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"data": [{"paperId": "a"}, {"paperId": "b"}]})
+ responses.get(f"{BASE_URL}/paper/b/{endpoint}", json={"data": [{related_field: {"paperId": "c"}}]})
+ manager = make_manager(
+ {"completed": [f"paper/a/{endpoint}"], "current": f"paper/b/{endpoint}", "child_state": {"cursor": 1000}}
+ )
+ result = semantic_scholar_source(CONFIG, make_inputs(endpoint), manager, "v1")
+ rows = [row for page in items(result) for row in page]
+ assert [(row["paper_id"], row["related_paper_id"]) for row in rows] == [("b", "c")]
+ assert len(responses.calls) == 2
+ assert parse_qs(urlsplit(responses.calls[1].request.url).query)["offset"] == ["1000"]
+
+
[email protected]("endpoint", ["papers", "citations", "references"])
+def test_empty_search_stops_without_child_requests(endpoint: str) -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"total": 0, "data": []})
+ result = semantic_scholar_source(CONFIG, make_inputs(endpoint), make_manager(), "v1")
+ assert list(items(result)) == []
+ assert len(responses.calls) == 1
+
+
+def test_bulk_limit_fails_before_yielding_partial_results() -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"total": 10_000_001, "data": [{"paperId": "a"}]})
+ result = semantic_scholar_source(CONFIG, make_inputs("papers"), make_manager(), "v1")
+ with pytest.raises(ValueError, match=LIMIT_ERROR):
+ list(items(result))
+
+
[email protected](("status", "message"), [(401, AUTH_ERROR), (403, AUTH_ERROR), (400, QUERY_ERROR)])
+def test_auth_and_query_errors_are_not_retryable(status: int, message: str) -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"message": "rejected"}, status=status)
+ result = semantic_scholar_source(CONFIG, make_inputs("papers"), make_manager(), "v1")
+ with pytest.raises(HTTPError) as error:
+ list(items(result))
+ mapping = SemanticScholarSource().get_non_retryable_errors()
+ assert next(value for key, value in mapping.items() if key in str(error.value)) == message
+ assert len(responses.calls) == 1
+
+
+ ("status", "message"),
+ [
+ (200, None),
+ (401, AUTH_ERROR),
+ (403, AUTH_ERROR),
+ (400, QUERY_ERROR),
+ (429, "Semantic Scholar is unavailable or has limited requests. Try again later."),
+ (500, "Semantic Scholar is unavailable or has limited requests. Try again later."),
+ ],
+)
+def test_validation_uses_one_call_and_maps_errors(status: int, message: str | None) -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"data": []}, status=status)
+ assert validate_credentials(CONFIG, "v1") == (status == 200, message)
+ assert len(responses.calls) == 1
+ assert responses.calls[0].request.headers["x-api-key"] == "test-api-key"
+ assert parse_qs(urlsplit(responses.calls[0].request.url).query)["fields"] == ["paperId"]
+
+
+def test_validation_hides_transport_error_details() -> None:
+ responses.get(f"{BASE_URL}/paper/search/bulk", body=Timeout("private transport detail"))
+ valid, message = validate_credentials(CONFIG, "v1")
+ assert not valid
+ assert message == "Semantic Scholar is unavailable or has limited requests. Try again later."
+
+
[email protected](("key", "query"), [("", "graph"), ("key\n", "graph"), ("é", "graph"), ("key", " ")])
+def test_invalid_config_does_not_make_requests(key: str, query: str) -> None:
+ valid, message = validate_credentials(SemanticScholarSourceConfig(api_key=key, query=query), "v1")
+ assert not valid
+ assert message
+ assert len(responses.calls) == 0
+
+
+def test_rate_limit_retries_same_page() -> None:
+ responses.get(
+ f"{BASE_URL}/paper/search/bulk", json={"message": "limited"}, status=429, headers={"Retry-After": "0"}
+ )
+ responses.get(f"{BASE_URL}/paper/search/bulk", json={"data": [{"paperId": "a"}]})
+ result = semantic_scholar_source(CONFIG, make_inputs("papers"), make_manager(), "v1")
+ assert list(items(result)) == [[{"paperId": "a"}]]
+ assert responses.calls[0].request.url == responses.calls[1].request.url