Repository navigation
Conversation
ad30a47 to
a5df87d
Compare
|
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. |
a5df87d to
58e2cc8
Compare
58e2cc8 to
010ca22
Compare
010ca22 to
a9925bb
Compare
a9925bb to
be42527
Compare
7603223 to
2e34ae6
Compare
| 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: |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
| assert await backend.aget_value(AssetScope(name="asset"), "key") == expected | ||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize("stored", ['{"a": [1]}', "invalid"]) |
There was a problem hiding this comment.
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
2e34ae6 to
aacaf42
Compare
related: #67799
This PR converts the four Execution API task state store routes to
async defwithAsyncSessionDep: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:
aget/aset/adelete/aclearwith the route's session. These methods are abstract onBaseStoreBackend, 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 thecommon.ioobject-storage backend does so.working_set IS TRUE. Before,session.get(TI, ...)loaded the full task instance and its joined Dag run.MetastoreBackend._aget_task_state_storeselects onlyvalueinstead of the full row. The column isNOT NULL, so a missing key still returnsNone.ReturnNotFoundForMissingDagRun404 handling that Return 404 when a DagRun disappears during task API writes #72907 added to PUT is kept around the asyncasetcall.MetastoreBackend._aset_task_state_storeraisesDagRunNotFoundlike the sync path.GET decoding and response validation
GET awaits the configured backend’s
aget_value. The default implementation runsjson.loadsin a worker thread. The backend guide explains that task GET callsaget_valueand asset GET callsget_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 passesregion_indexdirectly toTaskScope.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).
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
TestClientfrom 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 showsmedian / maxstall in ms for round 1; round 2.main.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)
PostgreSQL (psycopg async)
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.dumpsdoes 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 theJsonValuebody plus one cadwynmodel_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'ssolve_dependencies. With the synchronousSessionDep, that resolves the generator dependency throughcontextmanager_in_threadpool, which yields the loop in the middle of the framework work.AsyncSessionDepgives no such yield. A probe withawait asyncio.sleep(0)at handler entry recovered only part of the gap (PostgreSQL, PUT only):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
JsonValuebodies.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
versions/head/test_task_state_store.pypass. 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 abefore_executelistener. It now listens on the async engine from theasync_db_enginefixture, because the route no longer goes through the sync engine.versions/v2026_10_30/test_task_state_store.pynow autospecs the configured backend instance, soasetis an awaited mock that raisesDagRunNotFound. Before, it patched the syncset.test_routes_select_columns_without_loading_entities(all four routes) asserts that no ORM entity is loaded during the request. It fails onmain, whereTaskInstanceandDagRunare loaded. Two negative controls confirm that it detects loads throughAsyncSession: restoring the full-row value getter fails only the GET case, and restoringsession.get(TI, ...)fails all four cases.Checks run before the GET offload changes:
pytestwith 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 andtests/unit/state: 216 passed, 3 skipped. The skipped tests require a named database backend.mypyon the changed files, using themypy-airflow-corehook's environment: no issues.ruff formatandruff checkon the changed files: clean.versions/head/test_task_state_store.pyon SQLite, PostgreSQL and MySQL.Was generative AI tooling used to co-author this PR?
Generated-by: Claude Code (Opus 5.5) and Codex (GPT-6) following the guidelines
{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.