Dev-iL commented on code in PR #77736:
URL: https://github.com/apache/airflow/pull/77736#discussion_r4760163957
##########
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_asset_events.py:
##########
@@ -1150,3 +1151,70 @@ def test_filter_multiple_extra_keys(self, client,
extra_params, expected_count):
)
assert response.status_code == 200
assert len(response.json()["asset_events"]) == expected_count
+
+
+_ASYNC_ROUTE_CASES: list[tuple[str, dict[str, str | None]]] = [
+ ("/execution/asset-events/by-asset", {"name": "test_get_asset_by_name",
"uri": None}),
+ (
+ "/execution/asset-events/by-asset",
+ {"name": "test_get_asset_by_name", "uri": None,
"partition_key_regexp_pattern": "^2024-"},
+ ),
+ ("/execution/asset-events/by-asset-alias", {"name": "test_alias"}),
+ (
+ "/execution/asset-events/by-asset-alias",
+ {"name": "test_alias", "partition_key_regexp_pattern": "^2024-"},
+ ),
+]
+
+
+_ASYNC_REGEX_CASES = [case for case in _ASYNC_ROUTE_CASES if
"partition_key_regexp_pattern" in case[1]]
+
+
+class TestAsyncSessionUsage:
+ @pytest.fixture(autouse=True)
+ def _enable_regexp_query_filters(self):
+ with conf_vars({("api", "regexp_query_timeout"): "30"}):
+ yield
+
+ @pytest.mark.usefixtures("test_asset_alias")
+ @pytest.mark.parametrize(("path", "params"), _ASYNC_ROUTE_CASES)
+ def test_should_not_query_on_event_loop(self, client, event_loop_queries,
path, params):
+ response = client.get(path, params=params)
+
+ assert response.status_code == 200
Review Comment:
The regex cases at `test_asset_events.py:1184` get HTTP 200 with an empty
list. The `test_asset_alias` fixture seeds events with `partition_key=None`, so
`^2024-` matches nothing and the regex cases skip relationship loading. Seed a
matching event with a created Dag run and assert that it comes back on both
paths. That exercises the event-loop guard through the full regex response.
---
Drafted-by: Codex (GPT-6), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
##########
airflow-core/src/airflow/api_fastapi/execution_api/routes/asset_events.py:
##########
@@ -46,24 +47,30 @@
)
-def _get_asset_events_through_sql_clauses(
+async def _get_asset_events_through_sql_clauses(
*,
join_clause,
where_clause,
- session: SessionDep,
+ session: AsyncSessionDep,
ascending: bool = True,
limit: int | None = None,
filters: list[BaseParam] | None = None,
) -> AssetEventsResponse:
order_by_clause = AssetEvent.timestamp.asc() if ascending else
AssetEvent.timestamp.desc()
- asset_events_query =
select(AssetEvent).join(join_clause).where(where_clause).order_by(order_by_clause)
+ asset_events_query = (
+ select(AssetEvent)
+ .join(join_clause)
+ .where(where_clause)
+ .options(selectinload(AssetEvent.asset),
selectinload(AssetEvent.created_dagruns))
Review Comment:
`asset_events.py:64` eagerly hydrates full asset events, assets and Dag runs
on the event loop. The response never reads fields such as `DagRun.conf`.
Across both SQLite rounds, median stalls increased from 47–58 ms to 76–80 ms
with 1,000 events, even as each route dropped from 1,002 SQL statements to 5.
The 5,000-event profiles put ORM hydration at the top of the loop’s work. Can
we keep the batched reads and project the response columns? A column-only trial
brought median stalls to 51–56 ms at 1,000 events.
---
Drafted-by: Codex (GPT-6), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
##########
airflow-core/src/airflow/api_fastapi/common/parameters/search.py:
##########
@@ -357,6 +361,29 @@ def depends_regex(
return depends_regex
+def regex_param_factory_async(
+ attribute: ColumnElement,
+ pattern_name: str,
+ skip_none: bool = True,
+ description: str = _DEFAULT_REGEX_DESCRIPTION,
+) -> Callable[..., AsyncGenerator[_RegexParam, None]]:
+ """Async version of :func:`regex_param_factory`, for routes that use
``AsyncSessionDep``."""
+
+ async def depends_regex(
+ session: AsyncSessionDep,
+ value: str | None = Query(alias=pattern_name, default=None,
description=description),
+ ) -> AsyncGenerator[_RegexParam, None]:
+ param = _build_regex_param(attribute, value, skip_none)
+ if value is None:
+ yield param
+ return
+ # Has to be the route's async session, otherwise the timeout lands on
another connection.
+ async with apply_regex_query_timeout_async(session):
Review Comment:
`search.py:381` applies the timeout in both Cadwyn passes. On PostgreSQL 14
and MySQL 8.0, either selector held two connections at once and issued nine
statements for ten matching events. The first connection only reads, sets and
restores the timeout. The sync base does this too, as noted in the PR. Can we
keep pattern validation in the dependency and apply the timeout around the
query in the shared route helper? Assert that a regex request checks out one
connection and that the query runs within the timeout.
---
Drafted-by: Codex (GPT-6), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
##########
airflow-core/src/airflow/utils/sqlalchemy.py:
##########
@@ -98,34 +99,79 @@ def apply_regex_query_timeout(session: Session) ->
Generator[None, None, None]:
if timeout_seconds <= 0:
yield
return
- # ``timeout_ms`` is derived from the (operator-controlled) config, not
from user input.
- timeout_ms = int(timeout_seconds * 1000)
+ # ``timeout_ms`` is derived from the (operator-controlled) config, not
from user input. Clamp to
+ # 1 ms so a tiny positive value doesn't round down to 0, which disables
the timeout on both backends.
+ timeout_ms = max(1, int(timeout_seconds * 1000))
dialect_name = get_dialect_name(session)
if dialect_name == "postgresql":
previous = session.execute(text("SELECT
current_setting('statement_timeout')")).scalar()
- session.execute(
- text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(timeout=str(timeout_ms))
+ set_stmt = text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
+ timeout=str(timeout_ms)
+ )
+ # Restore the previous value (e.g. a global statement_timeout) instead
of clearing it, so
+ # the bound only applies to the regexp query and not later statements
in the transaction.
+ restore_stmt = text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
+ timeout=str(previous) if previous is not None else "0"
)
- try:
- yield
- finally:
- # Restore the previous value (e.g. a global statement_timeout)
instead of clearing it, so
- # the bound only applies to the regexp query and not later
statements in the transaction.
- session.execute(
- text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
- timeout=str(previous) if previous is not None else "0"
- )
- )
elif dialect_name == "mysql":
previous = session.execute(text("SELECT
@@SESSION.max_execution_time")).scalar()
- session.execute(text(f"SET SESSION max_execution_time = {timeout_ms}"))
- try:
- yield
- finally:
- # Restore the previous value so a global max_execution_time is
preserved.
- session.execute(text(f"SET SESSION max_execution_time =
{int(previous or 0)}"))
+ set_stmt = text(f"SET SESSION max_execution_time = {timeout_ms}")
+ # Restore the previous value so a global max_execution_time is
preserved.
+ restore_stmt = text(f"SET SESSION max_execution_time = {int(previous
or 0)}")
+ else:
+ yield
+ return
+ session.execute(set_stmt)
+ try:
+ yield
+ except BaseException:
+ # A failed query (e.g. one that hit this timeout) aborts the
transaction on PostgreSQL, so the
+ # restore fails as well and would hide the original error. The
PostgreSQL setting is
+ # transaction-local and goes away with the rollback, so keep the
original exception.
+ with contextlib.suppress(Exception):
+ session.execute(restore_stmt)
+ raise
+ session.execute(restore_stmt)
+
+
[email protected]
+async def apply_regex_query_timeout_async(session: AsyncSession) ->
AsyncGenerator[None, None]:
+ """
+ Async version of :func:`apply_regex_query_timeout` for an ``AsyncSession``.
+
+ Same behaviour: sets the PostgreSQL/MySQL timeout for the ``async with``
block and restores the
+ previous value afterwards. No-op on other backends and when the configured
timeout is ``0``.
+ """
+ timeout_seconds = conf.getfloat("api", "regexp_query_timeout")
+ if timeout_seconds <= 0:
+ yield
+ return
+ timeout_ms = max(1, int(timeout_seconds * 1000))
+ dialect_name = get_dialect_name(session.sync_session)
+ if dialect_name == "postgresql":
+ previous = (await session.execute(text("SELECT
current_setting('statement_timeout')"))).scalar()
+ set_stmt = text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
+ timeout=str(timeout_ms)
+ )
+ restore_stmt = text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
+ timeout=str(previous) if previous is not None else "0"
+ )
+ elif dialect_name == "mysql":
+ previous = (await session.execute(text("SELECT
@@SESSION.max_execution_time"))).scalar()
+ set_stmt = text(f"SET SESSION max_execution_time = {timeout_ms}")
+ restore_stmt = text(f"SET SESSION max_execution_time = {int(previous
or 0)}")
else:
yield
+ return
+ await session.execute(set_stmt)
+ try:
+ yield
+ except BaseException:
+ # See apply_regex_query_timeout: don't let a failing restore hide the
original error.
+ with contextlib.suppress(Exception):
Review Comment:
`sqlalchemy.py:171` preserves the query error by suppressing a failed
timeout restore. MySQL rollback leaves the connection-level
`max_execution_time` in place. In a fault-injection check, the original error
propagated and the next checkout of the same MySQL connection saw 250 ms
instead of its original 0 ms. Invalidate the MySQL connection when restoring
fails, while preserving the original error. Cover the next checkout in the
regression test and apply the same cleanup rule to the sync helper at
`sqlalchemy.py:131`.
---
Drafted-by: Codex (GPT-6), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
##########
airflow-core/src/airflow/utils/sqlalchemy.py:
##########
@@ -98,34 +99,79 @@ def apply_regex_query_timeout(session: Session) ->
Generator[None, None, None]:
if timeout_seconds <= 0:
yield
return
- # ``timeout_ms`` is derived from the (operator-controlled) config, not
from user input.
- timeout_ms = int(timeout_seconds * 1000)
+ # ``timeout_ms`` is derived from the (operator-controlled) config, not
from user input. Clamp to
+ # 1 ms so a tiny positive value doesn't round down to 0, which disables
the timeout on both backends.
+ timeout_ms = max(1, int(timeout_seconds * 1000))
dialect_name = get_dialect_name(session)
if dialect_name == "postgresql":
previous = session.execute(text("SELECT
current_setting('statement_timeout')")).scalar()
- session.execute(
- text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(timeout=str(timeout_ms))
+ set_stmt = text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
+ timeout=str(timeout_ms)
+ )
+ # Restore the previous value (e.g. a global statement_timeout) instead
of clearing it, so
+ # the bound only applies to the regexp query and not later statements
in the transaction.
+ restore_stmt = text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
+ timeout=str(previous) if previous is not None else "0"
)
- try:
- yield
- finally:
- # Restore the previous value (e.g. a global statement_timeout)
instead of clearing it, so
- # the bound only applies to the regexp query and not later
statements in the transaction.
- session.execute(
- text("SELECT set_config('statement_timeout', :timeout,
true)").bindparams(
- timeout=str(previous) if previous is not None else "0"
- )
- )
elif dialect_name == "mysql":
previous = session.execute(text("SELECT
@@SESSION.max_execution_time")).scalar()
- session.execute(text(f"SET SESSION max_execution_time = {timeout_ms}"))
- try:
- yield
- finally:
- # Restore the previous value so a global max_execution_time is
preserved.
- session.execute(text(f"SET SESSION max_execution_time =
{int(previous or 0)}"))
+ set_stmt = text(f"SET SESSION max_execution_time = {timeout_ms}")
+ # Restore the previous value so a global max_execution_time is
preserved.
+ restore_stmt = text(f"SET SESSION max_execution_time = {int(previous
or 0)}")
+ else:
+ yield
+ return
+ session.execute(set_stmt)
+ try:
+ yield
+ except BaseException:
+ # A failed query (e.g. one that hit this timeout) aborts the
transaction on PostgreSQL, so the
+ # restore fails as well and would hide the original error. The
PostgreSQL setting is
+ # transaction-local and goes away with the rollback, so keep the
original exception.
+ with contextlib.suppress(Exception):
+ session.execute(restore_stmt)
+ raise
+ session.execute(restore_stmt)
+
+
[email protected]
+async def apply_regex_query_timeout_async(session: AsyncSession) ->
AsyncGenerator[None, None]:
Review Comment:
Make `session` keyword-only in the new helper at `sqlalchemy.py:138`, as
required by the core session convention. Autospec the helper in
`test_parameters.py:731` so the dependency test catches a positional call or a
signature mismatch.
---
Drafted-by: Codex (GPT-6), reviewed by @Dev-iL before posting.
<!-- manifest-dev:review-pr -->
--
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]