kaxil commented on code in PR #77089:
URL: https://github.com/apache/airflow/pull/77089#discussion_r4681208662


##########
providers/huggingface/src/airflow/providers/huggingface/hooks/huggingface.py:
##########
@@ -97,12 +120,113 @@ def load_dataset(self, path: str, **kwargs: Any) -> Any:
     def get_dataset_info(self, repo_id: str, revision: str | None = None) -> 
Any:
         return self.get_conn().dataset_info(repo_id, revision=revision)
 
+    async def _aget_token(self) -> str | bool | None:
+        """Async token resolution mirroring get_token without blocking the 
event loop."""
+        if not self.huggingface_conn_id:
+            return None
+        try:
+            connection = await get_async_connection(self.huggingface_conn_id, 
hook=self)
+        except AirflowNotFoundException:
+            if self._allow_ambient_fallback:
+                return None
+            raise
+        return connection.password or False
+
+    @staticmethod
+    async def _aget(client: Any, url: str, *, headers: dict[str, str], 
**kwargs: Any) -> Any:
+        """GET a Hub endpoint on an open client and raise on HTTP errors."""
+        response = await client.get(url, headers=headers, **kwargs)
+        hf_raise_for_status(response)
+        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."""

Review 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.



##########
providers/huggingface/src/airflow/providers/huggingface/hooks/huggingface.py:
##########
@@ -20,14 +20,37 @@
 
 import re
 from typing import Any
+from urllib.parse import quote
 
-from huggingface_hub import HfApi
-from huggingface_hub.utils import RepositoryNotFoundError, 
RevisionNotFoundError
+from huggingface_hub import HfApi, constants
+from huggingface_hub.hf_api import DatasetInfo, GitCommitInfo
+from huggingface_hub.utils import (
+    RepositoryNotFoundError,
+    RevisionNotFoundError,
+    build_hf_headers,
+    hf_raise_for_status,
+    parse_datetime,
+)
 
-from airflow.exceptions import AirflowNotFoundException
+try:
+    from huggingface_hub.utils import get_async_session
+except ImportError:
+    get_async_session = None  # type: ignore[assignment]
+
+from airflow.exceptions import AirflowNotFoundException, 
AirflowOptionalProviderFeatureException
+from airflow.providers.common.compat.connection import get_async_connection

Review 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.



##########
providers/huggingface/tests/unit/huggingface/hooks/test_huggingface.py:
##########
@@ -172,3 +217,342 @@ def 
test_find_commit_by_marker_scans_pull_request_refs_when_requested():
     api.list_repo_refs.assert_called_once_with("org/data", 
repo_type="dataset", include_pull_requests=True)
     assert api.list_repo_commits.call_args_list[0].kwargs["revision"] == "main"
     assert api.list_repo_commits.call_args_list[1].kwargs["revision"] == 
"refs/pr/7"
+
+
+@requires_async_session
[email protected]
+async def test_aget_dataset_info_builds_url_and_returns_info(connection_env, 
mocker):
+    calls = []
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        calls.append((url, headers))
+        return SimpleNamespace(json=lambda: {"id": "org/data", "private": 
False})
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+    mocker.patch(
+        "airflow.providers.huggingface.hooks.huggingface.get_async_connection",
+        new=AsyncMock(return_value=SimpleNamespace(password="test-secret")),
+    )
+
+    hook = HuggingFaceHook("huggingface_test")
+    info = await hook.aget_dataset_info("org/data")
+
+    assert info.id == "org/data"
+    assert calls[0][0].endswith("/api/datasets/org/data")
+
+
+@requires_async_session
[email protected]
+async def test_aget_dataset_info_quotes_revision(connection_env, mocker):
+    calls = []
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        calls.append(url)
+        return SimpleNamespace(json=lambda: {"id": "org/data"})
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+
+    hook = HuggingFaceHook("huggingface_test")
+    await hook.aget_dataset_info("org/data", revision="release 1")
+
+    assert calls[0].endswith("/api/datasets/org/data/revision/release%201")
+
+
[email protected]
+async def 
test_aget_token_falls_back_to_ambient_for_default_connection(monkeypatch, 
mocker):

Review 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?



##########
providers/huggingface/src/airflow/providers/huggingface/hooks/huggingface.py:
##########
@@ -97,12 +120,113 @@ def load_dataset(self, path: str, **kwargs: Any) -> Any:
     def get_dataset_info(self, repo_id: str, revision: str | None = None) -> 
Any:
         return self.get_conn().dataset_info(repo_id, revision=revision)
 
+    async def _aget_token(self) -> str | bool | None:
+        """Async token resolution mirroring get_token without blocking the 
event loop."""
+        if not self.huggingface_conn_id:
+            return None
+        try:
+            connection = await get_async_connection(self.huggingface_conn_id, 
hook=self)
+        except AirflowNotFoundException:
+            if self._allow_ambient_fallback:
+                return None
+            raise
+        return connection.password or False
+
+    @staticmethod
+    async def _aget(client: Any, url: str, *, headers: dict[str, str], 
**kwargs: Any) -> Any:
+        """GET a Hub endpoint on an open client and raise on HTTP errors."""
+        response = await client.get(url, headers=headers, **kwargs)
+        hf_raise_for_status(response)
+        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."""
+        path = f"{constants.ENDPOINT}/api/datasets/{repo_id}"
+        if revision is not None:
+            path = f"{path}/revision/{quote(revision, safe='')}"
+        headers = build_hf_headers(token=await self._aget_token())
+        async with _create_async_session() as client:
+            response = await self._aget(client, path, headers=headers)
+        return DatasetInfo(**response.json())
+
+    async def afind_commit_by_marker(
+        self,
+        repo_id: str,
+        marker: str,
+        *,
+        revision: str | None = None,
+        include_pull_requests: bool = False,
+    ) -> Any | None:
+        """Async variant of :meth:`find_commit_by_marker`; scans the latest 
commit per requested ref."""
+        headers = build_hf_headers(token=await self._aget_token())
+        revisions = [revision] if revision else ["main"]
+        async with _create_async_session() as client:
+            if include_pull_requests:
+                try:
+                    refs_response = await self._aget(
+                        client,
+                        f"{constants.ENDPOINT}/api/datasets/{repo_id}/refs",
+                        headers=headers,
+                        params={"include_prs": "1"},
+                    )
+                except RepositoryNotFoundError:

Review 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.



##########
providers/huggingface/src/airflow/providers/huggingface/hooks/huggingface.py:
##########
@@ -97,12 +120,113 @@ def load_dataset(self, path: str, **kwargs: Any) -> Any:
     def get_dataset_info(self, repo_id: str, revision: str | None = None) -> 
Any:
         return self.get_conn().dataset_info(repo_id, revision=revision)
 
+    async def _aget_token(self) -> str | bool | None:
+        """Async token resolution mirroring get_token without blocking the 
event loop."""
+        if not self.huggingface_conn_id:
+            return None
+        try:
+            connection = await get_async_connection(self.huggingface_conn_id, 
hook=self)
+        except AirflowNotFoundException:
+            if self._allow_ambient_fallback:
+                return None
+            raise
+        return connection.password or False
+
+    @staticmethod
+    async def _aget(client: Any, url: str, *, headers: dict[str, str], 
**kwargs: Any) -> Any:
+        """GET a Hub endpoint on an open client and raise on HTTP errors."""
+        response = await client.get(url, headers=headers, **kwargs)
+        hf_raise_for_status(response)
+        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."""
+        path = f"{constants.ENDPOINT}/api/datasets/{repo_id}"

Review 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?



##########
providers/huggingface/tests/unit/huggingface/hooks/test_huggingface.py:
##########
@@ -172,3 +217,342 @@ def 
test_find_commit_by_marker_scans_pull_request_refs_when_requested():
     api.list_repo_refs.assert_called_once_with("org/data", 
repo_type="dataset", include_pull_requests=True)
     assert api.list_repo_commits.call_args_list[0].kwargs["revision"] == "main"
     assert api.list_repo_commits.call_args_list[1].kwargs["revision"] == 
"refs/pr/7"
+
+
+@requires_async_session
[email protected]
+async def test_aget_dataset_info_builds_url_and_returns_info(connection_env, 
mocker):
+    calls = []
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        calls.append((url, headers))
+        return SimpleNamespace(json=lambda: {"id": "org/data", "private": 
False})
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+    mocker.patch(
+        "airflow.providers.huggingface.hooks.huggingface.get_async_connection",
+        new=AsyncMock(return_value=SimpleNamespace(password="test-secret")),
+    )
+
+    hook = HuggingFaceHook("huggingface_test")
+    info = await hook.aget_dataset_info("org/data")
+
+    assert info.id == "org/data"
+    assert calls[0][0].endswith("/api/datasets/org/data")
+
+
+@requires_async_session
[email protected]
+async def test_aget_dataset_info_quotes_revision(connection_env, mocker):
+    calls = []
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        calls.append(url)
+        return SimpleNamespace(json=lambda: {"id": "org/data"})
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+
+    hook = HuggingFaceHook("huggingface_test")
+    await hook.aget_dataset_info("org/data", revision="release 1")
+
+    assert calls[0].endswith("/api/datasets/org/data/revision/release%201")
+
+
[email protected]
+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)
+
+    assert await hook._aget_token() is None
+
+
[email protected]
+async def test_aget_token_raises_for_explicit_missing_connection():
+    with patch.object(HuggingFaceHook, "get_connection", 
side_effect=AirflowNotFoundException("missing")):
+        hook = HuggingFaceHook("explicit_bad_id")
+        with pytest.raises(AirflowNotFoundException):
+            await hook._aget_token()
+
+
+def _commit_payload(commit_id, title, message=""):
+    return {
+        "id": commit_id,
+        "authors": [{"user": "unit-test"}],
+        "date": "2026-01-01T00:00:00.000Z",
+        "title": title,
+        "message": message,
+    }
+
+
+@requires_async_session
[email protected]
+async def test_afind_commit_by_marker_matches_first_ref(connection_env, 
mocker):
+    marker = "airflow-artifact-sha256:abc:target:def"
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        assert url.endswith("/api/datasets/org/data/commits/main")
+        return SimpleNamespace(
+            json=lambda: [
+                _commit_payload("b" * 40, f"Publish [{marker}]"),
+            ]
+        )
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+    mocker.patch(
+        "airflow.providers.huggingface.hooks.huggingface.get_async_connection",
+        new=AsyncMock(return_value=SimpleNamespace(password="test-secret")),
+    )
+
+    hook = HuggingFaceHook("huggingface_test")
+    commit = await hook.afind_commit_by_marker("org/data", marker)
+
+    assert commit is not None
+    assert commit.commit_id == "b" * 40
+    assert commit.title == f"Publish [{marker}]"
+
+
+@requires_async_session
[email protected]
+async def 
test_afind_commit_by_marker_does_not_reuse_historical_commit(connection_env, 
mocker):
+    marker = "airflow-artifact-sha256:abc:target:def"
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        return SimpleNamespace(
+            json=lambda: [
+                _commit_payload("b" * 40, "Publish newer artifact"),
+                _commit_payload("a" * 40, f"Publish [{marker}]"),
+            ]
+        )
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+
+    hook = HuggingFaceHook(None)
+    assert await hook.afind_commit_by_marker("org/data", marker) is None
+
+
+@requires_async_session
[email protected]
+async def test_afind_commit_by_marker_rejects_part_commits(connection_env, 
mocker):
+    marker = "airflow-artifact-sha256:abc:target:def"
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        return SimpleNamespace(
+            json=lambda: [_commit_payload("a" * 40, f"Publish [{marker}] (part 
00001-of-00002)")]
+        )
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)
+
+    hook = HuggingFaceHook(None)
+    assert await hook.afind_commit_by_marker("org/data", marker) is None
+
+
+@requires_async_session
[email protected]
+async def test_afind_commit_by_marker_scans_pull_request_refs(connection_env, 
mocker):
+    marker = "huggingface-stream-publish:target"
+    urls = []
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        urls.append(url)
+
+        def payload():
+            if url.endswith("/refs"):
+                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"):

Review 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?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to