Skip to content

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

feat(data-warehouse): implement hugging_face import source (#67795)

Tom Owers17815c48aeea
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 6650c707e9d4..434818ced74b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -171,6 +171,7 @@ the row lists both.
| guru | HTTP | requests | ✅ |
| hibob | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
+| hugging_face | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| iterable | HTTP | requests | ✅ |
@@ -450,7 +451,6 @@ doesn't conflict with concurrent PRs.
- hightouch
- hoorayhr
- hubplanner
-- hugging_face
- humanitix
- huntr
- ikas
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 030a882424e2..2790d053fc4f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1556,7 +1556,8 @@ class HubspotSourceConfig(config.Config):
@config.config
class HuggingFaceSourceConfig(config.Config):
- pass
+ api_token: str
+ author: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/canonical_descriptions.py
new file mode 100644
index 000000000000..dc9d3a091c5e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/canonical_descriptions.py
@@ -0,0 +1,59 @@
+"""Canonical, documentation-sourced descriptions for Hugging Face Hub endpoints and columns.
+
+Sourced from the official Hugging Face Hub API reference (https://huggingface.co/docs/hub/api).
+Keyed by the endpoint names in `settings.py` `HUGGING_FACE_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Hugging Face table. Columns absent here fall back to LLM
+enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Fields common to every repo kind returned by the list endpoints.
+_COMMON_COLUMNS = {
+ "id": "Repository identifier in `namespace/name` form (unique across the Hub).",
+ "_id": "Internal database identifier for the repository.",
+ "author": "The user or organization that owns the repository.",
+ "private": "Whether the repository is private.",
+ "gated": "Access-gating status of the repository (false, or a gating mode such as 'auto' or 'manual').",
+ "likes": "Number of users who have liked the repository.",
+ "tags": "Tags attached to the repository (task, library, language, license, etc.).",
+ "createdAt": "Time at which the repository was created.",
+ "lastModified": "Time at which the repository was last modified.",
+ "sha": "Commit SHA of the current main revision.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "models": {
+ "description": "A model repository on the Hugging Face Hub, owned by the connected namespace.",
+ "docs_url": "https://huggingface.co/docs/hub/api#get-apimodels",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "modelId": "Alias of `id`; the model repository identifier.",
+ "downloads": "Number of downloads of the model in the last 30 days.",
+ "pipeline_tag": "The primary task the model is for (e.g. text-generation, image-classification).",
+ "library_name": "The library the model is compatible with (e.g. transformers, diffusers).",
+ "trendingScore": "Score used to rank trending models.",
+ "siblings": "The files that make up the model repository.",
+ },
+ },
+ "datasets": {
+ "description": "A dataset repository on the Hugging Face Hub, owned by the connected namespace.",
+ "docs_url": "https://huggingface.co/docs/hub/api#get-apidatasets",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "downloads": "Number of downloads of the dataset in the last 30 days.",
+ "disabled": "Whether the dataset has been disabled.",
+ "key": "Internal search/relevance key for the dataset.",
+ },
+ },
+ "spaces": {
+ "description": "A Space (hosted app) repository on the Hugging Face Hub, owned by the connected namespace.",
+ "docs_url": "https://huggingface.co/docs/hub/api#get-apispaces",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "sdk": "The SDK the Space runs on (e.g. gradio, streamlit, docker, static).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/hugging_face.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/hugging_face.py
new file mode 100644
index 000000000000..1d8d9994f7a2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/hugging_face.py
@@ -0,0 +1,171 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.settings import (
+ HUGGING_FACE_ENDPOINTS,
+ HuggingFaceEndpointConfig,
+)
+
+HUGGING_FACE_BASE_URL = "https://huggingface.co"
+
+# The Hub caps list endpoints at 1000 rows per page; larger pages don't return more.
+PAGE_SIZE = 1000
+
+
+class HuggingFaceRetryableError(Exception):
+ pass
+
+
+class HuggingFaceResumeConfig:
+ # URL of the page to resume from. We checkpoint the *current* page (not the next one) after
+ # yielding it, so a crash re-fetches and re-yields that page rather than skipping it — the delta
+ # merge dedupes the re-pulled rows on the primary key.
+ resume_url: str
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _parse_next_url(link_header: str) -> str | None:
+ """Return the URL with rel="next" from the Hub's Link header, if any."""
+ if not link_header:
+ return None
+ for part in link_header.split(","):
+ part = part.strip()
+ match = re.match(r'<([^>]+)>;\s*rel="next"', part)
+ if match:
+ return match.group(1)
+ return None
+
+
+def validate_credentials(api_token: str) -> bool:
+ url = f"{HUGGING_FACE_BASE_URL}/api/whoami-v2"
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ HuggingFaceRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> requests.Response:
+ response = session.get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HuggingFaceRetryableError(f"Hugging Face API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Hugging Face API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response
+
+
+def _build_initial_url(config: HuggingFaceEndpointConfig, author: str) -> str:
+ # Sort ascending by createdAt (immutable), so new repos append to the end and don't shift pages
+ # we've already walked mid-sync. The Hub has no server-side timestamp range filter, so these
+ # endpoints are full refresh only.
+ params: dict[str, Any] = {
+ "author": author,
+ "sort": "createdAt",
+ "direction": 1,
+ "limit": PAGE_SIZE,
+ }
+ if config.full:
+ params["full"] = "true"
+ return f"{HUGGING_FACE_BASE_URL}{config.path}?{urlencode(params)}"
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ author: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HuggingFaceResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = HUGGING_FACE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ url = resume.resume_url
+ logger.debug(f"Hugging Face: resuming from URL: {url}")
+ else:
+ url = _build_initial_url(config, author)
+
+ while True:
+ response = _fetch_page(session, url, headers, logger)
+ items = response.json()
+ if not isinstance(items, list) or not items:
+ break
+
+ next_url = _parse_next_url(response.headers.get("Link", ""))
+
+ yield items
+
+ # Checkpoint AFTER yielding, and checkpoint the current page URL so a crash re-fetches this
+ # page (merge dedupes on the primary key) rather than skipping it.
+ if next_url:
+ resumable_source_manager.save_state(HuggingFaceResumeConfig(resume_url=url))
+ else:
+ break
+
+ url = next_url
+
+
+def hugging_face_source(
+ api_token: str,
+ endpoint: str,
+ author: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HuggingFaceResumeConfig],
+) -> SourceResponse:
+ config = HUGGING_FACE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ author=author,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/settings.py
new file mode 100644
index 000000000000..996f010e9d5e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/settings.py
@@ -0,0 +1,26 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class HuggingFaceEndpointConfig:
+ name: str
+ path: str
+ # createdAt is immutable, so it's a stable partition key (unlike lastModified). Every Hub
+ # repo object exposes it.
+ partition_key: str = "createdAt"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # `full=true` returns the richer object (e.g. pipeline_tag, library_name on models); harmless
+ # on endpoints that don't add fields.
+ full: bool = True
+
+
+# The Hub exposes each repo kind as a list endpoint with identical query semantics
+# (author filter, createdAt sort, Link-header cursor pagination). These three repo streams are
+# what a user connecting their account actually wants to pull into the warehouse.
+HUGGING_FACE_ENDPOINTS: dict[str, HuggingFaceEndpointConfig] = {
+ "models": HuggingFaceEndpointConfig(name="models", path="/api/models"),
+ "datasets": HuggingFaceEndpointConfig(name="datasets", path="/api/datasets"),
+ "spaces": HuggingFaceEndpointConfig(name="spaces", path="/api/spaces"),
+}
+
+ENDPOINTS = tuple(HUGGING_FACE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/source.py
index 83ebee157d85..794dfdd69ad3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/source.py
@@ -1,30 +1,150 @@
-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.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HuggingFaceSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.hugging_face import (
+ HuggingFaceResumeConfig,
+ hugging_face_source,
+ validate_credentials as validate_hugging_face_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.settings import ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HuggingFaceSource(SimpleSource[HuggingFaceSourceConfig]):
+class HuggingFaceSource(ResumableSource[HuggingFaceSourceConfig, HuggingFaceResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HUGGINGFACE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `author` selects which namespace the stored token reads from, so changing it retargets the
+ # saved credential at a different user or org's repos — force secret re-entry on a change.
+ return ["author"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.HUGGING_FACE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Hugging Face",
- iconPath="/static/services/hugging_face.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Hugging Face access token to pull your Hub repositories into the PostHog Data warehouse.
+
+Create a token in your [Hugging Face access token settings](https://huggingface.co/settings/tokens). A read token is enough for public repos; grant read access to your namespace's repo contents (and `read-org` if you're syncing an organization) to include private repos.
+
+Set **Username or organization** to the namespace whose models, datasets, and Spaces you want to sync (e.g. your username or an org you belong to).
+""",
+ iconPath="/static/services/hugging_face.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/hugging-face",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="hf_...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="author",
+ label="Username or organization",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="huggingface",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked token surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can't fix a credential problem, so stop the sync. Match
+ # the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://huggingface.co": "Your Hugging Face access token is invalid or has been revoked. Create a new token in your Hugging Face settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://huggingface.co": "Your Hugging Face access token is missing the permissions needed to sync this data. Grant read access to the namespace's repos, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HuggingFaceSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The Hub has no server-side timestamp range filter (it silently ignores `since`), so every
+ # endpoint is full refresh only. Repo metadata (likes, downloads, lastModified) mutates in
+ # place, so append-only would drop updates — hence no incremental/append.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: HuggingFaceSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_hugging_face_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Hugging Face access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HuggingFaceResumeConfig]:
+ return ResumableSourceManager[HuggingFaceResumeConfig](inputs, HuggingFaceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HuggingFaceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HuggingFaceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return hugging_face_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ author=config.author,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/tests/test_hugging_face.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/tests/test_hugging_face.py
new file mode 100644
index 000000000000..806393c4d819
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/tests/test_hugging_face.py
@@ -0,0 +1,216 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face import hugging_face
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.hugging_face import (
+ HuggingFaceResumeConfig,
+ HuggingFaceRetryableError,
+ _build_initial_url,
+ _parse_next_url,
+ get_rows,
+ hugging_face_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.settings import (
+ HUGGING_FACE_ENDPOINTS,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: HuggingFaceResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[HuggingFaceResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> HuggingFaceResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: HuggingFaceResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class _FakeResponse:
+ def __init__(self, items: Any, next_url: str | None) -> None:
+ self._items = items
+ link = f'<{next_url}>; rel="next"' if next_url else ""
+ self.headers = {"Link": link}
+
+ def json(self) -> Any:
+ return self._items
+
+
+class TestParseNextUrl:
+ @parameterized.expand(
+ [
+ (
+ "next_only",
+ '<https://huggingface.co/api/models?cursor=abc>; rel="next"',
+ "https://huggingface.co/api/models?cursor=abc",
+ ),
+ (
+ "prev_and_next",
+ '<https://huggingface.co/api/models?cursor=p>; rel="prev", '
+ '<https://huggingface.co/api/models?cursor=n>; rel="next"',
+ "https://huggingface.co/api/models?cursor=n",
+ ),
+ ("no_next", '<https://huggingface.co/api/models?cursor=p>; rel="prev"', None),
+ ("empty", "", None),
+ ]
+ )
+ def test_parse_next_url(self, _name: str, header: str, expected: str | None) -> None:
+ assert _parse_next_url(header) == expected
+
+
+class TestBuildInitialUrl:
+ def test_models_url_is_scoped_sorted_and_full(self) -> None:
+ url = _build_initial_url(HUGGING_FACE_ENDPOINTS["models"], author="huggingface")
+ assert url.startswith("https://huggingface.co/api/models?")
+ assert "author=huggingface" in url
+ # createdAt is immutable, so ascending pages don't shift mid-sync.
+ assert "sort=createdAt" in url
+ assert "direction=1" in url
+ assert "limit=1000" in url
+ assert "full=true" in url
+
+ @parameterized.expand([("models",), ("datasets",), ("spaces",)])
+ def test_every_endpoint_builds_a_scoped_url(self, endpoint: str) -> None:
+ url = _build_initial_url(HUGGING_FACE_ENDPOINTS[endpoint], author="acme")
+ assert f"/api/{endpoint}?" in url
+ assert "author=acme" in url
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(hugging_face, "make_tracked_session", return_value=session):
+ assert validate_credentials("hf_token") is expected
+
+ def test_network_error_is_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(hugging_face, "make_tracked_session", return_value=session):
+ assert validate_credentials("hf_token") is False
+
+
+class TestFetchPage:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_status_raises_retryable_error(self, _name: str, status_code: int) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(hugging_face._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(HuggingFaceRetryableError):
+ hugging_face._fetch_page(session, "https://huggingface.co/api/models", {}, MagicMock())
+
+ @parameterized.expand([("read_timeout", requests.ReadTimeout()), ("connection", requests.ConnectionError())])
+ def test_transient_errors_are_retried_then_succeed(self, _name: str, transient: Exception) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ session = MagicMock()
+ session.get.side_effect = [transient, good]
+ with patch.object(hugging_face._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = hugging_face._fetch_page(session, "https://huggingface.co/api/models", {}, MagicMock())
+ assert result is good
+
+ def test_unauthorized_raises_for_status(self) -> None:
+ response = MagicMock()
+ response.status_code = 401
+ response.ok = False
+ response.raise_for_status.side_effect = requests.HTTPError(
+ "401 Client Error: Unauthorized", response=requests.Response()
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(requests.HTTPError):
+ hugging_face._fetch_page(session, "https://huggingface.co/api/models", {}, MagicMock())
+
+
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, _FakeResponse], endpoint: str) -> list:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> _FakeResponse:
+ return pages[url]
+
+ monkeypatch.setattr(hugging_face, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(hugging_face, "make_tracked_session", lambda *a, **k: MagicMock())
+
+ rows: list = []
+ for page in get_rows(
+ api_token="hf_token",
+ endpoint=endpoint,
+ author="acme",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(page)
+ return rows
+
+
+class TestGetRows:
+ def test_follows_link_header_pagination(self, monkeypatch: Any) -> None:
+ start = _build_initial_url(HUGGING_FACE_ENDPOINTS["models"], author="acme")
+ page2 = "https://huggingface.co/api/models?cursor=2"
+ pages = {
+ start: _FakeResponse([{"id": "acme/a"}, {"id": "acme/b"}], next_url=page2),
+ page2: _FakeResponse([{"id": "acme/c"}], next_url=None),
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "models")
+ assert [r["id"] for r in rows] == ["acme/a", "acme/b", "acme/c"]
+
+ def test_checkpoints_current_page_after_yield(self, monkeypatch: Any) -> None:
+ # Saving the current (not next) page URL means a crash re-fetches it; merge dedupes on id.
+ start = _build_initial_url(HUGGING_FACE_ENDPOINTS["models"], author="acme")
+ page2 = "https://huggingface.co/api/models?cursor=2"
+ pages = {
+ start: _FakeResponse([{"id": "acme/a"}], next_url=page2),
+ page2: _FakeResponse([{"id": "acme/b"}], next_url=None),
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, pages, "models")
+ # Only the first page has a next page, so exactly one checkpoint — pointing at the first page.
+ assert [s.resume_url for s in manager.saved] == [start]
+
+ def test_resumes_from_saved_state(self, monkeypatch: Any) -> None:
+ start = _build_initial_url(HUGGING_FACE_ENDPOINTS["models"], author="acme")
+ page2 = "https://huggingface.co/api/models?cursor=2"
+ pages = {
+ start: _FakeResponse([{"id": "acme/a"}], next_url=page2),
+ page2: _FakeResponse([{"id": "acme/b"}], next_url=None),
+ }
+ manager = _FakeResumableManager(state=HuggingFaceResumeConfig(resume_url=page2))
+ rows = _collect(manager, monkeypatch, pages, "models")
+ # Resuming at page2 skips the already-synced first page.
+ assert [r["id"] for r in rows] == ["acme/b"]
+
+ def test_empty_response_terminates(self, monkeypatch: Any) -> None:
+ start = _build_initial_url(HUGGING_FACE_ENDPOINTS["datasets"], author="acme")
+ pages = {start: _FakeResponse([], next_url="https://huggingface.co/api/datasets?cursor=2")}
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "datasets")
+ assert rows == []
+
+
+class TestHuggingFaceSource:
+ @parameterized.expand([("models",), ("datasets",), ("spaces",)])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = hugging_face_source(
+ api_token="hf_token",
+ endpoint=endpoint,
+ author="acme",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/tests/test_hugging_face_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/tests/test_hugging_face_source.py
new file mode 100644
index 000000000000..3a58da089353
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hugging_face/tests/test_hugging_face_source.py
@@ -0,0 +1,106 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HuggingFaceSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.hugging_face import (
+ HuggingFaceResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.source import HuggingFaceSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> HuggingFaceSourceConfig:
+ return HuggingFaceSourceConfig(api_token="hf_token", author="acme")
+
+
+class TestHuggingFaceSourceClass:
+ def setup_method(self) -> None:
+ self.source = HuggingFaceSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HUGGINGFACE
+
+ def test_source_config_identity(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Hugging Face"
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hugging-face"
+
+ def test_source_config_fields(self) -> None:
+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(fields) == {"api_token", "author"}
+ # The token is a secret; the namespace is a plain text scope.
+ assert fields["api_token"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_token"].secret is True
+ assert fields["api_token"].required is True
+ assert fields["author"].type == SourceFieldInputConfigType.TEXT
+ assert fields["author"].secret is False
+ assert fields["author"].required is True
+
+ def test_connection_host_fields_force_secret_reentry_on_author_change(self) -> None:
+ # Changing author retargets the stored token at another namespace, so it must count as a host field.
+ assert self.source.connection_host_fields == ["author"]
+
+ @parameterized.expand([("models",), ("datasets",), ("spaces",)])
+ def test_get_schemas_are_full_refresh_only(self, endpoint: str) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert endpoint in schemas
+ # The Hub has no server-side timestamp filter, so incremental/append must be off.
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is False
+ assert schemas[endpoint].incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["datasets"])
+ assert [s.name for s in schemas] == ["datasets"]
+
+ @parameterized.expand([("unauthorized", "401 Client Error"), ("forbidden", "403 Client Error")])
+ def test_non_retryable_errors(self, _name: str, expected_key_prefix: str) -> None:
+ errors = self.source.get_non_retryable_errors()
+ assert any(key.startswith(expected_key_prefix) for key in errors)
+
+ def test_validate_credentials_success(self) -> None:
+ with patch.object(source_module, "validate_hugging_face_credentials", return_value=True):
+ assert self.source.validate_credentials(_config(), self.team_id) == (True, None)
+
+ def test_validate_credentials_failure(self) -> None:
+ with patch.object(source_module, "validate_hugging_face_credentials", return_value=False):
+ ok, error = self.source.validate_credentials(_config(), self.team_id)
+ assert ok is False
+ assert error is not None
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(MagicMock())
+ assert manager._data_class is HuggingFaceResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "datasets"
+ manager = MagicMock()
+ with patch.object(source_module, "hugging_face_source") as mock_source:
+ self.source.source_for_pipeline(_config(), manager, inputs)
+ mock_source.assert_called_once_with(
+ api_token="hf_token",
+ endpoint="datasets",
+ author="acme",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == {"models", "datasets", "spaces"}
+ for table in descriptions.values():
+ assert table["description"]
+ assert "id" in table["columns"]