You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "seanmuth (via GitHub)" <gi...@apache.org> on 2026/06/09 19:03:11 UTC

[PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

seanmuth opened a new pull request, #68305:
URL: https://github.com/apache/airflow/pull/68305

   `VaultBackend.get_connection()` constructed the returned `Connection` using
   `airflow.models.connection.Connection` — the SQLAlchemy ORM model. In Airflow 3,
   instantiating this model triggers lazy mapper initialisation for the *entire*
   Airflow model registry. In `PythonVirtualenvOperator` subprocesses (and other
   isolated task contexts), `DagModel` has not been imported when the secrets
   backend is consulted, so `DagScheduleAssetNameReference` cannot resolve its
   `'DagModel'` relationship string, raising:
   
   ```
   sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize …
   Triggering mapper: 'mapped class DagScheduleAssetNameReference->dag_schedule_asset_name_reference'.
   Original exception was: … expression 'DagModel' failed to locate a name ('DagModel').
   ```
   
   Because `context.py`'s secrets-backend loop catches all exceptions at `DEBUG`
   level (without `exc_info`), this error is silently swallowed. The connection
   appears undefined even when Vault returns a valid `200` response with the
   correct data.
   
   **Fix:** switch to `airflow.providers.common.compat.sdk.Connection`, which
   resolves to the Pydantic SDK `Connection` in Airflow 3 (no SQLAlchemy mapper
   involvement) and falls back to the SQLAlchemy model in Airflow 2.  For the
   URI path, use `Connection.from_uri()` guarded by `AIRFLOW_V_3_0_PLUS` to
   handle both Airflow versions correctly.
   
   Two new regression tests verify that `get_connection()` returns an instance of
   the SDK `Connection` type rather than the SQLAlchemy ORM model.
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes — Claude Code (Sonnet 4.6)
   
   Generated-by: Claude Code (Sonnet 4.6) following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3492583406


##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -121,8 +122,10 @@ def test_get_connection(self, mock_hvac):
         }
 
         test_client = VaultBackend(**kwargs)
+        if hasattr(test_client, "_set_connection_class"):
+            test_client._set_connection_class(SdkConnection)
         connection = test_client.get_connection(conn_id="test_postgres")
-        assert connection.get_uri() == "postgresql://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"
+        assert connection.get_uri() == "postgres://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"

Review Comment:
   is it possible for a probablistic LLM to ever truly be "intentional?" lol, should be `postgresql`, idk why it did that, will revert along with the requested changes above



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3484502388


##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -759,3 +784,78 @@ def test_config_path_none_value(self, mock_hvac):
         test_client = VaultBackend(**kwargs)
         assert test_client.get_config("test") is None
         mock_hvac.Client.assert_not_called()
+
+    @mock.patch("airflow.providers.hashicorp._internal_client.vault_client.hvac")
+    @pytest.mark.skipif(
+        not hasattr(VaultBackend, "_set_connection_class"),

Review Comment:
   These gate on `hasattr(VaultBackend, "_set_connection_class")` and then call `_set_connection_class(SdkConnection)` by hand. That method only exists on 3.2+, so the tests only run against 3.2+ and never exercise 2.11/3.0/3.1, the versions where behavior actually differs. If the override is dropped per the other comment, the unit test reduces to asserting `get_conn_value` returns the URI verbatim or `json.dumps(dict)`, leaving deserialization to the base.



##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -224,32 +224,68 @@ def _get_team_or_global_secret(self, base_path: str | None, team_name: str | Non
 
         return self._get_secret_with_base(path, key)
 
-    # Make sure connection is imported this way for type checking, otherwise when importing
-    # the backend it will get a circular dependency and fail
-    if TYPE_CHECKING:
-        from airflow.models.connection import Connection
+    def get_connection(self, conn_id: str, team_name: str | None = None):
+        """
+        Return connection object with a given ``conn_id``.
+
+        Overrides the base to accept ``team_name`` on all supported Airflow versions and
+        to fall back to the compat SDK Connection when the framework-level class injection
+        (``deserialize_connection`` / ``_get_connection_class``) is not yet available.
 
-    def get_connection(self, conn_id: str, team_name: str | None = None) -> Connection | None:
+        :param conn_id: connection id
+        :param team_name: Team name associated to the task trying to access the connection (if any)
+        :return: Connection object or None
         """
-        Get connection from Vault as secret.
+        value = self.get_conn_value(conn_id=conn_id, team_name=team_name)
+        if value is None:
+            return None
+        # Prefer the base-class deserializer when available — it uses _get_connection_class()
+        # which the framework populates with the right Connection class per execution context.
+        if hasattr(self, "deserialize_connection"):

Review Comment:
   The fallback below this line never runs: `deserialize_connection` is defined on the base on every supported version (checked the 2.11.0, 3.0.0, 3.1.0 tags and main), so `hasattr(self, "deserialize_connection")` is always true and the `from_json` / `from_uri` / `Connection(uri=)` ladder is dead code. It can be removed.
   
   The bigger problem is that delegating to `self.deserialize_connection` only fixes the worker on 3.2+. On 3.0/3.1 the base `deserialize_connection` hard-imports `airflow.models.connection.Connection` (`airflow-core/src/airflow/secrets/base_secrets.py:61` at those tags), the ORM model whose mapper init is the bug. The per-process class injection (`_get_connection_class` / `_set_connection_class`) that lets the base avoid the ORM only landed in 3.2+, so as written this doesn't fix the 3.0/3.1 workers the title targets, only 3.2+.
   
   The clean shape is what Amazon (`secrets_manager.py:200`) and Google (`secret_manager.py:159`) do: override only `get_conn_value` (you already have it) and drop the `get_connection` override. The base `get_connection` forwards `team_name` to `get_conn_value` via `call_secrets_backend_method`, so the override's "accept team_name on all versions" reason isn't needed. That deletes the dead ladder and the re-implementation of `_deserialize_connection_value`, and fixes 3.2+ through the framework's injection. For 3.0/3.1 the base imports the ORM regardless of what the provider does, so a provider-only change can't avoid it there; worth either scoping the claim to 3.2+ or calling 3.0/3.1 out as a separate core limitation. (akeyless has the same hard-coded-ORM override and wants the same treatment.)



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on PR #68305:
URL: https://github.com/apache/airflow/pull/68305#issuecomment-4692346466

   ready


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3384263950


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # from_uri is available on the SDK Connection (Airflow 3.2+ / task-sdk 1.2.0+).
+            # On Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            # On Airflow 3.0/3.1 the attrs-based Connection has neither from_uri nor a uri=
+            # constructor arg; return None so the secrets-backend loop tries the next backend.
+            if hasattr(Connection, "from_uri"):
+                return Connection.from_uri(uri, conn_id=conn_id)  # type: ignore[attr-defined]
+            try:
+                return Connection(conn_id=conn_id, uri=uri)  # type: ignore[call-arg]

Review Comment:
   I don't think we need `# type: ignore[call-arg]` call here and on L256 too (# type: ignore[attr-defined])



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on PR #68305:
URL: https://github.com/apache/airflow/pull/68305#issuecomment-4810789156

   > Requesting changes to avoid accidental merge, @kaxil's suggestion is right on this one. We can merge once that's done.
   > 
   > @seanmuth pls validate if the fix works practically too, theory wise it seems perfect.
   
   On it now, last week was an on-call week for me, always causes stuff to fall of my plate.
   
   Will also add a quick confirmation that this works the way we're expecting it does 🫡 


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on PR #68305:
URL: https://github.com/apache/airflow/pull/68305#issuecomment-4663949913

   Force-pushed twice to update this branch after rebasing onto `main`. Both times the pre-push hook ran against all files that diverged between the remote and local tip (including upstream commits pulled in by the rebase), hitting pre-existing failures in unrelated files (`providers/common/ai`, etc.) — not caused by changes in this PR.
   
   ---
   Drafted-by: Claude Code (Sonnet 4.6); reviewed by @seanmuth before posting


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3404958255


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # from_uri is available on the SDK Connection (Airflow 3.2+ / task-sdk 1.2.0+).
+            # On Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            # On Airflow 3.0/3.1 the attrs-based Connection has neither from_uri nor a uri=
+            # constructor arg; return None so the secrets-backend loop tries the next backend.
+            if hasattr(Connection, "from_uri"):
+                return Connection.from_uri(uri, conn_id=conn_id)  # type: ignore[attr-defined]
+            try:
+                return Connection(conn_id=conn_id, uri=uri)  # type: ignore[call-arg]

Review Comment:
   @kaxil FYI ^^



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3483003134


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection

Review Comment:
   Thanks for the detailed review — the approach has been reworked per your suggestions.
   
   **What changed:**
   
   `get_connection()` is now replaced by a `get_conn_value()` override, which returns a plain string: the `conn_uri` value verbatim, or `json.dumps(response)` for field-based secrets. The base-class `get_connection()` then deserializes that string using `_get_connection_class()`, which the framework populates per execution context (ORM Connection on the server, SDK Connection in workers) — fixing the original mapper-init bug without regressing `airflow connections get`.
   
   **Compat shim for older Airflow (3.0/3.1/2.11):**
   
   On those versions `BaseSecretsBackend.get_connection()` predates both `team_name` support and the `deserialize_connection` / `_get_connection_class` pipeline, so `get_conn_value()` alone is not enough. A `get_connection()` override is kept for those versions: it calls `get_conn_value()` then `deserialize_connection()` when available, and falls back to the compat SDK Connection (with the same `hasattr(Connection, "from_uri")` guard) when it is not.
   
   **Tests:**
   
   `_set_connection_class()` calls are guarded with `hasattr` since the method did not exist before the shared secrets-backend was introduced. The two `isinstance(SdkConnection)` assertion tests are skipped on older Airflow where class injection is unavailable.
   
   Also noted: the `akeyless` backend has the mirror of the original bug (hard-coded ORM Connection); the same `get_conn_value()` pattern would fix it there too.
   
   ---
   Drafted-by: Claude Code (Sonnet 4.6); reviewed by @seanmuth before posting



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3383662898


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,27 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # In Airflow 3 the SDK Connection's __init__ is keyword-only and attrs-generated;
+            # uri= is not in the attrs fields so we use the classmethod directly.
+            # In Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            from airflow.providers.common.compat.version_compat import AIRFLOW_V_3_0_PLUS
 
-        return Connection(conn_id, **response)
+            if AIRFLOW_V_3_0_PLUS:
+                return Connection.from_uri(uri, conn_id=conn_id)  # type: ignore[attr-defined]

Review Comment:
   Good catch — switched to `hasattr(Connection, "from_uri")` matching the pattern in `_deserialize_connection_value` in `airflow_shared/secrets_backend/base.py`. Added a comment noting that `conn_uri`-style secrets remain broken on Airflow 3.0/3.1 (pre-existing, not introduced here).
   
   ---
   Drafted-by: Claude Code (Sonnet 4.6); reviewed by @seanmuth before posting



##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,27 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # In Airflow 3 the SDK Connection's __init__ is keyword-only and attrs-generated;
+            # uri= is not in the attrs fields so we use the classmethod directly.
+            # In Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            from airflow.providers.common.compat.version_compat import AIRFLOW_V_3_0_PLUS

Review Comment:
   Agreed — removed the `AIRFLOW_V_3_0_PLUS` import entirely by switching to `hasattr`, so there's nothing left to move.
   
   ---
   Drafted-by: Claude Code (Sonnet 4.6); reviewed by @seanmuth before posting



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3390062559


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # from_uri is available on the SDK Connection (Airflow 3.2+ / task-sdk 1.2.0+).
+            # On Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            # On Airflow 3.0/3.1 the attrs-based Connection has neither from_uri nor a uri=
+            # constructor arg; return None so the secrets-backend loop tries the next backend.
+            if hasattr(Connection, "from_uri"):
+                return Connection.from_uri(uri, conn_id=conn_id)
+            try:
+                return Connection(conn_id=conn_id, uri=uri)
+            except TypeError:
+                self.log.warning(
+                    "Cannot deserialize conn_uri for connection '%s': upgrade to Airflow 3.2+ "
+                    "or store the connection using individual fields (conn_type, host, login, "
+                    "etc.) in Vault.",
+                    conn_id,
+                )
+                return None

Review Comment:
   agreed, widened to include both



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "amoghrajesh (via GitHub)" <gi...@apache.org>.
amoghrajesh commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3576471433


##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -576,7 +583,14 @@ def test_jwt_auth_type(self, mock_hvac):
             "renewable": False,
             "lease_duration": 0,
             "data": {
-                "data": {"conn_uri": "postgresql://airflow:airflow@host:5432/airflow"},
+                "data": {
+                    "conn_type": "postgres",
+                    "login": "airflow",
+                    "password": "airflow",
+                    "host": "host",
+                    "port": "5432",
+                    "schema": "airflow",
+                },

Review Comment:
   Thanks for pointing to it. LGTM now.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3416876712


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection

Review Comment:
   @amoghrajesh Does that look right? wdyt?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #68305:
URL: https://github.com/apache/airflow/pull/68305#issuecomment-4798269273

   @seanmuth — this PR has 2 unresolved review thread(s) that still look like they need your attention. Once you've addressed them (push changes and/or reply in-thread), please resolve the threads or reply to confirm, and give the reviewer a nudge for another look. Thanks!
   
   See the [PR quality criteria](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-quality-criteria).
   
   <sub>Automated first-pass triage note drafted by an AI-assisted tool — may get things wrong; once addressed, a real Apache Airflow maintainer takes the next look. ([why automated](https://github.com/apache/airflow/blob/main/contributing-docs/25_maintainer_pr_triage.md))</sub>
   
   ---
   Drafted-by: Claude Code (Opus 4.8); reviewed by @potiuk before posting
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "amoghrajesh (via GitHub)" <gi...@apache.org>.
amoghrajesh merged PR #68305:
URL: https://github.com/apache/airflow/pull/68305


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "amoghrajesh (via GitHub)" <gi...@apache.org>.
amoghrajesh commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3489664334


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -224,32 +224,68 @@ def _get_team_or_global_secret(self, base_path: str | None, team_name: str | Non
 
         return self._get_secret_with_base(path, key)
 
-    # Make sure connection is imported this way for type checking, otherwise when importing
-    # the backend it will get a circular dependency and fail
-    if TYPE_CHECKING:
-        from airflow.models.connection import Connection
+    def get_connection(self, conn_id: str, team_name: str | None = None):

Review Comment:
   Type annotation please.



##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -576,7 +583,14 @@ def test_jwt_auth_type(self, mock_hvac):
             "renewable": False,
             "lease_duration": 0,
             "data": {
-                "data": {"conn_uri": "postgresql://airflow:airflow@host:5432/airflow"},
+                "data": {
+                    "conn_type": "postgres",
+                    "login": "airflow",
+                    "password": "airflow",
+                    "host": "host",
+                    "port": "5432",
+                    "schema": "airflow",
+                },

Review Comment:
   There's no coverage for `conn_uri` now? 
   
   The JWT auth test in particular was validating that JWT authenticated vault reads with `conn_uri` worked end-to-end & switching it to field-based means there is no test confirming URI secrets work with JWT auth



##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -121,8 +122,10 @@ def test_get_connection(self, mock_hvac):
         }
 
         test_client = VaultBackend(**kwargs)
+        if hasattr(test_client, "_set_connection_class"):
+            test_client._set_connection_class(SdkConnection)
         connection = test_client.get_connection(conn_id="test_postgres")
-        assert connection.get_uri() == "postgresql://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"
+        assert connection.get_uri() == "postgres://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"

Review Comment:
   Intentional? 



##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -192,7 +197,7 @@ def test_get_connection_value_multi_team(
                 for path in exp_paths
             ]
         )
-        assert connection.get_uri() == "postgresql://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"
+        assert connection.get_uri() == "postgres://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"

Review Comment:
   Same here.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3546750638


##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -576,7 +583,14 @@ def test_jwt_auth_type(self, mock_hvac):
             "renewable": False,
             "lease_duration": 0,
             "data": {
-                "data": {"conn_uri": "postgresql://airflow:airflow@host:5432/airflow"},
+                "data": {
+                    "conn_type": "postgres",
+                    "login": "airflow",
+                    "password": "airflow",
+                    "host": "host",
+                    "port": "5432",
+                    "schema": "airflow",
+                },

Review Comment:
   The URI-with-JWT path is still covered — `test_jwt_auth_type_conn_uri` (added in `c948bf7a29`, just above the field-based test) sets `auth_type="jwt"`, returns a `conn_uri` secret, and asserts both that the verbatim URI is returned and that `jwt_login` was called. `test_jwt_auth_type_field_based` is the complementary case for field-based secrets, so both the URI and dict paths are exercised under JWT auth. Happy to consolidate or rename them if you'd prefer.
   
   ---
   Drafted-by: Claude Code (Opus 4.8); reviewed by @seanmuth before posting



##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -82,7 +82,9 @@ def variable_result(self):
         }
 
     @mock.patch("airflow.providers.hashicorp._internal_client.vault_client.hvac")
-    def test_get_connection(self, mock_hvac):
+    def test_get_conn_value(self, mock_hvac):
+        import json

Review Comment:
   Done in `59b4285e77` — hoisted a single `import json` to the module top and dropped the five in-body copies.
   
   ---
   Drafted-by: Claude Code (Opus 4.8); reviewed by @seanmuth before posting



##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -224,32 +224,30 @@ def _get_team_or_global_secret(self, base_path: str | None, team_name: str | Non
 
         return self._get_secret_with_base(path, key)
 
-    # Make sure connection is imported this way for type checking, otherwise when importing
-    # the backend it will get a circular dependency and fail
-    if TYPE_CHECKING:
-        from airflow.models.connection import Connection
-
-    def get_connection(self, conn_id: str, team_name: str | None = None) -> Connection | None:
+    def get_conn_value(self, conn_id: str, team_name: str | None = None) -> str | None:
         """
-        Get connection from Vault as secret.
+        Retrieve a connection from Vault as a serialized string.
 
-        Prioritize conn_uri if exists, if not fall back to normal Connection creation.
+        Returns the ``conn_uri`` value verbatim when present, otherwise serializes
+        the secret dict to JSON.  The base-class ``get_connection`` deserializes the
+        returned string using the Connection class that the framework injected for the
+        current execution context (ORM Connection on the server, SDK Connection in
+        workers), which avoids triggering SQLAlchemy mapper initialization in

Review Comment:
   Done in `59b4285e77` — qualified the docstring to "On Airflow 3.2+…" and spelled out that on the older supported releases (2.11 / 3.0 / 3.1) the base `deserialize_connection` imports the ORM `Connection` directly, so the mapper-initialization avoidance doesn't apply there.
   
   ---
   Drafted-by: Claude Code (Opus 4.8); reviewed by @seanmuth before posting



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on PR #68305:
URL: https://github.com/apache/airflow/pull/68305#issuecomment-4919391432

   I think I've addressed everything in the comments? Ready for another pass @kaxil @amoghrajesh 


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "amoghrajesh (via GitHub)" <gi...@apache.org>.
amoghrajesh commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3389759518


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # from_uri is available on the SDK Connection (Airflow 3.2+ / task-sdk 1.2.0+).
+            # On Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            # On Airflow 3.0/3.1 the attrs-based Connection has neither from_uri nor a uri=
+            # constructor arg; return None so the secrets-backend loop tries the next backend.
+            if hasattr(Connection, "from_uri"):
+                return Connection.from_uri(uri, conn_id=conn_id)
+            try:
+                return Connection(conn_id=conn_id, uri=uri)
+            except TypeError:
+                self.log.warning(
+                    "Cannot deserialize conn_uri for connection '%s': upgrade to Airflow 3.2+ "
+                    "or store the connection using individual fields (conn_type, host, login, "
+                    "etc.) in Vault.",
+                    conn_id,
+                )
+                return None

Review Comment:
   `except TypeError` is narrow. Fine for the compat (3.0/3.1), but a `ValueError` from Pydantic or a future attrs validator change would slip through and get re-swallowed by the secrets-backend loop, same silent failure this PR is fixing. widen to (TypeError, ValueError) 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on PR #68305:
URL: https://github.com/apache/airflow/pull/68305#issuecomment-4693364499

   thought we fixed that test already, looking


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3416874037


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection

Review Comment:
   This swaps one hard-coded Connection class for another. The old code pinned the ORM `Connection` (that's the worker bug), and this pins `compat.sdk.Connection` instead, but the framework already hands each backend the right class for the process it runs in: the ORM `Connection` on the server (`airflow-core/src/airflow/configuration.py:764,772`) and the SDK `Connection` in the worker (`task-sdk/src/airflow/sdk/configuration.py:293,301`), both through `_set_connection_class()`. You can read it back here with `self._get_connection_class()`.
   
   Pinning the SDK class fixes the `PythonVirtualenvOperator` path but regresses the server side. `airflow connections get <vault_conn>` goes through `Connection.get_connection_from_secrets`, which returns whatever the backend hands back, and the CLI then runs that through `ConnectionDisplayMapper.full_details`, which reads `conn.id` and `conn.is_encrypted` (`connection_command.py:79,88`). The attrs SDK Connection has neither field, so that's an `AttributeError` on a command that worked before this change.
   
   If you build from `conn_class = self._get_connection_class()`, the worker gets the SDK class (mapper init avoided, original bug fixed) and the server keeps the ORM class (no regression). That's also what the shared base already does in `_deserialize_connection_value` (`airflow-core/src/airflow/_shared/secrets_backend/base.py:128`), with the same `hasattr(conn_class, "from_uri")` check this code reinvents. akeyless (`akeyless.py:177`) hard-codes the ORM class the same way and has the mirror of the worker bug, so the injected class would be the consistent fix for both.
   
   Minor: the comment just above calls the Airflow 3 SDK Connection "Pydantic", it's attrs-based.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "amoghrajesh (via GitHub)" <gi...@apache.org>.
amoghrajesh commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3433375578


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection

Review Comment:
   `_get_connection_class()` is the correct mechanism here as you mentioned. The framework already injects the right connection class per execution context and we should use that instead of pinning to `compat.sdk.Connection`. Thanks for bringing that up. That solution is fine for now.
   
   But I think the proper way to do this is to migrate `VaultBackend` to override `get_conn_value()` instead of `get_connection()`, returning a json string for the field based case and a URI string for the `conn_uri` case. The base `get_connection()` already calls `deserialize_connection()` which calls `_get_connection_class()`, so class injection would work automatically. That also removes the `hasattr(Connection, "from_uri")` guard here since `_deserialize_connection_value` already handles it.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3383520046


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,27 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # In Airflow 3 the SDK Connection's __init__ is keyword-only and attrs-generated;
+            # uri= is not in the attrs fields so we use the classmethod directly.
+            # In Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            from airflow.providers.common.compat.version_compat import AIRFLOW_V_3_0_PLUS
 
-        return Connection(conn_id, **response)
+            if AIRFLOW_V_3_0_PLUS:
+                return Connection.from_uri(uri, conn_id=conn_id)  # type: ignore[attr-defined]

Review Comment:
   `from_uri` only exists on the SDK Connection starting with task-sdk 1.2.0 / Airflow 3.2 (added in #55972). This provider supports `apache-airflow>=2.11.0`, so on Airflow 3.0/3.1 this line raises `AttributeError` (the attrs Connection there has neither `from_uri` nor a `uri=` kwarg), and the secrets-backend loop in `execution_time/context.py` swallows it at DEBUG level, the same silent failure this PR is fixing.
   
   The shared secrets base uses `hasattr(conn_class, "from_uri")` as the discriminator for exactly this case (`_deserialize_connection_value` in `airflow_shared/secrets_backend/base.py`), which would be a safer gate than the Airflow version check. 3.0/3.1 would still need an explicit fallback (or a comment noting that `conn_uri`-style secrets remain broken there).
   
   The comment above is also slightly off for 3.2+: since #62211 the SDK Connection has a hand-written `__init__` that does accept `uri=`, so it's only 3.0/3.1 where neither spelling works.



##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,27 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # In Airflow 3 the SDK Connection's __init__ is keyword-only and attrs-generated;
+            # uri= is not in the attrs fields so we use the classmethod directly.
+            # In Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            from airflow.providers.common.compat.version_compat import AIRFLOW_V_3_0_PLUS

Review Comment:
   If the version check stays, this import can move to the top of the file next to the existing `compat.sdk` import. The circular-import concern in the old comment was about the Connection model, not `version_compat`.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "seanmuth (via GitHub)" <gi...@apache.org>.
seanmuth commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3404946458


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # from_uri is available on the SDK Connection (Airflow 3.2+ / task-sdk 1.2.0+).
+            # On Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            # On Airflow 3.0/3.1 the attrs-based Connection has neither from_uri nor a uri=
+            # constructor arg; return None so the secrets-backend loop tries the next backend.
+            if hasattr(Connection, "from_uri"):
+                return Connection.from_uri(uri, conn_id=conn_id)  # type: ignore[attr-defined]
+            try:
+                return Connection(conn_id=conn_id, uri=uri)  # type: ignore[call-arg]

Review Comment:
   Restored `# type: ignore[call-arg]` on the `Connection(conn_id=conn_id, uri=uri)` line after a mypy CI failure — the attrs mypy plugin replaces the manually-written `@overload` signatures (which do include `uri=`) with the attrs-generated `__init__` (which only knows about declared fields). So mypy never sees `uri=` as valid regardless of what's written in the class body. The ignore on that specific line is load-bearing.
   
   Drafted-by: Claude Code (Sonnet 4.6); reviewed by @seanmuth before posting



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3384274878


##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -237,19 +237,35 @@ def get_connection(self, conn_id: str, team_name: str | None = None) -> Connecti
 
         :return: A Connection object constructed from Vault data
         """
-        # The Connection needs to be locally imported because otherwise we get into cyclic import
-        # problems when instantiating the backend during configuration
-        from airflow.models.connection import Connection
+        # Use the compat SDK Connection (Pydantic in Airflow 3, SQLAlchemy in Airflow 2) to avoid
+        # triggering SQLAlchemy mapper initialization for unrelated models (e.g. DagModel) in
+        # task-execution subprocesses such as PythonVirtualenvOperator.
+        from airflow.providers.common.compat.sdk import Connection
 
         response = self._get_team_or_global_secret(self.connections_path, team_name, conn_id)
         if response is None:
             return None
 
         uri = response.get("conn_uri")
         if uri:
-            return Connection(conn_id, uri=uri)
+            # from_uri is available on the SDK Connection (Airflow 3.2+ / task-sdk 1.2.0+).
+            # On Airflow 2 the SQLAlchemy Connection accepts uri= in its __init__.
+            # On Airflow 3.0/3.1 the attrs-based Connection has neither from_uri nor a uri=
+            # constructor arg; return None so the secrets-backend loop tries the next backend.
+            if hasattr(Connection, "from_uri"):
+                return Connection.from_uri(uri, conn_id=conn_id)  # type: ignore[attr-defined]
+            try:
+                return Connection(conn_id=conn_id, uri=uri)  # type: ignore[call-arg]
+            except TypeError:
+                self.log.warning(
+                    "Cannot deserialize conn_uri for connection '%s': upgrade to Airflow 3.2+ "
+                    "or store the connection using individual fields (conn_type, host, login, "
+                    "etc.) in Vault.",
+                    conn_id,
+                )
+                return None

Review Comment:
   @amoghrajesh Would be good to get your review here



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "kaxil (via GitHub)" <gi...@apache.org>.
kaxil commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3500653207


##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -82,7 +82,9 @@ def variable_result(self):
         }
 
     @mock.patch("airflow.providers.hashicorp._internal_client.vault_client.hvac")
-    def test_get_connection(self, mock_hvac):
+    def test_get_conn_value(self, mock_hvac):
+        import json

Review Comment:
   `import json` is repeated inside five test bodies (86, 201, 245, 622, 795) and there's no module-level import. Hoist a single `import json` to the top with the other stdlib imports and drop the in-method copies.



##########
providers/hashicorp/src/airflow/providers/hashicorp/secrets/vault.py:
##########
@@ -224,32 +224,30 @@ def _get_team_or_global_secret(self, base_path: str | None, team_name: str | Non
 
         return self._get_secret_with_base(path, key)
 
-    # Make sure connection is imported this way for type checking, otherwise when importing
-    # the backend it will get a circular dependency and fail
-    if TYPE_CHECKING:
-        from airflow.models.connection import Connection
-
-    def get_connection(self, conn_id: str, team_name: str | None = None) -> Connection | None:
+    def get_conn_value(self, conn_id: str, team_name: str | None = None) -> str | None:
         """
-        Get connection from Vault as secret.
+        Retrieve a connection from Vault as a serialized string.
 
-        Prioritize conn_uri if exists, if not fall back to normal Connection creation.
+        Returns the ``conn_uri`` value verbatim when present, otherwise serializes
+        the secret dict to JSON.  The base-class ``get_connection`` deserializes the
+        returned string using the Connection class that the framework injected for the
+        current execution context (ORM Connection on the server, SDK Connection in
+        workers), which avoids triggering SQLAlchemy mapper initialization in

Review Comment:
   This reads as unconditional, but the framework's per-process Connection-class injection (`_get_connection_class`) only exists on 3.2+. On the older releases this provider still supports (2.11 / 3.0 / 3.1) the base `deserialize_connection` hard-imports the ORM `Connection`, so the mapper-init avoidance doesn't hold there. Same 3.0/3.1 gap as the earlier thread; worth qualifying the docstring (e.g. "on Airflow 3.2+") so it doesn't promise more than the supported floor delivers.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix VaultBackend.get_connection() breaking PythonVirtualenvOperator in Airflow 3 [airflow]

Posted by "amoghrajesh (via GitHub)" <gi...@apache.org>.
amoghrajesh commented on code in PR #68305:
URL: https://github.com/apache/airflow/pull/68305#discussion_r3503304477


##########
providers/hashicorp/tests/unit/hashicorp/secrets/test_vault.py:
##########
@@ -121,8 +122,10 @@ def test_get_connection(self, mock_hvac):
         }
 
         test_client = VaultBackend(**kwargs)
+        if hasattr(test_client, "_set_connection_class"):
+            test_client._set_connection_class(SdkConnection)
         connection = test_client.get_connection(conn_id="test_postgres")
-        assert connection.get_uri() == "postgresql://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"
+        assert connection.get_uri() == "postgres://airflow:airflow@host:5432/airflow?foo=bar&baz=taz"

Review Comment:
   Haha!



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org