Skip to content

Allow DAGs to trigger on Datasets with wildcard/regex #39017

Closed

Description

@w0ut0

Description

I would like to have the possibility to have a DAG trigger on ANY dataset matching a wildcard/regex.

Use case/motivation

We have 2 (similar) use cases.

Trigger ingestion process on file arrival.

Files land in blob storage, which triggers events like:

{
"filename": "/raw/my/folder1/2024/04/15/file1.csv",
"event": "fileCreated"
}

and

{
"filename": "/raw/my/folder1/2024/04/15/file1.json",
"event": "fileCreated"
}

and

{
"filename": "/raw/my/folder1/2024/02/10/file1.json",
"event": "fileCreated"
}

These events are converted to Dataset update events, either by calling the Airflow API, or a DAG that polls a queue that contains the above events. In the above case, three Datasets would be updated:

  • ingestionblob://raw/my/folder1/2024/04/15/file1.csv
  • ingestionblob://raw/my/folder1/2024/04/15/file1.json
  • ingestionblob://raw/my/folder1/2024/02/10/file1.json

Image that we have a DAG ingestCSVFromRawRealTime. I would like to be able to trigger that DAG on datasets with wildcards ingestionblob://raw/my/folder1/{today.year}/{today.month}/{today.day}/*.csv.

Similarly for some DAGs like ingestJsonFromRawRealTime or ingestBackfilledCsvFromRaw.

Ideally, we can create capture groups in the regex of the Dataset trigger, and use these capture groups as DAG parameter.

Monitor database updates

Our (Databricks) DWH, like almost all other dbms's, has a 3-level namespace: database.schema.table. We will create a mechanism to emit dataset events like

  • database1.bronze.table7
  • database4.silver.view3
  • database2.gold.streamingTable1
  • ...

Sometimes, we want to be notified on updates to the whole database, schema or table. There are some use cases where having wildcard triggers would be beneficial:

  • Airflow needs to trigger a sync in our BI tool (eg. PowerBI, Tableau) if an object from the gold schema in database2 is updated.
  • When data arrived in the bronze schema, some curation scripts needs to be kicked-off to generate a 'cleaned' silver table.

Related issues

  • 34534. But with the new logical operators for Datasets, we can already trigger on more than 1 dataset.

Are you willing to submit a PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:feature
    needs-triage
    on Apr 15, 2024
  2. changed the title [-]Allow DAGs to trigger on Datasets with wildcard[/-] [+]Allow DAGs to trigger on Datasets with wildcard/regex[/+] on Apr 15, 2024
  3. lotrias17 commented on Apr 22, 2024

    @lotrias17
    Contributor

    Hello, could a colleague (@TiDeane) and I be assigned to this issue? We are working for a university project and would be grateful to implement this feature. Thank you in advance.

  4. lotrias17 commented on Apr 22, 2024

    @lotrias17
    Contributor

    Also, we would be very grateful for any guidance from anyone if possible.

  5. kovla commented on Apr 22, 2024

    @kovla

    The original proposal seconded.

  6. Lee-W commented on Apr 30, 2024

    @Lee-W
    Member

    Hi @lotrias17, I just assigned this one to you. I can not assign it to @TiDeane. Once a comment has been left from @TiDeane, I should be able to assign it

  7. removed
    needs-triage
    on Apr 30, 2024
  8. Lee-W commented on Apr 30, 2024

    @Lee-W
    Member

    @sunank200 As you submitted a bunch of dataset related PRs these days, I think you might be interested in join the discussion 🙂

  9. TiDeane commented on Apr 30, 2024

    @TiDeane
    Contributor

    Hello, just commenting so you can assign me as well @Lee-W. I'm going to be working on this with @lotrias17.

  10. Lee-W commented on Apr 30, 2024

    @Lee-W
    Member

    Just assigned @TiDeane . Thanks
    !

  11. lotrias17 commented on May 18, 2024

    @lotrias17
    Contributor

    We are running into problems with Session. How could we initialize a session in a function inside class DAG (in models/dag.py), with the intention of searching the db for the datasets related to the DAG? Thank you in advance.

  12. 2 remaining items

  13. TiDeane commented on Jun 14, 2024

    @TiDeane
    Contributor

    We haven't been able to get much progress on this feature, so unfortunately we're going to drop it so others with more experience can pick it up. We're very sorry, and hope for the best for future contributors.

  14. removed their assignment
    on Jun 14, 2024
  15. added
    area:data-aware-scheduling
    and removed on Mar 25, 2025
  16. sjyangkevin commented on Apr 28, 2025

    @sjyangkevin
    Contributor

    Hi, could I be assigned to this issue? I am currently working on a project with the exact same use case. This feature will be helpful for a more flexible data-aware scheduling. Thanks.

  17. potiuk commented on Apr 28, 2025

    @potiuk
    Member

    Hi, could I be assigned to this issue? I am currently working on a project with the exact same use case. This feature will be helpful for a more flexible data-aware scheduling. Thanks.

    Feel free. That's a good motivation to contribute :)

  18. sjyangkevin commented on May 4, 2025

    @sjyangkevin
    Contributor

    Hi, I want to share some updates about the progress so far and also ask some questions. I would appreciate if anyone can provide me some feedback or suggestions.

    Considering all the assets generated at runtime can actually be attached to an asset alias. The consumer task can treat the asset alias as a single “asset” and be triggered when a new asset is attached and updated by producer.

    From my perspective, the use cases can be achieved by either being able to access the name or uri of the asset that is attached to the asset alias, or through the extra keyword from the triggering_asset_events from the context in the consumer task.

    However, I've run some experiments, and found that these information are not propagated to either the inlet_events or the triggering_asset_events, as shown below the log from the consumer task.

    [2025-05-03, 21:44:35] INFO - inlet_events: InletEventsAccessors(_inlets=[AssetAlias(name='file_asset_event', group='asset')], _assets={}, _asset_aliases={AssetAliasUniqueKey(name='file_asset_event'): AssetAlias(name='file_asset_event', group='asset')}): chan="stdout": source="task"
    
    [2025-05-03, 21:26:43] INFO - triggering_asset_events: TriggeringAssetEventAccessor(_events=defaultdict(<class 'list'>, {})): chan="stdout": source="task"
    

    I actually attached the information in the outlet_events, and below is the log from the producer task.

    [2025-05-03, 21:44:35] INFO - outlet_events:  OutletEventAccessors(_dict={AssetAliasUniqueKey(name='file_asset_event'): OutletEventAccessor(key=AssetAliasUniqueKey(name='file_asset_event'), extra={}, asset_alias_events=[AssetAliasEvent(source_alias_name='file_asset_event', dest_asset_key=AssetUniqueKey(name='/raw/data/file_05032025.csv', uri='/raw/data/file_05032025.csv'), extra={'filename': '/raw/data/file_05032025.csv'})])}): chan="stdout": source="task"
    

    In terms of implementation, I am trying to see if the following information can be accessible from the consumer task when the consumer DAG is triggered through asset alias.

    1. AssetUniqueKey(name='/raw/data/file_05032025.csv', uri='/raw/data/file_05032025.csv') in inlet_events.
    2. Or extra={'filename': '/raw/data/file_05032025.csv'} in triggering_asset_events.

    Questions:

    1. I am wondering if it is the right approach to the issue?
    2. Is there any caveat I should keep in mind when populating the information in inlet_events and triggering_asset_events?
    3. I am looking at the InletEventsAccessors under task-sdk/src/airflow/sdk/execution_time/context.py. Is it the right place to look at and modify the information being included in inlet_events?

    Below is what I think about why this approach can resolve the issue.

    1. In the producer task, we can match wildcard/regex and make the file as an asset and attach it to an asset alias.
    2. The file path information can be propagated to the consumer DAG and task to further process.
    3. The consumer DAG is triggered by the asset alias (it can be treated as a single "asset").

    Below is my producer and consumer DAG code that generate the logs above. Thanks.

    Producer

    from airflow.sdk import Asset, AssetAlias, DAG, Param
    from airflow.providers.standard.operators.python import PythonOperator
    
    # Define the alias once
    file_asset_alias = AssetAlias("file_asset_event")
    
    with DAG(
        dag_id="asset_alias_producer",
        params={"filename": Param(type="string")}
    ):
    
        def my_function(**context):
            filename = context["params"]["filename"]
            print("filename:", filename)
    
            outlet_events = context["outlet_events"]
            outlet_events[file_asset_alias].add(
                Asset(filename),
                extra={"filename": filename}
            )
            print("outlet_events: ", outlet_events)
    
        my_task = PythonOperator(
            task_id="producer_task",
            python_callable=my_function,
            outlets=[file_asset_alias]  # use the same alias
        )
    

    Consumer

    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:", context)
    
            inlet_events = context["inlet_events"]
            print("inlet_events:", inlet_events)
    
            triggering_asset_events = context["triggering_asset_events"]
            for event in triggering_asset_events[AssetAlias("file_asset_event")]:
                print(event)
    
        my_task = PythonOperator(
            task_id="consumer_task",
            python_callable=my_function,
            inlets=[file_asset_alias]
        )
    
    
  19. sjyangkevin commented on May 4, 2025

    @sjyangkevin
    Contributor

    Link the asset alias with the asset event and propagate information to consumer task, accessing through triggering_asset_events via context.

    Asset /raw/data/file_05032025.csv created at runtime, and event attached to alias can be accessed by consumer task.
    Image
    Asset /raw/data/file_05042025.csv created at runtime, and event attached to alias can be accessed by consumer task.
    Image

    In this way, producer task can dynamically generate asset, and attached the asset event to the alias, using alias as outlets. Consumer DAG can be scheduled on a single asset alias, and gather information about those dynamically created asset.

  20. sjyangkevin commented on May 5, 2025

    @sjyangkevin
    Contributor

    Hi @Lee-W , I opened a draft PR and want to get an early feedback. I still need to figure out how to run proper testing on my local environment and experiments with more scenarios of the use cases mentioned in the issue. Below is the link to the draft PR. Can I get your help to have a look on it? Thank you!

    #50182

  21. Lee-W commented on May 6, 2025

    @Lee-W
    Member

    However, I've run some experiments, and found that these information are not propagated to either the inlet_events or the triggering_asset_events

    Do you mean extra? I think they're there. Just not included in the __repr__.

    Also, you'll need to actally access the inlets.
    e.g.,

    inlet_events[Asset(name="abc")]

    I am wondering if it is the right approach to the issue?

    sounds reasonable to me

    Is there any caveat I should keep in mind when populating the information in inlet_events and triggering_asset_events?

    inlet_events should be fine. But inlet_events is not something used to triggered a dag. It's more like an extra infomration a dag can requested from the history.

    triggering_asset_events should probably be fine as well 🤔

    I am looking at the InletEventsAccessors under task-sdk/src/airflow/sdk/execution_time/context.py. Is it the right place to look at and modify the information being included in inlet_events?

    kind of? depends on what kind of information. this is how we request the asset event history for a specific asset. e.g., the following logic is implemented here

    inlet_events[Asset(name="abc")]

    Below is what I think about why this approach can resolve the issue.

    sounds reasonable to me

  22. sjyangkevin commented on May 6, 2025

    @sjyangkevin
    Contributor

    Thank you very much for the followup. Sorry for writing a very long text trying to explain my thinking. Please let me know if there is any follow up questions.

    I want to explain it using my DAG code and logs. From what I understand the use case, each event will be mapped to an asset respectively. Suppose I have three file drop events pulled by the producer DAG and it generates three different assets.

    file_A_2025-05-03 -> Asset(name='file_A_2025-05-03')
    file_A_2025-05-04 -> Asset(name='file_A_2025-05-04')
    file_A_2025-05-05 -> Asset(name='file_A_2025-05-05')

    I think the original objective is to have the consumer DAG trigger on updates to Asset(name='file_A_{year}-{month}-{day}'), but asset name doesn't support regex kind of definition. After a few experiments, I found that we can create Assets and attached the corresponding asset event to the Asset Alias defined through outlet_events. The consumer DAG can then be triggered on the Asset Alias. In this way, the producer DAG can define regex/wildcard matching (through DAG code) and create an asset event on match. Please see the DAG code below for my experiment. Now come to the question:

    Do you mean extra? I think they're there. Just not included in the __repr__.

    TL;DR

    The extra seems only available for DAG trigger on Asset but not available for DAG trigger on AssetAlias.

    [2025-05-05, 23:33:37] INFO - inlet_events [inlets]: AssetAlias(name='file_asset_event', group='asset'): chan="stdout": source="task"
    [2025-05-05, 23:33:37] INFO - inlet_events [asset]: {}: chan="stdout": source="task"
    [2025-05-05, 23:33:37] INFO - inlet_events [asset alias]: {AssetAliasUniqueKey(name='file_asset_event'): AssetAlias(name='file_asset_event', group='asset')}: chan="stdout": source="task"
    [2025-05-05, 23:33:37] INFO - triggering_asset_events: TriggeringAssetEventAccessor(_events=defaultdict(<class 'list'>, {})): chan="stdout": source="task"
    [2025-05-05, 23:33:37] INFO - See Asset Alias `file_asset_event`: []: chan="stdout": source="task"
    

    In the consumer task, I tried to access the inlet_events and the triggering_asset_events, and wasn't able to see either the Asset or the AssetEevent attached to the AssetAlias, as shown above. These information seems only available when the DAG is triggered on Asset, as shown in the screenshot below.

    Image

    Why the asset event or asset information matter in this case?

    It can be thought as a work around to implement the requirements in a simplified way. When the consumer task can access the asset event, suppose a file drop create Asset(name='file_A_2025-05-04') and attach to the Asset Alias. Downstream task trigger on the alias can fetch the asset's name, uri, or even extra from the triggering_asset_events from context. In this way, for each consumer DAG Run triggered by the event on the asset alias, the consumer task can access the corresponding asset event and process on the correct file drop. This might also answer: #50182 (review).

    Producer DAG

    from airflow.sdk import Asset, AssetAlias, DAG, Param
    from airflow.providers.standard.operators.python import PythonOperator
    
    # Define the alias once
    file_asset_alias = AssetAlias("file_asset_event")
    
    with DAG(
        dag_id="asset_alias_producer",
        params={"filename": Param(type="string")}
    ):
    
        def my_function(**context):
            # here, the filename is from Airflow Parameter, for testing purpose, but can be a regex matching on filename.
            filename = context["params"]["filename"]
            print("filename:", filename)
            # define the outlet event and then attach the event to alias.
            outlet_events = context["outlet_events"]
            outlet_events[file_asset_alias].add(
                Asset(filename),
                extra={"filename": filename}
            )
            print("outlet_events: ", outlet_events)
    
        my_task = PythonOperator(
            task_id="producer_task",
            python_callable=my_function,
            outlets=[file_asset_alias]  # use the alias as outlet
        )

    Consumer DAG

    from airflow.sdk import Asset, AssetAlias, DAG
    from airflow.providers.standard.operators.python import PythonOperator
    
    file_asset_alias = AssetAlias("file_asset_event")
    # DAG to trigger on the alias
    with DAG(
        dag_id="asset_alias_consumer",
        schedule=[file_asset_alias]
    ):
        
        def my_function(**context):
    
            print("context:", context)
            # try to access the inlet events from context
            inlet_events = context["inlet_events"]
            print("inlet_events [inlets]:", inlet_events._inlets[0])
            print("inlet_events [asset]:", inlet_events._assets)
            print("inlet_events [asset alias]:", inlet_events._asset_aliases)
    
            # try to access the asset events
            triggering_asset_events = context["triggering_asset_events"]
            print("triggering_asset_events:", triggering_asset_events)
            print("See Asset Alias `file_asset_event`:", triggering_asset_events[AssetAlias("file_asset_event")])
            for event in triggering_asset_events[AssetAlias("file_asset_event")]:
                print("Received asset URI:", event.asset.key.name) # here is a mistake, but the `triggering_asset_events` is empty.
                print("Extra metadata:", event.extra)
    
        my_task = PythonOperator(
            task_id="consumer_task",
            python_callable=my_function,
            inlets=[file_asset_alias]
        )
  23. sjyangkevin commented on May 6, 2025

    @sjyangkevin
    Contributor

    I also want to attach an example when the Asset and AssetAlias are used in joint. After the code change #50182, the asset event is available for DAG trigger on alias, by accessing triggering_asset_events.

    Image

    Consumer DAG

    from airflow.sdk import Asset, AssetAlias, DAG
    from airflow.providers.standard.operators.python import PythonOperator
    
    file_asset_alias = AssetAlias("file_asset_event")
    asset = Asset("my_asset")
    
    with DAG(
        dag_id="mixed_asset_consumer",
        schedule=[asset & file_asset_alias]
    ):
        
        def my_function(**context):
    
            print("context:", context)
    
            inlet_events = context["inlet_events"]
            print("inlet_events:", inlet_events)
    
            triggering_asset_events = context["triggering_asset_events"]
            for event in triggering_asset_events[AssetAlias("file_asset_event")]:
                print(event)
            for event in triggering_asset_events[Asset("my_asset")]:
                print(event)
    
        my_task = PythonOperator(
            task_id="consumer_task",
            python_callable=my_function,
            inlets=[file_asset_alias]
        )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:corearea:data-aware-schedulingkind:feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions