Skip to content

Make task state store Execution API routes async - #75381

Open
Dev-iL wants to merge 1 commit into
apache:mainfrom
Dev-iL:2610/async-task-state-store
Open

Dev-iL wants to merge 1 commit into
apache:mainfrom
Dev-iL:2610/async-task-state-store

Conversation

@Dev-iL

@Dev-iL Dev-iL commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

related: #67799

This PR converts the four Execution API task state store routes to async def with AsyncSessionDep:

  • GET /store/ti/{task_instance_id}/{key} (get_task_state_store)
  • PUT /store/ti/{task_instance_id}/{key} (set_task_state_store)
  • DELETE /store/ti/{task_instance_id}/{key} (delete_task_state_store)
  • DELETE /store/ti/{task_instance_id} (clear_task_state_store)

Details:

  • The routes call the configured backend's aget / aset / adelete / aclear with the route's session. These methods are abstract on BaseStoreBackend, so every backend already implements them. The state store docs already tell custom backends with a synchronous client to offload their async methods to a thread, and the common.io object-storage backend does so.
  • The task instance lookup selects the five columns it uses and filters on working_set IS TRUE. Before, session.get(TI, ...) loaded the full task instance and its joined Dag run.
  • MetastoreBackend._aget_task_state_store selects only value instead of the full row. The column is NOT NULL, so a missing key still returns None.
  • The ReturnNotFoundForMissingDagRun 404 handling that Return 404 when a DagRun disappears during task API writes #72907 added to PUT is kept around the async aset call. MetastoreBackend._aset_task_state_store raises DagRunNotFound like the sync path.

GET decoding and response validation

GET awaits the configured backend’s aget_value. The default implementation runs json.loads in a worker thread. The backend guide explains that task GET calls aget_value and asset GET calls get_value. Backends returning native values in both paths should override both methods. GET also builds and validates the response model in a worker thread. FastAPI still serializes the response on the event loop. The task instance lookup passes region_index directly to TaskScope.

The HTTP contract does not change, so no Execution API version change is needed.

Benchmarks and Testing

GET event-loop stall measurements with both offloads

The table reports median loop stalls in ms for a 688.9 KB GET in each of three rounds. Each unpinned round used 10 warm requests per variant. The SQLite repeat used 30 warm requests per variant with CPU affinity and reversed variant order. The synchronous route, the async route with inline decoding and validation, and the async route with both offloads used the same dependencies within each comparison (Python 3.14.10, SQLAlchemy 2.0.57, Breeze CI image).

Backend Synchronous Async, inline Async, both offloads
SQLite 94 / 117 / 116 131 / 153 / 131 106 / 135 / 127
PostgreSQL 134 / 113 / 246 335 / 153 / 158 109 / 213 / 117
SQLite repeat 232 / 117 / 108 323 / 206 / 166 200 / 235 / 99

The synchronous baseline and the health endpoint control varied across rounds. The async route with both offloads had higher median stalls than the synchronous route in some rounds and lower medians in others. GET stall parity remains unverified.

Event-loop stall measurements from an earlier revision

The harness is adapted from the review of #74540. Each request runs over HTTP through TestClient from a separate thread. A 1 ms ticker on the server loop records its longest sleep per request. Every case asserts the status and the returned or stored value. 10 warm requests per case, cold request dropped, 2 rounds per version run interleaved in one container. GET/PUT values are integer arrays. Each cell shows median / max stall in ms for round 1; round 2.

  • base: the synchronous routes on main.
  • head: async routes without any offload.
  • offload: head plus offloading GET decoding/model building and PUT json.dumps.

This comparison used Python 3.14.8 and SQLAlchemy 2.0.54 in Breeze. The GET table above uses the backend default decoder and route response validation offloads now in the PR.

SQLite (aiosqlite)

Request Value base head offload
GET 0.4 KB 2 / 2; 2 / 3 3 / 4; 3 / 4 4 / 5; 3 / 4
GET 58.9 KB 14 / 17; 15 / 24 16 / 31; 14 / 31 16 / 28; 15 / 23
GET 688.9 KB 106 / 144; 119 / 200 144 / 217; 144 / 158 123 / 145; 102 / 139
PUT 0.4 KB 2 / 5; 3 / 6 3 / 6; 3 / 4 3 / 4; 3 / 5
PUT 58.9 KB 7 / 17; 9 / 17 11 / 15; 12 / 25 12 / 14; 12 / 25
PUT 688.9 KB 60 / 86; 81 / 159 89 / 109; 93 / 102 103 / 138; 100 / 119
DELETE - 2 / 3; 4 / 5 3 / 4; 4 / 4 4 / 8; 4 / 4
CLEAR, 1000 keys - 2 / 2; 2 / 3 3 / 4; 4 / 4 4 / 4; 4 / 4
CLEAR, 5000 keys - 2 / 3; 2 / 4 3 / 4; 3 / 3 3 / 4; 3 / 4

