Skip to content

Add async metadata calls to the Hugging Face hook - #77089

Open
Anurag-S1ngh wants to merge 13 commits into
apache:mainfrom
Anurag-S1ngh:fix/76470-hf-async-metadata
Open

Anurag-S1ngh wants to merge 13 commits into
apache:mainfrom
Anurag-S1ngh:fix/76470-hf-async-metadata

Conversation

@Anurag-S1ngh

Copy link
Copy Markdown
Contributor

Summary

Adds native async variants of the Hub metadata calls to the Hugging Face hook, so they can be used from async tasks and triggers without blocking the event loop.

Changes

  • New async def aget_dataset_info() and async def afind_commit_by_marker() mirroring the sync methods, returning the same types (DatasetInfo, GitCommitInfo)
  • Token resolution for async contexts via get_async_connection from common.compat; ambient fallback and explicit-connection error semantics match get_token()
  • Shared _marker_matches() helper used by both sync and async find_commit_by_marker()
  • Only Hub REST calls are used (dataset_info, refs, commits); load_dataset/push_to_hub stay sync

Testing

  • uv run --project providers/huggingface pytest providers/huggingface/tests/unit/huggingface/hooks/test_huggingface.py -q (23 passed)
  • prek run ruff --files ... and prek run ruff-format --files ... pass

Closes #76470

@kaxil

kaxil commented Nov 14, 2026

Copy link
Copy Markdown
Member

Please upload demo video/gif/screenshots

@Anurag-S1ngh

Copy link
Copy Markdown
Contributor Author

Test suite:
hf-async-checks

@kaxil

kaxil commented Nov 15, 2026

Copy link
Copy Markdown
Member

A screenshot of the unit tests isn't a demo. Every new async test patches _aget, so nothing in this PR has made a real request to the Hub, and we still haven't seen aget_dataset_info or afind_commit_by_marker run from a trigger or an async task. Has this been run against a real dataset?

@Anurag-S1ngh

Copy link
Copy Markdown
Contributor Author

Ran both calls against a dataset
airflow-dag-run
airflow-report-log
airflow-trigger-xcom

airflow-trigger-log

@dabla dabla left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed

  • Demo asked by @kaxil ("Has this been run against a real dataset?"): the author's screenshots of 2026-11-16 show a Dag run where aget_dataset_info and afind_commit_by_marker return real data for rajpurkar/squad, from an async @task and from a trigger (HubMetadataSensor). I compared the logged values with the public Hub API and they match (commit 7b6d24c4…, "Update dataset card (#8)"). Happy path only: no pull-request refs, no missing repo or revision, no private dataset with a token.
  • get_async_session missing on huggingface-hub 0.x (@its-amann): fixed by the floor bump in 49a540b834. The thread has no reply from the author and is still unresolved on GitHub; see [1] for the cost of that fix.

Open

  • @kaxil's second point, that every new async test patches _aget, still holds on this head; [3] suggests how to close it.
  • [1] the hub floor conflicts with transformers 4.x (warning).
  • [2] _marker_matches no longer honours a subclass override of _commit_is_complete (nit).
  • Out of scope: I did not run the test suite locally; CI on this head is green (64 passed, 29 skipped).

Reviewed at 49a540b834, diff-based. The async methods were compared call by call with HfApi.dataset_info, list_repo_refs and list_repo_commits in huggingface-hub 2.4.0 and 1.0.0: URLs, revision quoting, the include_prs parameter, the GitCommitInfo fields and the token semantics (None ambient, False disabled) all match, and reading only the first commits page is correct since only the newest commit is used. The status codes and error headers in [3] were probed on the public Hub. get_async_connection(..., hook=self) is the right way to resolve the token on an event loop.

Comment thread providers/huggingface/pyproject.toml Resolved
calls.append((url, headers))
return SimpleNamespace(json=lambda: {"id": "org/data", "private": False})

mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] A way to close the test gap @kaxil raised, without the network.

Mocking one level lower than _aget runs the request code, hf_raise_for_status, the Authorization header and params={"include_prs": "1"}: patch get_async_session to return an AsyncClient with a MockTransport whose handler answers what the Hub really sends (probed on the public API):

Request Real Hub answer
GET /api/datasets/{repo}/commits/{missing-rev} 404, X-Error-Code: RevisionNotFound
GET /api/datasets/{missing-repo}/commits/main or /refs 401, no X-Error-Code
GET /api/datasets/{repo}/refs?include_prs=1 {"pullRequests": [{"name", "ref", "targetCommit"}], ...}

