Repository navigation
Async support for /task-instances/states and /task-instances/count API routes - #73966
zach-overflow wants to merge 5 commits into
Conversation
/task-instances/states and /task-instances/count API routes
Dev-iL
left a comment
There was a problem hiding this comment.
The migration correctly reuses Airflow’s async session infrastructure, explicitly detaches serialized Dag rows before threaded deserialization, and preserves the tested endpoint contracts across SQLite, PostgreSQL, and MySQL.
The main comment is related to a performance regression (see evidence in the section below). I'll update the migration skill to be careful about similar mechanical replacements.
Breeze verification by Codex
Head: 33c54041cb54f640975630db239a26e0ea1e5e21.
Comparison base (merge base): 508301ab263dc6df7a492b8f284229259c889fff.
Current target branch SHA when fetched: f7a276337416bc3ba97a7bfb5836144568d46410.
The final read of GitHub confirmed the head was unchanged: final-head.json.
Review checkout: /tmp/airflow-review-73966.
Base checkout: /tmp/airflow-review-73966-base.
Tests ran through Breeze, using the cached Python 3.10 CI image and the checkout's mounted sources. Pytest reported Python 3.10.21 and function-scoped asyncio fixtures. No production source file was changed. Temporary instrumentation was confined to dev/review_73966.py in those review checkouts; its final source is retained as verification-harness.py.
Contract and helper tests
| Revision | Backend | Async driver | Scope | Result | Log |
|---|---|---|---|---|---|
| Head | SQLite, initially selected default | aiosqlite | Both changed endpoint classes and full common/model DagBag test files | 85 passed | SQLite head |
| Head | PostgreSQL 14 | psycopg async dialect | Same scope | 85 passed | PostgreSQL head |
| Head | MySQL 8.0 | aiomysql | Same scope | 85 passed | MySQL head |
| Base | SQLite, initially selected default | aiosqlite | Both changed endpoint classes | 40 passed | SQLite base |
| Head | SQLite, explicitly selected | aiosqlite | Both classes × API versions 2025-04-11 and 2026-10-30 × compression false/true | 160 passed | SQLite matrix |
| Head | PostgreSQL 14 | psycopg async dialect | Same version/compression matrix | 160 passed | PostgreSQL matrix |
| Head | MySQL 8.0 | aiomysql | Same version/compression matrix | 160 passed | MySQL matrix |
The configured drivers were traced in settings.py; PostgreSQL runtime introspection reported postgresql psycopg psycopg, MySQL introspection reported mysqldb aiomysql, and the explicitly selected SQLite probes reported sqlite aiosqlite. The PostgreSQL result used the configured psycopg asynchronous implementation, rather than assuming asyncpg. Database drivers/configuration were not changed by this PR; PgBouncer and driver overrides were not tested.
Reproduce the 85-test head suite from the head checkout, substituting sqlite, postgres, or mysql:
breeze run --backend sqlite --skip-image-upgrade-check --answer no pytest \
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py::TestGetCount \
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py::TestGetTaskStates \
airflow-core/tests/unit/api_fastapi/common/test_dagbag.py \
airflow-core/tests/unit/models/test_dagbag.py -qThe original SQLite invocation omitted --backend after Breeze initialized its fresh worktree with SQLite. PostgreSQL and MySQL were explicitly selected. The 40-test base command uses only the first two test targets above.
The version/compression matrix invokes the existing tests without changing their assertions. The temporary pytest plugin sets the requested Airflow-API-Version and compression setting before test Dag creation:
breeze run --backend sqlite --skip-image-upgrade-check --answer no \
python dev/review_73966.py versionsOnly the oldest and newest negotiated versions, plus the unversioned head tests, were exercised; intermediate version headers were not separately tested. Existing count/state filters, map indexes, task groups, missing Dag/group responses, and response shapes passed within this scope.
Ruff lint and formatting checks passed on all six changed Python files through Breeze: see the end of postgres-extra-verification.log. This was a review, not a full CI run: no mypy or complete prek suite was run.
Finding 1: event-loop stalls during full TaskInstance loading
The harness creates a real Dag run with one ordinary task instance and 1,000 or 5,000 mapped instances of the same task, with no inflated executor configuration or Dag-run payload. It sends actual HTTP requests to /execution/task-instances/states with both dag_id and run_ids, verifies HTTP 200 and the returned state count, and measures a 1 ms ticker running on the same TestClient event loop. The existing test authentication override remains in use.
Each dataset receives three sequential requests. The first request for each dataset is excluded from the warm comparison. Cold calls also show substantial stalls at the base revision, so they are not used as PR-specific evidence. These are small local samples, not a production throughput benchmark.
| Revision/query | Returned states | Warm ticker gaps (ms) | Warm HTTP duration (ms) | Warm awaited query duration (ms) |
|---|---|---|---|---|
| Base, synchronous handler | 1,001 | 15.20 / 11.92 | 228.27 / 289.30 | Not instrumented |
| Head, first reproduction | 1,001 | 158.85 / 109.94 | 189.49 / 139.37 | Not instrumented |
| Base, synchronous handler | 5,001 | 15.24 / 12.46 | 1,051.24 / 1,226.62 | Not instrumented |
| Head, first reproduction | 5,001 | 638.35 / 758.60 | 720.87 / 868.52 | Not instrumented |
| Head, instrumented full-entity query | 5,001 | 754.84 / 693.19 | 903.55 / 842.09 | 816.52 / 766.61 |
| Head, temporary four-column projection | 5,001 | 36.26 / 37.52 | 56.19 / 62.71 | 17.50 / 20.96 |
Logs: base probe, first head probe, head/projection comparison.
The source-level mechanism is the full select(TI) at task_instances.py:1325, executed inside the async handler at line 1339. TaskInstance.dag_run has lazy="joined"; ORM result processing loads the entire TaskInstance/DagRun graph, although the response consumes only run_id, task_id, map_index, and state. Moving the handler from a synchronous FastAPI worker to the event loop also moves this CPU work there. Awaiting database I/O does not offload ORM result processing.
The projection experiment replaces only TaskInstance statements inside the temporary AsyncSession.scalars wrapper with statement.with_only_columns(...), awaits execute on the same session, and supplies buffered row objects to the original route. Production code is untouched. It tests a mitigation for this reproduction; it is not a completed production patch and does not independently establish compatibility for every filter/group combination. _get_group_tasks also selects complete TaskInstances, so the draft asks that its results use the same required column set.
The measured regression is event-loop availability. The original head route returned faster than the base in the initial comparison; the finding does not claim that the endpoint itself got slower.
# Run from the base checkout and from the head checkout.
breeze run --backend sqlite --skip-image-upgrade-check --answer no \
python dev/review_73966.py states
# Run from the head checkout for the local projection experiment.
breeze run --backend sqlite --skip-image-upgrade-check --answer no \
python dev/review_73966.py projected-statesThe base copy of the harness predates query-duration/projection instrumentation; its ticker and HTTP request construction match the initial head reproduction.
Finding 2: committed private workspace instructions
The end of sqlite-states-comparison.log contains the actual committed CLAUDE.local.md and AGENTS.local.md, read through Breeze using git show HEAD:<path> with the mounted main Git directory. It verifies:
CLAUDE.local.md:20importsAGENTS.local.md.AGENTS.local.md:22–27declares a Workforest and a fixed author-specific branch.AGENTS.local.md:31–34requires branch registration withforest.command -v forestfails in the standard Breeze CI image, producingforest-unavailable-in-breeze.
The applicability concern follows from those committed instructions: their workspace facts do not describe arbitrary Airflow checkouts. The draft asks to remove the two private setup files. The tool-availability observation is limited to the tested Breeze image.
Investigated leads and setup limitations
The detached serialized-Dag row contains the scalar columns _read_dag accesses. Existing model tests validate worker execution, detached state, compressed/uncompressed deserialization, missing rows, and worker exceptions; the version/compression matrix also exercises actual database-backed group routes. Cache writes in the API's CachedDBDagBag are protected by an existing RLock. These leads did not produce another finding.
33c5404 to
b9b8f90
Compare
b9b8f90 to
026f787
Compare
Dev-iL
left a comment
There was a problem hiding this comment.
Please see #73966 (comment)
026f787 to
be60f19
Compare
be60f19 to
66be871
Compare
3e30bc0 to
417b4e6
Compare
417b4e6 to
4d1603a
Compare
4d1603a to
4fd89d1
Compare
hussein-awala
left a comment
There was a problem hiding this comment.
Small nit: could you make session keyword-only in the new get_latest_version_of_dag_async and _find_superseded_ids_async helpers, and update their callers to pass session=session? This follows the repository rule: “Use keyword-only session parameters.”
97ea309 to
89276f2
Compare
Task-group lookups can decompress and deserialize serialized Dags and initialize operator links. This work must stay off the API event loop when database reads use an async session.
The async states route ran ORM entity hydration for every matching task instance and its eagerly joined Dag run on the API event loop, stalling other requests on large mapped runs. Only four columns are consumed. Per-developer agent instruction files must never be committed.
Building the response row by row and processing the full result in one piece still blocked the event loop longer than the old synchronous handler on large mapped runs. The Dag-wide query also ran when a task group without task IDs was requested, although its result was discarded.
Pooled async connections are bound to the event loop that opened them. The in-process Execution API used by dag.test() starts its own loop but shared the async pool with earlier loops, so the first async route request could pick up a stale connection and fail. On MySQL this broke mapped task groups, whose upstream map-index resolution now goes through the async task-instance count route.
Airflow code takes `session` as a keyword-only parameter so callers cannot pass it positionally by mistake. The new async helpers did not follow that convention.
89276f2 to
106bb97
Compare
dabla
left a comment
There was a problem hiding this comment.
Addressed
- Full
TaskInstanceentities hydrated on the event loop (@Dev-iL, r4153260724): both/statesqueries and_get_group_tasksselect columns only;test_get_task_states_does_not_load_task_instancescovers the Dag-wide and the task-group query and passes on this head. - Row-by-row response building and one-piece result processing (@Dev-iL, same thread, follow-up): the Dag-wide query is streamed in partitions of 500 and skipped for a group-only request. The rows are collected before the map is built, which the superseded-pass filter added on
mainsince then needs. AGENTS.local.md/CLAUDE.local.mdin the PR (@Dev-iL, r4153294357): neither file is in the diff; both are in.gitignore.- Keyword-only
sessiononget_latest_version_of_dag_asyncand_find_superseded_ids_async(@hussein-awala, review): done in106bb97b5c, callers passsession=session.
Open
- Comments [1] and [2]: two duplicated blocks next to their sync twins (the 404 response, the
dag_hashquery). These are why the event is COMMENT and not APPROVE. - Comment [3]: question on the direction the pool reset covers.
- Comments [4] and [5]: a missing test for the skipped query, a function name.
- CI has not run on this head: the PR carries
need workflow approvaland shows three checks only. The two approvals (@Dev-iL on66be8718d1, @hussein-awala on69e07245ea) are on revisions from before the rebase of 2026-11-16. - Not flagged, by choice: the remaining sync/async twins (
AsyncTaskCoordinateResolver,load_region_ancestry_async,_find_superseded_ids_async) repeat only the await-bearing control flow; their pure parts are shared, and the sync versions keep callers (get_previous_task_instancepath, the public API routes).
The pass: head 106bb97b5c, local source checkout, full read of the six changed source files plus SerializedDagModel, settings.py (async engine and pool), AsyncSessionDep and the three InProcessExecutionAPI call sites. Checked as intended: sync/async parity of DBDagBag._get_dag versus get_dag_async (window, revalidation, double-checked load, miss metric) and of both resolvers; the detached SerializedDagModel handed to the worker thread reads loaded columns only (data, data_compressed, dag_hash, dag_version_id), no relationship; response and 404/409 behaviour of both routes unchanged; no test of the base removed; new mocks carry a spec. Tests run locally on SQLite/aiosqlite: models/test_dagbag.py, common/test_dagbag.py, models/test_task_coordinates.py, TestGetTaskStates, TestGetCount: 148 passed. execution_api/test_app.py (the in-process pool test) could not be collected in my environment, and nothing ran on PostgreSQL or MySQL, so comment [3] rests on reading the code.
| return dag | ||
|
|
||
|
|
||
| async def get_latest_version_of_dag_async( |
There was a problem hiding this comment.
[warning] The async helper copies the whole "Dag not found" block of get_latest_version_of_dag.
Only the lookup differs between the two functions (dag_bag.get_latest_version_of_dag(...) versus await dag_bag.get_latest_version_of_dag_async(...)); the include_reason branch, the status code and both messages are now written twice, so the next change to the 404 payload has to be made in two places (DontRepeatYourself). The rest of this PR already solves the same problem by pulling the shared part out (_build_live_tasks_query, _find_superseded_in_passes, _build_region_batch_query). The same here keeps one home for the response:
def _dag_not_found(dag_id: str, *, include_reason: bool) -> HTTPException:
message = f"The Dag with ID: `{dag_id}` was not found"
detail = {"reason": "not_found", "message": message} if include_reason else message
return HTTPException(status.HTTP_404_NOT_FOUND, detail=detail)with both functions reduced to if not dag: raise _dag_not_found(dag_id, include_reason=include_reason). (See also comment [2] in models/dagbag.py.)
| if dag is not None: | ||
| return dag | ||
| if cached is not None: | ||
| current_hash = await session.scalar( |
There was a problem hiding this comment.
[warning] get_dag_async writes the dag_hash lookup of _current_dag_hash a second time.
_current_dag_hash (a few lines up) and this statement are the same select(SerializedDagModel.dag_hash).where(SerializedDagModel.dag_version_id == version_id). The revalidation logic was split out so both paths share it, but the query that feeds it was not, so a change to how staleness is detected (another column, a join) can reach the sync path and miss this one. A statement builder that both call, as done for the other queries in this PR, closes that:
@staticmethod
def _build_current_dag_hash_query(version_id: UUID | str) -> Select:
from airflow.models.serialized_dag import SerializedDagModel
return select(SerializedDagModel.dag_hash).where(SerializedDagModel.dag_version_id == version_id)(See also comment [1] in api_fastapi/common/dagbag.py.)
| # Pooled async connections are bound to the event loop that opened them, and reusing one on | ||
| # this loop fails (e.g. aiomysql). Drop connections opened elsewhere without closing them here. | ||
| if settings.async_engine is not None: | ||
| await settings.async_engine.dispose(close=False) |
There was a problem hiding this comment.
[nit] This drops connections opened before the in-process loop starts; a loop that uses the pool afterwards still shares it.
dispose(close=False) runs once, at lifespan start, so it covers the case the new test builds: another loop queried first, then the in-process API. The pool stays process-wide after that. Any other loop in the same process that calls create_session_async() later (a second asyncio.run(...) in a dag.test() caller, an async fixture in the test suite) checks out connections this loop returned, and the reverse, which is the same aiomysql failure from the other side. I could not reproduce it without MySQL at hand, and with in_process_api_server() cached to one instance it may not occur in practice today, so this is a question more than a request: is the one-time dispose meant as the full fix, or would a pool that never hands a connection to another loop (NullPool for the in-process engine, or a pool per loop) be the safer end state? If the one-time dispose is the intent, a sentence in the comment saying that it only covers earlier loops would help the next reader.
| results = session.execute(query).tuples().all() | ||
| results: list[Any] = [] | ||
| # Without task_ids, task_group_id replaces the Dag-wide match instead of extending it. | ||
| if task_ids or not task_group_id: |
There was a problem hiding this comment.
[nit] Skipping the Dag-wide query for a group-only request has no test that fails without it.
The PR body lists this as a change, and the existing parametrised tests only check the response, which is identical with or without the skip. A statement-count assertion on a request with task_group_id and no task_ids (the assert_queries_count helper from tests_common.test_utils.asserts, or the same event.listen approach the new does_not_load_task_instances test uses) would pin it, so a later refactor cannot quietly bring the discarded query back.
|
|
||
|
|
||
| def _get_group_tasks( | ||
| async def _get_group_tasks( |
There was a problem hiding this comment.
[nit] _get_group_tasks now returns task instance ids, not tasks.
Both callers already name the result group_ti_ids; renaming the function to match (_get_group_ti_ids) and updating the "Get all tasks in the task group" comment keeps the name honest now that the return type is Sequence[UUID].
What?
AsyncSessionDep/task-instances/states(get_task_instance_states)/task-instances/count(get_task_instance_count)DBDagBaglookups for these routes; Dag deserialization runs in a worker thread so it does not block the event loop./task-instances/statesselects only the columns it returns instead of loading fullTaskInstancerows with their joined Dag runs, and skips the Dag-wide query for a task group without task IDs.dag.test()drops pooled async connections opened on other event loops, which otherwise broke mapped task groups on MySQL.Why?
Was generative AI tooling used to co-author this PR?
Generated-by: Codex GPT-Astra following the guidelines
PR description written by human, some manual de-slopification of docstrings, test structure also done by hand.
{pr_number}.significant.rst, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.