This is an automated email from the ASF dual-hosted git repository.
Lee-W pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 75026dce164 Fix race when concurrent tasks first emit the same asset
through an alias (#76827)
75026dce164 is described below
commit 75026dce164ab70799290cbe9dcce39b7b181c75
Author: Vladimir <[email protected]>
AuthorDate: Fri Nov 20 11:35:53 2026 +0000
Fix race when concurrent tasks first emit the same asset through an alias
(#76827)
---
airflow-core/src/airflow/assets/manager.py | 34 ++++++++---
airflow-core/src/airflow/models/taskinstance.py | 13 ++--
airflow-core/tests/unit/assets/test_manager.py | 71 +++++++++++++++++++++-
.../tests/unit/models/test_taskinstance.py | 48 +++++++++++++++
4 files changed, 151 insertions(+), 15 deletions(-)
diff --git a/airflow-core/src/airflow/assets/manager.py
b/airflow-core/src/airflow/assets/manager.py
index b732ad0de00..c2cb9e723a0 100644
--- a/airflow-core/src/airflow/assets/manager.py
+++ b/airflow-core/src/airflow/assets/manager.py
@@ -65,6 +65,7 @@ if TYPE_CHECKING:
log = structlog.get_logger(__name__)
_APDR_GET_OR_CREATE_ATTEMPTS = 2
+_ALIAS_ASSOCIATION_ATTEMPTS = 2
class AssetManager(LoggingMixin):
@@ -112,16 +113,29 @@ class AssetManager(LoggingMixin):
*,
session: Session,
) -> None:
- already_related = {m.name for m in asset_model.aliases}
- existing_aliases = {
- m.name: m
- for m in
session.scalars(select(AssetAliasModel).where(AssetAliasModel.name.in_(alias_names)))
- }
- asset_model.aliases.extend(
- existing_aliases.get(name, AssetAliasModel(name=name))
- for name in alias_names
- if name not in already_related
- )
+ # Tolerate a concurrent writer linking the same alias.
+ for attempt in range(1, _ALIAS_ASSOCIATION_ATTEMPTS + 1):
+ already_related = {m.name for m in asset_model.aliases}
+ missing = [name for name in alias_names if name not in
already_related]
+ if not missing:
+ return
+ existing_aliases = {
+ m.name: m
+ for m in
session.scalars(select(AssetAliasModel).where(AssetAliasModel.name.in_(missing)))
+ }
+ try:
+ with session.begin_nested():
+ asset_model.aliases.extend(
+ existing_aliases.get(name, AssetAliasModel(name=name))
for name in missing
+ )
+ except exc.IntegrityError:
+ if attempt == _ALIAS_ASSOCIATION_ATTEMPTS:
+ raise
+ cls.logger().debug(
+ "Another process linked aliases %s to asset %s first;
retrying",
+ missing,
+ asset_model.uri,
+ )
@classmethod
def _filter_dags_by_team(
diff --git a/airflow-core/src/airflow/models/taskinstance.py
b/airflow-core/src/airflow/models/taskinstance.py
index 27c23915413..4bc4120e105 100644
--- a/airflow-core/src/airflow/models/taskinstance.py
+++ b/airflow-core/src/airflow/models/taskinstance.py
@@ -65,7 +65,7 @@ from sqlalchemy import (
update,
)
from sqlalchemy.dialects import postgresql
-from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.mutable import MutableDict
@@ -2695,9 +2695,12 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
)
if event is None:
ti.log.info("Dynamically creating AssetModel %s",
asset_key)
- session.add(AssetModel.from_serialized(asset))
- session.flush() # So event can set up its asset fk.
- asset_manager.register_asset_change(
+ try:
+ with session.begin_nested():
+ session.add(AssetModel.from_serialized(asset))
+ except IntegrityError:
+ ti.log.info("AssetModel %s was created concurrently;
reusing it", asset_key)
+ event = asset_manager.register_asset_change(
task_instance=ti,
asset=asset,
source_alias_names=event_aliase_names,
@@ -2707,6 +2710,8 @@ class TaskInstance(Base, LoggingMixin, BaseWorkload):
callback_sink=callback_sink,
session=session,
)
+ if event is None:
+ ti.log.error("Could not register asset event for %s",
asset_key)
return callback_sink
diff --git a/airflow-core/tests/unit/assets/test_manager.py
b/airflow-core/tests/unit/assets/test_manager.py
index 8192db17b0a..c27b989238f 100644
--- a/airflow-core/tests/unit/assets/test_manager.py
+++ b/airflow-core/tests/unit/assets/test_manager.py
@@ -27,7 +27,7 @@ from unittest import mock
import pytest
from sqlalchemy import event, exc, func, insert, select
from sqlalchemy.dialects import mysql, postgresql, sqlite
-from sqlalchemy.orm import Session
+from sqlalchemy.orm import Session, joinedload
from airflow import settings
from airflow._shared.observability.metrics.base_stats_logger import StatsLogger
@@ -44,6 +44,7 @@ from airflow.models.asset import (
DagScheduleAssetReference,
DagScheduleAssetUriReference,
PartitionedAssetKeyLog,
+ alias_association_table,
)
from airflow.models.dag import DagModel
from airflow.models.dagbundle import DagBundleModel
@@ -188,6 +189,74 @@ class TestAssetManager:
)
assert
session.scalar(select(func.count()).select_from(AssetDagRunQueue)) == 2
+ @pytest.mark.backend("postgres", "mysql")
+ @pytest.mark.usefixtures("testing_dag_bundle")
+ def test_add_asset_alias_association_tolerates_concurrent_link(self,
session):
+ """Another writer links the same alias to the asset after we read its
aliases."""
+ session.add(AssetModel(uri="test://race/", name="race_asset",
group="asset"))
+ session.commit()
+
+ def _load(s):
+ return s.scalar(
+ select(AssetModel)
+ .where(AssetModel.name == "race_asset")
+ .options(joinedload(AssetModel.aliases))
+ )
+
+ stale = _load(session)
+ assert stale.aliases == []
+
+ if TYPE_CHECKING:
+ assert settings.Session
+ assert settings.Session.session_factory
+ other = settings.Session.session_factory()
+ try:
+ AssetManager._add_asset_alias_association(["race_alias"],
_load(other), session=other)
+ other.commit()
+ finally:
+ other.close()
+
+ AssetManager._add_asset_alias_association(["race_alias"], stale,
session=session)
+ session.flush()
+
+ assert [a.name for a in stale.aliases] == ["race_alias"]
+ assert
session.scalar(select(func.count()).select_from(alias_association_table)) == 1
+
+ @pytest.mark.backend("postgres", "mysql")
+ @pytest.mark.usefixtures("testing_dag_bundle")
+ def
test_add_asset_alias_association_tolerates_concurrent_alias_create(self,
session):
+ """Another writer creates the same alias after our lookup missed it."""
+ asset = AssetModel(uri="test://race/", name="race_asset",
group="asset")
+ session.add(asset)
+ session.commit()
+
+ if TYPE_CHECKING:
+ assert settings.Session
+ assert settings.Session.session_factory
+ real_scalars = session.scalars
+ calls = 0
+
+ def _lookup_then_create_alias(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ result = list(real_scalars(*args, **kwargs))
+ if calls == 1:
+ other = settings.Session.session_factory()
+ try:
+ other.add(AssetAliasModel(name="race_alias"))
+ other.commit()
+ finally:
+ other.close()
+ return result
+
+ with mock.patch.object(session, "scalars",
side_effect=_lookup_then_create_alias, autospec=True):
+ AssetManager._add_asset_alias_association(["race_alias"], asset,
session=session)
+ session.flush()
+
+ assert calls == 2
+ assert [a.name for a in asset.aliases] == ["race_alias"]
+ assert
session.scalar(select(func.count()).select_from(AssetAliasModel)) == 1
+
@pytest.mark.parametrize("reference_kind", ["asset", "alias", "name",
"uri"])
def test_register_asset_change_does_not_queue_draining_dag(
self, reference_kind, session, mock_task_instance, testing_dag_bundle
diff --git a/airflow-core/tests/unit/models/test_taskinstance.py
b/airflow-core/tests/unit/models/test_taskinstance.py
index cfc7fb0e91f..ddf6f570829 100644
--- a/airflow-core/tests/unit/models/test_taskinstance.py
+++ b/airflow-core/tests/unit/models/test_taskinstance.py
@@ -44,6 +44,8 @@ from airflow import plugins_manager, settings
from airflow._shared.observability.metrics.base_stats_logger import StatsLogger
from airflow._shared.observability.traces import new_dagrun_trace_carrier,
new_task_run_carrier
from airflow._shared.timezones import timezone
+from airflow.api_fastapi.execution_api.datamodels.asset import AssetProfile
+from airflow.assets.manager import asset_manager
from airflow.exceptions import (
AirflowException,
AirflowSkipException,
@@ -4562,6 +4564,52 @@ def
test_register_asset_changes_in_db_no_outlets_is_a_noop(dag_maker, session):
)
[email protected]("postgres", "mysql")
+def
test_register_asset_changes_in_db_alias_asset_created_concurrently(dag_maker,
session):
+ """Another writer creates the alias-emitted asset after our lookup missed
it."""
+ alias = AssetAlias("race_alias")
+ with dag_maker(dag_id="alias_race", schedule=None, session=session):
+ EmptyOperator(task_id="hi", outlets=[alias])
+ dr = dag_maker.create_dagrun(session=session)
+ [ti] = dr.get_task_instances(session=session)
+ session.commit()
+
+ real_register = asset_manager.register_asset_change
+ calls = 0
+
+ def _register_after_asset_appears(**kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ with create_session() as other:
+ other.add(AssetModel(name="race_asset",
uri="s3://bucket/race_asset", group="asset"))
+ return None
+ return real_register(**kwargs)
+
+ with mock.patch.object(
+ asset_manager, "register_asset_change",
side_effect=_register_after_asset_appears, autospec=True
+ ):
+ TaskInstance.register_asset_changes_in_db(
+ ti=ti,
+ task_outlets=[AssetProfile(name="race_alias", type="AssetAlias")],
+ outlet_events=[
+ {
+ "source_alias_name": "race_alias",
+ "dest_asset_key": {"name": "race_asset", "uri":
"s3://bucket/race_asset"},
+ "dest_asset_extra": {},
+ "extra": {},
+ }
+ ],
+ session=session,
+ )
+ session.commit()
+
+ assert session.scalar(select(func.count()).select_from(AssetModel)) == 1
+ event = session.scalar(select(AssetEvent).where(AssetEvent.source_dag_id
== "alias_race"))
+ assert event is not None
+ assert [a.name for a in event.source_aliases] == ["race_alias"]
+
+
def test_when_dag_run_has_partition_then_asset_does(dag_maker, session):
asset = Asset(name="hello")
with dag_maker(dag_id="asset_event_tester",
schedule=PartitionedAtRuntime()) as dag: