Repository navigation
Add async metadata calls to the Hugging Face hook - #77089
Anurag-S1ngh wants to merge 13 commits into
Conversation
|
Please upload demo video/gif/screenshots |
|
A screenshot of the unit tests isn't a demo. Every new async test patches |
dabla
left a comment
There was a problem hiding this comment.
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_infoandafind_commit_by_markerreturn real data forrajpurkar/squad, from an async@taskand from a trigger (HubMetadataSensor). I compared the logged values with the public Hub API and they match (commit7b6d24c4…, "Update dataset card (#8)"). Happy path only: no pull-request refs, no missing repo or revision, no private dataset with a token. get_async_sessionmissing on huggingface-hub 0.x (@its-amann): fixed by the floor bump in49a540b834. 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_matchesno 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.
| calls.append((url, headers)) | ||
| return SimpleNamespace(json=lambda: {"id": "org/data", "private": False}) | ||
|
|
||
| mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
|
Added tests that exercise the HTTP layer: |
| get_async_session = None # type: ignore[assignment] | ||
|
|
||
| from airflow.exceptions import AirflowNotFoundException, AirflowOptionalProviderFeatureException | ||
| from airflow.providers.common.compat.connection import get_async_connection |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.""" |
There was a problem hiding this comment.
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}" |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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"): |
There was a problem hiding this comment.
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?
|
All six points are addressed. The compat floor is 1.23.0, both async methods call |
| @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) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Addressed
- Hub floor vs
transformers4.x (my comment,1bf207f224): the floor is back athuggingface-hub>=0.24,get_async_sessionis an optional import and both async methods raiseAirflowOptionalProviderFeatureExceptionwithout it. I checked the remaining module-level imports (DatasetInfoandGitCommitInfofromhf_api,validate_repo_id,parse_datetime,build_hf_headers,hf_raise_for_status) against huggingface-hub 0.25.0, the lowest versiondatasets>=5.0.0allows: all exist. _marker_matchessubclass dispatch (my comment,fa53cb4105): now a classmethod callingcls._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 patchget_async_sessionwith aMockTransportclient 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_infoand the request has noauthorizationheader (ec5a849bad); - a 401 on
/refsand arevisionthat is also a listed PR ref are covered (3468bf2d40); - the common-compat floor is 1.23.0 (
1b9ad9063c), see [1] for its side effect.
- docstrings state the hub 1.0 requirement and the exception (
Open
- [1] CI is red on this head because of the common-compat floor bump; a maintainer has to set the
allow provider dependency bumplabel, 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_connectioncame after the last commit and still holds: withHuggingFaceHook(None)the test returns on the first line of_aget_tokenand 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", |
There was a problem hiding this comment.
[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).





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
async def aget_dataset_info()andasync def afind_commit_by_marker()mirroring the sync methods, returning the same types (DatasetInfo,GitCommitInfo)get_async_connectionfrom common.compat; ambient fallback and explicit-connection error semantics matchget_token()_marker_matches()helper used by both sync and asyncfind_commit_by_marker()dataset_info,refs,commits);load_dataset/push_to_hubstay syncTesting
uv run --project providers/huggingface pytest providers/huggingface/tests/unit/huggingface/hooks/test_huggingface.py -q(23 passed)prek run ruff --files ...andprek run ruff-format --files ...passCloses #76470