: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add hugging face discussions, collections, likes and tag tables (#111306)
Tom Owers9e0404ab2401
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 2549757fb5d8..d694b71553e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -4150,19 +4150,19 @@ Note: Diffed the Sections/\*.md files in the official hubplanner/API repo agains## HuggingFace — **thin**-Today (3): `datasets`, `models`, `spaces`+Today (8): `collections`, `dataset_tags`, `datasets`, `discussions`, `likes`, `model_tags`, `models`, `spaces`Diffed against: <https://huggingface.co/.well-known/openapi.json>-- [ ] `/api/{repoType}/{namespace}/{repo}/discussions` — discussions and pull requests per repo - the main community activity signal on repos we already sync (high)-- [ ] `/api/collections` — curated collections grouping models, datasets and spaces we already sync (high)-- [ ] `/api/models-tags-by-type and /api/datasets-tags-by-type` — lookup tables resolving the tag strings carried on every model and dataset row (high)+- [x] `/api/{repoType}/{namespace}/{repo}/discussions` — discussions and pull requests per repo - the main community activity signal on repos we already sync (high)+- [x] `/api/collections` — curated collections grouping models, datasets and spaces we already sync (high)+- [x] `/api/models-tags-by-type and /api/datasets-tags-by-type` — lookup tables resolving the tag strings carried on every model and dataset row (high)- [ ] `/api/trending` — Hub-wide trending repos - the headline discovery metric (medium)- [ ] `/api/models|datasets|spaces/{namespace}/{repo}/commits/{rev}` — commit history per repo, the change/velocity fact table for repos we sync (medium)- [ ] `/api/daily_papers and /api/papers` — papers linked to models and datasets, plus daily paper rankings (medium)- [ ] `/api/organizations/{name}/members` — org membership roster resolving repo owners (medium)- [ ] `/api/spaces/{namespace}/{repo}/metrics` — runtime usage metrics for spaces we already sync (medium)-- [ ] `/api/users/{username}/likes` — per-user likes, the engagement edge between users and repos (medium)+- [x] `/api/users/{username}/likes` — per-user likes, the engagement edge between users and repos (medium)- [ ] `/api/jobs/{namespace} (and /{jobId}/metrics)` — compute job runs and their metrics for cost/usage analysis (low)- [ ] `/api/models|datasets/{namespace}/{repo}/refs` — branches and tags per repo, needed to interpret revision-scoped data (low)- [ ] `/api/models|datasets/{namespace}/{repo}/lfs-files` — per-file storage footprint for repo size analysis (low)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.pyindex dc9d3a091c5e..8a8ed60426ed 100644--- 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@@ -56,4 +56,70 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"sdk": "The SDK the Space runs on (e.g. gradio, streamlit, docker, static).",},},+ "discussions": {+ "description": "A discussion or pull request on a model, dataset, or Space repository owned by the connected namespace.",+ "docs_url": "https://huggingface.co/docs/hub/repositories-pull-requests-discussions",+ "columns": {+ "num": "Number of the discussion, unique within its repository.",+ "repo_type": "Kind of repository the discussion belongs to (model, dataset, or space).",+ "repo_name": "Repository identifier in `namespace/name` form.",+ "repo": "The repository the discussion belongs to.",+ "title": "Title of the discussion.",+ "status": "Status of the discussion (open, closed, merged, or draft).",+ "isPullRequest": "Whether the discussion is a pull request.",+ "author": "The user or organization that opened the discussion.",+ "createdAt": "Time at which the discussion was opened.",+ "numComments": "Number of comments on the discussion.",+ "numReactionUsers": "Number of users who reacted to the discussion.",+ "topReactions": "The most used reactions on the discussion.",+ "pinned": "Whether the discussion is pinned on the repository.",+ "repoOwner": "The owner of the repository and its relation to the discussion.",+ },+ },+ "collections": {+ "description": "A collection owned by the connected namespace, grouping models, datasets, Spaces, and papers.",+ "docs_url": "https://huggingface.co/docs/hub/collections",+ "columns": {+ "slug": "Collection identifier in `namespace/title-id` form (unique across the Hub).",+ "title": "Title of the collection.",+ "description": "Description of the collection.",+ "owner": "The user or organization that owns the collection.",+ "items": "The models, datasets, Spaces, and papers in the collection.",+ "lastUpdated": "Time at which the collection was last updated.",+ "private": "Whether the collection is private.",+ "upvotes": "Number of upvotes on the collection.",+ "theme": "Display color theme of the collection.",+ "gating": "Access-gating status applied to the collection's items.",+ },+ },+ "likes": {+ "description": "A repository liked by the connected user. Empty when the namespace is an organization.",+ "docs_url": "https://huggingface.co/docs/hub/api",+ "columns": {+ "repo_type": "Kind of liked repository (model, dataset, or space).",+ "repo_name": "Liked repository identifier in `namespace/name` form.",+ "repo": "The liked repository.",+ "createdAt": "Time at which the user liked the repository.",+ },+ },+ "model_tags": {+ "description": "Lookup of the tags that can appear on model repositories, grouped by tag type.",+ "docs_url": "https://huggingface.co/docs/hub/api",+ "columns": {+ "id": "Tag string as it appears in a model's `tags`.",+ "label": "Human-readable label of the tag.",+ "type": "Tag type (e.g. pipeline_tag, library, language, license).",+ "subType": "Optional subdivision of the tag type.",+ },+ },+ "dataset_tags": {+ "description": "Lookup of the tags that can appear on dataset repositories, grouped by tag type.",+ "docs_url": "https://huggingface.co/docs/hub/api",+ "columns": {+ "id": "Tag string as it appears in a dataset's `tags`.",+ "label": "Human-readable label of the tag.",+ "type": "Tag type (e.g. task_categories, modality, format, license).",+ "subType": "Optional subdivision of the tag type.",+ },+ },}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.pyindex ec040cfbe231..2421acb0bdb7 100644--- 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@@ -1,36 +1,47 @@import dataclasses+from collections.abc import Callable, Iteratorfrom typing import Any, Optionalfrom requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (- RESTAPIConfig,rest_api_resource,+ rest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (HeaderLinkPaginator,+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.hugging_face.settings import (HUGGING_FACE_ENDPOINTS,+ REPO_KINDS,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+# The Hub answers 403 with this body for a repo whose owner turned discussions off.+DISCUSSIONS_DISABLED_ERROR = "Discussions are disabled for this repo"[email protected](frozen=True)class HuggingFaceResumeConfig:# URL of the page to resume from. We checkpoint the *next* page's self-contained Link-header URL# after a page is yielded, so a resumed run continues from where it left off (already-yielded# pages are persisted before the checkpoint; the delta merge dedupes on the primary key).- resume_url: str+ resume_url: Optional[str] = None+ # The rest_source fan-out state for discussions: child paths already synced plus the one in progress.+ fanout_state: Optional[dict[str, Any]] = Noneclass HuggingFaceLinkPaginator(HeaderLinkPaginator):@@ -48,6 +59,29 @@ class HuggingFaceLinkPaginator(HeaderLinkPaginator):super().update_state(response, data)+class HuggingFaceDiscussionsPaginator(PageNumberPaginator):+ """Pages a repo's discussions with ``?p=``, stopping once ``start + len(page)`` reaches ``count``.++ Stopping on the reported total saves the trailing empty-page request, which the fan-out would+ otherwise pay once per repo.+ """++ def __init__(self) -> None:+ super().__init__(base_page=0, page_param="p")++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page or not data:+ return+ try:+ body = response.json()+ except ValueError:+ return+ start, count = body.get("start"), body.get("count")+ if isinstance(start, int) and isinstance(count, int) and start + len(data) >= count:+ self._has_next_page = False++def hugging_face_source(api_token: str,endpoint: str,@@ -58,60 +92,191 @@ def hugging_face_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = HUGGING_FACE_ENDPOINTS[endpoint]- params = _build_initial_params(config, author)-- rest_config: RESTAPIConfig = {- "client": {- "base_url": HUGGING_FACE_BASE_URL,- # Auth (Bearer) is supplied via the framework auth config so its value is redacted from- # logs and raised errors; only the non-secret Accept header is set here.- "headers": {"Accept": "application/json"},- "auth": {"type": "bearer", "token": api_token},- "paginator": HuggingFaceLinkPaginator(),- },- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": params,- },- }- ],+ client: ClientConfig = {+ "base_url": HUGGING_FACE_BASE_URL,+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted from+ # logs and raised errors; only the non-secret Accept header is set here.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_token},+ "paginator": HuggingFaceLinkPaginator(),}- 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.resume_url}+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Persist only when a next page remains; save AFTER a page is yielded so a resumed run picks- # up at the next self-contained Link-header URL.- if state and state.get("next_url"):- resumable_source_manager.save_state(HuggingFaceResumeConfig(resume_url=state["next_url"]))+ if config.kind == "tags":+ resource = _tags_resource(client, config, team_id, job_id)+ elif config.kind == "discussions":- resource = rest_api_resource(- rest_config,- team_id,- job_id,- db_incremental_field_last_value,- resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,- )+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(HuggingFaceResumeConfig(fanout_state=state))++ resource = _discussions_resource(+ client,+ config,+ author,+ team_id,+ job_id,+ resume_hook=save_fanout_checkpoint,+ initial_state=resume.fanout_state if resume else None,+ )+ else:++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a resumed run picks+ # up at the next self-contained Link-header URL.+ if state and state.get("next_url"):+ resumable_source_manager.save_state(HuggingFaceResumeConfig(resume_url=state["next_url"]))++ resource = _list_resource(+ client,+ config,+ author,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_state={"next_url": resume.resume_url} if resume and resume.resume_url else None,+ )++ partitioning: dict[str, Any] = {}+ if config.partition_key:+ partitioning = {+ "partition_count": 1,+ "partition_size": 1,+ "partition_mode": "datetime",+ "partition_format": "month",+ "partition_keys": [config.partition_key],+ }return SourceResponse(name=endpoint,items=lambda: resource,primary_keys=config.primary_keys,- partition_count=1,- partition_size=1,- partition_mode="datetime",- partition_format="month",- partition_keys=[config.partition_key],column_hints=resource.column_hints,+ # The tag lookups are one request with no cursor to checkpoint.+ supports_resume=config.kind != "tags",+ **partitioning,+ )+++def _list_resource(+ client: ClientConfig,+ config: HuggingFaceEndpointConfig,+ author: str,+ team_id: int,+ job_id: str,+ db_incremental_field_last_value: Optional[Any],+ resume_hook: Callable[[Optional[dict[str, Any]]], None],+ initial_state: Optional[dict[str, Any]],+) -> Resource:+ endpoint: Endpoint = {+ "path": config.path.replace("{author}", author),+ "params": _build_initial_params(config, author),+ }+ if not config.stop_on_empty_page:+ endpoint["paginator"] = HeaderLinkPaginator()+ if config.ignore_not_found:+ endpoint["response_actions"] = [{"status_code": 404, "action": "ignore"}]++ resource = rest_api_resource(+ {"client": client, "resources": [{"name": config.name, "endpoint": endpoint}]},+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=resume_hook,+ initial_paginator_state=initial_state,+ )+ if config.flatten_repo:+ resource.add_map(_flatten_repo)+ return resource+++def _tags_resource(client: ClientConfig, config: HuggingFaceEndpointConfig, team_id: int, job_id: str) -> Resource:+ resource = rest_api_resource(+ {+ "client": client,+ "resources": [{"name": config.name, "endpoint": {"path": config.path, "paginator": "single_page"}}],+ },+ team_id,+ job_id,+ None,+ )+ return resource.add_map(_tag_rows)+++def _discussions_resource(+ client: ClientConfig,+ config: HuggingFaceEndpointConfig,+ author: str,+ team_id: int,+ job_id: str,+ resume_hook: Callable[[Optional[dict[str, Any]]], None],+ initial_state: Optional[dict[str, Any]],+) -> Resource:+ # One parent stream over every repo kind keeps the fan-out a single dependent resource, so the+ # framework's per-parent resume covers models, datasets and Spaces together.+ parent: EndpointResource = {+ "name": "repos",+ "endpoint": {"path": "/api/models"},+ "data_iterator": lambda: _repo_pages(client, author, team_id, job_id),+ }+ child: EndpointResource = {+ "name": config.name,+ "endpoint": {+ "path": config.path,+ "params": {+ "repo_kind": {"type": "resolve", "resource": "repos", "field": "repo_kind"},+ "repo_id": {"type": "resolve", "resource": "repos", "field": "id"},+ },+ "paginator": HuggingFaceDiscussionsPaginator(),+ "data_selector": "discussions",+ "response_actions": [+ {+ "status_code": 403,+ "json_field": "error",+ "json_values": [DISCUSSIONS_DISABLED_ERROR],+ "action": "ignore",+ },+ # A repo deleted between the listing and its discussions fetch.+ {"status_code": 404, "action": "ignore"},+ ],+ },+ }+ resources = rest_api_resources(+ {"client": client, "resources": [parent, child]},+ team_id,+ job_id,+ None,+ resume_hook=resume_hook,+ initial_paginator_state=initial_state,)+ resource = next(r for r in resources if r.name == config.name)+ return resource.add_map(_flatten_repo)+++def _repo_pages(client: ClientConfig, author: str, team_id: int, job_id: str) -> Iterator[list[dict[str, Any]]]:+ for kind in REPO_KINDS:+ repo_config = HUGGING_FACE_ENDPOINTS[kind]+ # The fan-out only needs repo ids, so skip the heavier `full` payload.+ params = {key: value for key, value in _build_initial_params(repo_config, author).items() if key != "full"}+ resource = rest_api_resource(+ {"client": client, "resources": [{"name": kind, "endpoint": {"path": repo_config.path, "params": params}}]},+ team_id,+ job_id,+ None,+ )+ for page in resource:+ yield [{"repo_kind": kind, "id": row["id"]} for row in page]+++def _flatten_repo(row: dict[str, Any]) -> dict[str, Any]:+ return {**row, "repo_type": row["repo"]["type"], "repo_name": row["repo"]["name"]}+++def _tag_rows(tags_by_type: dict[str, Any]) -> list[dict[str, Any]]:+ # Each tag already carries its `type`, so flattening the per-type groups loses nothing.+ return [tag for tags in tags_by_type.values() for tag in tags]def validate_credentials(api_token: str) -> bool:@@ -124,10 +289,8 @@ def validate_credentials(api_token: str) -> bool:def _build_initial_params(config: HuggingFaceEndpointConfig, author: str) -> dict[str, Any]:- # 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"+ # The Hub has no server-side timestamp range filter, so these endpoints are full refresh only.+ params: dict[str, Any] = dict(config.params)+ if config.author_param:+ params[config.author_param] = authorreturn paramsdiff --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.pyindex 34cb6d7c1690..8e8cab20338d 100644--- 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@@ -1,28 +1,97 @@from dataclasses import dataclass, field+from typing import Any, Literalfrom products.warehouse_sources.backend.types import IncrementalField+# The Hub caps list endpoints at 1000 rows per page; larger pages don't return more.+PAGE_SIZE = 1000-@dataclass+# Sort repo lists ascending by createdAt (immutable), so new repos append to the end and don't shift+# pages we've already walked mid-sync. `full=true` returns the richer object (e.g. pipeline_tag,+# library_name on models); harmless on endpoints that don't add fields.+REPO_LIST_PARAMS: dict[str, Any] = {"sort": "createdAt", "direction": 1, "limit": PAGE_SIZE, "full": "true"}++REPO_KINDS = ("models", "datasets", "spaces")+++@dataclass(frozen=True)class HuggingFaceEndpointConfig:name: strpath: str- # createdAt is immutable, so it's a stable partition key (unlike lastModified). Every Hub- # repo object exposes it.- partition_key: str = "createdAt"+ # createdAt is immutable, so it's a stable partition key (unlike lastModified). None for+ # endpoints whose rows carry no creation time.+ partition_key: str | None = "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+ # Query param that scopes the endpoint to the connected namespace. None when the namespace sits+ # in the path or the endpoint is Hub-wide.+ author_param: str | None = "author"+ params: dict[str, Any] = field(default_factory=lambda: dict(REPO_LIST_PARAMS))+ # "list" pages a list endpoint, "tags" flattens a tags-by-type lookup, "discussions" fans out+ # over every repo of the namespace.+ kind: Literal["list", "tags", "discussions"] = "list"+ # Endpoints that filter rows after paging (likes, collections) can return a short or empty page+ # while a next link remains, so they must follow the Link header to its end.+ stop_on_empty_page: bool = True+ # Lift the nested `repo: {name, type}` to top-level columns so they can form the primary key.+ flatten_repo: bool = False+ # Treat a 404 as an empty table rather than a failed sync.+ ignore_not_found: bool = False-# 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"),+ "discussions": HuggingFaceEndpointConfig(+ name="discussions",+ path="/api/{repo_kind}/{repo_id}/discussions",+ # `num` is only unique within a repo.+ primary_keys=["repo_type", "repo_name", "num"],+ # The namespace scopes the repo listing the fan-out walks; on this endpoint `author` would+ # filter by discussion author instead.+ author_param=None,+ params={},+ kind="discussions",+ flatten_repo=True,+ ),+ "collections": HuggingFaceEndpointConfig(+ name="collections",+ path="/api/collections",+ partition_key=None,+ primary_keys=["slug"],+ author_param="owner",+ params={"sort": "lastModified", "limit": 100},+ stop_on_empty_page=False,+ ),+ "likes": HuggingFaceEndpointConfig(+ name="likes",+ path="/api/users/{author}/likes",+ primary_keys=["repo_type", "repo_name"],+ author_param=None,+ params={"limit": PAGE_SIZE},+ stop_on_empty_page=False,+ flatten_repo=True,+ # Likes only exist for users, so an organization namespace answers 404.+ ignore_not_found=True,+ ),+ "model_tags": HuggingFaceEndpointConfig(+ name="model_tags",+ path="/api/models-tags-by-type",+ partition_key=None,+ primary_keys=["type", "id"],+ author_param=None,+ params={},+ kind="tags",+ ),+ "dataset_tags": HuggingFaceEndpointConfig(+ name="dataset_tags",+ path="/api/datasets-tags-by-type",+ partition_key=None,+ primary_keys=["type", "id"],+ author_param=None,+ params={},+ kind="tags",+ ),}ENDPOINTS = tuple(HUGGING_FACE_ENDPOINTS.keys())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.pyindex 0d2ff1fa9624..bbee5e888797 100644--- 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@@ -62,6 +62,29 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,return snapshots+def _route(session: mock.MagicMock, routes: dict[tuple[str, int | None], Response]) -> list[tuple[str, Any]]:+ """Wire a mock session that answers by URL and ``p`` page param; return the requests sent, in order."""+ session.headers = {}+ sent: list[tuple[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ prepared = mock.MagicMock()+ prepared.key = (request.url, (request.params or {}).get("p"))+ return prepared++ def _send(prepared: Any, **_kwargs: Any) -> Response:+ sent.append(prepared.key)+ return routes[prepared.key]++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = _send+ return sent+++def _discussion(repo: str, repo_type: str, num: int) -> dict[str, Any]:+ return {"num": num, "repo": {"name": repo, "type": repo_type}, "createdAt": "2024-01-01T00:00:00.000Z"}++def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]@@ -76,10 +99,12 @@ class TestBuildInitialParams:assert params["limit"] == 1000assert params["full"] == "true"- @parameterized.expand([("models",), ("datasets",), ("spaces",)])- def test_every_endpoint_is_scoped_to_author(self, endpoint: str) -> None:+ @parameterized.expand(+ [("models", "author"), ("datasets", "author"), ("spaces", "author"), ("collections", "owner")]+ )+ def test_every_endpoint_is_scoped_to_author(self, endpoint: str, param: str) -> None:params = _build_initial_params(HUGGING_FACE_ENDPOINTS[endpoint], author="acme")- assert params["author"] == "acme"+ assert params[param] == "acme"class TestPagination:@@ -168,6 +193,154 @@ class TestPagination:assert session.send.call_count == 1+class TestLikes:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_next_link_past_empty_page_and_flattens_repo(self, MockSession) -> None:+ # The Hub filters likes after paging, so an empty page can still carry a next link.+ session = MockSession.return_value+ page2 = "https://huggingface.co/api/users/acme/likes?cursor=2"+ page3 = "https://huggingface.co/api/users/acme/likes?cursor=3"+ snapshots = _wire(+ session,+ [+ _response([], next_url=page2),+ _response(+ [{"createdAt": "2024-01-01T00:00:00.000Z", "repo": {"name": "x/y", "type": "model"}}],+ next_url=page3,+ ),+ _response([{"createdAt": "2024-01-02T00:00:00.000Z", "repo": {"name": "x/y", "type": "dataset"}}]),+ ],+ )++ rows = _rows(+ hugging_face_source(+ "hf_token", "likes", "acme", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ )++ assert snapshots[0]["url"] == f"{HUGGING_FACE_BASE_URL}/api/users/acme/likes"+ assert [(r["repo_type"], r["repo_name"]) for r in rows] == [("model", "x/y"), ("dataset", "x/y")]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_organization_namespace_syncs_no_rows(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"error": "This user does not exist"}, status=404)])++ rows = _rows(+ hugging_face_source(+ "hf_token", "likes", "acme", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ )++ assert rows == []+++class TestTags:+ @parameterized.expand([("model_tags", "/api/models-tags-by-type"), ("dataset_tags", "/api/datasets-tags-by-type")])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_flattens_tags_grouped_by_type(self, endpoint: str, path: str, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response(+ {+ "library": [{"id": "pytorch", "label": "PyTorch", "type": "library"}],+ "license": [+ {"id": "license:mit", "label": "mit", "type": "license"},+ {"id": "license:apache-2.0", "label": "apache-2.0", "type": "license"},+ ],+ }+ )+ ],+ )++ rows = _rows(+ hugging_face_source(+ "hf_token", endpoint, "acme", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ )++ assert snapshots[0]["url"] == f"{HUGGING_FACE_BASE_URL}{path}"+ assert [(r["type"], r["id"]) for r in rows] == [+ ("library", "pytorch"),+ ("license", "license:mit"),+ ("license", "license:apache-2.0"),+ ]+ assert session.send.call_count == 1+++class TestDiscussions:+ def _routes(self) -> dict[tuple[str, int | None], Response]:+ base = HUGGING_FACE_BASE_URL+ return {+ (f"{base}/api/models", None): _response([{"id": "acme/m1"}, {"id": "acme/m2"}]),+ (f"{base}/api/datasets", None): _response([{"id": "acme/d1"}]),+ (f"{base}/api/spaces", None): _response([]),+ (f"{base}/api/models/acme/m1/discussions", 0): _response(+ {+ "discussions": [_discussion("acme/m1", "model", 3), _discussion("acme/m1", "model", 2)],+ "count": 3,+ "start": 0,+ }+ ),+ (f"{base}/api/models/acme/m1/discussions", 1): _response(+ {"discussions": [_discussion("acme/m1", "model", 1)], "count": 3, "start": 2}+ ),+ (f"{base}/api/models/acme/m2/discussions", 0): _response(+ {"error": "Discussions are disabled for this repo"}, status=403+ ),+ (f"{base}/api/datasets/acme/d1/discussions", 0): _response(+ {"discussions": [_discussion("acme/d1", "dataset", 1)], "count": 1, "start": 0}+ ),+ }++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_every_repo_kind(self, MockSession) -> None:+ session = MockSession.return_value+ sent = _route(session, self._routes())++ rows = _rows(+ hugging_face_source(+ "hf_token", "discussions", "acme", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ )++ assert [(r["repo_type"], r["repo_name"], r["num"]) for r in rows] == [+ ("model", "acme/m1", 3),+ ("model", "acme/m1", 2),+ ("model", "acme/m1", 1),+ ("dataset", "acme/d1", 1),+ ]+ # Pagination stops at the reported count, so no repo pays a trailing empty-page request.+ assert (f"{HUGGING_FACE_BASE_URL}/api/models/acme/m1/discussions", 2) not in sent+ assert (f"{HUGGING_FACE_BASE_URL}/api/datasets/acme/d1/discussions", 1) not in sent++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_skips_repos_already_synced(self, MockSession) -> None:+ session = MockSession.return_value+ sent = _route(session, self._routes())+ manager = _make_manager(+ HuggingFaceResumeConfig(+ fanout_state={"completed": ["/api/models/acme/m1/discussions"], "current": None, "child_state": None}+ )+ )++ rows = _rows(+ hugging_face_source(+ "hf_token", "discussions", "acme", team_id=1, job_id="j", resumable_source_manager=manager+ )+ )++ assert [(r["repo_name"], r["num"]) for r in rows] == [("acme/d1", 1)]+ assert not any(url.endswith("/acme/m1/discussions") for url, _ in sent)+ assert manager.save_state.call_args.args[0].fanout_state["completed"] == [+ "/api/datasets/acme/d1/discussions",+ "/api/models/acme/m1/discussions",+ "/api/models/acme/m2/discussions",+ ]++class TestRetries:@mock.patch(TENACITY_SLEEP_PATCH)@mock.patch(CLIENT_SESSION_PATCH)