dabla commented on code in PR #73966:
URL: https://github.com/apache/airflow/pull/73966#discussion_r4680542076
##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py:
##########
@@ -1778,30 +1816,39 @@ def get_task_instance_states(
if run_ids:
query = query.where(TI.run_id.in_(run_ids))
- results = session.execute(query).tuples().all()
+ results: list[Any] = []
+ # Without task_ids, task_group_id replaces the Dag-wide match instead of
extending it.
+ if task_ids or not task_group_id:
Review Comment:
**[nit]** Skipping the Dag-wide query for a group-only request has no test
that fails without it.
The PR body lists this as a change, and the existing parametrised tests only
check the response, which is identical with or without the skip. A
statement-count assertion on a request with `task_group_id` and no `task_ids`
(the `assert_queries_count` helper from `tests_common.test_utils.asserts`, or
the same `event.listen` approach the new `does_not_load_task_instances` test
uses) would pin it, so a later refactor cannot quietly bring the discarded
query back.
##########
airflow-core/src/airflow/models/dagbag.py:
##########
@@ -112,54 +114,101 @@ def _current_dag_hash(version_id: UUID | str, session:
Session) -> str | None:
select(SerializedDagModel.dag_hash).where(SerializedDagModel.dag_version_id ==
version_id)
)
- def _get_dag(self, version_id: UUID | str, session: Session) ->
SerializedDAG | None:
+ def _get_valid_cached_dag(
+ self, version_id: UUID | str
+ ) -> tuple[SerializedDAG | None, _CacheEntry | None]:
+ """Return a cached Dag within its revalidation window, else the cached
entry to revalidate."""
with self._lock:
cached = self._dags.get(version_id)
+ if cached is None:
+ return None, None
+ # A serialized DAG cannot be rewritten more often than
+ # [core] min_serialized_dag_update_interval, so an entry validated
within that window
+ # cannot have gone stale yet -- serve it without touching the DB.
+ if time.monotonic() - cached.last_validated <
self._revalidation_interval:
+ self._on_cache_hit()
+ return cached.dag, None
+ return None, cached
+
+ def _revalidate_cached_dag(
+ self, version_id: UUID | str, cached: _CacheEntry, current_hash: str |
None
+ ) -> SerializedDAG | None:
+ """Serve ``cached`` when ``current_hash`` still matches it, else drop
it so the caller reloads."""
+ # Past the window: a version may have been updated in place (same
dag_version_id, new
+ # content + new dag_hash) by SerializedDagModel.write_dag, so the
caller confirms the cached
+ # copy against the current dag_hash. That validation is a single-row
lookup on the
+ # uniquely-indexed serialized_dag.dag_version_id column.
+ if current_hash == cached.dag_hash:
+ # Still current: restart the revalidation window so the next hits
skip the query.
+ # (For a TTLCache this write-back also refreshes the entry's
TTL/LRU recency, which
+ # is fine -- the entry was just re-confirmed against the DB.)
+ with self._lock:
+ current = self._dags.get(version_id)
+ if current is not None and current.dag_hash == cached.dag_hash:
+ self._dags[version_id] =
current._replace(last_validated=time.monotonic())
+ self._on_cache_hit()
+ return cached.dag
+ # Stale (updated in place) or the version no longer exists: drop and
reload.
+ with self._lock:
+ self._dags.pop(version_id, None)
+ return None
- if cached is not None:
- now = time.monotonic()
- # A serialized DAG cannot be rewritten more often than
- # [core] min_serialized_dag_update_interval, so an entry validated
within that window
- # cannot have gone stale yet -- serve it without touching the DB.
- if now - cached.last_validated < self._revalidation_interval:
- self._on_cache_hit()
- return cached.dag
- # Past the window: a version may have been updated in place (same
dag_version_id, new
- # content + new dag_hash) by SerializedDagModel.write_dag, so
confirm the cached copy
- # against the current dag_hash. That validation is a single-row
lookup on the
- # uniquely-indexed serialized_dag.dag_version_id column.
- if self._current_dag_hash(version_id, session) == cached.dag_hash:
- # Still current: restart the revalidation window so the next
hits skip the query.
- # (For a TTLCache this write-back also refreshes the entry's
TTL/LRU recency, which
- # is fine -- the entry was just re-confirmed against the DB.)
- with self._lock:
- current = self._dags.get(version_id)
- if current is not None and current.dag_hash ==
cached.dag_hash:
- self._dags[version_id] =
current._replace(last_validated=now)
+ def _get_dag_cached_since_load(self, version_id: UUID | str) ->
SerializedDAG | None:
+ """Return a Dag another thread cached while this one queried the DB,
else record a cache miss."""
+ # Double-checked locking: such an entry was just loaded from the DB,
so it is well within its
+ # revalidation window and is served without an extra hash check. Only
emit the miss metric
+ # after confirming no other thread cached it, to avoid counting a
single lookup as both a
+ # miss and a hit.
+ with self._lock:
+ if (cached := self._dags.get(version_id)) is not None:
self._on_cache_hit()
return cached.dag
- # Stale (updated in place) or the version no longer exists: drop
and reload below.
- with self._lock:
- self._dags.pop(version_id, None)
+ self._on_cache_miss()
+ return None
+
+ def _get_dag(self, version_id: UUID | str, session: Session) ->
SerializedDAG | None:
+ dag, cached = self._get_valid_cached_dag(version_id)
+ if dag is not None:
+ return dag
+ if cached is not None:
+ current_hash = self._current_dag_hash(version_id, session)
+ if (dag := self._revalidate_cached_dag(version_id, cached,
current_hash)) is not None:
+ return dag
dag_version = session.get(DagVersion, version_id,
options=[joinedload(DagVersion.serialized_dag)])
if not dag_version:
return None
if not (serdag := dag_version.serialized_dag):
return None
-
- # Double-checked locking: another thread may have cached it while we
queried DB. Such an
- # entry was just loaded from the DB, so it is well within its
revalidation window and is
- # served without an extra hash check, consistent with the policy
above. Only emit the miss
- # metric after confirming no other thread cached it, to avoid counting
a single lookup as
- # both a miss and a hit.
- with self._lock:
- if (cached := self._dags.get(version_id)) is not None:
- self._on_cache_hit()
- return cached.dag
- self._on_cache_miss()
+ if (dag := self._get_dag_cached_since_load(version_id)) is not None:
+ return dag
return self._read_dag(serdag)
+ async def get_dag_async(self, version_id: UUID | str, *, session:
AsyncSession) -> SerializedDAG | None:
+ """Get a Dag by its version id asynchronously, deserializing a cache
miss in a worker thread."""
+ from airflow.models.serialized_dag import SerializedDagModel
+
+ dag, cached = self._get_valid_cached_dag(version_id)
+ if dag is not None:
+ return dag
+ if cached is not None:
+ current_hash = await session.scalar(
Review Comment:
**[warning]** `get_dag_async` writes the `dag_hash` lookup of
`_current_dag_hash` a second time.
`_current_dag_hash` (a few lines up) and this statement are the same
`select(SerializedDagModel.dag_hash).where(SerializedDagModel.dag_version_id ==
version_id)`. The revalidation logic was split out so both paths share it, but
the query that feeds it was not, so a change to how staleness is detected
(another column, a join) can reach the sync path and miss this one. A statement
builder that both call, as done for the other queries in this PR, closes that:
```python
@staticmethod
def _build_current_dag_hash_query(version_id: UUID | str) -> Select:
from airflow.models.serialized_dag import SerializedDagModel
return
select(SerializedDagModel.dag_hash).where(SerializedDagModel.dag_version_id ==
version_id)
```
(See also comment [1] in `api_fastapi/common/dagbag.py`.)
##########
airflow-core/src/airflow/api_fastapi/execution_api/in_process.py:
##########
@@ -157,6 +157,10 @@ def transport(self) -> httpx2.WSGITransport:
# https://github.com/abersheeran/a2wsgi/discussions/64
async def start_lifespan(cm: AsyncExitStack, app: FastAPI):
+ # Pooled async connections are bound to the event loop that opened
them, and reusing one on
+ # this loop fails (e.g. aiomysql). Drop connections opened
elsewhere without closing them here.
+ if settings.async_engine is not None:
+ await settings.async_engine.dispose(close=False)
Review Comment:
**[nit]** This drops connections opened *before* the in-process loop starts;
a loop that uses the pool *afterwards* still shares it.
`dispose(close=False)` runs once, at lifespan start, so it covers the case
the new test builds: another loop queried first, then the in-process API. The
pool stays process-wide after that. Any other loop in the same process that
calls `create_session_async()` later (a second `asyncio.run(...)` in a
`dag.test()` caller, an async fixture in the test suite) checks out connections
this loop returned, and the reverse, which is the same aiomysql failure from
the other side. I could not reproduce it without MySQL at hand, and with
`in_process_api_server()` cached to one instance it may not occur in practice
today, so this is a question more than a request: is the one-time dispose meant
as the full fix, or would a pool that never hands a connection to another loop
(`NullPool` for the in-process engine, or a pool per loop) be the safer end
state? If the one-time dispose is the intent, a sentence in the comment saying
that it only covers earlier loops would help the next reader.
##########
airflow-core/src/airflow/api_fastapi/common/dagbag.py:
##########
@@ -74,6 +75,23 @@ def get_latest_version_of_dag(
return dag
+async def get_latest_version_of_dag_async(
Review Comment:
**[warning]** The async helper copies the whole "Dag not found" block of
`get_latest_version_of_dag`.
Only the lookup differs between the two functions
(`dag_bag.get_latest_version_of_dag(...)` versus `await
dag_bag.get_latest_version_of_dag_async(...)`); the `include_reason` branch,
the status code and both messages are now written twice, so the next change to
the 404 payload has to be made in two places
([DontRepeatYourself](https://wiki.c2.com/?DontRepeatYourself)). The rest of
this PR already solves the same problem by pulling the shared part out
(`_build_live_tasks_query`, `_find_superseded_in_passes`,
`_build_region_batch_query`). The same here keeps one home for the response:
```python
def _dag_not_found(dag_id: str, *, include_reason: bool) -> HTTPException:
message = f"The Dag with ID: `{dag_id}` was not found"
detail = {"reason": "not_found", "message": message} if include_reason
else message
return HTTPException(status.HTTP_404_NOT_FOUND, detail=detail)
```
with both functions reduced to `if not dag: raise _dag_not_found(dag_id,
include_reason=include_reason)`. (See also comment [2] in `models/dagbag.py`.)
##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py:
##########
@@ -1851,17 +1898,17 @@ def _is_eligible_to_retry(state: str, try_number: int,
max_tries: int) -> bool:
return max_tries != 0 and try_number <= max_tries
-def _get_group_tasks(
+async def _get_group_tasks(
Review Comment:
**[nit]** `_get_group_tasks` now returns task instance ids, not tasks.
Both callers already name the result `group_ti_ids`; renaming the function
to match (`_get_group_ti_ids`) and updating the "Get all tasks in the task
group" comment keeps the name honest now that the return type is
`Sequence[UUID]`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]