Repository navigation
Conversation
0b8adb7 to
e36fac8
Compare
|
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 Latest run: https://github.com/Dev-iL/airflow/actions/runs/44750526051 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. |
e36fac8 to
a3fe4cc
Compare
a3fe4cc to
9679c1a
Compare
shahar1
left a comment
There was a problem hiding this comment.
The conversion and the offloading read correctly, and I found no break in the HTTP contract or the pool-wait reasoning, but XCom writes now go through an async engine that lacks the sync engine's MySQL session setup, which stores wrong timestamps on a non-UTC server. That should be settled before this merges.
XCom writes use an async engine without the MySQL session setup (airflow-core/src/airflow/api_fastapi/execution_api/routes/xcoms.py:790)
Details are in the inline comment. The sync engine's setup carries these two source comments:
this ensures coherence in mysql when storing datetimes (not required for postgres)
(airflow-core/src/airflow/utils/orm_event_handlers.py)
The default isolation level for MySQL (REPEATABLE READ) can introduce inconsistencies when running multiple schedulers, as repeated queries on the same session may read from stale snapshots.
(airflow-core/src/airflow/settings.py)
Smaller observations
xcoms.py:612(inline): the owner check keeps its async connection checked out while the lookup runs on a worker thread.- PR description, benchmark table: the PostgreSQL large-value row reports a median of about 165 ms but a maximum of 553 and 556 ms in the two runs. SQLite's maximum is 156 and 175 ms. The stall is still well below
main, but a near-identical half-second outlier in both runs looks systematic. Do you know what causes it? The harness isn't in the PR, so reviewers can't check.
This review was drafted by an AI-assisted tool and
confirmed by an Apache Airflow maintainer. The findings
below are observations, not blockers; an Apache Airflow
maintainer — a real person — will take the next look at the
PR. If you think a finding is mis-applied, please reply on
the PR and a maintainer will weigh in.More on how Apache Airflow handles maintainer review:
Contributing guide.
9679c1a to
81d58f1
Compare
On the ~550 ms PostgreSQL maximum for the large value: I re-measured and couldn't reproduce it, and I can't name its cause. I re-ran it in Breeze, PostgreSQL, Python 3.14.10, SQLAlchemy 2.0.55, alternating base (
Longer head runs stayed in the same range: 40 warm requests twice, 160 / 234 and 171 / 251, then 150 warm requests, 156 / 259. Across 230 warm requests the largest stall was 259 ms. With the review changes, measured at What I could rule out, from the probe below, which records garbage-collector pauses and which thread they ran on:
On the loop, each large read now spends about 95 ms in psycopg's JSON decoding and about 60 + 57 ms in Cadwyn's decode and re-encode of the Probe (disposable, not part of the PR)Copy it to breeze run --python 3.14 --backend postgres bash -c "python dev/xcom_stall_probe.py --scenario big --requests 11 --label head --out dev/xcom_stall_out.jsonl"#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Event-loop stall probe for the Execution API XCom routes (disposable; not part of any PR).
Run inside Breeze from the checkout root, e.g.:
breeze run --python 3.14 --backend postgres bash -c "python dev/xcom_stall_probe.py \
--scenario big --requests 11 --label head-run1 --out dev/xcom_stall_out.jsonl"
The probe is injected into pytest collection of the Execution API XCom test module, so it gets that
directory's ``client``, ``dag_maker``, ``session`` and ``exec_app`` fixtures. A 1 ms ticker on the
server's event loop records each sleep's own duration; the maximum during a request is its stall. The
HTTP request goes through ``client`` from a worker thread, so routing, dependencies, validation and
serialization are all measured. Every response's status and size are asserted.
Per request it also records:
- connections: checkouts from the sync and async pools, and the peak number held at once;
- async_idle_ms: time the async connection stayed checked out while a sync connection was also out;
- gc: garbage-collector pauses, with the thread they ran on (loop thread or not).
"""
from __future__ import annotations
import argparse
import asyncio
import gc
import json
import os
import statistics
import sys
import threading
import time
import pytest
from fastapi import Request
TEST_MODULE = "airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_xcoms.py"
SCENARIOS = ("big", "small-owner", "small-multiteam", "loop-cold", "loop-warm")
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--scenario", choices=SCENARIOS, required=True)
parser.add_argument("--requests", type=int, default=11)
parser.add_argument("--label", required=True)
parser.add_argument("--out", required=True)
parser.add_argument("--profile", action="store_true", help="profile the loop thread on 1 extra request")
parser.add_argument("--loop-tasks", type=int, default=1000)
return parser.parse_args()
ARGS = parse_args()
class PoolTracker:
"""Track checkouts across the sync and async pools of the metadata DB."""
def __init__(self):
self.lock = threading.Lock()
self.reset()
def reset(self):
with self.lock:
self.held = {"sync": 0, "async": 0}
self.checkouts = {"sync": 0, "async": 0}
self.peak = 0
self.async_out_since = None
self.overlap_start = None
self.overlap_ms = 0.0
def _total(self):
return self.held["sync"] + self.held["async"]
def _update_overlap(self, now):
both = self.held["sync"] > 0 and self.held["async"] > 0
if both and self.overlap_start is None:
self.overlap_start = now
elif not both and self.overlap_start is not None:
self.overlap_ms += (now - self.overlap_start) * 1000
self.overlap_start = None
def install(self, sync_engine, async_engine):
from sqlalchemy import event
for kind, engine in (("sync", sync_engine), ("async", async_engine.sync_engine)):
def on_checkout(dbapi_conn, record, proxy, kind=kind):
with self.lock:
self.held[kind] += 1
self.checkouts[kind] += 1
self.peak = max(self.peak, self._total())
self._update_overlap(time.monotonic())
def on_checkin(dbapi_conn, record, kind=kind):
with self.lock:
self.held[kind] = max(0, self.held[kind] - 1)
self._update_overlap(time.monotonic())
event.listen(engine.pool, "checkout", on_checkout)
event.listen(engine.pool, "checkin", on_checkin)
def snapshot(self):
with self.lock:
if self.overlap_start is not None:
self._update_overlap(time.monotonic())
return {
"checkouts": dict(self.checkouts),
"peak_held": self.peak,
"both_pools_held_ms": round(self.overlap_ms, 2),
}
class GcTracker:
def __init__(self):
self.events = []
self.loop_thread = None
self._start = {}
def __call__(self, phase, info):
tid = threading.get_ident()
if phase == "start":
self._start[tid] = time.monotonic()
elif tid in self._start:
ms = (time.monotonic() - self._start.pop(tid)) * 1000
self.events.append(
{"gen": info["generation"], "ms": round(ms, 2), "on_loop": tid == self.loop_thread}
)
def take(self):
events, self.events = self.events, []
return events
def seed_big(dag_maker, session):
from airflow.models.xcom import XComModel
from airflow.providers.standard.operators.empty import EmptyOperator
with dag_maker(dag_id="stall_big", serialized=True):
EmptyOperator(task_id="producer") >> EmptyOperator(task_id="consumer")
dr = dag_maker.create_dagrun()
tis = {ti.task_id: ti for ti in dr.task_instances}
value = [{"index": i, "name": f"item-{i:06d}"} for i in range(100_000)]
XComModel.set_for_attempt(
task_instance_id=tis["producer"].id, key="big", value=value, serialize=False, session=session
)
session.commit()
url = f"/execution/xcoms/{dr.dag_id}/{dr.run_id}/producer/big"
return url, tis["consumer"], lambda body: len(body["value"]) == 100_000
def seed_small(dag_maker, session):
from airflow.models.xcom import XComModel
from airflow.providers.standard.operators.empty import EmptyOperator
with dag_maker(dag_id="stall_small", serialized=True):
EmptyOperator(task_id="producer") >> EmptyOperator(task_id="consumer")
dr = dag_maker.create_dagrun()
tis = {ti.task_id: ti for ti in dr.task_instances}
XComModel.set_for_attempt(
task_instance_id=tis["producer"].id, key="small", value={"a": 1}, serialize=False, session=session
)
session.commit()
url = f"/execution/xcoms/{dr.dag_id}/{dr.run_id}/producer/small"
return url, tis["consumer"], lambda body: body["value"] == {"a": 1}
def seed_loop(dag_maker, session):
from airflow.models.dynamic_region import DynamicRegion
from airflow.models.xcom import XComModel
from airflow.providers.standard.operators.empty import EmptyOperator
from airflow.sdk import task_group
from airflow.sdk.definitions._internal.loop import create_loop
@task_group
def body():
EmptyOperator(task_id="producer") >> EmptyOperator(task_id="consumer")
with dag_maker(dag_id="stall_loop", serialized=True):
start = EmptyOperator(task_id="outside")
start >> create_loop(body, max_iterations=3)
for i in range(ARGS.loop_tasks):
start >> EmptyOperator(task_id=f"filler_{i:04d}")
dr = dag_maker.create_dagrun()
region = DynamicRegion.get_or_create(dag_id=dr.dag_id, run_id=dr.run_id, node_id="body", session=session)
session.add(region)
session.flush()
tis = {ti.task_id: ti for ti in dr.task_instances}
producer, consumer = tis["body.producer"], tis["body.consumer"]
producer.region_id, producer.region_index = region.id, 1
consumer.region_id, consumer.region_index = region.id, 1
session.flush()
XComModel.set_for_attempt(
task_instance_id=producer.id, key="key", value="current", serialize=False, session=session
)
session.commit()
url = f"/execution/xcoms/{dr.dag_id}/{dr.run_id}/{producer.task_id}/key"
return url, consumer, lambda body: body["value"] == "current"
def probe(client, dag_maker, session, exec_app):
from airflow import settings
from airflow.api_fastapi.execution_api.datamodels.token import TIClaims, TIToken
from airflow.api_fastapi.execution_api.security import require_auth
from tests_common.test_utils.config import conf_vars
scenario = ARGS.scenario
seed = {"big": seed_big, "loop-cold": seed_loop, "loop-warm": seed_loop}.get(scenario, seed_small)
url, caller, check = seed(dag_maker, session)
session.close()
async def authenticated(request: Request) -> TIToken:
return TIToken(id=caller.id, claims=TIClaims(scope="execution"))
exec_app.dependency_overrides[require_auth] = authenticated
pools = PoolTracker()
pools.install(settings.engine, settings.async_engine)
gc_tracker = GcTracker()
gc.callbacks.append(gc_tracker)
import sqlalchemy
env = {
"python": sys.version.split()[0],
"sqlalchemy": sqlalchemy.__version__,
"async_driver": settings.async_engine.url.drivername,
"sync_driver": settings.engine.url.drivername,
"loadavg": os.getloadavg(),
}
def one_request(profile=False):
if scenario == "loop-cold":
exec_app.state.dag_bag.clear_cache()
pools.reset()
gc_tracker.take()
async def run():
gc_tracker.loop_thread = threading.get_ident()
stalls: list[float] = []
done = asyncio.Event()
async def ticker():
while not done.is_set():
t0 = time.monotonic()
await asyncio.sleep(0.001)
stalls.append((time.monotonic() - t0) * 1000)
task = asyncio.create_task(ticker())
await asyncio.sleep(0.01)
stalls.clear()
prof = None
if profile:
import cProfile
prof = cProfile.Profile()
prof.enable()
t0 = time.monotonic()
response = await asyncio.to_thread(client.get, url)
elapsed = (time.monotonic() - t0) * 1000
if prof is not None:
prof.disable()
done.set()
await task
return response, elapsed, stalls, prof
response, elapsed, stalls, prof = client.portal.call(run)
assert response.status_code == 200, response.text[:500]
assert check(response.json()), response.text[:200]
return {
"request_ms": round(elapsed, 2),
"stall_max_ms": round(max(stalls), 2) if stalls else 0.0,
"ticks": len(stalls),
"bytes": len(response.content),
**pools.snapshot(),
"gc": gc_tracker.take(),
}, prof
ctx = conf_vars({("core", "multi_team"): "True"}) if scenario == "small-multiteam" else None
if ctx is not None:
ctx.__enter__()
try:
samples = [one_request()[0] for _ in range(ARGS.requests)]
profile_text = None
if ARGS.profile:
import io
import pstats
_, prof = one_request(profile=True)
buf = io.StringIO()
pstats.Stats(prof, stream=buf).sort_stats("tottime").print_stats(25)
profile_text = buf.getvalue()
finally:
if ctx is not None:
ctx.__exit__(None, None, None)
gc.callbacks.remove(gc_tracker)
warm = samples[1:]
summary = {
"label": ARGS.label,
"scenario": scenario,
"env": env,
"stall_median_ms": round(statistics.median(s["stall_max_ms"] for s in warm), 2),
"stall_max_ms": round(max(s["stall_max_ms"] for s in warm), 2),
"request_median_ms": round(statistics.median(s["request_ms"] for s in warm), 2),
"peak_held_max": max(s["peak_held"] for s in warm),
"checkouts_last": warm[-1]["checkouts"],
"both_pools_held_median_ms": round(statistics.median(s["both_pools_held_ms"] for s in warm), 2),
"samples": samples,
"profile": profile_text,
}
with open(ARGS.out, "a") as f:
f.write(json.dumps(summary) + "\n")
print(
f"RESULT {ARGS.label} {scenario}: stall median/max {summary['stall_median_ms']}/"
f"{summary['stall_max_ms']} ms, request median {summary['request_median_ms']} ms, "
f"peak held {summary['peak_held_max']}, both-pools median {summary['both_pools_held_median_ms']} ms, "
f"per-request stalls {[s['stall_max_ms'] for s in samples]}"
)
class _Swap:
@pytest.hookimpl(trylast=True)
def pytest_collection_modifyitems(self, session, config, items):
anchor = next(item for item in items if isinstance(item.parent, pytest.Module))
items[:] = [pytest.Function.from_parent(anchor.parent, name="xcom_stall_probe", callobj=probe)]
if __name__ == "__main__":
sys.exit(pytest.main([TEST_MODULE, "-x", "-q", "-p", "no:cacheprovider", "-s"], plugins=[_Swap()]))Drafted-by: Claude Code (Opus 5.5) (no human review before posting) |
81d58f1 to
4531b90
Compare
4531b90 to
b8fc013
Compare
b8fc013 to
09d893d
Compare
dabla
left a comment
There was a problem hiding this comment.
Addressed
- MySQL session time zone on the async engine (@shahar1, r4484303049): the base of this head calls
setup_event_handlers(async_engine.sync_engine)in_configure_async_session(#76505), so the wrong-timestamp case is gone. - MySQL isolation level (same thread): #76694 is merged and this head is rebased on it;
_configure_async_sessionnow applies_get_isolation_level_argsto the async engine. The MySQL note in the description can go. - Async connection held across the producer lookup (@shahar1, r4484303058): the archived-caller check now runs inside the lookup's own sync session, and
has_xcom_accessand_resolve_trigger_tokenquery in short sessions of their own. Read in the source; the twoholds_no_route_connectiontests cover it.
Open
- Inline [1] (nit) and [2] (warning).
- PR description: "a request holding an async connection may wait for a sync one" contradicts the table above it, which says no request holds both. One of the two sentences is out of date.
Reviewed at b8fc01325b from a local checkout; the head was rebased to 09d893db45 since, with no change to the PR's own lines, and the comments are anchored on the new head. I read the full source of the route module and the helpers it calls. What I checked and found as intended: the working-set filter is registered on Session itself, so it also applies to the AsyncSession reads; no dependency of these routes sets a response header that returning a JSONResponse would drop (the refreshed token is set by middleware); no Cadwyn version change migrates the three XCom response models; the statements _build_xcom_read returns carry no session state; the 410/404 order of the archived-caller check is the same as on main; set_for_attempt and delete_for_attempts under run_sync are SQL only, which matches the rule in #67799. Nothing outside the module calls the changed helpers except the in-process override of has_xcom_access. I did not run the tests locally (the run timed out on my machine) and rely on the fork CI, which is green; the benchmarks were not re-run.
09d893d to
c8b22ea
Compare
Ordinary XCom database waits should not occupy the worker pool shared with synchronous endpoints. A queued renderer should not retain a scarce async connection either. Cold Dag deserialization and large-value encoding still need isolation from the event loop. PostgreSQL comparisons of the lookup alternatives favor the async common path: at sixteen clients, ordinary reads gain 39% throughput and writes gain 15% over the unconditional bridge. Warm regional reads lose 12-15%, and about 25% under sync-endpoint contention, because their preflight and second async checkout have a cost. Releasing the connection avoids holding both pools together; retaining it gives no consistent throughput win. Against main, three alternating runs at sixteen clients improve ordinary reads/writes by 17%/24% and large reads by 182%, but cold regional reads lose 34-39%. This favors ordinary and large-value traffic rather than establishing a universal throughput winner for regional-heavy workloads. Loop JSON encoding is faster, but under sustained contention it raises p99 loop delay from 683 to 986 ms. The worker renderer preserves that responsiveness trade-off. Keeping the same bridge while releasing only the renderer connection cuts mean async occupancy from 6.47 to 3.16. TODO: Repeat the bridge, released/held preflight, fully async resolver and rendering comparisons with deployment traffic mixes and other database backends. Evaluate async warm-region resolution with cold Dag CPU work isolated without retaining the route connection across a worker wait.
c8b22ea to
43ea2c7
Compare
Convert the six Execution API XCom routes to async database access so ordinary producer lookups and value queries release worker capacity while waiting for the database. Value reads also return their async connection before waiting for JSON rendering. Paths, parameters, status/error bodies, task-attempt identity, team and bundle access, loop/mapped semantics, and response models stay unchanged.
related: #67799, #67800, #73405, #76505, #76694
Ordinary reads and writes use the route's
AsyncSessionthroughrun_syncfor shared synchronous query-building/model operations; database I/O remains async. Own-attempt writes stay on that path even for regional or archived attempts. Cross-task writes pin the legacy selector after a negative region preflight, avoiding another region query and preventing a concurrent regional insert from starting Dag loading on the loop.Dag-aware resolution can deserialize a Dag, so it retries on a worker with an independent non-scoped sync session after the read-only async preflight returns its connection. This fallback also applies with a warm Dag cache, and its extra queries/checkout have a measurable cost. Mutation commit/rollback remains with the session dependency. Read-only transactions end before worker lookup or rendering waits.
These XCom paths release one pool before waiting for the other. Concurrent requests can still use both pools: on pooled backends, defaults allow up to 15 sync plus 15 async connections per API server process. Budget that across processes and replicas. MySQL uses the sync engine's session time zone and
READ COMMITTEDisolation through #76505 and #76694.The three value-returning routes select JSON values directly and return
JSONResponse, avoiding repeatedJsonValuevalidation while preserving explicit response models. A stored NULL remains a found value. JSON encoding stays on a worker; Cadwyn still decodes and encodes the response on the event loop (upstream issue).The threadpool guard explicitly tracks four retained sites in
known_api_server_threadpool_offloads.txt:_resolve_xcom_coordinatesfor Dag-aware resolution, plus the three JSON renderers. Their CPU rationale is documented beside the entries. Ordinary DB lookup no longer unconditionally offloads on all six routes.Benchmarks and selected trade-offs
PostgreSQL 14, Breeze Python 3.14.10, i7-3770, default pools (5 + 10 overflow each) and 40 AnyIO worker tokens. The in-process HTTP harness retains FastAPI/Cadwyn and real database I/O; JWT verification and socket-client overhead are excluded. A 1 ms probe measures excess loop scheduling delay. Cold reads use a fresh DagBag per request with 500 padding tasks; the large response is 3.70 MB. Concurrent writes use distinct task instances. Synthetic contention is 40 sync clients, each doing
SELECT 1and holding its sync connection during a 20 ms sleep.The actual-
maincomparison uses three alternating base/PR runs on target base75026dce16, with medians below. An unchanged async HTTP control moved 1.6% at one client and 4.9% at sixteen clients, below the 10% noise threshold. One-second admission windows drain outstanding requests before throughput is calculated; large-value entries here are burst-drain measurements.main, req/smain→ PRThe regional penalty is an explicit trade-off for async ordinary calls and the separated CPU fallback. Cold-loop p99 loop delay also worsens against
main: 106 → 342 ms at sixteen clients without synthetic contention. Regional-heavy deployments should account for that cost; these samples establish no fleet-wide gain without a traffic mix.A separate 396-sample, three-round randomized matrix compares the original PR's unconditional bridge with released/held preflight connections, fully async resolution, worker-only Dag deserialization, and rendering alternatives. This is a comparison of lookup configurations, rather than the
maincomparison above. At sixteen clients, the selected split improved ordinary reads/writes 39%/15% over that bridge, while warm loop/mapped reads lost 15%/12%, and about 25% under contention.Holding the preflight connection produced no consistent throughput win in those runs. On contended cold-loop reads, holding versus releasing gave 5.45 versus 5.54 req/s with overlapping ranges; releasing reduced mean async occupancy from 8.08 to 4.26 and removed per-request overlap between pools. Keeping the same unconditional bridge and changing only renderer connection lifetime reduced mean async occupancy on contended large reads from 6.47 to 3.16, with throughput approximately 3.42 versus 3.41 req/s.
The fully async resolver was the cold-cache throughput winner in the configuration matrix, but solitary cold-loop p99 loop delay rose from 8.0 to 37.9 ms. The CPU-only Dag prototype improved warm-loop throughput at sixteen clients from 22.6 to 41.5 req/s, but retained async connections while waiting for CPU workers; under contended cold-loop load mean async occupancy rose from 4.26 to 9.98 and p99 loop delay from 273 to 384 ms. Those prototypes are outside this change.
An additional eighteen ten-second samples compare sustained large-value rendering, with three repeats per combination:
Loop encoding gained 18% foreground throughput under contention but raised p99 loop delay 44%; worst loop delay rose from 837 to 1,386 ms. Worker rendering is retained for that responsiveness trade-off. Returning Python data through normal
JsonValuevalidation was slower in the short matrix's contended large-value case: 1.74 req/s and 9.17 s request p95, versus workerJSONResponseat 3.63 req/s and 4.39 s.The configuration/rendering matrix covers 414 samples and 18,350 measured XCom requests; the actual-base/PR check adds 90 samples and 1,991 XCom requests plus unchanged-control requests. These are local samples without confidence intervals; CPU affinity/frequency are not pinned. SQLite/MySQL performance, multi-team/trigger-specific performance, production traffic mixes and multiple server processes remain unmeasured. Timing scripts are outside the PR.
Regression coverage includes ordinary async DB lookup and query limits, cold Dag loading on workers, connection release before lookup/render queues, preserved NULL handling, archived attempts, trigger identity, once-per-request team checks, and a region change between writer preflight and selection.
Validation uses the workspace sources in Breeze, with Python 3.14 for tests:
main; they are unrelated to XCom lookup or rendering.SIGILLon this CPU; the two provider-manager failures reproduce on unmodifiedmain. Documentation was attempted for core, Task SDK, common.compat and fab: Task SDK succeeded; the other three reached Pagefind indexing, where its installed binary also exits withSIGILL(132). The stalled indexing build was stopped. These checks are not reported as fully passing.Was generative AI tooling used to co-author this PR?
Generated-by: Claude Code (Claude Opus 5.5), Codex following the guidelines
Drafted-by: Codex (no human review before posting)