Repository navigation
Conversation
|
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 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. |
ashb
left a comment
There was a problem hiding this comment.
Shouldn't the same treatment be applied to XCom responses as well?
|
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
|
Yes, this is noted in the description under the "Not in this PR" section:
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.
I tried plain |
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
4446eb0 to
99ad649
Compare
|
@ashb could you take another look please? |
dabla
left a comment
There was a problem hiding this comment.
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 topydantic.types._get_type_nameon validation and onmodel_dump(mode="json")(100,001 each with plainJsonValue), and the field's JSON schema equals theJsonValueone in both modes.
Open
- Inline comment [1], a docstring nit; nothing blocking.
- The question whether plain
Anywould 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
TaskStateStorePutBodyandTaskStateStoreResponseas before the change, and still rejectsnulland a top-level NaN. - No leak onto
JsonValue.SerializeAsAnysets the serializer on the schema it wraps; a plainJsonValuefield 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/datamodelsand 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_namecalls 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
TestDecodedJsonValueassertions against plainJsonValue, the type withoutSerializeAsAny,AnyandSkipValidation[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
TestClientfrom 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), base6c0e890415against this head, SQLite only, Python 3.12.3, pydantic 2.14.2, FastAPI 0.162.0, outside Breeze. Cells aremedian / maxstall 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``. |
There was a problem hiding this comment.
[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."
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
DecodedJsonValuetype for already-decoded JSON and uses it for thevaluefield of the four Execution API state store models:TaskStateStoreResponse,TaskStateStorePutBodyAssetStateStoreResponse,AssetStateStorePutBodyFor 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
JsonValuewith 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. Onmainthese routes are synchronous, but this framework work runs on the event loop, so it already blocks every other request there.DecodedJsonValuewraps theJsonValueschema with a validator that returns the value unchanged and a serializer that passes it through. The JSON schema is generated from the wrappedJsonValue, so the field still references theJsonValuecomponent. The OpenAPI document of the Execution API app is identical before and after this change, and thegenerate-tasksdk-datamodelshook produces no diff.nulland NaN values still run.to_pythonin JSON mode, which no longer calls back into Python, and the stdlibjsonencoder. Each takes about 14 ms for a 689 KB value under the profiler.Behaviour differences:
get_valuereturns. With the built-in backends, this is the decoded JSON from storage. A custom backend that overridesget_valueand returns a Python object that is not JSON, such as adatetime, got a 500 before, because the response model rejected it. Now pydantic serializes it by inferring its type, as it does for anAnyfield (adatetimebecomes an ISO 8601 string). I left this unguarded becauseget_valueis typed to returnJsonValue, so such a backend already breaks its contract.Not in this PR:
execution_api/datamodels/xcom.py) and the public API state store models have the sameJsonValuefields. I want to measure those routes before changing them, and I will open follow-ups.JsonValuePython serialization pydantic/pydantic#13995 ("Improve performance ofJsonValuePython 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.Benchmarks and Testing
Event-loop stall measurements
The harness is the one from #75381. 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. Values are integer arrays.mainat5addde0337, with synchronous routes. This PR's parent (ce559e40ef) is 18 commits newer; none of them touchapi_fastapi, the state store code oruv.lock.airflow-core/srcdiff, applied unchanged.Each stall cell shows
median / maxin 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)
PostgreSQL (psycopg async)
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
TestDecodedJsonValuehas three tests:test_validation_returns_decoded_containers_unchangedasserts that validation returns the same list or dict object.test_serialization_skips_the_json_value_checksserializes adatetimewith pydantic's serializer warnings turned into errors. PlainJsonValueproduces the same output but warns that the value is none of its members.test_model_field_publishes_the_json_value_schemacompares the JSON schema of a model field, in validation and serialization mode, with a plainJsonValuefield. The comparison has to be on a model field: for a bareTypeAdapter,AnyandJsonValuepublish the same schema.Each test fails under at least one of the implementations I tried and rejected:
DecodedJsonValuedefined asJsonValueAny(drops the$ref)SkipValidation[JsonValue](addstitle: Value)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.pyandexecution_api/test_app.py: 153 passed on each backend:sqlite/sqlite+aiosqlite)postgresql+psycopg/postgresql+psycopg_async)mysql/mysql+asyncmy)prek run mypy-airflow-coreon the changed files: no issues.prek run --stage pre-commiton the changed files: passed, includinggenerate-tasksdk-datamodelswith no diff.Was generative AI tooling used to co-author this PR?
Generated-by: Claude Code (Opus 5.5) 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.