The handler can then assert the URL, the query string and the token header. One caveat: huggingface-hub 1.x is built on httpx and 2.x on httpx2, so the client and transport must come from the library the installed hub uses, otherwise hf_raise_for_status does not catch the status error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added HTTP-level tests that patch get_async_session with a MockTransport client, so the request code, token header, include_prs and the Hub error mapping run for real. The client and transport come from the httpx module the installed hub uses, so they match 1.x and 2.x. This also covers the point about every async test patching _aget.

get_async_session and the top-level DatasetInfo export only exist in huggingface-hub 1.x, so importing them unconditionally broke the sync hook on the declared floor. Import DatasetInfo from hf_api, guard the async client behind a feature check, and keep the floor at 0.24 so the provider still installs next to transformers 4.x.
The shared marker helper called HuggingFaceHook._commit_is_complete directly, so a subclass override was silently bypassed. Make the helper a classmethod that dispatches through cls.
Patch get_async_session with a MockTransport client instead of _aget, so the tests run the request code, the token header, the include_prs query and the Hub error mapping. This closes the gap where every async test replaced the HTTP call itself.
@Anurag-S1ngh

Copy link
Copy Markdown
Contributor Author

Added tests that exercise the HTTP layer: get_async_session is patched with a MockTransport client, so the async methods build the real URL, send the token header and query string, and handle the Hub 401 and 404 responses. The earlier integration screenshots are unchanged.

get_async_session = None # type: ignore[assignment]

from airflow.exceptions import AirflowNotFoundException, AirflowOptionalProviderFeatureException
from airflow.providers.common.compat.connection import get_async_connection

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

airflow.providers.common.compat.connection doesn't exist in common-compat 1.8.0, and get_async_connection only takes hook= from 1.17.0, but the provider still declares apache-airflow-providers-common-compat>=1.8.0. Anyone on an older compat gets a ModuleNotFoundError importing the hook, so the sync methods and the operators break too. Can the floor go to >=1.23.0? That's the release where get_async_connection stops calling the base aget_connection on Airflow < 3.3.2, which raises DeadlockImminentError when another async call is in flight on the same loop, the normal case on a triggerer running other triggers.



@pytest.mark.asyncio
async def test_aget_token_falls_back_to_ambient_for_default_connection(monkeypatch, mocker):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With None as the conn id, _aget_token returns before any lookup, so this never reads the env var it sets. No async test reaches the ambient fallback or password or False. I changed or False to or None and every test still passed, yet with that change an empty named connection would send the worker's HF_TOKEN. Could you add an async version of test_empty_named_connection_disables_ambient_token_fallback that goes through aget_dataset_info and checks the request has no authorization header?

return response

async def aget_dataset_info(self, repo_id: str, revision: str | None = None) -> Any:
"""Async variant of :meth:`get_dataset_info`; reads the Hub over HTTP."""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can the docstrings here and on afind_commit_by_marker say they need huggingface-hub 1.0+ and raise AirflowOptionalProviderFeatureException otherwise? The provider deliberately still allows 0.24, so someone pinned there by transformers 4.x only finds out when the task runs.


async def aget_dataset_info(self, repo_id: str, revision: str | None = None) -> Any:
"""Async variant of :meth:`get_dataset_info`; reads the Hub over HTTP."""
path = f"{constants.ENDPOINT}/api/datasets/{repo_id}"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sync methods go through HfApi, which runs validate_repo_id on dataset_info, list_repo_refs and list_repo_commits. Here repo_id goes straight into the URL, so org/data/extra raises HFValidationError from the sync call but becomes a request to a different path from the async one. Call validate_repo_id(repo_id) at the top of both async methods?

headers=headers,
params={"include_prs": "1"},
)
except RepositoryNotFoundError:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test reaches this branch: catching the wrong exception here, or dropping the seen dedup below, leaves the suite green. A MockTransport case with include_pull_requests=True and a 401 on /refs would cover the first, and a revision that is also a listed PR ref the second.

