Skip to content

Allow a DAG to be scheduled when any related DataSet is updated - #28333

Closed
hugochinchilla wants to merge 8 commits into
apache:mainfrom
hugochinchilla:schedule-on-any-dataset-changed
Closed

hugochinchilla wants to merge 8 commits into
apache:mainfrom
hugochinchilla:schedule-on-any-dataset-changed

Conversation

@hugochinchilla

@hugochinchilla hugochinchilla commented Dec 13, 2022 •

Copy link
Copy Markdown

This comes from the discussion in #28253

Currently the behavior for a DAG which depends on multiple DataSets is to be executed only when all datasets have been updated since the last DAG execution. This feature would enable a DAG to run every time any of the multiple DataSets change.

The motivation is to allow better traceability of changes in a derived dataset, being able to track down changes along all the DAGs chain for every change in every dataset.

This adds a new field to the DAG and DagModel to allow for a DAG to be scheduled anytime any of it's datasets passed in the schedule field is updated, instead of waiting for all datasets to be updated.

Still to do:

  • pass community review
  • update the UI to remove the "x of y datasets updated" in the column for next schedule

ping @ashb @potiuk

@boring-cyborg

boring-cyborg Bot commented Dec 13, 2022

Copy link
Copy Markdown

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 Contribution Guide (https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst)
Here are some useful points:

  • Pay attention to the quality of your code (flake8, mypy and type annotations). Our pre-commits will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example DAG that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: [email protected]
    Slack: https://s.apache.org/airflow-slack

@ashb

ashb commented Dec 13, 2022

Copy link
Copy Markdown
Member

I'm okay with not having the full power of an arbitrary boolean condition, but I think I would like to avoid adding an extra argument for this, and instead pass something like

DAG(
    ...
    schedule=any_of(ds1, ds2),
)

