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): add OpenAlex source (#77147)

Tom Owers0f700601e297
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ce8e5d198015..61b3e4f6c290 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -452,6 +452,7 @@ the row lists both.
| open_meteo | HTTP (date windows) | requests | ✅ |
| openai | HTTP | requests | ✅ |
| openai_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| openalex | HTTP (cursor pagination) | requests + `rest_source.RESTClient` | ✅ |
| opinion_stage | HTTP | requests | ✅ |
| opuswatch | HTTP | requests + `rest_source.RESTClient` | ✅ |
| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1177,7 +1178,6 @@ doesn't conflict with concurrent PRs.
- onesignal
- open_data_dc
- open_dental
-- openalex
- opencorporates
- openfec
- opn_payments
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openalex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openalex.py
index 09af297d8fbe..7f68394891db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openalex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openalex.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class OpenalexSourceConfig(config.Config):
- pass
+ api_key: str
+ works_filter: str | None = None
+ authors_filter: str | None = None
+ awards_filter: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/canonical_descriptions.py
new file mode 100644
index 000000000000..c48a7c54000a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/canonical_descriptions.py
@@ -0,0 +1,451 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_BASE = "https://developers.openalex.org/api-reference"
+
+# Present on every OpenAlex entity.
+_SHARED_COLUMNS = {
+ "id": "Canonical OpenAlex URL for the record, for example https://openalex.org/W3038568908. Primary key.",
+ "display_name": "Primary name OpenAlex shows for the record.",
+ "created_date": "Date the record was first added to OpenAlex, as YYYY-MM-DD.",
+ "updated_date": "Date the record was last changed in OpenAlex.",
+ "ids": "Object of external identifiers for the record, such as DOI, ROR, ORCID, ISSN and Wikidata.",
+ "works_count": "Number of works associated with the record.",
+ "cited_by_count": "Total number of citations to works associated with the record.",
+ "counts_by_year": "Works and citation counts for each of the last ten years.",
+ "works_api_url": "URL of the OpenAlex works list filtered to this record.",
+ "summary_stats": "Citation metrics for the record, including 2-year mean citedness, h-index and i10-index.",
+ "description": "Short description of the record.",
+ "homepage_url": "Website for the record.",
+}
+
+
+def _columns(*names: str, **extra: str) -> dict[str, str]:
+ return {**{name: _SHARED_COLUMNS[name] for name in names}, **extra}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "works": {
+ "description": "Scholarly documents indexed by OpenAlex: journal articles, books, datasets, preprints and theses.",
+ "docs_url": f"{_DOCS_BASE}/works/list-works",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "cited_by_count",
+ "counts_by_year",
+ doi="DOI for the work, as a URL. OpenAlex treats the DOI as the work's canonical external ID.",
+ title="Title of the work. Same value as display_name.",
+ publication_year="Year the work was published.",
+ publication_date="Date the work was published, as YYYY-MM-DD.",
+ language="Two-letter ISO 639-1 code for the language of the work.",
+ type="Type of the work, for example article, book-chapter, dataset or preprint.",
+ authorships="List of authors and the institutions they were affiliated with on this work.",
+ primary_location="Where the work is hosted at its publisher of record, including the source and open access status.",
+ best_oa_location="Best openly available copy of the work OpenAlex knows about.",
+ locations="Every location OpenAlex has found the work at, including repositories.",
+ locations_count="Number of locations the work has been found at.",
+ open_access="Open access status of the work, including its oa_status colour and a link to a free copy.",
+ apc_list="List price of the article processing charge for the work's source.",
+ apc_paid="Article processing charge actually paid for the work, when known.",
+ biblio="Volume, issue and page numbers for the work.",
+ primary_topic="Topic OpenAlex assigns the work with the highest score.",
+ topics="Topics assigned to the work, each with a confidence score.",
+ keywords="Keywords assigned to the work, each with a relevance score.",
+ concepts="Legacy concept tags for the work. Superseded by topics.",
+ mesh="Medical Subject Headings tags, present for works indexed in PubMed.",
+ sustainable_development_goals="UN Sustainable Development Goals the work relates to, each with a score.",
+ funders="Funders credited on the work.",
+ awards="Grants and awards credited on the work.",
+ referenced_works="OpenAlex IDs of the works this work cites.",
+ referenced_works_count="Number of works this work cites.",
+ related_works="OpenAlex IDs of works with similar topic assignments.",
+ abstract_inverted_index="Abstract as an inverted index mapping each word to its positions in the text.",
+ has_fulltext="Whether OpenAlex has searched the full text of the work.",
+ indexed_in="Sources the work is indexed in, such as crossref, pubmed or doaj.",
+ is_retracted="Whether the work has been retracted.",
+ is_paratext="Whether the work is front or back matter rather than research content.",
+ fwci="Field-weighted citation impact: citations relative to similar works in the same field and year.",
+ citation_normalized_percentile="Citation count as a percentile among works of the same field, year and type.",
+ cited_by_percentile_year="Citation count percentile range among works published the same year.",
+ institutions_distinct_count="Number of distinct institutions across the work's authorships.",
+ countries_distinct_count="Number of distinct countries across the work's authorships.",
+ corresponding_author_ids="OpenAlex IDs of the authors listed as corresponding.",
+ corresponding_institution_ids="OpenAlex IDs of the institutions listed as corresponding.",
+ ),
+ },
+ "authors": {
+ "description": "People who create scholarly works, disambiguated by OpenAlex into one record per person.",
+ "docs_url": f"{_DOCS_BASE}/authors/list-authors",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "counts_by_year",
+ "works_api_url",
+ "summary_stats",
+ orcid="ORCID identifier for the author, as a URL. ORCID is the author's canonical external ID.",
+ display_name_alternatives="Other names this author has published under.",
+ affiliations="Institutions the author has been affiliated with, with the years of each affiliation.",
+ last_known_institutions="Institutions on the author's most recent work.",
+ topics="Topics the author publishes on, each with a count of works.",
+ topic_share="Topics the author publishes on, scored by the author's share of that topic.",
+ x_concepts="Legacy concept tags for the author. Superseded by topics.",
+ ),
+ },
+ "sources": {
+ "description": "Journals, conferences, book series and repositories that host works.",
+ "docs_url": f"{_DOCS_BASE}/sources/list-sources",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "counts_by_year",
+ "works_api_url",
+ "summary_stats",
+ "homepage_url",
+ issn_l="Linking ISSN for the source, the single canonical ISSN OpenAlex uses.",
+ issn="Every ISSN assigned to the source.",
+ alternate_titles="Other names the source is known by.",
+ type="Type of source, for example journal, repository, conference or book series.",
+ host_organization="OpenAlex ID of the publisher or institution that hosts the source.",
+ host_organization_name="Name of the publisher or institution that hosts the source.",
+ host_organization_lineage="OpenAlex IDs of the host organization and its parents.",
+ country_code="Two-letter ISO 3166-1 country code of the source's publisher.",
+ is_oa="Whether the source is fully open access right now.",
+ is_in_doaj="Whether the source is listed in the Directory of Open Access Journals.",
+ apc_prices="Article processing charge list prices for the source, per currency.",
+ apc_usd="Article processing charge list price for the source in USD.",
+ topics="Topics of the works published in this source.",
+ topic_share="Topics of the works published in this source, scored by the source's share of each topic.",
+ ),
+ },
+ "institutions": {
+ "description": "Universities and other organizations that authors are affiliated with.",
+ "docs_url": f"{_DOCS_BASE}/institutions/list-institutions",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "counts_by_year",
+ "works_api_url",
+ "summary_stats",
+ "homepage_url",
+ ror="ROR identifier for the institution, as a URL. ROR is the institution's canonical external ID.",
+ country_code="Two-letter ISO 3166-1 country code of the institution.",
+ type="Type of institution, for example education, healthcare, company or government.",
+ lineage="OpenAlex IDs of this institution and every parent institution above it.",
+ associated_institutions="Institutions related to this one, each labelled parent, child or related.",
+ geo="Geographic location of the institution, including city, region, country and coordinates.",
+ display_name_acronyms="Acronyms the institution is known by.",
+ display_name_alternatives="Other names the institution is known by.",
+ repositories="Repositories hosted by the institution.",
+ roles="Other OpenAlex entities that represent this organization, such as a funder or publisher record.",
+ international="Institution name translated into other languages.",
+ topics="Topics of the works affiliated with this institution.",
+ topic_share="Topics of the works affiliated with this institution, scored by the institution's share of each topic.",
+ ),
+ },
+ "publishers": {
+ "description": "Companies and organizations that publish journals, books and other sources.",
+ "docs_url": f"{_DOCS_BASE}/publishers/list-publishers",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "counts_by_year",
+ "summary_stats",
+ "homepage_url",
+ alternate_titles="Other names the publisher is known by.",
+ hierarchy_level="Depth of the publisher in its corporate hierarchy. 0 is a root publisher.",
+ parent_publisher="OpenAlex ID of the publisher directly above this one.",
+ lineage="OpenAlex IDs of this publisher and every parent publisher above it.",
+ country_codes="Two-letter ISO 3166-1 country codes where the publisher operates.",
+ roles="Other OpenAlex entities that represent this organization, such as an institution or funder record.",
+ sources_api_url="URL of the OpenAlex sources list filtered to this publisher.",
+ ),
+ },
+ "funders": {
+ "description": "Organizations that fund research, linked to the works and awards they support.",
+ "docs_url": f"{_DOCS_BASE}/funders/list-funders",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "counts_by_year",
+ "summary_stats",
+ "homepage_url",
+ "description",
+ alternate_titles="Other names the funder is known by.",
+ country_code="Two-letter ISO 3166-1 country code of the funder.",
+ awards_count="Number of awards OpenAlex has linked to this funder.",
+ roles="Other OpenAlex entities that represent this organization, such as an institution or publisher record.",
+ ),
+ },
+ "awards": {
+ "description": "Grants and other research awards, linked to their funder and to the works they produced.",
+ "docs_url": f"{_DOCS_BASE}/awards/list-awards",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "description",
+ "works_api_url",
+ doi="DOI for the award, as a URL, when the funder registers one.",
+ funder="Funder that made the award.",
+ funder_award_id="Identifier the funder uses for the award in its own systems.",
+ funder_scheme="Funding scheme or program the award was made under.",
+ funding_type="Type of funding, for example grant or fellowship.",
+ amount="Value of the award.",
+ currency="Three-letter ISO 4217 currency code for the amount.",
+ start_date="Date the award period starts.",
+ end_date="Date the award period ends.",
+ start_year="Year the award period starts.",
+ end_year="Year the award period ends.",
+ lead_investigator="Principal investigator on the award.",
+ co_lead_investigator="Co-lead investigator on the award.",
+ investigators="Everyone listed as an investigator on the award.",
+ institution_awarded="Institution the award was made to.",
+ funded_outputs="Works OpenAlex has linked to this award.",
+ funded_outputs_count="Number of works linked to this award.",
+ landing_page_url="Funder's page for the award.",
+ provenance="Where OpenAlex sourced the award record from.",
+ primary_topic="Topic OpenAlex assigns the award with the highest score.",
+ topics="Topics assigned to the award, each with a confidence score.",
+ ),
+ },
+ "topics": {
+ "description": "Roughly 4,500 research topics that works, authors and sources are classified into.",
+ "docs_url": f"{_DOCS_BASE}/topics/list-topics",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ subfield="Subfield the topic sits in.",
+ field="Field the topic sits in.",
+ domain="Domain the topic sits in.",
+ keywords="Keywords that describe the topic.",
+ siblings="Other topics in the same subfield.",
+ ),
+ },
+ "keywords": {
+ "description": "Free-text keywords assigned to works, with usage and citation counts.",
+ "docs_url": f"{_DOCS_BASE}/keywords/list-keywords",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ ),
+ },
+ "domains": {
+ "description": "Top level of the topic hierarchy: four broad areas of research.",
+ "docs_url": f"{_DOCS_BASE}/domains/list-domains",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ fields="Fields that belong to this domain.",
+ siblings="The other domains.",
+ display_name_alternatives="Other names the domain is known by.",
+ ),
+ },
+ "fields": {
+ "description": "Second level of the topic hierarchy: 26 fields, each belonging to a domain.",
+ "docs_url": f"{_DOCS_BASE}/fields/list-fields",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ domain="Domain this field belongs to.",
+ subfields="Subfields that belong to this field.",
+ siblings="Other fields in the same domain.",
+ display_name_alternatives="Other names the field is known by.",
+ ),
+ },
+ "subfields": {
+ "description": "Third level of the topic hierarchy: 252 subfields, each belonging to a field.",
+ "docs_url": f"{_DOCS_BASE}/subfields/list-subfields",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ field="Field this subfield belongs to.",
+ domain="Domain this subfield belongs to.",
+ topics="Topics that belong to this subfield.",
+ siblings="Other subfields in the same field.",
+ display_name_alternatives="Other names the subfield is known by.",
+ ),
+ },
+ "sdgs": {
+ "description": "The 17 UN Sustainable Development Goals that works are tagged against.",
+ "docs_url": f"{_DOCS_BASE}/sdgs/list-sdgs",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ ),
+ },
+ "countries": {
+ "description": "Countries used in institution and authorship records, with their research output counts.",
+ "docs_url": f"{_DOCS_BASE}/countries/list-countries",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ country_code="Two-letter ISO 3166-1 code for the country.",
+ continent="Continent the country belongs to.",
+ is_global_south="Whether the country is counted as part of the Global South.",
+ institutions_api_url="URL of the OpenAlex institutions list filtered to this country.",
+ authors_api_url="URL of the OpenAlex authors list filtered to this country.",
+ display_name_alternatives="Other names the country is known by.",
+ ),
+ },
+ "continents": {
+ "description": "The seven continents countries are grouped into.",
+ "docs_url": f"{_DOCS_BASE}/continents/list-continents",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "ids",
+ "description",
+ countries="Countries that belong to this continent.",
+ display_name_alternatives="Other names the continent is known by.",
+ ),
+ },
+ "languages": {
+ "description": "Languages works are written in, with their work and citation counts.",
+ "docs_url": f"{_DOCS_BASE}/languages/list-languages",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ ),
+ },
+ "work_types": {
+ "description": "Types a work can be classified as, such as article, book-chapter or dataset.",
+ "docs_url": f"{_DOCS_BASE}/work-types/list-work-types",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ ),
+ },
+ "source_types": {
+ "description": "Types a source can be classified as, such as journal, repository or conference.",
+ "docs_url": f"{_DOCS_BASE}/source-types/list-source-types",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ ),
+ },
+ "institution_types": {
+ "description": "Types an institution can be classified as, such as education, company or government.",
+ "docs_url": f"{_DOCS_BASE}/institution-types/list-institution-types",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ ),
+ },
+ "licenses": {
+ "description": "Licenses that open access copies of works are published under.",
+ "docs_url": f"{_DOCS_BASE}/licenses/list-licenses",
+ "columns": _columns(
+ "id",
+ "display_name",
+ "created_date",
+ "updated_date",
+ "works_count",
+ "cited_by_count",
+ "works_api_url",
+ "description",
+ url="Link to the full text of the license.",
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/openalex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/openalex.py
new file mode 100644
index 000000000000..3378321fa91a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/openalex.py
@@ -0,0 +1,239 @@
+import datetime
+import dataclasses
+from typing import Any, Optional
+
+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 (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import 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 SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.settings import (
+ OPENALEX_ENDPOINTS,
+ OpenAlexEndpointConfig,
+)
+
+OPENALEX_BASE_URL = "https://api.openalex.org"
+# Maximum the API accepts; anything higher is rejected with "per-page parameter must be
+# between 1 and 200".
+PAGE_SIZE = 200
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Rows are large enough (works carry inverted abstracts and full reference lists) that the
+# pipeline default of 5000 rows per chunk can materialize an oversized Arrow table.
+LARGE_ROW_CHUNK_SIZE = 1000
+LARGE_ROW_CHUNK_SIZE_BYTES = 100 * 1024 * 1024
+
+
+class OpenAlexResumeConfig:
+ cursor: str
+
+
+def utc_today() -> datetime.date:
+ return datetime.datetime.now(datetime.UTC).date()
+
+
+def _as_date(value: Any) -> Optional[datetime.date]:
+ """Coerce an incremental watermark to a date, or None if there isn't a usable one."""
+ if value is None:
+ return None
+ if isinstance(value, datetime.datetime):
+ return value.date()
+ if isinstance(value, datetime.date):
+ return value
+ text = str(value).strip()
+ if not text:
+ return None
+ try:
+ return datetime.date.fromisoformat(text[:10])
+ except ValueError:
+ # Not a date we can reason about, so drop the bound rather than send OpenAlex
+ # something it will 400 on. Worst case the run re-reads rows the merge dedupes.
+ return None
+
+
+def build_filter(
+ base_filter: Optional[str],
+ from_publication_date: Any = None,
+ to_publication_date: Optional[datetime.date] = None,
+) -> Optional[str]:
+ """Combine the user's scoping filter with the incremental date bounds.
+
+ OpenAlex ANDs comma-separated clauses inside a single `filter` param, so they all live in
+ one string. `from_publication_date` is inclusive, which means each run re-reads the
+ watermark day and the merge dedupes it — no gap at the boundary.
+
+ `to_publication_date` caps the window at today. OpenAlex carries future publication dates
+ (ahead-of-print and scheduled records), and the pipeline checkpoints the largest value of
+ the incremental field it saw. Without the cap, a single work dated a year out pins the
+ watermark a year into the future and every work published between now and then is silently
+ skipped — permanently, because nothing ever lowers a watermark. Capping keeps the
+ checkpoint at or below today; a future-dated work is picked up by the run that happens on
+ or after its publication date instead.
+ """
+ clauses = []
+ if base_filter and base_filter.strip():
+ clauses.append(base_filter.strip())
+ from_date = _as_date(from_publication_date)
+ # Belt and braces: a watermark already past the cap (persisted before this cap existed, or
+ # by a full refresh) would otherwise make every window empty and stay stuck forever.
+ if from_date is not None and to_publication_date is not None and from_date > to_publication_date:
+ from_date = to_publication_date
+ if from_date is not None:
+ clauses.append(f"from_publication_date:{from_date.isoformat()}")
+ if to_publication_date is not None:
+ clauses.append(f"to_publication_date:{to_publication_date.isoformat()}")
+ return ",".join(clauses) or None
+
+
+def get_resource(
+ endpoint_config: OpenAlexEndpointConfig,
+ entity_filter: Optional[str],
+ should_use_incremental_field: bool,
+) -> EndpointResource:
+ params: dict[str, Any] = {
+ "per_page": PAGE_SIZE,
+ # Seeds cursor pagination; the paginator replaces it with `meta.next_cursor` from
+ # each response.
+ "cursor": "*",
+ "sort": endpoint_config.sort,
+ }
+
+ if should_use_incremental_field:
+ # Pinned once per run rather than read per page: the filter has to stay identical for
+ # the life of a cursor walk, and a long sync can cross midnight.
+ cap = utc_today()
+ params["filter"] = {
+ "type": "incremental",
+ "cursor_path": "publication_date",
+ "initial_value": None,
+ "convert": lambda last_value: build_filter(entity_filter, last_value, cap),
+ }
+ else:
+ params["filter"] = build_filter(entity_filter)
+
+ return {
+ "name": endpoint_config.name,
+ "table_name": endpoint_config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "data_selector": "results",
+ # Every list response wraps its rows in `results`; a body without it is a shape
+ # change, not an empty page.
+ "data_selector_required": True,
+ "params": params,
+ },
+ "table_format": "delta",
+ }
+
+
+def openalex_source(
+ api_key: str,
+ endpoint: str,
+ entity_filter: Optional[str],
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[OpenAlexResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+) -> SourceResponse:
+ endpoint_config = OPENALEX_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": OPENALEX_BASE_URL,
+ "auth": {
+ "type": "api_key",
+ "name": "api_key",
+ "api_key": api_key,
+ "location": "query",
+ },
+ "paginator": JSONResponseCursorPaginator(cursor_path="meta.next_cursor", cursor_param="cursor"),
+ },
+ "resources": [get_resource(endpoint_config, entity_filter, should_use_incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"cursor": resume_config.cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(OpenAlexResumeConfig(cursor=str(state["cursor"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if should_use_incremental_field else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=lambda: resource,
+ primary_keys=[endpoint_config.primary_key],
+ column_hints=resource.column_hints,
+ # Only `works` can be sorted on the incremental field, so it is the only endpoint whose
+ # arrival order we can assert. The rest arrive in the API's undocumented cursor order.
+ sort_mode="asc" if endpoint_config.sort else None,
+ partition_count=1 if endpoint_config.partition_key else None,
+ partition_size=1 if endpoint_config.partition_key else None,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ chunk_size=LARGE_ROW_CHUNK_SIZE if endpoint_config.large_rows else None,
+ chunk_size_bytes=LARGE_ROW_CHUNK_SIZE_BYTES if endpoint_config.large_rows else None,
+ )
+
+
+def validate_credentials(api_key: str, filters: dict[str, Optional[str]]) -> tuple[bool, Optional[str]]:
+ """Probe the API key, then each configured filter expression.
+
+ `/domains` is the cheapest list endpoint (four rows). Filters are checked against their own
+ entity because OpenAlex rejects an unknown filter field with a 400 and names it, which is a
+ far better setup-time error than a sync that fails on its first page.
+ """
+ session = make_tracked_session(redact_values=(api_key,))
+
+ probe_params: dict[str, str] = {"per_page": "1", "api_key": api_key}
+
+ response = session.get(
+ f"{OPENALEX_BASE_URL}/domains",
+ params=probe_params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code in (401, 403):
+ return False, "Invalid OpenAlex API key"
+ if not response.ok:
+ return False, f"OpenAlex API returned {response.status_code}"
+
+ for endpoint, entity_filter in filters.items():
+ if not entity_filter or not entity_filter.strip():
+ continue
+ endpoint_config = OPENALEX_ENDPOINTS[endpoint]
+ filter_response = session.get(
+ f"{OPENALEX_BASE_URL}{endpoint_config.path}",
+ params={**probe_params, "filter": entity_filter.strip()},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if filter_response.status_code == 400:
+ return False, f"The {endpoint} filter is not a valid OpenAlex filter expression"
+ if filter_response.status_code == 403:
+ return False, f"The {endpoint} filter needs an OpenAlex plan your API key does not have"
+ if not filter_response.ok:
+ return False, f"OpenAlex API returned {filter_response.status_code} for the {endpoint} filter"
+
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/settings.py
new file mode 100644
index 000000000000..2e00207d989f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/settings.py
@@ -0,0 +1,79 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass(frozen=True)
+class OpenAlexEndpointConfig:
+ name: str
+ # Path segment of the entity list endpoint, e.g. `/works`.
+ path: str
+ # Every OpenAlex entity is keyed by its canonical OpenAlex URL, e.g.
+ # `https://openalex.org/W3038568908`. Unique across the whole entity type.
+ primary_key: str = "id"
+ # Date OpenAlex first indexed the record. Stable (unlike `updated_date`, which moves on
+ # every metadata revision), so it is safe to partition on.
+ partition_key: Optional[str] = "created_date"
+ # Name of the source config field holding an optional OpenAlex filter expression that
+ # scopes this table. Only set for the entity types too large to sync in full.
+ filter_config_field: Optional[str] = None
+ # Value passed as `sort=`. Only `works` has a free, time-ordered sort, and it is the only
+ # endpoint whose response order we can guarantee.
+ sort: Optional[str] = None
+ # Rows carry large nested structures (abstracts, reference lists), so batch them tighter
+ # than the pipeline default to keep the source-to-Arrow conversion off the memory ceiling.
+ large_rows: bool = False
+
+
+OPENALEX_ENDPOINTS: dict[str, OpenAlexEndpointConfig] = {
+ "works": OpenAlexEndpointConfig(
+ name="works",
+ path="/works",
+ filter_config_field="works_filter",
+ sort="publication_date",
+ large_rows=True,
+ ),
+ "authors": OpenAlexEndpointConfig(
+ name="authors",
+ path="/authors",
+ filter_config_field="authors_filter",
+ ),
+ "awards": OpenAlexEndpointConfig(
+ name="awards",
+ path="/awards",
+ filter_config_field="awards_filter",
+ ),
+ "sources": OpenAlexEndpointConfig(name="sources", path="/sources"),
+ "institutions": OpenAlexEndpointConfig(name="institutions", path="/institutions"),
+ "publishers": OpenAlexEndpointConfig(name="publishers", path="/publishers"),
+ "funders": OpenAlexEndpointConfig(name="funders", path="/funders"),
+ "topics": OpenAlexEndpointConfig(name="topics", path="/topics"),
+ "keywords": OpenAlexEndpointConfig(name="keywords", path="/keywords"),
+ "domains": OpenAlexEndpointConfig(name="domains", path="/domains"),
+ "fields": OpenAlexEndpointConfig(name="fields", path="/fields"),
+ "subfields": OpenAlexEndpointConfig(name="subfields", path="/subfields"),
+ "sdgs": OpenAlexEndpointConfig(name="sdgs", path="/sdgs"),
+ "countries": OpenAlexEndpointConfig(name="countries", path="/countries"),
+ "continents": OpenAlexEndpointConfig(name="continents", path="/continents"),
+ "languages": OpenAlexEndpointConfig(name="languages", path="/languages"),
+ "work_types": OpenAlexEndpointConfig(name="work_types", path="/work-types"),
+ "source_types": OpenAlexEndpointConfig(name="source_types", path="/source-types"),
+ "institution_types": OpenAlexEndpointConfig(name="institution_types", path="/institution-types"),
+ "licenses": OpenAlexEndpointConfig(name="licenses", path="/licenses"),
+}
+
+ENDPOINTS = tuple(OPENALEX_ENDPOINTS.keys())
+
+# OpenAlex gates its record-modification filters (`from_updated_date`, `from_created_date`) and
+# `sort=updated_date` behind a Premium, Institutional or Partner plan — a free key gets
+# "Plan upgrade required" back. `from_publication_date` is free, so `works` is the one table
+# with a usable server-side timestamp filter. It tracks when a paper was published rather than
+# when OpenAlex last revised it, so an incremental run picks up newly published work but not
+# late edits to older records; full refresh those when you need the corrections. Incremental
+# runs also cap the window at today, because OpenAlex carries future publication dates and one
+# of those rows would otherwise checkpoint a watermark nothing can lower again.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "works": [incremental_field("publication_date", IncrementalFieldType.Date)],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/source.py
index a2f810d6d940..8bcb82a33784 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/source.py
@@ -1,32 +1,173 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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,
+ build_endpoint_schemas,
+)
+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.openalex import (
OpenalexSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.openalex import (
+ OpenAlexResumeConfig,
+ openalex_source,
+ validate_credentials as validate_openalex_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ OPENALEX_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# Endpoints whose table can be narrowed with an OpenAlex filter expression, mapped to the
+# config field holding it.
+FILTERABLE_ENDPOINTS: dict[str, str] = {
+ name: endpoint.filter_config_field
+ for name, endpoint in OPENALEX_ENDPOINTS.items()
+ if endpoint.filter_config_field is not None
+}
+
@SourceRegistry.register
-class OpenalexSource(SimpleSource[OpenalexSourceConfig]):
+class OpenalexSource(ResumableSource[OpenalexSourceConfig, OpenAlexResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs
+ # OpenAlex serves a single unversioned API at api.openalex.org: no version path segment,
+ # header or param, so there is nothing to pin.
+ api_docs_url = "https://developers.openalex.org/api-reference/introduction"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OPENALEX
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.openalex.org": "Your OpenAlex API key is invalid or expired. Create a new key at openalex.org/settings/api and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.openalex.org": "OpenAlex rejected this request as needing a paid plan. Check that your filters only use fields your OpenAlex plan includes.",
+ "400 Client Error: Bad Request for url: https://api.openalex.org": "OpenAlex rejected the request. Check that your filter expressions use valid OpenAlex filter fields.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: OpenalexSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: OpenalexSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ filters = {endpoint: self._filter_for(config, endpoint) for endpoint in FILTERABLE_ENDPOINTS}
+ return validate_openalex_credentials(config.api_key, filters)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenAlexResumeConfig]:
+ return ResumableSourceManager[OpenAlexResumeConfig](inputs, OpenAlexResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OpenalexSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OpenAlexResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return openalex_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ entity_filter=self._filter_for(config, inputs.schema_name),
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
+ )
+
+ @staticmethod
+ def _filter_for(config: OpenalexSourceConfig, endpoint: str) -> Optional[str]:
+ field_name = FILTERABLE_ENDPOINTS.get(endpoint)
+ if field_name is None:
+ return None
+ value = getattr(config, field_name, None)
+ return value if isinstance(value, str) else None
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.OPENALEX,
category=DataWarehouseSourceCategory.ANALYTICS,
label="OpenAlex",
+ caption="""Enter your OpenAlex API key to pull scholarly metadata into the PostHog Data warehouse.
+
+Keys are free and take about a minute to create at [openalex.org/settings/api](https://openalex.org/settings/api).
+
+OpenAlex indexes over 300 million works and 120 million authors, which is more than a free key's daily allowance covers. Use the filter fields to narrow the works, authors and awards tables to the records you care about, for example `authorships.institutions.lineage:i27837315` for one institution's papers. The [filtering guide](https://developers.openalex.org/guides/filtering) lists the available filter fields. Leave a filter blank to sync the whole entity.""",
iconPath="/static/services/openalex.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/openalex",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["research", "scholarly", "citations", "publications"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="works_filter",
+ label="Works filter (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="authorships.institutions.lineage:i27837315",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="authors_filter",
+ label="Authors filter (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="last_known_institutions.id:i27837315",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="awards_filter",
+ label="Awards filter (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="funder.id:f4320306076",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/tests/test_openalex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/tests/test_openalex.py
new file mode 100644
index 000000000000..8c3fa3f26010
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/tests/test_openalex.py
@@ -0,0 +1,377 @@
+import json
+import datetime
+from collections.abc import Iterable
+from typing import Any, Optional, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.openalex import (
+ PAGE_SIZE,
+ OpenAlexResumeConfig,
+ build_filter,
+ openalex_source,
+ utc_today,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.settings import (
+ ENDPOINTS,
+ OPENALEX_ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.openalex.openalex"
+INSTITUTION_FILTER = "authorships.institutions.lineage:i27837315"
+TODAY = utc_today()
+
+
+def _page(cursor: Optional[str], rows: Optional[list[dict[str, Any]]] = None) -> Response:
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps(
+ {"meta": {"count": 1, "next_cursor": cursor}, "results": rows if rows is not None else [{"id": "W1"}]}
+ ).encode()
+ response.headers["Content-Type"] = "application/json"
+ return response
+
+
+def _http(status_code: int) -> Response:
+ response = Response()
+ response.status_code = status_code
+ response._content = b"{}"
+ return response
+
+
+def _manager(resume_state: Optional[OpenAlexResumeConfig] = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _drive(
+ endpoint: str,
+ responses: list[Response],
+ manager: MagicMock,
+ entity_filter: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> list[dict[str, Any]]:
+ # The paginator mutates one Request in place across pages, so snapshot params at send time
+ # rather than reading them back off the mock's call list.
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as mock_session_factory:
+ session = mock_session_factory.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request
+ session.send.side_effect = fake_send
+
+ response = openalex_source(
+ api_key="key",
+ endpoint=endpoint,
+ entity_filter=entity_filter,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ return sent_params
+
+
+class TestBuildFilter:
+ @pytest.mark.parametrize(
+ "base_filter,watermark,expected",
+ [
+ (None, None, None),
+ ("", None, None),
+ (" ", None, None),
+ (INSTITUTION_FILTER, None, INSTITUTION_FILTER),
+ (" " + INSTITUTION_FILTER + " ", None, INSTITUTION_FILTER),
+ (None, datetime.date(2026, 7, 1), "from_publication_date:2026-07-01"),
+ (None, datetime.datetime(2026, 7, 1, 13, 45), "from_publication_date:2026-07-01"),
+ (None, "2026-07-01", "from_publication_date:2026-07-01"),
+ (None, "2026-07-01T13:45:00Z", "from_publication_date:2026-07-01"),
+ (None, "", None),
+ (None, "not-a-date", None),
+ (
+ INSTITUTION_FILTER,
+ datetime.date(2026, 7, 1),
+ f"{INSTITUTION_FILTER},from_publication_date:2026-07-01",
+ ),
+ ],
+ )
+ def test_clauses_are_comma_joined(self, base_filter: Any, watermark: Any, expected: Optional[str]) -> None:
+ assert build_filter(base_filter, watermark) == expected
+
+ def test_the_cap_is_rendered_as_a_to_publication_date_clause(self) -> None:
+ assert build_filter(None, datetime.date(2026, 7, 1), datetime.date(2026, 7, 20)) == (
+ "from_publication_date:2026-07-01,to_publication_date:2026-07-20"
+ )
+
+ def test_a_cap_without_a_watermark_still_bounds_the_first_run(self) -> None:
+ assert build_filter(INSTITUTION_FILTER, None, datetime.date(2026, 7, 20)) == (
+ f"{INSTITUTION_FILTER},to_publication_date:2026-07-20"
+ )
+
+ def test_a_watermark_past_the_cap_is_pulled_back_to_it(self) -> None:
+ # A watermark ahead of the cap would otherwise ask for an empty window on every run,
+ # and nothing ever lowers a watermark, so the table would never sync again.
+ assert build_filter(None, datetime.date(2027, 1, 1), datetime.date(2026, 7, 20)) == (
+ "from_publication_date:2026-07-20,to_publication_date:2026-07-20"
+ )
+
+
+class TestPagination:
+ def test_first_request_seeds_the_cursor_and_later_pages_follow_next_cursor(self) -> None:
+ manager = _manager()
+
+ sent_params = _drive("topics", [_page("c1"), _page("c2"), _page(None)], manager)
+
+ # Without the "*" seed OpenAlex falls back to page-number paging, which is capped at
+ # 10,000 records, so a large table would silently truncate.
+ assert [params["cursor"] for params in sent_params] == ["*", "c1", "c2"]
+ assert {params["per_page"] for params in sent_params} == {PAGE_SIZE}
+
+ def test_state_is_saved_after_every_non_terminal_page(self) -> None:
+ manager = _manager()
+
+ _drive("topics", [_page("c1"), _page("c2"), _page(None)], manager)
+
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ OpenAlexResumeConfig(cursor="c1"),
+ OpenAlexResumeConfig(cursor="c2"),
+ ]
+
+ def test_single_page_run_saves_no_state(self) -> None:
+ manager = _manager()
+
+ _drive("topics", [_page(None)], manager)
+
+ manager.save_state.assert_not_called()
+ manager.load_state.assert_not_called()
+
+ def test_resume_starts_from_the_saved_cursor(self) -> None:
+ manager = _manager(OpenAlexResumeConfig(cursor="saved-cursor"))
+
+ sent_params = _drive("topics", [_page(None)], manager)
+
+ assert sent_params[0]["cursor"] == "saved-cursor"
+
+
+class TestRequestParams:
+ def test_incremental_run_sends_the_watermark_as_a_server_side_filter(self) -> None:
+ sent_params = _drive(
+ "works",
+ [_page(None)],
+ _manager(),
+ entity_filter=INSTITUTION_FILTER,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.date(2026, 7, 1),
+ )
+
+ assert sent_params[0]["filter"] == (
+ f"{INSTITUTION_FILTER},from_publication_date:2026-07-01,to_publication_date:{TODAY.isoformat()}"
+ )
+ # The watermark only advances correctly if rows arrive oldest first.
+ assert sent_params[0]["sort"] == "publication_date"
+
+ def test_first_incremental_run_sends_the_user_filter_and_the_cap(self) -> None:
+ sent_params = _drive(
+ "works",
+ [_page(None)],
+ _manager(),
+ entity_filter=INSTITUTION_FILTER,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+
+ assert sent_params[0]["filter"] == f"{INSTITUTION_FILTER},to_publication_date:{TODAY.isoformat()}"
+
+ def test_incremental_runs_never_read_past_today(self) -> None:
+ # OpenAlex carries future publication dates. The pipeline checkpoints the largest
+ # value it sees, so fetching one would pin the watermark in the future and silently
+ # skip everything published between now and then, forever.
+ sent_params = _drive(
+ "works",
+ [_page(None)],
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.date(2026, 7, 1),
+ )
+
+ assert f"to_publication_date:{TODAY.isoformat()}" in sent_params[0]["filter"]
+
+ def test_a_future_watermark_does_not_wedge_the_table(self) -> None:
+ # Nothing ever lowers a watermark, so a bound past the cap has to be pulled back to it
+ # rather than left asking for an empty window on every run.
+ sent_params = _drive(
+ "works",
+ [_page(None)],
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=TODAY + datetime.timedelta(days=365),
+ )
+
+ assert sent_params[0]["filter"] == (
+ f"from_publication_date:{TODAY.isoformat()},to_publication_date:{TODAY.isoformat()}"
+ )
+
+ def test_the_cap_stays_stable_across_pages_of_one_run(self) -> None:
+ # The filter has to stay identical for the life of a cursor walk, so the cap is pinned
+ # once per run rather than recomputed per page.
+ sent_params = _drive(
+ "works",
+ [_page("c1"), _page(None)],
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.date(2026, 7, 1),
+ )
+
+ assert sent_params[0]["filter"] == sent_params[1]["filter"]
+
+ def test_full_refresh_sends_no_publication_date_bounds(self) -> None:
+ # A full refresh checkpoints nothing, so there is no watermark to protect and no
+ # reason to hide ahead-of-print works from the table.
+ sent_params = _drive("works", [_page(None)], _manager(), should_use_incremental_field=False)
+
+ assert "filter" not in sent_params[0]
+
+ def test_full_refresh_ignores_a_stale_watermark(self) -> None:
+ sent_params = _drive(
+ "works",
+ [_page(None)],
+ _manager(),
+ entity_filter=INSTITUTION_FILTER,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime.date(2026, 7, 1),
+ )
+
+ assert sent_params[0]["filter"] == INSTITUTION_FILTER
+
+ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if name != "works"])
+ def test_only_works_sends_a_sort(self, endpoint: str) -> None:
+ # `sort=publication_date` is a works-only field; sending it elsewhere is a 400.
+ sent_params = _drive(endpoint, [_page(None)], _manager())
+
+ assert "sort" not in sent_params[0]
+
+ @pytest.mark.parametrize("endpoint", [name for name in ENDPOINTS if name not in ("works", "authors", "awards")])
+ def test_unfilterable_endpoints_send_no_filter(self, endpoint: str) -> None:
+ sent_params = _drive(endpoint, [_page(None)], _manager())
+
+ assert "filter" not in sent_params[0]
+
+
+class TestSourceResponseMetadata:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ endpoint_config = OPENALEX_ENDPOINTS[endpoint]
+ response = openalex_source(
+ api_key="key",
+ endpoint=endpoint,
+ entity_filter=None,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_manager(),
+ db_incremental_field_last_value=None,
+ )
+
+ assert response.name == endpoint
+ # Every OpenAlex entity is keyed by its canonical OpenAlex URL, unique per entity type.
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [endpoint_config.partition_key]
+ # Declaring "asc" on an endpoint we cannot order would checkpoint a bogus watermark.
+ assert response.sort_mode == ("asc" if endpoint == "works" else None)
+
+ def test_works_rows_are_batched_tighter_than_the_default(self) -> None:
+ works = openalex_source(
+ api_key="key",
+ endpoint="works",
+ entity_filter=None,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_manager(),
+ db_incremental_field_last_value=None,
+ )
+ topics = openalex_source(
+ api_key="key",
+ endpoint="topics",
+ entity_filter=None,
+ team_id=1,
+ job_id="job",
+ resumable_source_manager=_manager(),
+ db_incremental_field_last_value=None,
+ )
+
+ assert works.chunk_size is not None and works.chunk_size_bytes is not None
+ assert topics.chunk_size is None and topics.chunk_size_bytes is None
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code,expected_ok,expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid OpenAlex API key"),
+ (403, False, "Invalid OpenAlex API key"),
+ (500, False, "OpenAlex API returned 500"),
+ ],
+ )
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_key_probe_status_mapping(
+ self, mock_session: MagicMock, status_code: int, expected_ok: bool, expected_message: Optional[str]
+ ) -> None:
+ mock_session.return_value.get.return_value = _http(status_code)
+
+ assert validate_credentials("key", {}) == (expected_ok, expected_message)
+
+ @pytest.mark.parametrize(
+ "status_code,expected_message",
+ [
+ (400, "The works filter is not a valid OpenAlex filter expression"),
+ (403, "The works filter needs an OpenAlex plan your API key does not have"),
+ (500, "OpenAlex API returned 500 for the works filter"),
+ ],
+ )
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_a_rejected_filter_is_not_reported_as_a_bad_key(
+ self, mock_session: MagicMock, status_code: int, expected_message: str
+ ) -> None:
+ mock_session.return_value.get.side_effect = [_http(200), _http(status_code)]
+
+ assert validate_credentials("key", {"works": "bogus_field:x"}) == (False, expected_message)
+
+ @pytest.mark.parametrize("entity_filter", [None, "", " "])
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_blank_filters_are_not_probed(self, mock_session: MagicMock, entity_filter: Optional[str]) -> None:
+ mock_session.return_value.get.return_value = _http(200)
+
+ assert validate_credentials("key", {"works": entity_filter}) == (True, None)
+ assert mock_session.return_value.get.call_count == 1
+
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_every_configured_filter_is_probed_against_its_own_entity(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.get.return_value = _http(200)
+
+ assert validate_credentials("key", {"works": INSTITUTION_FILTER, "awards": "funder.id:f1"}) == (True, None)
+
+ probed = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert probed == [
+ "https://api.openalex.org/domains",
+ "https://api.openalex.org/works",
+ "https://api.openalex.org/awards",
+ ]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/tests/test_openalex_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/tests/test_openalex_source.py
new file mode 100644
index 000000000000..7511324eb40f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openalex/tests/test_openalex_source.py
@@ -0,0 +1,160 @@
+from typing import Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.openalex import (
+ OpenalexSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.openalex import OpenAlexResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openalex.source import OpenalexSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.openalex.source"
+
+
+def _inputs(schema_name: str) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestOpenalexSource:
+ def setup_method(self) -> None:
+ self.source = OpenalexSource()
+ self.config = OpenalexSourceConfig(api_key="key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.OPENALEX
+
+ def test_source_ships_visible_in_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.label == "OpenAlex"
+ assert config.iconPath == "/static/services/openalex.png"
+
+ def test_fields(self) -> None:
+ fields = [f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)]
+
+ assert [f.name for f in fields] == ["api_key", "works_filter", "authors_filter", "awards_filter"]
+
+ api_key = fields[0]
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+ assert all(f.required is False and f.secret is False for f in fields[1:])
+
+ def test_get_schemas_lists_every_endpoint_without_credentials(self) -> None:
+ schemas = self.source.get_schemas(OpenalexSourceConfig(api_key=""), team_id=1)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["works", "topics"])
+
+ assert {schema.name for schema in schemas} == {"works", "topics"}
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_only_works_advertises_incremental_sync(self, endpoint: str) -> None:
+ # OpenAlex gates its updated/created date filters behind a paid plan, so `works` is the
+ # only table with a usable server-side timestamp filter.
+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)
+
+ if endpoint == "works":
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["publication_date"]
+ else:
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_incremental_fields_only_cover_known_endpoints(self) -> None:
+ assert set(INCREMENTAL_FIELDS) <= set(ENDPOINTS)
+
+ def test_canonical_descriptions_are_keyed_by_schema_name(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert descriptions is CANONICAL_DESCRIPTIONS
+ assert set(descriptions) <= set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.openalex.org/works?per_page=200",
+ "403 Client Error: Forbidden for url: https://api.openalex.org/works?per_page=200",
+ "400 Client Error: Bad Request for url: https://api.openalex.org/works?per_page=200",
+ ],
+ )
+ def test_auth_and_plan_failures_are_non_retryable(self, observed_error: str) -> None:
+ assert any(prefix in observed_error for prefix in self.source.get_non_retryable_errors())
+
+ def test_resumable_manager_is_bound_to_the_cursor_dataclass(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs("works"))
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OpenAlexResumeConfig
+
+ @pytest.mark.parametrize(
+ "endpoint,expected_filter",
+ [
+ ("works", "works-scope"),
+ ("authors", "authors-scope"),
+ ("awards", "awards-scope"),
+ ("topics", None),
+ ("institutions", None),
+ ],
+ )
+ @patch(f"{SOURCE_MODULE}.openalex_source")
+ def test_each_table_gets_its_own_filter(
+ self, mock_openalex_source: MagicMock, endpoint: str, expected_filter: Optional[str]
+ ) -> None:
+ # Sending the works filter to another entity would be rejected as an invalid filter field.
+ config = OpenalexSourceConfig(
+ api_key="key",
+ works_filter="works-scope",
+ authors_filter="authors-scope",
+ awards_filter="awards-scope",
+ )
+
+ self.source.source_for_pipeline(config, MagicMock(spec=ResumableSourceManager), _inputs(endpoint))
+
+ assert mock_openalex_source.call_args.kwargs["entity_filter"] == expected_filter
+ assert mock_openalex_source.call_args.kwargs["endpoint"] == endpoint
+
+ @patch(f"{SOURCE_MODULE}.validate_openalex_credentials")
+ def test_validate_credentials_probes_every_configured_filter(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ config = OpenalexSourceConfig(api_key="key", works_filter="works-scope", awards_filter="awards-scope")
+
+ assert self.source.validate_credentials(config, team_id=1) == (True, None)
+
+ assert mock_validate.call_args.args[0] == "key"
+ assert mock_validate.call_args.args[1] == {
+ "works": "works-scope",
+ "authors": None,
+ "awards": "awards-scope",
+ }