Skip to content

Speed up Execution API state store requests with large values - #77113

Open
Dev-iL wants to merge 2 commits into
apache:mainfrom
Dev-iL:2611/unwalked-jsonvalue
Open

Dev-iL wants to merge 2 commits into
apache:mainfrom
Dev-iL:2611/unwalked-jsonvalue

Conversation

@Dev-iL

@Dev-iL Dev-iL commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

related: #67799

A task state store or asset state store request with a large value spends most of its CPU time in pydantic's checks on that value, not in the database. This PR adds a DecodedJsonValue type for already-decoded JSON and uses it for the value field of the four Execution API state store models:

  • TaskStateStoreResponse, TaskStateStorePutBody
  • AssetStateStoreResponse, AssetStateStorePutBody

For a 689 KB value, the median event loop stall drops by 70–85% (GET 126–153 ms → 34–35 ms, PUT 81–90 ms → 12–24 ms), and the median request duration by 39–68%. The published OpenAPI schema does not change, so the generated Task SDK models and the HTTP contract stay the same.

Details

  • Pydantic checks a JsonValue with a Python discriminator function (pydantic.types._get_type_name) that it calls once for every element, and it walks the value again to serialize it. A state store request does this several times: FastAPI validates the body, cadwyn dumps and re-validates it for the version migration, and a read validates and serializes the response. For a 100,000-element value, the loop-thread profile at the measured base below shows 400,004 calls for a GET and 300,003 for a PUT. On main these routes are synchronous, but this framework work runs on the event loop, so it already blocks every other request there.
  • DecodedJsonValue wraps the JsonValue schema with a validator that returns the value unchanged and a serializer that passes it through. The JSON schema is generated from the wrapped JsonValue, so the field still references the JsonValue component. The OpenAPI document of the Execution API app is identical before and after this change, and the generate-tasksdk-datamodels hook produces no diff.
  • The field validators that reject null and NaN values still run.
  • What remains on the loop for a large GET is rendering the response body: pydantic's to_python in JSON mode, which no longer calls back into Python, and the stdlib json encoder. Each takes about 14 ms for a 689 KB value under the profiler.

Behaviour differences:

  • A request body is always decoded JSON, so the walk could never reject one, and PUT accepts and rejects the same bodies as before.
  • A read returns what the state backend's get_value returns. With the built-in backends, this is the decoded JSON from storage. A custom backend that overrides get_value and returns a Python object that is not JSON, such as a datetime, got a 500 before, because the response model rejected it. Now pydantic serializes it by inferring its type, as it does for an Any field (a datetime becomes an ISO 8601 string). I left this unguarded because get_value is typed to return JsonValue, so such a backend already breaks its contract.

Not in this PR:

  • The XCom models (execution_api/datamodels/xcom.py) and the public API state store models have the same JsonValue fields. I want to measure those routes before changing them, and I will open follow-ups.
  • Upstream pydantic merged Improve performance of JsonValue Python serialization pydantic/pydantic#13995 ("Improve performance of JsonValue Python serialization") on 2026-10-14. It is not in a release yet (the latest is 2.14.3), and it covers serialization only. Validation, which is most of the PUT cost, still walks every element.
  • Make task state store Execution API routes async #75381 converts the task state store routes to async and is independent of this PR. The two do not touch the same files, and earlier runs of a functionally identical revision of this type on top of it showed the same gain.

Benchmarks and Testing

Event-loop stall measurements

The harness is the one from #75381. 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. Values are integer arrays.

  • base: main at 5addde0337, with synchronous routes. This PR's parent (ce559e40ef) is 18 commits newer; none of them touch api_fastapi, the state store code or uv.lock.
  • this PR: base plus this PR's airflow-core/src diff, applied unchanged.

Each stall cell shows median / max in ms, and each duration cell the median request duration in ms, for round 1; round 2.

Python 3.14.10, SQLAlchemy 2.0.57, FastAPI 0.162.0, cadwyn 8.2.0, pydantic 2.14.2, Breeze CI image. These are small local samples of event-loop availability, not throughput. Only the task state store routes were measured; the asset state store routes use the same type.

SQLite (aiosqlite)

Request Value base stall this PR stall base duration this PR duration
GET 0.4 KB 2 / 7; 3 / 5 3 / 4; 3 / 4 22; 22 22; 21
GET 58.9 KB 25 / 36; 24 / 25 8 / 10; 9 / 10 52; 53 28; 27
GET 688.9 KB 133 / 137; 126 / 151 34 / 38; 34 / 41 228; 199 79; 80
PUT 0.4 KB 4 / 7; 2 / 4 5 / 6; 3 / 4 26; 14 26; 24
PUT 58.9 KB 15 / 17; 8 / 20 6 / 7; 3 / 4 51; 28 34; 19
PUT 688.9 KB 81 / 84; 82 / 92 24 / 28; 24 / 28 190; 189 98; 94

PostgreSQL (psycopg async)

Request Value base stall this PR stall base duration this PR duration
GET 0.4 KB 4 / 6; 4 / 6 4 / 5; 4 / 4 26; 26 25; 26
GET 58.9 KB 25 / 31; 29 / 36 7 / 8; 7 / 8 56; 61 32; 32
GET 688.9 KB 135 / 137; 153 / 225 35 / 42; 34 / 35 240; 260 88; 89
PUT 0.4 KB 3 / 4; 4 / 5 4 / 4; 3 / 4 30; 32 31; 30
PUT 58.9 KB 15 / 16; 17 / 20 3 / 5; 4 / 5 62; 65 22; 43
PUT 688.9 KB 81 / 85; 90 / 100 12 / 18; 24 / 35 251; 263 81; 161

Small values do not change beyond noise. The PostgreSQL PUT rounds of this PR differ (81 ms and 161 ms for 689 KB); both are below base.

Tests

TestDecodedJsonValue has three tests:

  • test_validation_returns_decoded_containers_unchanged asserts that validation returns the same list or dict object.
  • test_serialization_skips_the_json_value_checks serializes a datetime with pydantic's serializer warnings turned into errors. Plain JsonValue produces the same output but warns that the value is none of its members.
  • test_model_field_publishes_the_json_value_schema compares the JSON schema of a model field, in validation and serialization mode, with a plain JsonValue field. The comparison has to be on a model field: for a bare TypeAdapter, Any and JsonValue publish the same schema.

Each test fails under at least one of the implementations I tried and rejected:

DecodedJsonValue defined as Failing tests
plain JsonValue validation (both cases), serialization
this type without the pass-through serializer serialization
Any (drops the $ref) schema (both modes)
SkipValidation[JsonValue] (adds title: Value) serialization, schema (both modes)

The existing route tests cover the null and NaN rejection and the round trip of stored values through both versions of the API.

Checks run on this revision, in Breeze with Python 3.14.10:

  • tests/unit/api_fastapi/common/test_types.py, execution_api/versions/head/test_task_state_store.py, execution_api/versions/head/test_asset_state_store.py, execution_api/versions/v2026_10_30/test_task_state_store.py and execution_api/test_app.py: 153 passed on each backend:
    • SQLite (sqlite / sqlite+aiosqlite)
    • PostgreSQL (postgresql+psycopg / postgresql+psycopg_async)
    • MySQL (mysql / mysql+asyncmy)
  • prek run mypy-airflow-core on the changed files: no issues.
  • prek run --stage pre-commit on the changed files: passed, including generate-tasksdk-datamodels with no diff.


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

Generated-by: Claude Code (Opus 5.5) 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 Nov 15, 2026
@github-actions github-actions Bot 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 15, 2026
@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Fork CI: green. CI for the latest commit passed in your fork. The pull request is ready for maintainer review.

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.

Fork CI tested this branch merged with main at 6c0e890415, as project CI would, 7 commits behind main when the run turned green.

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

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 marked this pull request as ready for review November 15, 2026 12:34
@Dev-iL
Dev-iL requested a review from dabla November 15, 2026 12:35
@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 15, 2026
@Dev-iL Dev-iL self-assigned this Nov 17, 2026

@ashb ashb left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Shouldn't the same treatment be applied to XCom responses as well?

@ashb

ashb commented Nov 19, 2026

Copy link
Copy Markdown
Member

@Dev-iL

Dev-iL commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Shouldn't the same treatment be applied to XCom responses as well?

Yes, this is noted in the description under the "Not in this PR" section:

The XCom models (execution_api/datamodels/xcom.py) and the public API state store models have the same JsonValue fields. I want to measure those routes before changing them, and I will open follow-ups.

I agree the same cost most likely applies. I scoped this PR to the state stores because those are the routes I measured. I’d like to measure the XCom response paths and check their value sources before applying the same treatment in a follow-up.


The pydantic docs say this https://pydantic.dev/docs/validation/latest/concepts/performance/#dont-do-validation-when-you-dont-have-to-use-any-to-keep-the-value-unchanged

I tried plain Any and SkipValidation[JsonValue]. Plain Any changes the published field schema, and SkipValidation[JsonValue] changes the schema and retains the JsonValue serialization checks. The custom type preserves the existing schema while skipping both walks. I may have missed a simpler combination of Pydantic’s built-ins, though; I’m happy to check one if you have it in mind.

Pydantic checks and serializes a JsonValue field by calling a Python
function for every element of the value, and a state store request runs
that walk several times: FastAPI validates the body, cadwyn dumps and
re-validates it for the version migration, and a read validates and
serializes the response. For a value of a few hundred kilobytes this
costs tens of milliseconds of CPU per request, and because the framework
does this work on the event loop, it holds up every other request the
API server is handling, even though the routes themselves are
synchronous.

These values are already decoded JSON, either a request body or a value
the state backend decoded from storage, so the walk has nothing to
reject. Passing them through unchanged removes that cost and keeps the
published OpenAPI schema, and therefore the generated Task SDK models,
the same.