etc. (Not that particular name necessarily - it's just an example)

@hugochinchilla
hugochinchilla force-pushed the schedule-on-any-dataset-changed branch from 139a663 to 8f8c0fe Compare December 13, 2022 13:57
@hugochinchilla
hugochinchilla force-pushed the schedule-on-any-dataset-changed branch from ec7af67 to 986ba8d Compare December 13, 2022 14:49
@hugochinchilla

Copy link
Copy Markdown
Author

@ashb I like your idea, I implemented it just like that.

@hugochinchilla
hugochinchilla force-pushed the schedule-on-any-dataset-changed branch from 986ba8d to 1b66d29 Compare December 14, 2022 07:39
@hugochinchilla

Copy link
Copy Markdown
Author

Can we get this moving?

@bolkedebruin

bolkedebruin commented Dec 15, 2022 •

Copy link
Copy Markdown
Contributor

I am wondering if this is generic enough. I can imagine that you want full business rule implementation and that any_of is an implementation of such rule.

For example if you have dataset_1, _2, _3 and have dag_1 be dependent on all these datasets and dag_2 be dependent on dataset_1, dataset_2 only if dataset_3 hasnt changed. This currently requires a sensor which defeats the purpose of having this (kind of) event driven.

This change 'only' adds any to all. I think i'd like to see a more strategic approach. Or at least one that would fit with such an approach and this one seems too idiosyncratic.

What about something along the lines of

class Rule():
  def evaluate(List[Dataset]) -> bool:
    return True

def AnyOf(Rule):

or maybe with a decorator:

@rule
def any_of(List[Dataset]) -> bool:
  return True

Which looks a bit nicer.

@hugochinchilla

Copy link
Copy Markdown
Author

@bolkedebruin what you propose escapes of the scope of a small incremental improvement, right now the scheduler decisions are evaluated in pure SQL and this MR adds a little more capabilities based on the same design.

I think that what you propose is a very powerful idea but this can be added as a later improvement for a later release, I would like if we can avoid a "perfect is enemy of good" situation here.

Also I have a concern with moving the evaluation of dependencies outside SQL, because of how the scheduling loop is executed it could happen that the query would return a set of rows, the rules would ignore them all, and do nothing, the next scheduling loop would return the same set of rows and the problem would repeat, making the scheduler starve while there are other DAGs available to execute. So this is not a change that can be made without rethinking a lot of assumptions on core parts that I'm not so familiar with.

Comment thread airflow/datasets/__init__.py Outdated
Comment on lines 48 to 55

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t see how this can’t simply be

class anyof(list):
    pass

@bolkedebruin bolkedebruin Dec 15, 2022 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should go into its own file and not be here. It confused me as I first thought it was derived from Dataset.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@uranusjr if this was a subclass of list you would need to use it like this:

any_of([dataset1, dataset2])

# with the actual implementation you do:

any_of(dataset1, dataset2)

@bolkedebruin can you suggest a better place for it? I thought it was handy to import both Dataset and any_of from the same module as they are closely related.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it is confusing as one is a rule and the other is a Data class. Ie. one references something while the other operates on the one that references.

I think this should be located in rules.py

@bolkedebruin

Copy link
Copy Markdown
Contributor

@hugochinchilla I understand that you don't want to take on the scope of what I proposed, but I'd like your change to be compatible and future proof. Now a new field is added to the database which would need to be removed / migrated again in the future for example. Can this be more generic so that a migration isn't needed?

I'm no sure if I share your concern with respect of the the scheduler starving. While performance wise their might be a difference between a Python filter vs a sql filter I don't see how the scheduler would starve.

Another approach could be that Rules should be returning SQLAlchemy filters, however they would be less flexible.

So, the idea is not to stand in the way of the change, but neither having to fully re-implement what you have created if there is already a path to the future. Some technical debt is acceptable, but preferably in code rather than in db for example.

@hugochinchilla

Copy link
Copy Markdown
Author

@bolkedebruin there is the setting scheduler.max_dagruns_to_create_per_loop which limits the query that retrieves the dags that can be run (see here).

It could happen that all the returned items are returned because they are in dataset_triggered_dag_ids, then the rules evaluated in python could reject all items. If that where to happen the scheduler would loop forever without consuming any job.

@bolkedebruin

bolkedebruin commented Dec 16, 2022 •

Copy link
Copy Markdown
Contributor

@hugochinchilla the scheduler won't starve in case the dataset_triggered_dag_ids is filtered before the query with max_dagruns_to_create_per_loop runs. This is the case already, so that does not require extra work.

depending the approach this line:

.having(func.count() == func.sum(case((DDRQ.target_dag_id.is_not(None), 1), else_=0)))

changed to support SQLAlchemy filtering or python filtering.

I currently do not think that an extra field in the database is warranted, also not for the simple implementation.

What also is sticking out is that a change to the serialization format is being made. I think this should be versioned as it is backwards incompatible.

@bolkedebruin
bolkedebruin self-requested a review December 16, 2022 12:19
@hugochinchilla
hugochinchilla force-pushed the schedule-on-any-dataset-changed branch from fd5a841 to 83ab9cc Compare December 19, 2022 08:07
@hugochinchilla

Copy link
Copy Markdown
Author

I've modified the database implementation to use a string column.

I still have to make it nice, move the strings to some constants and maybe try to implement some python evaluators for the conditions to allow custom modes.

@hugochinchilla

Copy link
Copy Markdown
Author

I've cleaned up a bit the code.

IMHO, the current state of datasets allow treating the dataset dependencies as an AND rule, with this change we have the OR rule. For more complex situations you can split your logic in multiple DAGs and combine the rules to create almost anything you need (as suggested by @potiuk here #28253 (reply in thread)).

Things like #28455 are elevating the project complexity to a very high level just in case we want to do something else later, without even considering which are this potential use cases, and also before having anyone asking for it. I think to consider having something like a "rule engine" we should first define the use cases we want to support, and this should be backed by real needs, not hypothetical cases just to justify the existence of the added complexity.

@bolkedebruin

bolkedebruin commented Dec 19, 2022 •

Copy link
Copy Markdown
Contributor

I do not think Iam sharing your feelings. I have already explained one use case above and this was actually based on a real world request.

A DAG is typically seen a a "unit-of-work", e.g. generating a Dataset. If it is required to split this unit of work because the DSL isnt expressive enough I don't think that is the right way. Therefore, I disagree with @potiuk that what is described in #28253 (reply in thread) is actually simple. The example I gave above would mix event driven with a pull based mechanism (sensor) that is not logical neither intuitive. Next to that, the approach described is inefficient (a database query vs multiple task runs).

However, even if we would accept the above stance that simplicity on the user side is preferred for now and at the same time we would like to keep our options for the future open, I think your current implementation is not forward compatible. If applying the thinking of #28455 all code here would need to be changed, the dag serialization schema would need to be deprecated and changed and database would need to be migrated. I do not think that is the right path.

I do think that what you would like to achieve is quite easily done with the approach I put into #28455 and I would argue it is the same amount of work. In this case it would just be adding the filtering logic. If we then decide to add additional Rules in the future this can be done without changing any of the scheduler code, database and schema. WIth rules being able to be serialized, visualization is quite easy to achieve.

@hugochinchilla

Copy link
Copy Markdown
Author

I don't have time for implementing anything more complex than this. I had a need and this was all I needed to make it work, as I see this is gonna take too much time and effort to put into a release I've found a simple workaround that works for me.

If anybody needs to be able to change the default behavior so that all dags are run whenever any related dataset is updated, just use this dag:

@dag(schedule=timedelta(minutes=1), max_active_runs=1, start_date=datetime(2022, 1, 1), catchup=False)
def schedule_dags_on_datasets_updated():
    @task
    def find_updated_datasets():
        from airflow.models.dataset import DagScheduleDatasetReference, DatasetDagRunQueue as DDRQ
        from airflow.utils.session import create_session
        from sqlalchemy import insert, and_
        from sqlalchemy.sql.functions import now

        with create_session() as session:
            select = (
                session.query(
                    DagScheduleDatasetReference.dataset_id,
                    DagScheduleDatasetReference.dag_id,
                    now(),
                )
                .join(
                    DDRQ,
                    and_(
                        DDRQ.dataset_id == DagScheduleDatasetReference.dataset_id,
                        DDRQ.target_dag_id == DagScheduleDatasetReference.dag_id,
                    ),
                    isouter=True,
                )
                .filter(DDRQ.target_dag_id.is_(None))
            )

            insert_stmt = insert(DDRQ).from_select([
                DDRQ.dataset_id,
                DDRQ.target_dag_id,
                DDRQ.created_at
            ], select)

            session.execute(insert_stmt)

    find_updated_datasets()

schedule_dags_on_datasets_updated()

This will fill the DatasetDagRunQueue with fake events for each missing event to make the scheduler run every time a single dataset has been updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants