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

[PR] Reject async callables in @task.virtualenv and @task.external_python [airflow]

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

   ## Why
   
   - `PythonVirtualenvOperator` uses a virtualenv built from `requirements`, and `ExternalPythonOperator` uses the interpreter given in `python`. An `async def` callable never reaches `execute_callable()`, so `requirements`, `python`, and `venv_cache_path` are ignored.
   - Either the callable runs with the worker's own packages and the task still succeeds, or it fails with an `ImportError` that looks like a broken virtualenv.
   
   ## How
   
   - `_BasePythonVirtualenvOperator.__init__` raises `ValueError` for async callables. The Dag now fails at parse time.
   
   ## Verification
   
   - Unit test: `uv run --frozen --project providers/standard pytest providers/standard/tests/unit/standard/operators/test_python.py`
   - Integration test:
   
   1. Setup
   
   ```sh
   export DEMO_DIR="${TMPDIR:-/tmp}/airflow-async-venv-demo"
   export AIRFLOW_HOME="$DEMO_DIR/airflow-home"
   export AIRFLOW__CORE__DAGS_FOLDER="$DEMO_DIR/dags"
   export AIRFLOW__CORE__LOAD_EXAMPLES=False
   mkdir -p "$AIRFLOW__CORE__DAGS_FOLDER"
   uv run --frozen --no-dev --project providers/standard --with "pandas>=3,<4" airflow db migrate
   uv venv --allow-existing "$DEMO_DIR/pandas2-venv"
   uv pip install --python "$DEMO_DIR/pandas2-venv/bin/python" "pandas>=2.2,<3"
   ```
   
   2. Create Dags
   
   ```sh
   cat > "$AIRFLOW__CORE__DAGS_FOLDER/virtualenv_example.py" <<'EOF'
   from __future__ import annotations
   
   from airflow.sdk import dag, task
   
   
   @dag(schedule=None)
   def virtualenv_example():
       @task.virtualenv(requirements=["pandas>=2.2,<3"], system_site_packages=False)
       def virtualenv_sync():
           import sys
   
           import pandas as pd
   
           return {"python": sys.executable, "pandas": pd.__version__}
   
       @task.virtualenv(requirements=["pandas>=2.2,<3"], system_site_packages=False)
       async def virtualenv_async():
           import sys
   
           import pandas as pd
   
           return {"python": sys.executable, "pandas": pd.__version__}
   
       virtualenv_sync()
       virtualenv_async()
   
   
   example_dag = virtualenv_example()
   
   if __name__ == "__main__":
       dag_run = example_dag.test()
       for ti in sorted(dag_run.get_task_instances(), key=lambda ti: ti.task_id):
           print(f"EXAMPLE STATE {ti.task_id} {ti.state}")
   EOF
   
   cat > "$AIRFLOW__CORE__DAGS_FOLDER/external_python_example.py" <<'EOF'
   from __future__ import annotations
   
   import os
   
   from airflow.sdk import dag, task
   
   PANDAS2_PYTHON = os.path.join(os.environ["DEMO_DIR"], "pandas2-venv", "bin", "python")
   
   
   @dag(schedule=None)
   def external_python_example():
       @task.external_python(python=PANDAS2_PYTHON)
       def external_python_sync():
           import sys
   
           import pandas as pd
   
           return {"python": sys.executable, "pandas": pd.__version__}
   
       @task.external_python(python=PANDAS2_PYTHON)
       async def external_python_async():
           import sys
   
           import pandas as pd
   
           return {"python": sys.executable, "pandas": pd.__version__}
   
       external_python_sync()
       external_python_async()
   
   
   example_dag = external_python_example()
   
   if __name__ == "__main__":
       dag_run = example_dag.test()
       for ti in sorted(dag_run.get_task_instances(), key=lambda ti: ti.task_id):
           print(f"EXAMPLE STATE {ti.task_id} {ti.state}")
   EOF
   ```
   
   3. Run dags to check result
   
   On main branch:
   
   ```sh
   uv run --frozen --no-dev --project providers/standard --with "pandas>=3,<4" python "$AIRFLOW__CORE__DAGS_FOLDER/virtualenv_example.py" 2>&1 | grep -oE "running task <TaskInstance: [^ ]+|Returned value was: \{[^}]*\}|EXAMPLE STATE .*"
   uv run --frozen --no-dev --project providers/standard --with "pandas>=3,<4" python "$AIRFLOW__CORE__DAGS_FOLDER/external_python_example.py" 2>&1 | grep -oE "running task <TaskInstance: [^ ]+|Returned value was: \{[^}]*\}|EXAMPLE STATE .*"
   ```
   
   All four tasks succeed. The sync tasks report pandas 2 from the virtualenv or the external environment. The async tasks report pandas 3 from the `uv run` environment, which shows they ignored `requirements` and `python`:
   
   ```text
   running task <TaskInstance: virtualenv_example.virtualenv_sync
   Returned value was: {'python': '.../venvymv4y504/bin/python', 'pandas': '2.3.3'}
   running task <TaskInstance: virtualenv_example.virtualenv_async
   Returned value was: {'python': '.../builds-v0/.tmpDC6uaL/bin/python', 'pandas': '3.0.5'}
   EXAMPLE STATE virtualenv_sync success
   EXAMPLE STATE virtualenv_async success
   running task <TaskInstance: external_python_example.external_python_sync
   Returned value was: {'python': '.../airflow-async-venv-demo/pandas2-venv/bin/python', 'pandas': '2.3.3'}
   running task <TaskInstance: external_python_example.external_python_async
   Returned value was: {'python': '.../builds-v0/.tmp90SjJP/bin/python', 'pandas': '3.0.5'}
   EXAMPLE STATE external_python_sync success
   EXAMPLE STATE external_python_async success
   ```
   
   On this branch, both Dags now fail at parse time.
   
   ```sh
   uv run --frozen --no-dev --project providers/standard --with "pandas>=3,<4" python "$AIRFLOW__CORE__DAGS_FOLDER/virtualenv_example.py" 2>&1 | grep ValueError
   uv run --frozen --no-dev --project providers/standard --with "pandas>=3,<4" python "$AIRFLOW__CORE__DAGS_FOLDER/external_python_example.py" 2>&1 | grep ValueError
   ```
   
   ```text
       raise ValueError(
   ValueError: _PythonVirtualenvDecoratedOperator does not support async functions as python_callable. Call asyncio.run() inside a regular function instead.
       raise ValueError(
   ValueError: _PythonExternalDecoratedOperator does not support async functions as python_callable. Call asyncio.run() inside a regular function instead.
   ```
   
    <!-- SPDX-License-Identifier: Apache-2.0
         https://www.apache.org/licenses/LICENSE-2.0 -->
   
   <!--
   Thank you for contributing!
   
   Please provide above a brief description of the changes made in this pull request.
   Write a good git commit message following this guide: https://chris.beams.io/posts/git-commit/
   
   Please make sure that your code changes are covered with tests.
   And in case of new features or big changes remember to adjust the documentation.
   
   For user-facing UI changes, please attach before/after screenshots (or a short
   screen recording) so reviewers can assess the visual impact.
   
   Feel free to ping (in general) for the review if you do not see reaction for a few days
   (72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications.
   
   In case of an existing issue, reference it using one of the following:
   
   * closes: #ISSUE
   * related: #ISSUE
   -->
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   <!--
   If generative AI tooling has been used in the process of authoring this PR, please
   change below checkbox to `[X]` followed by the name of the tool, uncomment the "Generated-by".
   -->
   
   - [X] Yes - Claude Code
   
   <!--
   Generated-by: [Tool Name] following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   -->
   
   ---
   
   * Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
   * For fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   * When adding dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: `{pr_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments). You can add this file in a follow-up commit after the PR is created so you know the PR number.
   


-- 
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] Reject async callables in @task.virtualenv and @task.external_python [airflow]

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

   Hello @FrankYang0529 - thank you for your contributions to Apache Airflow!
   
   The Airflow community has introduced a limit of **5 open pull requests at a time** for contributors without write access to the repository. You currently have 30 open pull requests, so - as a one-time step of introducing the limit - we closed the ones where maintainers have not engaged yet:
   
   * #69698 - Avoid deactivating configured Dag bundles on transient get bundle errors
   * #71678 - Add gzip compression option for GCS remote task logs
   * #71775 - Fix comma-separated selected_fields in BigQuery to SQL transfers
   * #71837 - Fix the API server silently ignoring its gunicorn worker hooks
   * #72027 - Fix docs omitting asset from the Dag discovery safe-mode heuristic
   * #72104 - Add missing Druid Ingest connection type
   * #72138 - Fix scheduler crash when the Kafka event producer plugin is enabled
   * #72153 - Fix unscheduled tasks left on a stale Dag version
   * #72317 - Make AzureBatchOperator batch_max_retries take effect
   * #72593 - Fix airflow.utils.context deprecation shim returning a module object
   * #72626 - Support team-scoped secrets in LocalFilesystemBackend
   * #72802 - Honour dag_ignore_file_syntax in Task SDK and example plugin loading
   * #72858 - Restore CLI commands from custom executors and auth managers
   * #72884 - Restore helpful error for unregistered priority weight strategies
   * #72919 - Fix flaky test_trigger_log in triggerer job tests
   * #72920 - Fix API server failing to start when [api] access_logfile is set
   * #73020 - Fix missing task display name and map index in API audit logs
   * #73029 - Fail Gemini batch job operators when the job does not succeed
   * #73031 - Fix extra Dag versions from template field callables if paths change
   * #73032 - Fix Dags staying blocked by max_active_runs until the next parse
   * #73081 - Reject async callables in @task.virtualenv and @task.external_python
   * #73136 - Fix env var names in airflow config list for dotted and team sections
   * #73247 - Fix OpenLineage jobDependencies run ID after upstream task is cleared
   * #73312 - Fix SFTPSensor skipping python_callable in deferrable mode
   
   These pull requests stay open because maintainers are already engaged in them - they count towards your limit:
   
   * #68625 - Add KafkaSharedStreamProducer and KafkaSharedStreamTrigger
   * #68778 - Add rerun policy for rollups when an upstream partition is re-run
   * #70351 - Replace AirflowException with ValueError in ProduceToTopicOperator
   * #71869 - Catch stale entries in the Java SDK dependency trust list
   * #72057 - Support priority_weight in EdgeExecutor
   * #73021 - Speed up the event logs API by loading only display names
   
   This is **not** a judgement of you or of your changes. We never told contributors before that opening many pull requests at once was a problem, so there is nothing to feel bad about - and nothing is lost: your branches, commits and the review history stay where they are.
   
   What we ask you to do is to make your **first prioritization decision**: choose which of the pull requests above matter most to you, and reopen them (up to 5 open at a time, including the ones still open) with the "Reopen pull request" button or `gh pr reopen <PR_NUMBER> --repo apache/airflow`. Reopen the ones you are ready to follow through - keep them rebased, respond to review comments and fix failing checks.
   
   While your pull requests are waiting for review, the most valuable thing you can do is help in other ways - reviewing other contributors' pull requests, helping with issues, and taking part in the discussions on the devlist and Slack.
   
   Why we introduced the limit, what it means for you and how to reopen or restore a pull request is explained in https://github.com/apache/airflow/blob/main/contributing-docs/32_open_pull_request_limit.rst.
   
   ---
   Drafted-by: Claude Code (Opus 5); 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] Reject async callables in @task.virtualenv and @task.external_python [airflow]

Posted by "Vamsi-klu (via GitHub)" <gi...@apache.org>.
Vamsi-klu commented on code in PR #73081:
URL: https://github.com/apache/airflow/pull/73081#discussion_r4002487503


##########
providers/standard/src/airflow/providers/standard/operators/python.py:
##########
@@ -509,6 +509,12 @@ def __init__(
             raise ValueError(f"{type(self).__name__} only supports functions for python_callable arg")
         if inspect.isgeneratorfunction(python_callable):
             raise ValueError(f"{type(self).__name__} does not support using 'yield' in python_callable")
+        # aexecute() awaits async callables in the worker process and never calls execute_callable().
+        if is_async_callable(python_callable):

Review Comment:
   is_async_callable (compat → SDK on 3.2+, local shim on older) checks coroutine functions and async __call__. It does not check inspect.isasyncgenfunction. An async def that yields still constructs.
   
   On the 3.1 shim it also does not inspect.unwrap, so a @functools.wraps wrapper around an async function slips through. Check async generators, and unwrap before the test, in this operator if compat will not. The existing test only covers async def f(): return 1.



-- 
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] Reject async callables in @task.virtualenv and @task.external_python [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk closed pull request #73081: Reject async callables in @task.virtualenv and @task.external_python
URL: https://github.com/apache/airflow/pull/73081


-- 
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] Reject async callables in @task.virtualenv and @task.external_python [airflow]

Posted by "Vamsi-klu (via GitHub)" <gi...@apache.org>.
Vamsi-klu commented on code in PR #73081:
URL: https://github.com/apache/airflow/pull/73081#discussion_r4002487503


##########
providers/standard/src/airflow/providers/standard/operators/python.py:
##########
@@ -509,6 +509,12 @@ def __init__(
             raise ValueError(f"{type(self).__name__} only supports functions for python_callable arg")
         if inspect.isgeneratorfunction(python_callable):
             raise ValueError(f"{type(self).__name__} does not support using 'yield' in python_callable")
+        # aexecute() awaits async callables in the worker process and never calls execute_callable().
+        if is_async_callable(python_callable):

Review Comment:
   is_async_callable (compat → SDK on 3.2+, local shim on older) checks coroutine functions and async __call__. It does not check inspect.isasyncgenfunction. An async def that yields still constructs.
   
   On the 3.1 shim it also does not inspect.unwrap, so a @functools.wraps wrapper around an async function slips through. Check async generators, and unwrap before the test, in this operator if compat will not. The existing test only covers async def f(): return 1.



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