related: apache#67799
@Dev-iL
Dev-iL force-pushed the 2611/unwalked-jsonvalue branch from 4446eb0 to 99ad649 Compare November 19, 2026 21:49
@github-actions github-actions Bot added ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. and removed ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. labels Nov 19, 2026
@Dev-iL
Dev-iL requested a review from ashb November 20, 2026 09:13
@Dev-iL

Dev-iL commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

@ashb could you take another look please?

@dabla dabla left a comment

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.

Addressed

  • Thread on common/types.py ("Is there really not a type built in to pydantic that does this already for us?"): the head builds the type from pydantic's public annotations only (WrapValidator + SerializeAsAny). Checked on pydantic 2.14.2 and on the minimum supported 2.12.0: validation returns the same object, a 100,000-element list makes 0 calls to pydantic.types._get_type_name on validation and on model_dump(mode="json") (100,001 each with plain JsonValue), and the field's JSON schema equals the JsonValue one in both modes.

Open

  • Inline comment [1], a docstring nit; nothing blocking.
  • The question whether plain Any would do (issue comment, answered by the author with the schema difference) is between the author and the reviewer who asked; I have nothing to add to it.

The pass: head 99ad649653, diff-based, with the full files read at that commit and probes run against the PR's code. What I checked beyond the diff:

  • Versioned models. cadwyn regenerates the models per API version, so I generated them for all 11 versions with the PR's code: each one keeps the pass-through (0 discriminator calls, same object back), publishes the same schema for TaskStateStorePutBody and TaskStateStoreResponse as before the change, and still rejects null and a top-level NaN.
  • No leak onto JsonValue. SerializeAsAny sets the serializer on the schema it wraps; a plain JsonValue field in the same model, or in a model defined afterwards, still validates and still warns on a non-JSON value.
  • Accepted and rejected bodies. Through model_validate_json, the old and the new PUT body accept and reject the same inputs (nested NaN was accepted before and still is). The only difference is for Python objects that are not JSON, which a request body cannot contain.
  • Other consumers. The public API models with the same names live in core_api/datamodels and are untouched, as the description says.
  • Tests. The five test files the description names, run on this head with SQLite: 153 passed, the count the description gives. I did not run PostgreSQL or MySQL locally. CI is green (7 passed, 1 skipped).
  • Call counts. Profiling the server loop thread for one request with a 100,000-element value: the base (6c0e890415) makes 300,003 _get_type_name calls for a PUT and 400,004 for a GET, exactly the numbers in the description; this head makes 0 for both.
  • Rejected implementations. I re-ran the three TestDecodedJsonValue assertions against plain JsonValue, the type without SerializeAsAny, Any and SkipValidation[JsonValue]: each fails the tests the description's table says it fails.
  • Stall benchmark. A harness of my own built to the description (requests through TestClient from the test thread, a 1 ms ticker on the server loop, status and value asserted, 10 warm requests after a dropped cold one, 2 rounds per version interleaved), base 6c0e890415 against this head, SQLite only, Python 3.12.3, pydantic 2.14.2, FastAPI 0.162.0, outside Breeze. Cells are median / max stall and median duration in ms, round 1; round 2:
Request Value base stall this PR stall base duration this PR duration
GET 0.4 KB 3 / 4; 2 / 3 2 / 3; 2 / 4 18; 16 17; 15
GET 58.9 KB 12 / 14; 12 / 13 3 / 5; 3 / 4 29; 26 17; 19
GET 688.9 KB 84 / 615; 78 / 101 18 / 30; 17 / 21 131; 121 41; 41
PUT 0.4 KB 3 / 4; 3 / 5 2 / 3; 3 / 4 21; 19 23; 20
PUT 58.9 KB 7 / 9; 7 / 9 3 / 5; 3 / 5 32; 31 24; 22
PUT 688.9 KB 51 / 69; 46 / 72 9 / 12; 10 / 12 125; 109 45; 53

For the 689 KB value the median stall drops by 77–79% on GET and 78–83% on PUT, and the median duration by 51–69%, which is in line with the 70–85% and 39–68% the description reports; small values do not change. My absolute numbers are lower than the description's (another machine and Python 3.12 instead of 3.14). The 615 ms maximum in the first base round is a single outlier.


Pydantic validates and serializes ``JsonValue`` with a Python callback for every element, which takes
tens of milliseconds for a value of a few hundred kilobytes. Decoded JSON cannot fail that check, so this
type passes the value through unchanged while publishing the same schema as ``JsonValue``.

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 docstring could say that the precondition is the caller's and is no longer checked.

"Decoded JSON cannot fail that check" is true, but the type itself now accepts anything. With this definition a model field takes a tuple, a set, a datetime, bytes or a dict with int keys, all of which plain JsonValue rejects, and on the way out they are serialized by inferred type (bytes that are not UTF-8 and arbitrary objects still raise). The PR description explains this for a custom backend's get_value, but the next person who reaches for the type (the XCom follow-up, where values do not always come straight from a JSON column) only sees the docstring. One sentence would do, for example: "The type does not check this: use it only where the value is known to be decoded JSON, because anything else is accepted and serialized by inferring its type."

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. ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants