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 GLEIF import source (#84371)

Tom Owersaeb096740b50
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/canonical_descriptions.py
new file mode 100644
index 000000000000..def50c98b57f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/canonical_descriptions.py
@@ -0,0 +1,89 @@
+"""Canonical, documentation-sourced descriptions for GLEIF endpoints and columns.
+
+Sourced from the official GLEIF API (https://www.gleif.org/en/lei-data/gleif-api) and verified
+against live responses. Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced GLEIF table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "LeiRecords": {
+ "description": (
+ "A Legal Entity Identifier (LEI) record: the legal name, address, jurisdiction, "
+ "status, and registration details of one legally distinct entity."
+ ),
+ "docs_url": "https://www.gleif.org/en/lei-data/gleif-api",
+ "columns": {
+ "id": "The 20-character Legal Entity Identifier (LEI) code, same as `lei`.",
+ "lei": "The 20-character Legal Entity Identifier (LEI) code.",
+ "entity": "The entity's legal name, addresses, jurisdiction, legal form, and status (nested).",
+ "registration": "LEI registration metadata: registration status, dates, and managing LOU (nested).",
+ "bic": "Business Identifier Code(s) (SWIFT/ISO 9362) associated with the entity, if any.",
+ "mic": "Market Identifier Code(s) (ISO 10383) associated with the entity, if any.",
+ "ocid": "Open Corporates ID associated with the entity, if any.",
+ "conformityFlag": "GLEIF's assessment of how well the record conforms to the LEI data standard.",
+ "initial_registration_date": "Date the LEI was first issued. Promoted from `registration.initialRegistrationDate`; stable, used to partition the table.",
+ "last_update_date": "Date the LEI record was last updated. Promoted from `registration.lastUpdateDate`; used for incremental sync.",
+ },
+ },
+ "LeiIssuers": {
+ "description": "A Local Operating Unit (LOU) accredited by GLEIF to issue and maintain LEIs.",
+ "docs_url": "https://www.gleif.org/en/lei-data/gleif-api",
+ "columns": {
+ "id": "The issuer's own LEI code.",
+ "lei": "The issuer's own LEI code.",
+ "name": "The issuer's legal name.",
+ "marketingName": "The issuer's public-facing/marketing name.",
+ "website": "URL of the issuer's LEI-issuance website.",
+ "accreditationDate": "Date GLEIF accredited the issuer.",
+ },
+ },
+ "EntityLegalForms": {
+ "description": "A jurisdiction's entity legal form (e.g. LLC, GmbH) from the ISO 20275 code list.",
+ "docs_url": "https://www.gleif.org/en/lei-data/gleif-api",
+ "columns": {
+ "id": "The ISO 20275 Entity Legal Form (ELF) code.",
+ "code": "The ISO 20275 Entity Legal Form (ELF) code, same as `id`.",
+ "country": "Country the legal form applies in.",
+ "countryCode": "ISO 3166-1 alpha-2 country code.",
+ "jurisdiction": "Subdivision jurisdiction the legal form applies in, if narrower than the country.",
+ "dateCreated": "Date this legal form entry was added to the ISO 20275 code list.",
+ "status": "Whether the legal form code is active (`ACTV`) or retired (`INAC`).",
+ "names": "Localized names and abbreviations for the legal form (nested list).",
+ },
+ },
+ "RegistrationAuthorities": {
+ "description": "An official business registry (e.g. a companies house) recognized by GLEIF.",
+ "docs_url": "https://www.gleif.org/en/lei-data/gleif-api",
+ "columns": {
+ "id": "The GLEIF Registration Authority (RA) code.",
+ "code": "The GLEIF Registration Authority (RA) code, same as `id`.",
+ "internationalName": "The registry's name in English/international form.",
+ "localName": "The registry's name in the local language, if different.",
+ "website": "URL of the registration authority.",
+ "jurisdictions": "Countries and subdivisions this registration authority covers (nested list).",
+ },
+ },
+ "Countries": {
+ "description": "An ISO 3166-1 country used to classify LEI records and legal forms.",
+ "docs_url": "https://www.gleif.org/en/lei-data/gleif-api",
+ "columns": {
+ "id": "ISO 3166-1 alpha-2 country code, same as `code`.",
+ "code": "ISO 3166-1 alpha-2 country code.",
+ "name": "The country's English name.",
+ },
+ },
+ "Jurisdictions": {
+ "description": "An ISO 3166-2 jurisdiction (country or country subdivision) used to classify LEI records.",
+ "docs_url": "https://www.gleif.org/en/lei-data/gleif-api",
+ "columns": {
+ "id": "ISO 3166-1/3166-2 jurisdiction code, same as `code`.",
+ "code": "ISO 3166-1/3166-2 jurisdiction code (e.g. `US`, `US-CA`).",
+ "name": "The jurisdiction's English name.",
+ "names": "Localized names for the jurisdiction (nested list).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/gleif.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/gleif.py
new file mode 100644
index 000000000000..d91109ef67c6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/gleif.py
@@ -0,0 +1,159 @@
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+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 (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+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.gleif.settings import (
+ BASE_URL,
+ ENDPOINT_PATHS,
+ INCREMENTAL_FIELDS,
+ LEI_RECORDS,
+ PAGE_SIZE,
+)
+
+_HEADERS = {"Accept": "application/vnd.api+json"}
+
+
+@frozen
+class GleifResumeConfig:
+ # GLEIF's `links.next` is a full, self-contained URL (JSON:API convention) covering both
+ # the cursor pagination `lei-records` uses and the page-number pagination the small
+ # reference tables use.
+ next_url: str
+
+
+def _flatten_json_api_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Hoist a JSON:API resource's `attributes` to the row root, keeping the top-level `id`."""
+ attributes = item.get("attributes")
+ if not isinstance(attributes, dict):
+ return {"id": item.get("id")}
+ return {"id": item.get("id"), **attributes}
+
+
+def _flatten_lei_record(item: dict[str, Any]) -> dict[str, Any]:
+ """Flatten a `lei-records` resource, additionally promoting the two registration dates
+ GLEIF nests under `registration` to top-level columns so the table can be partitioned and
+ incremental sync can filter/checkpoint on them.
+ """
+ row = _flatten_json_api_item(item)
+ registration = row.get("registration")
+ if isinstance(registration, dict):
+ row["initial_registration_date"] = registration.get("initialRegistrationDate")
+ row["last_update_date"] = registration.get("lastUpdateDate")
+ return row
+
+
+def _format_gte_filter(value: Any) -> str:
+ """Format a watermark as GLEIF's `>=` date filter value.
+
+ `registration.lastUpdateDate` is stored (and persisted as the incremental watermark) as an
+ ISO-8601 UTC timestamp string, which GLEIF's date filter accepts directly (verified live).
+ """
+ return f">={value}"
+
+
+def gleif_source(
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[GleifResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ incremental_mode = should_use_incremental_field and bool(INCREMENTAL_FIELDS.get(endpoint))
+ use_filter = incremental_mode and db_incremental_field_last_value is not None
+
+ params: dict[str, Any] = {"page[size]": PAGE_SIZE}
+ if endpoint == LEI_RECORDS:
+ # `page[number]` pagination on `lei-records` is rejected past ~10,000 results (verified
+ # live: page 51 at page[size]=200 returns 400), so every sync of this ~3.4M row endpoint
+ # must traverse it via the opaque `page[cursor]` instead.
+ params["page[cursor]"] = "*"
+ params["sort"] = "registration.lastUpdateDate"
+ if use_filter:
+ params["filter[registration.lastUpdateDate]"] = {
+ "type": "incremental",
+ "convert": _format_gte_filter,
+ }
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "headers": _HEADERS,
+ "paginator": JSONResponsePaginator(next_url_path="links.next"),
+ # `links.next` is response-controlled; pin every paginated/resumed request to the
+ # GLEIF API host so a tampered next link can't redirect it elsewhere.
+ "allowed_hosts": [],
+ },
+ "resource_defaults": {
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if incremental_mode
+ else "replace",
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "table_format": "delta",
+ "endpoint": {
+ "path": ENDPOINT_PATHS[endpoint],
+ "params": params,
+ "data_selector": "data",
+ },
+ "data_map": _flatten_lei_record if endpoint == LEI_RECORDS else _flatten_json_api_item,
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"next_url": resume.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion. Called AFTER a page is yielded, so a crash re-yields the last page (merge/
+ # replace both tolerate the duplicate) rather than skipping it.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(GleifResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value if use_filter else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ sort_mode="asc",
+ partition_mode="datetime" if endpoint == LEI_RECORDS else None,
+ partition_format="month" if endpoint == LEI_RECORDS else None,
+ partition_keys=["initial_registration_date"] if endpoint == LEI_RECORDS else None,
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials() -> bool:
+ """GLEIF's API is fully open with no authentication; the only thing to validate is that
+ the service is reachable."""
+ query = urlencode({"page[size]": 1})
+ response = make_tracked_session().get(f"{BASE_URL}/lei-records?{query}", headers=_HEADERS)
+ return response.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/settings.py
new file mode 100644
index 000000000000..ccea82872d88
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/settings.py
@@ -0,0 +1,40 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+BASE_URL = "https://api.gleif.org/api/v1"
+
+# GLEIF caps `page[size]` at 200 (verified live; 201 returns 400).
+PAGE_SIZE = 200
+
+LEI_RECORDS = "LeiRecords"
+LEI_ISSUERS = "LeiIssuers"
+ENTITY_LEGAL_FORMS = "EntityLegalForms"
+REGISTRATION_AUTHORITIES = "RegistrationAuthorities"
+COUNTRIES = "Countries"
+JURISDICTIONS = "Jurisdictions"
+
+ENDPOINTS = (
+ LEI_RECORDS,
+ LEI_ISSUERS,
+ ENTITY_LEGAL_FORMS,
+ REGISTRATION_AUTHORITIES,
+ COUNTRIES,
+ JURISDICTIONS,
+)
+
+ENDPOINT_PATHS: dict[str, str] = {
+ LEI_RECORDS: "/lei-records",
+ LEI_ISSUERS: "/lei-issuers",
+ ENTITY_LEGAL_FORMS: "/entity-legal-forms",
+ REGISTRATION_AUTHORITIES: "/registration-authorities",
+ COUNTRIES: "/countries",
+ JURISDICTIONS: "/jurisdictions",
+}
+
+# Only `lei-records` exposes a server-side timestamp filter (verified live:
+# `filter[registration.lastUpdateDate]=>=DATE`). The reference tables (issuers, legal forms,
+# registration authorities, countries, jurisdictions) change rarely and expose no filter, so
+# they sync full refresh only.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ LEI_RECORDS: [incremental_field("last_update_date")],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/source.py
index c609baf07a5d..be5f5b337662 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/source.py
@@ -1,30 +1,106 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
)
-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.gleif import GleifSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.gleif import (
+ GleifResumeConfig,
+ gleif_source,
+ validate_credentials as validate_gleif_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GleifSource(SimpleSource[GleifSourceConfig]):
+class GleifSource(ResumableSource[GleifSourceConfig, GleifResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://www.gleif.org/en/lei-data/gleif-api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GLEIF
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: GleifSourceConfig,
+ 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: GleifSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_gleif_credentials():
+ return True, None
+ return False, "Could not reach the GLEIF API. Please try again in a moment."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GleifResumeConfig]:
+ return ResumableSourceManager[GleifResumeConfig](inputs, GleifResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GleifSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GleifResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return gleif_source(
+ endpoint=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
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.GLEIF,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
+ keywords=["lei", "legal entity identifier"],
label="GLEIF (Global Legal Entity Identifier Foundation)",
+ caption=(
+ "Import Legal Entity Identifier (LEI) reference data from GLEIF's free, public "
+ "registry. No API key or account is required."
+ ),
iconPath="/static/services/gleif.png",
+ releaseStatus=ReleaseStatus.ALPHA,
fields=cast(list[FieldType], []),
- unreleasedSource=True,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/tests/test_gleif.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/tests/test_gleif.py
new file mode 100644
index 000000000000..66b56f516300
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/tests/test_gleif.py
@@ -0,0 +1,267 @@
+import json
+from collections.abc import Iterable
+from typing import Any, 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.gleif.gleif import (
+ GleifResumeConfig,
+ _flatten_json_api_item,
+ _flatten_lei_record,
+ _format_gte_filter,
+ gleif_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.settings import LEI_ISSUERS, LEI_RECORDS
+
+_LEI_ITEM = {
+ "type": "lei-records",
+ "id": "984500I2ABE9B792FF06",
+ "attributes": {
+ "lei": "984500I2ABE9B792FF06",
+ "entity": {"legalName": {"name": "DA Digital GmbH", "language": "de"}},
+ "registration": {
+ "initialRegistrationDate": "2026-05-30T00:00:00Z",
+ "lastUpdateDate": "2026-08-17T22:46:53Z",
+ },
+ "bic": None,
+ },
+}
+
+
+class TestFlattenJsonApiItem:
+ def test_merges_id_and_attributes(self) -> None:
+ row = _flatten_json_api_item({"id": "abc", "attributes": {"code": "AD", "name": "Andorra"}})
+ assert row == {"id": "abc", "code": "AD", "name": "Andorra"}
+
+ @pytest.mark.parametrize("attributes", [None, "not-a-dict", []])
+ def test_returns_bare_id_when_attributes_missing_or_malformed(self, attributes: Any) -> None:
+ row = _flatten_json_api_item({"id": "abc", "attributes": attributes})
+ assert row == {"id": "abc"}
+
+ def test_missing_attributes_key(self) -> None:
+ assert _flatten_json_api_item({"id": "abc"}) == {"id": "abc"}
+
+
+class TestFlattenLeiRecord:
+ def test_promotes_registration_dates_to_top_level(self) -> None:
+ row = _flatten_lei_record(_LEI_ITEM)
+ assert row["id"] == "984500I2ABE9B792FF06"
+ assert row["initial_registration_date"] == "2026-05-30T00:00:00Z"
+ assert row["last_update_date"] == "2026-08-17T22:46:53Z"
+ # The nested structure is kept alongside the promoted scalars.
+ assert row["registration"]["lastUpdateDate"] == "2026-08-17T22:46:53Z"
+
+ def test_no_registration_key_does_not_add_promoted_fields(self) -> None:
+ row = _flatten_lei_record({"id": "abc", "attributes": {"lei": "abc"}})
+ assert "initial_registration_date" not in row
+ assert "last_update_date" not in row
+
+
+class TestFormatGteFilter:
+ def test_prefixes_value_with_gte_operator(self) -> None:
+ assert _format_gte_filter("2026-08-17T00:00:00Z") == ">=2026-08-17T00:00:00Z"
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(("status_code", "expected"), [(200, True), (429, False), (500, False)])
+ def test_reflects_http_status(self, status_code: int, expected: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.gleif.gleif.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = _make_http_response({}, status_code=status_code)
+ assert validate_credentials() is expected
+
+
+class TestGleifSourceResumeBehavior:
+ # Drives `gleif_source` with a mocked HTTP session. Returns (rows, sent_requests), where
+ # sent_requests is one entry per HTTP call with the request's url and params at send time.
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ sent_requests: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_requests.append({"url": request.url, "params": 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:
+ mock_session = mock_session_factory.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = gleif_source(
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ pages = list(cast(Iterable[Any], response.items()))
+ rows = [row for page in pages for row in page]
+ return rows, sent_requests
+
+ def test_lei_records_fresh_run_uses_cursor_pagination(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(
+ {
+ "data": [_LEI_ITEM],
+ "links": {"next": "https://api.gleif.org/api/v1/lei-records?page%5Bcursor%5D=abc"},
+ }
+ ),
+ _make_http_response({"data": [_LEI_ITEM]}),
+ ]
+ rows, sent = self._drive(LEI_RECORDS, manager, responses)
+
+ assert sent[0]["params"] == {"page[size]": 200, "page[cursor]": "*", "sort": "registration.lastUpdateDate"}
+ # The second request is driven entirely by the response's `links.next` URL.
+ assert sent[1]["url"] == "https://api.gleif.org/api/v1/lei-records?page%5Bcursor%5D=abc"
+ assert sent[1]["params"] == {}
+ assert rows[0]["last_update_date"] == "2026-08-17T22:46:53Z"
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [GleifResumeConfig(next_url="https://api.gleif.org/api/v1/lei-records?page%5Bcursor%5D=abc")]
+
+ def test_lei_records_incremental_run_adds_gte_filter(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [_LEI_ITEM]})]
+ _, sent = self._drive(
+ LEI_RECORDS,
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-08-17T00:00:00Z",
+ )
+
+ assert sent[0]["params"]["filter[registration.lastUpdateDate]"] == ">=2026-08-17T00:00:00Z"
+
+ def test_lei_records_incremental_without_watermark_omits_filter(self) -> None:
+ # A schema's first incremental sync has no watermark yet, so it must fetch everything.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [_LEI_ITEM]})]
+ _, sent = self._drive(
+ LEI_RECORDS, manager, responses, should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
+
+ assert "filter[registration.lastUpdateDate]" not in sent[0]["params"]
+
+ def test_reference_table_uses_page_size_only(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [{"id": "029200067A7K6CH0H586", "attributes": {"name": "CSCS"}}]})]
+ rows, sent = self._drive(LEI_ISSUERS, manager, responses)
+
+ assert sent[0]["params"] == {"page[size]": 200}
+ assert rows == [{"id": "029200067A7K6CH0H586", "name": "CSCS"}]
+
+ def test_resume_seeds_paginator_with_saved_next_url(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = GleifResumeConfig(
+ next_url="https://api.gleif.org/api/v1/lei-records?page%5Bcursor%5D=resumed"
+ )
+
+ responses = [_make_http_response({"data": [_LEI_ITEM]})]
+ _, sent = self._drive(LEI_RECORDS, manager, responses)
+
+ assert sent[0]["url"] == "https://api.gleif.org/api/v1/lei-records?page%5Bcursor%5D=resumed"
+ assert sent[0]["params"] == {}
+ manager.load_state.assert_called_once()
+
+ def test_terminal_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [_LEI_ITEM]})]
+ self._drive(LEI_RECORDS, manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"data": [_LEI_ITEM]})]
+ self._drive(LEI_RECORDS, manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("endpoint", "should_use_incremental_field", "expected_disposition"),
+ [
+ (LEI_RECORDS, True, "merge"),
+ (LEI_RECORDS, False, "replace"),
+ (LEI_ISSUERS, True, "replace"), # LeiIssuers has no incremental field to key a merge on
+ (LEI_ISSUERS, False, "replace"),
+ ],
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.gleif.gleif.rest_api_resource")
+ def test_write_disposition_follows_incremental_support(
+ self,
+ mock_rest_api_resource: MagicMock,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ expected_disposition: str,
+ ) -> None:
+ mock_result = MagicMock()
+ mock_result.name = endpoint
+ mock_result.column_hints = None
+ mock_rest_api_resource.return_value = mock_result
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ response = gleif_source(
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value="2026-08-17T00:00:00Z" if should_use_incremental_field else None,
+ )
+
+ config = mock_rest_api_resource.call_args.args[0]
+ write_disposition = config["resource_defaults"]["write_disposition"]
+ if expected_disposition == "merge":
+ assert write_disposition == {"disposition": "merge", "strategy": "upsert"}
+ else:
+ assert write_disposition == "replace"
+
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ if endpoint == LEI_RECORDS:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["initial_registration_date"]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/tests/test_gleif_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/tests/test_gleif_source.py
new file mode 100644
index 000000000000..79d23ef0aa7b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gleif/tests/test_gleif_source.py
@@ -0,0 +1,111 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.gleif import GleifSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.gleif import GleifResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LEI_RECORDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.gleif.source import GleifSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_VALIDATE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.gleif.source.validate_gleif_credentials"
+)
+_SOURCE_FN_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.gleif.source.gleif_source"
+
+
+class TestGleifSource:
+ def setup_method(self) -> None:
+ self.source = GleifSource()
+ self.team_id = 123
+ self.config = GleifSourceConfig()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.GLEIF
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Gleif"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # The source must ship visible: unreleasedSource hides it from every user.
+ assert not config.unreleasedSource
+ # GLEIF is fully open and keyless, so the connect form has nothing to fill in.
+ assert config.fields == []
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_lei_records_supports_incremental(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}
+ assert incremental == {LEI_RECORDS}
+ assert schemas[LEI_RECORDS].incremental_fields == INCREMENTAL_FIELDS[LEI_RECORDS]
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=[LEI_RECORDS])
+ assert [schema.name for schema in schemas] == [LEI_RECORDS]
+
+ @pytest.mark.parametrize(("mock_return", "expected_valid"), [(True, True), (False, False)])
+ @mock.patch(_VALIDATE_PATCH)
+ def test_validate_credentials(self, mock_validate: mock.MagicMock, mock_return: bool, expected_valid: bool) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert (error_message is None) is expected_valid
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is GleifResumeConfig
+
+ @mock.patch(_SOURCE_FN_PATCH)
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = LEI_RECORDS
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-08-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["endpoint"] == LEI_RECORDS
+ assert kwargs["team_id"] is inputs.team_id
+ assert kwargs["job_id"] is inputs.job_id
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-08-01T00:00:00Z"
+
+ @mock.patch(_SOURCE_FN_PATCH)
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = LEI_RECORDS
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-08-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so the public docs can render it.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_documented_tables_uses_canonical_descriptions(self) -> None:
+ tables = self.source.get_documented_tables()
+
+ assert {table["name"] for table in tables} == set(ENDPOINTS)
+ lei_records = next(table for table in tables if table["name"] == LEI_RECORDS)
+ assert lei_records["description"]
+ assert "Incremental" in lei_records["sync_methods"]