return {"pullRequests": [{"name": "7", "ref": "refs/pr/7", "targetCommit": "deadbeef"}]}
if url.endswith("/commits/main"):
return []
if url.endswith("refs%2Fpr%2F7") or url.endswith("/commits/refs/pr/7"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This accepts both the quoted and the unquoted ref, so it can't catch a quoting regression. Now that the MockTransport tests below pin the real paths, can this and the other _aget-patched tests they repeat go?

@Anurag-S1ngh

Copy link
Copy Markdown
Contributor Author

All six points are addressed. The compat floor is 1.23.0, both async methods call validate_repo_id and document the hub 1.0 requirement, the empty named connection case now goes through aget_dataset_info and asserts the request has no authorization header, and the MockTransport tests cover the 401 on /refs and the ref dedup. The _aget tests those replace are removed. Unit suite and ruff pass.

@pytest.mark.asyncio
async def test_aget_token_falls_back_to_ambient_for_default_connection(monkeypatch, mocker):
monkeypatch.setenv("AIRFLOW_CONN_HUGGINGFACE_DEFAULT", '{"conn_type":"huggingface"}')
hook = HuggingFaceHook(None)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With HuggingFaceHook(None), _aget_token returns on its first line, so this still never reaches the ambient fallback (and with the empty default connection it sets, HuggingFaceHook() would get False, not None). Removing the if self._allow_ambient_fallback: return None branch leaves the whole suite green, though that's the path every HuggingFaceHook() without a huggingface_default connection takes. Can this delete the env var instead, use HuggingFaceHook() and assert None?

@dabla dabla left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed

  • Hub floor vs transformers 4.x (my comment, 1bf207f224): the floor is back at huggingface-hub>=0.24, get_async_session is an optional import and both async methods raise AirflowOptionalProviderFeatureException without it. I checked the remaining module-level imports (DatasetInfo and GitCommitInfo from hf_api, validate_repo_id, parse_datetime, build_hf_headers, hf_raise_for_status) against huggingface-hub 0.25.0, the lowest version datasets>=5.0.0 allows: all exist.
  • _marker_matches subclass dispatch (my comment, fa53cb4105): now a classmethod calling cls._commit_is_complete, with a subclass test.
  • Tests that never reach the HTTP layer (@kaxil's point and my suggestion, ea23f1dbfa, 3468bf2d40, 71fae6e0d3): the tests patch get_async_session with a MockTransport client taken from the HTTP library the installed hub uses, and assert path, query string and token header. The _aget-patched tests they repeat are removed.
  • @kaxil's review of 2026-11-24, each point checked in the code of this head:
    • docstrings state the hub 1.0 requirement and the exception (c82c553077);
    • validate_repo_id(repo_id) is the first statement of both async methods, with a test that no session is created (c18ec49031);
    • the empty named connection goes through aget_dataset_info and the request has no authorization header (ec5a849bad);
    • a 401 on /refs and a revision that is also a listed PR ref are covered (3468bf2d40);
    • the common-compat floor is 1.23.0 (1b9ad9063c), see [1] for its side effect.

Open

  • [1] CI is red on this head because of the common-compat floor bump; a maintainer has to set the allow provider dependency bump label, and the test jobs have not run on the last six commits.
  • @kaxil's comment of 2026-11-25 on test_aget_token_falls_back_to_ambient_for_default_connection came after the last commit and still holds: with HuggingFaceHook(None) the test returns on the first line of _aget_token and never reaches the ambient fallback branch.
  • Out of scope: I could not run the test file locally, so with CI skipped nobody has seen the tests of this head pass.

Reviewed at 71fae6e0d3, diff-based, whole change read again and not only the delta. The async request code is unchanged since the first round, where it was compared call by call with HfApi in huggingface-hub 2.4.0 and 1.0.0; the additions since (validate_repo_id, the optional import, the classmethod) match what the sync path does.

dependencies = [
"apache-airflow>=3.0,<4",
"apache-airflow-providers-common-compat>=1.8.0",
"apache-airflow-providers-common-compat>=1.23.0",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[warning] This floor bump fails "Build info", so CI never ran on the last six commits.

The selective check stops with:

Provider dependency version bumps detected that should only be performed by Release Managers!
providers/huggingface/pyproject.toml: apache-airflow-providers-common-compat >= version changed from 1.8.0 to 1.23.0
If this change is intentional and approved, please set the label on the PR: 'allow provider dependency bump'

Because that job fails first, every test job is skipped on this head: the provider tests last ran on ea23f1dbfa, before the floor change, the validate_repo_id calls, the new MockTransport cases and the removal of the _aget-patched tests.

The bump itself is right for the reasons @kaxil gave (the connection module and hook= do not exist in 1.8.0), and 1.23.0 is released, so no # use next version marker is needed. It needs a maintainer to set the allow provider dependency bump label and a CI re-run before merge (contributing docs).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add native async variants of the metadata call for HF Provider

4 participants