PostgreSQL (psycopg async)

Request Value base head offload
GET 0.4 KB 3 / 5; 3 / 4 5 / 5; 4 / 5 4 / 5; 4 / 5
GET 58.9 KB 19 / 27; 17 / 24 24 / 31; 21 / 27 19 / 27; 17 / 27
GET 688.9 KB 143 / 153; 147 / 155 206 / 256; 199 / 232 152 / 171; 127 / 153
PUT 0.4 KB 3 / 5; 3 / 4 4 / 4; 4 / 5 4 / 6; 4 / 6
PUT 58.9 KB 10 / 18; 12 / 16 18 / 25; 15 / 19 19 / 24; 18 / 20
PUT 688.9 KB 90 / 104; 86 / 95 133 / 161; 121 / 170 128 / 165; 125 / 138
DELETE - 3 / 4; 3 / 4 3 / 4; 4 / 6 4 / 4; 4 / 5
CLEAR, 1000 keys - 3 / 4; 3 / 4 4 / 5; 4 / 5 4 / 5; 3 / 5
CLEAR, 5000 keys - 3 / 5; 3 / 4 3 / 4; 4 / 6 4 / 5; 3 / 6

Findings:

  • PUT is above base, and I found no remedy inside the route. For a 689 KB value, the median stall is 15–78% above base, depending on backend and round. For a 59 KB value, it is 2–9 ms longer. Offloading json.dumps does not help (about 7 ms of the work). The loop-thread profiles show the same CPU on the loop in all three versions: three pydantic validations of the JsonValue body plus one cadwyn model_dump. The difference is where the loop gets a break. My reading of the code, which I have not instrumented directly: cadwyn's request migration re-runs FastAPI's solve_dependencies. With the synchronous SessionDep, that resolves the generator dependency through contextmanager_in_threadpool, which yields the loop in the middle of the framework work. AsyncSessionDep gives no such yield. A probe with await asyncio.sleep(0) at handler entry recovered only part of the gap (PostgreSQL, PUT only):

    Value base head head + yield
    58.9 KB 11 / 12; 10 / 15 18 / 26; 19 / 25 16 / 22; 16 / 26
    688.9 KB 79 / 91; 101 / 120 141 / 172; 145 / 183 124 / 145; 134 / 165

    PUT keeps the current handler. #77502 tracks the framework’s request-body cost and whether it affects other async Execution API routes that accept large JsonValue bodies.

  • Small requests: every route keeps the loop about 1 ms longer than base, because async SQLAlchemy work now runs on the loop instead of in a worker thread. Request duration is equal or lower.

I did not measure stalls on MySQL. The contract tests ran there.

Tests

  • The HTTP contract tests in versions/head/test_task_state_store.py pass. One test needed an adjustment, and one version test needed an adapted mock:
    • test_put_dagrun_deleted_after_scope_lookup_returns_404 (from Return 404 when a DagRun disappears during task API writes #72907) deletes the Dag run from a before_execute listener. It now listens on the async engine from the async_db_engine fixture, because the route no longer goes through the sync engine.
    • versions/v2026_10_30/test_task_state_store.py now autospecs the configured backend instance, so aset is an awaited mock that raises DagRunNotFound. Before, it patched the sync set.
  • test_routes_select_columns_without_loading_entities (all four routes) asserts that no ORM entity is loaded during the request. It fails on main, where TaskInstance and DagRun are loaded. Two negative controls confirm that it detects loads through AsyncSession: restoring the full-row value getter fails only the GET case, and restoring session.get(TI, ...) fails all four cases.
  • Regression tests check that the default backend decodes a valid JSON value in a worker thread and that GET constructs its response model off the event loop. On the rebased revision, the API offload guard, both route-version suites and the metastore tests ran in Breeze on Python 3.11 with SQLite (114 passed, 1 existing expected failure).
  • With both GET offloads in place, the two route-version suites and metastore tests passed locally in Breeze on SQLite, PostgreSQL and MySQL (112 passed each). The shared-state suite passed on the rebased revision (27 passed).

Checks run before the GET offload changes:

  • pytest with SQLite from the local workspace venv on the task state store route tests for both Execution API versions, the public API task state store tests and tests/unit/state: 216 passed, 3 skipped. The skipped tests require a named database backend.
  • mypy on the changed files, using the mypy-airflow-core hook's environment: no issues.
  • ruff format and ruff check on the changed files: clean.
  • Fork CI passed versions/head/test_task_state_store.py on SQLite, PostgreSQL and MySQL.


Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

Generated-by: Claude Code (Opus 5.5) and Codex (GPT-6) following the guidelines


  • Read the 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) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {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.

@boring-cyborg boring-cyborg Bot added area:API Airflow's REST/HTTP API area:task-sdk labels Oct 22, 2026
@Dev-iL Dev-iL added the fork ci required Gated by AIP-120: CI must pass in the contributor's fork. Managed by the fork CI reconciler. label Nov 2, 2026
@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch from ad30a47 to a5df87d Compare November 2, 2026 20:29
@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Fork CI: running. CI for the latest commit is running in your fork.

Pull requests from contributors run their CI in the contributor's own fork. GitHub Actions is free and has no minute limit on public forks, while the CI capacity of the Apache Software Foundation is shared by every ASF project and is finite.

Latest run: https://github.com/Dev-iL/airflow/actions/runs/45235407061

How this works: CI in your fork.


This comment was posted automatically by the fork CI monitor from templates drafted with an AI-assisted tool, so it may contain mistakes. An Apache Airflow maintainer, a real person, will review the pull request once its fork CI is green. Why the first pass is automated.

@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch from a5df87d to 58e2cc8 Compare November 5, 2026 15:22
@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch from 58e2cc8 to 010ca22 Compare November 14, 2026 07:20
@Dev-iL
Dev-iL marked this pull request as ready for review November 14, 2026 07:21
@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch from 010ca22 to a9925bb Compare November 14, 2026 09:18
@github-actions github-actions Bot added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Nov 14, 2026
@Dev-iL Dev-iL self-assigned this Nov 17, 2026
@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch from a9925bb to be42527 Compare November 21, 2026 11:34
@Dev-iL
Dev-iL requested a review from potiuk as a code owner November 21, 2026 11:34
@github-actions github-actions Bot removed the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Nov 21, 2026
@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch 2 times, most recently from 7603223 to 2e34ae6 Compare November 22, 2026 07:50
@github-actions github-actions Bot added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Nov 22, 2026
scope = _get_task_scope_for_ti(task_instance_id, session)
if (value := get_state_backend().get_value(scope, key, session=session)) is None:
scope = await _get_task_scope_for_ti(task_instance_id, session)
if (value := await get_state_backend().aget_value(scope, key, session=session)) is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A custom backend that overrides only get_value to skip decoding now gets the default json.loads here. Can you update task-and-asset-state-store.rst (it still says the Execution API reads through get_value) to say task state reads go through aget_value, so both need to be overridden?

scope = await _get_task_scope_for_ti(task_instance_id, session)
try:
get_state_backend().set(
await get_state_backend().aset(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About the PUT stall you raised: I am fine leaving it as is since the cost comes from the framework body handling and not from the route itself. Can you create an issue to track it? It probably affects every async Execution API route with a large JsonValue body.

Comment thread shared/state/tests/state/test_state.py Outdated
assert await backend.aget_value(AssetScope(name="asset"), "key") == expected

@pytest.mark.asyncio
@pytest.mark.parametrize("stored", ['{"a": [1]}', "invalid"])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the invalid case only tests that json.loads raises, I would drop it and remove the if/else from the test

Running tasks read and write their state store through these routes. As
synchronous routes, each request held a threadpool worker for every
database wait, competing with the rest of the Execution API for the same
workers. Native async database calls let the event loop serve other
requests during those waits.

Validating a large stored value into the response model is CPU work
that would otherwise block the event loop in an async route, so the read
route keeps it in a worker thread, as the synchronous route did.

related: apache#67799
@Dev-iL
Dev-iL force-pushed the 2610/async-task-state-store branch from 2e34ae6 to aacaf42 Compare November 23, 2026 18:09
@github-actions github-actions Bot removed the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:API Airflow's REST/HTTP API area:task-sdk fork ci required Gated by AIP-120: CI must pass in the contributor's fork. Managed by the fork CI reconciler.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants