Repository navigation
Propagate AssetEvent through context when Consumer DAG triggering on AssetAlias - #50182
Conversation
|
Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide (https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
|
|
The following unit tests have been run and all passed. |
49b6b60 to
274ea65
Compare
Lee-W
left a comment
There was a problem hiding this comment.
I'm a bit confused by why do we need to change the scheduler here. Could you help me understand it a bit? Thanks 🙂
We use something like
to expand an alias to assets and let them works like other assets
Thanks for the follow up. The main reason in short, is to let the consumer task able to access the corresponding asset event attached to the asset alias on which the consumer DAG Run is triggered. I also left some thinking about why it is changed in scheduler: #39017 (comment). |
274ea65 to
29115cf
Compare
|
Found a unit test case |
for using traditional syntax, you can access the value through |
Hi Wei, thank you. I modified the DAG code to access the asset events from context based on the document you provided. However, the asset event associated with the alias is not in the Also, I could try to explain it from the source code. From line 1606 to 1634 # here, we only query on events join with `DagScheduleAssetReference`, so I think when the DAG is scheduled on asset
# alias, this query return empty results, and hence not populate the `consumed_asset_events`
asset_events = session.scalars(
select(AssetEvent)
.join(
DagScheduleAssetReference,
AssetEvent.asset_id == DagScheduleAssetReference.asset_id,
)
.where(
DagScheduleAssetReference.dag_id == dag.dag_id,
AssetEvent.timestamp <= triggered_date,
AssetEvent.timestamp > func.coalesce(cte.c.previous_dag_run_run_after, date.min),
)
).all()
dag_run = dag.create_dagrun(
run_id=DagRun.generate_run_id(
run_type=DagRunType.ASSET_TRIGGERED, logical_date=None, run_after=triggered_date
),
logical_date=None,
data_interval=None,
run_after=triggered_date,
run_type=DagRunType.ASSET_TRIGGERED,
triggered_by=DagRunTriggeredByType.ASSET,
state=DagRunState.QUEUED,
creating_job_id=self.job.id,
session=session,
)
Stats.incr("asset.triggered_dagruns")
dag_run.consumed_asset_events.extend(asset_events)
session.execute(delete(AssetDagRunQueue).where(AssetDagRunQueue.target_dag_id == dag_run.dag_id))In Consumer DAG from airflow.sdk import Asset, AssetAlias, DAG
from airflow.providers.standard.operators.python import PythonOperator
file_asset_alias = AssetAlias("file_asset_event")
with DAG(
dag_id="asset_alias_consumer",
schedule=[file_asset_alias]
):
def my_function(**context):
print(context)
inlet_events = context["inlet_events"]
outlet_events = context["outlet_events"]
print("Access triggering_asset_events in the consumer task")
print("triggering_asset_events:", context["triggering_asset_events"])
print("Access inlet_events in the consumer task, from asset alias 'file_asset_event'")
print("inlet_events:", inlet_events[AssetAlias(name="file_asset_event")])
print("inlet_events:", inlet_events.for_asset_alias(name="file_asset_event"))
print("Access outlet_events in the consumer task, from asset alias 'file_asset_event'")
print("outlet_events:", outlet_events[AssetAlias(name="file_asset_event")])
print("outlet_events:", outlet_events.for_asset_alias(name="file_asset_event"))
my_task = PythonOperator(
task_id="consumer_task",
python_callable=my_function,
inlets=[file_asset_alias]
) |
7de9110 to
7489210
Compare
After having a deeper look into the test cases. The AssetAlias is in the |
c2328b5 to
71c4593
Compare
71c4593 to
6d2ff49
Compare
uranusjr
left a comment
There was a problem hiding this comment.
I think this makes sense. A few questions on the implementation:
- I don’t think we need to explicitly join the association table. I believe SQLAlchemy has some tools to join the two models directly together (such as
.any()). Can you look into this? - Is it possible to merge the two events select queries into one?
- If the second point is not possible, is calling
extend()OK if the two queries contain duplicates? I don’t recall how SQLAlchemy works well enough around this. It may emit a constraint conflict.
Very appreciate the feedback. Your point is totally valid.
for 2.) and 3.), I have run a few testing with mixed Asset and AssetAlias, but maybe if one event is belong to both an Asset and an Alias. Will investigate more into it. |
By "inactive," do you mean that this asset will no longer be used, rather than becoming invalid? |
Sounds like a good idea. I think this is something we thought of but decide to defer it till someone asks 👀 |
1 similar comment
Sounds like a good idea. I think this is something we thought of but decide to defer it till someone asks 👀 |
Lee-W
left a comment
There was a problem hiding this comment.
In general, the idea looks good. Producing runtime assets was the reason why we implemented asset_alias back then. But making it able to consume asset event this way looks like a good idea 👍
In the metadata store, there is a table for tracking active asset, if I remembered correctly. By "inactive" means the asset is not in that table. I can double-check it when I revisit the code. |
Thanks for the feedback! Yeah, I think it make sense for attaching asset at runtime and emit asset event. I feel this is what can make the asset alias as powerful as it is expected. I feel that it solves the problem like "I want to use a set of assets to trigger my DAG, so I use asset alias. When my DAG is triggered, how do i know which asset/asset event trigger it. Should I treat all those assets in the same way. Or each should be treated differently, or do I need to know which asset to process." However, it also adds some caveats. For example, how we can manage those assets, when a large amount of assets are created at runtime, e.g., 1000s, 10,000s. Is it still a good use case for asset alias, or other patterns should be considered. |
Means an asset is referenced or does not conflict with another asset. In Airflow 3, the design changes a bit. there's an
not solid reason I think. it's just not yet asked 🤔
yep, it's denitily something need more discussion 🤔 |
…ng_asset_events in context, allow downstream consumer task to access the actual asset event when triggered by the asset alias.
6d2ff49 to
0a0777e
Compare
|
Want to share some small updates. I've merged the two queries into one and run all the unit tests in jobs/, create an actual DAG to test the behavior, and profile the query runtime. I observed the following behaviours for the DAG (attached at the end of the comment)
Since the query use multiple Two queries (the first implementation)Since it results in two DAG Runs, the first one captures 2 asset events of the regular One query (merged, current implementation)The runtime is 0.0050 seconds and 0.0060 seconds. Producer DAGfrom airflow.sdk import Asset, AssetAlias, DAG
from airflow.providers.standard.operators.python import PythonOperator
from airflow.providers.standard.operators.empty import EmptyOperator
asset_alias = AssetAlias("asset_alias_massive_events")
asset_1 = Asset("my_asset_1")
asset_2 = Asset("my_asset_2")
with DAG(
dag_id="profile_asset_query_producer",
):
def _generate_regular_asset_event():
print("generate 100 asset events for regular assets")
def _attach_asset_event_to_alias(**context):
outlet_events = context["outlet_events"]
for i in range(1, 101): # I also tried 1001, generate 1000 DAGs
outlet_events[asset_alias].add(
Asset(f"my_asset_alias_{i}"),
extra={"filename": f"my_asset_alias_{i}"}
)
start = EmptyOperator(task_id="start")
generate_regular_asset_event = PythonOperator(
task_id="generate_regular_asset_event",
python_callable=_generate_regular_asset_event,
outlets=[asset_1, asset_2]
)
attach_asset_event_to_alias = PythonOperator(
task_id="attach_asset_event_to_alias",
python_callable=_attach_asset_event_to_alias,
outlets=[asset_alias]
)
end = EmptyOperator(task_id="end")
start >> [generate_regular_asset_event, attach_asset_event_to_alias] >> endConsumer DAGfrom airflow.sdk import Asset, AssetAlias, DAG
from airflow.providers.standard.operators.python import PythonOperator
from airflow.providers.standard.operators.empty import EmptyOperator
asset_alias = AssetAlias("asset_alias_massive_events")
asset_1 = Asset("my_asset_1")
asset_2 = Asset("my_asset_2")
with DAG(
dag_id="profile_asset_query_consumer",
schedule=(asset_1 | asset_2 | asset_alias)
):
def _log_asset_events(**context):
print("context:", context)
log_asset_events = PythonOperator(
task_id="log_asset_events",
python_callable=_log_asset_events,
inlets=[asset_1, asset_2, asset_alias]
) |
|
Hi @Lee-W and @uranusjr , don’t want to rush you, but I wanted to kindly follow up on any feedback if you could have some time to review it. I am planning to add more explanation about the change in query. Feel free to let me know if there is anything I can put in to help the review. Very appreciate your time |
Co-authored-by: Wei Lee <[email protected]>
Co-authored-by: Wei Lee <[email protected]>
Thank you! |
|
@uranusjr I'm thinking of merging this, but I'd like to know your thoughts on this one. Thanks! |
Thank you very much for reviewing it and really happy to hear it is the right direction to go! |
|
On airflow 3.0.6, there's no Can we backport this to airflow 3.0+? 🙏🏼 Here's the code snippet. from pprint import pprint
from typing import Any
from airflow.sdk import Asset, AssetAlias, Context, dag, task
from airflow.sdk.execution_time.context import (
OutletEventAccessors,
TriggeringAssetEventsAccessor,
)
@dag(schedule=None, tags=["demo"])
def assetalias_producer():
@task(outlets=[AssetAlias("asset_alias_0")])
def producer(**context: Context):
outlets: list[Any] = context["outlets"]
outlet_events: OutletEventAccessors = context["outlet_events"]
run_after = context["dag_run"].run_after
for a in outlets:
pprint(a)
match a:
case AssetAlias():
if int(run_after.timestamp()) % 2 == 0:
outlet_events[a].add(Asset("local0", extra={"run_after": run_after}))
else:
outlet_events[a].add(Asset("local1", extra={"n": 1}))
outlet_events[a].add(Asset("local2", extra={"run_after": run_after}))
case Asset():
outlet_events[a].extra = {"rc": 100}
case _:
raise ValueError(f"unexpected outlet type: {type(a)}")
return 0
producer()
@dag(schedule=[AssetAlias("asset_alias_0")], tags=["demo"])
def assetalias_consumer():
@task
def consumer(**context: Context):
triggering_events: TriggeringAssetEventsAccessor = context[
"triggering_asset_events"
]
pprint(triggering_events[AssetAlias("asset_alias_0")])
consumer()
assetalias_producer()
assetalias_consumer() |
|
I just noticed we might not have 3.0.7 as 3.1.0 beta has been released. But this will be included in 3.1.0 |
|
I'm going to backport anyway 👀 |
…AssetAlias (apache#50182) * attach asset event that is attached to an asset alias to the triggering_asset_events in context, allow downstream consumer task to access the actual asset event when triggered by the asset alias. * precommit fix * add test case * profile merge and unmerge query * merge queries into one * Update airflow-core/tests/unit/jobs/test_scheduler_job.py Co-authored-by: Wei Lee <[email protected]> * Update airflow-core/tests/unit/jobs/test_scheduler_job.py Co-authored-by: Wei Lee <[email protected]> --------- Co-authored-by: Wei Lee <[email protected]> (cherry picked from commit 825c322)
…AssetAlias (#50182) (#55534) Co-authored-by: Kevin Yang <[email protected]>







The motivation of this PR is to approach the request “I would like to have the possibility to have a DAG trigger on ANY dataset matching a wildcard/regex” (#39017). The two main use cases include 1.) Trigger ingestion process on file arrival and 2.) Monitor database updates.
Close #39017
Design Solution
Looking at the file arrival use case, the consumer DAG should be triggered on updates to any asset that can be matched to a specific regex pattern. In other words, the consumer DAG will be scheduled on a single Dataset (i.e. Asset) of which the name is some sort of regex string. In this way, the consumer DAG is scheduled on a SINGLE asset and multiple asset events generated by the producer DAG can trigger the consumer DAG.
Considering the concept of AssetAlias, an asset event can be created for any asset that is generated at runtime and be attached to an asset alias. The consumer DAG can be scheduled on a SINGLE asset alias and multiple asset events can be attached to the alias to trigger the consumer DAG. Therefore, utilizing asset aliases can also fulfill the two use cases.
Now, the problem comes. After experimenting with asset aliases, I found that the consumer task within the consumer DAG is not aware of the underlying asset event when it is scheduled on the asset alias. Please check the discussion in the issue for more details.
#39017 (comment)
Therefore, in order to let the consumer task pick up the corresponding asset to process, it needs the access to the underlying asset event that triggers the DAG Run, when the consumer DAG is scheduled on asset aliases (Note: when the consumer DAG is scheduled on Asset, the asset event is propagated to the “triggering_asset_events” in Airflow context and the “inlet_events”, but it is not the case for asset alias in schedule).
The changes made in this PR updates the scheduler code to propagate this information to the “consumed_asset_events” such that the “triggering_asset_events” can include this information when the consumer DAG is scheduled on an asset alias. In this way, the consumer task in the consumer DAG can utilize the information to determine the asset event and pick up the corresponding asset to process, aligning with the use case objective.
The downsides of using AssetAlias?
When an asset is created at runtime and attached to an asset alias, the asset is not set in the “outlets” or “inlets”, so the created asset will be inactive. This asset will show up in the Airflow UI as well as persist in the Airflow metadata store, even though it will be just used once. Therefore, for use cases that create different assets every time when the producer DAG runs, it generates inactive/orphan/unused assets without being able to clean up.
A Potential Solution
Probably we can create an API endpoint to clean up those unused assets related to an asset alias.
Unit tests
The following use case is run to test the scheduler job run. I have created a test case
test_create_dag_runs_asset_alias_with_asset_event_attachedto validate that the AssetEvent will be attached to the context when the consumer DAG is trigger on AssetAlias.Other test suites related to asset-aware scheduling are run.
#50182 (comment)
^ Add meaningful description above
Read the Pull Request Guidelines for more information.
In case of fundamental code changes, an Airflow Improvement Proposal (AIP) is needed.
In case of a new dependency, check compliance with the ASF 3rd Party License Policy.
In case of backwards incompatible changes please leave a note in a newsfragment file, named
{pr_number}.significant.rstor{issue_number}.significant.rst, in airflow-core/newsfragments.